lib.php 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * This file contains classes used to manage the repository plugins in Moodle
  18. *
  19. * @since Moodle 2.0
  20. * @package core_repository
  21. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die();
  25. require_once($CFG->libdir . '/filelib.php');
  26. require_once($CFG->libdir . '/formslib.php');
  27. define('FILE_EXTERNAL', 1);
  28. define('FILE_INTERNAL', 2);
  29. define('FILE_REFERENCE', 4);
  30. define('RENAME_SUFFIX', '_2');
  31. /**
  32. * This class is used to manage repository plugins
  33. *
  34. * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
  35. * A repository type can be edited, sorted and hidden. It is mandatory for an
  36. * administrator to create a repository type in order to be able to create
  37. * some instances of this type.
  38. * Coding note:
  39. * - a repository_type object is mapped to the "repository" database table
  40. * - "typename" attibut maps the "type" database field. It is unique.
  41. * - general "options" for a repository type are saved in the config_plugin table
  42. * - when you delete a repository, all instances are deleted, and general
  43. * options are also deleted from database
  44. * - When you create a type for a plugin that can't have multiple instances, a
  45. * instance is automatically created.
  46. *
  47. * @package core_repository
  48. * @copyright 2009 Jerome Mouneyrac
  49. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  50. */
  51. class repository_type implements cacheable_object {
  52. /**
  53. * Type name (no whitespace) - A type name is unique
  54. * Note: for a user-friendly type name see get_readablename()
  55. * @var String
  56. */
  57. private $_typename;
  58. /**
  59. * Options of this type
  60. * They are general options that any instance of this type would share
  61. * e.g. API key
  62. * These options are saved in config_plugin table
  63. * @var array
  64. */
  65. private $_options;
  66. /**
  67. * Is the repository type visible or hidden
  68. * If false (hidden): no instances can be created, edited, deleted, showned , used...
  69. * @var boolean
  70. */
  71. private $_visible;
  72. /**
  73. * 0 => not ordered, 1 => first position, 2 => second position...
  74. * A not order type would appear in first position (should never happened)
  75. * @var integer
  76. */
  77. private $_sortorder;
  78. /**
  79. * Return if the instance is visible in a context
  80. *
  81. * @todo check if the context visibility has been overwritten by the plugin creator
  82. * (need to create special functions to be overvwritten in repository class)
  83. * @param stdClass $context context
  84. * @return bool
  85. */
  86. public function get_contextvisibility($context) {
  87. global $USER;
  88. if ($context->contextlevel == CONTEXT_COURSE) {
  89. return $this->_options['enablecourseinstances'];
  90. }
  91. if ($context->contextlevel == CONTEXT_USER) {
  92. return $this->_options['enableuserinstances'];
  93. }
  94. //the context is SITE
  95. return true;
  96. }
  97. /**
  98. * repository_type constructor
  99. *
  100. * @param int $typename
  101. * @param array $typeoptions
  102. * @param bool $visible
  103. * @param int $sortorder (don't really need set, it will be during create() call)
  104. */
  105. public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
  106. global $CFG;
  107. //set type attributs
  108. $this->_typename = $typename;
  109. $this->_visible = $visible;
  110. $this->_sortorder = $sortorder;
  111. //set options attribut
  112. $this->_options = array();
  113. $options = repository::static_function($typename, 'get_type_option_names');
  114. //check that the type can be setup
  115. if (!empty($options)) {
  116. //set the type options
  117. foreach ($options as $config) {
  118. if (array_key_exists($config, $typeoptions)) {
  119. $this->_options[$config] = $typeoptions[$config];
  120. }
  121. }
  122. }
  123. //retrieve visibility from option
  124. if (array_key_exists('enablecourseinstances',$typeoptions)) {
  125. $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
  126. } else {
  127. $this->_options['enablecourseinstances'] = 0;
  128. }
  129. if (array_key_exists('enableuserinstances',$typeoptions)) {
  130. $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
  131. } else {
  132. $this->_options['enableuserinstances'] = 0;
  133. }
  134. }
  135. /**
  136. * Get the type name (no whitespace)
  137. * For a human readable name, use get_readablename()
  138. *
  139. * @return string the type name
  140. */
  141. public function get_typename() {
  142. return $this->_typename;
  143. }
  144. /**
  145. * Return a human readable and user-friendly type name
  146. *
  147. * @return string user-friendly type name
  148. */
  149. public function get_readablename() {
  150. return get_string('pluginname','repository_'.$this->_typename);
  151. }
  152. /**
  153. * Return general options
  154. *
  155. * @return array the general options
  156. */
  157. public function get_options() {
  158. return $this->_options;
  159. }
  160. /**
  161. * Return visibility
  162. *
  163. * @return bool
  164. */
  165. public function get_visible() {
  166. return $this->_visible;
  167. }
  168. /**
  169. * Return order / position of display in the file picker
  170. *
  171. * @return int
  172. */
  173. public function get_sortorder() {
  174. return $this->_sortorder;
  175. }
  176. /**
  177. * Create a repository type (the type name must not already exist)
  178. * @param bool $silent throw exception?
  179. * @return mixed return int if create successfully, return false if
  180. */
  181. public function create($silent = false) {
  182. global $DB;
  183. //check that $type has been set
  184. $timmedtype = trim($this->_typename);
  185. if (empty($timmedtype)) {
  186. throw new repository_exception('emptytype', 'repository');
  187. }
  188. //set sortorder as the last position in the list
  189. if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
  190. $sql = "SELECT MAX(sortorder) FROM {repository}";
  191. $this->_sortorder = 1 + $DB->get_field_sql($sql);
  192. }
  193. //only create a new type if it doesn't already exist
  194. $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
  195. if (!$existingtype) {
  196. //create the type
  197. $newtype = new stdClass();
  198. $newtype->type = $this->_typename;
  199. $newtype->visible = $this->_visible;
  200. $newtype->sortorder = $this->_sortorder;
  201. $plugin_id = $DB->insert_record('repository', $newtype);
  202. //save the options in DB
  203. $this->update_options();
  204. $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
  205. //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
  206. //be possible for the administrator to create a instance
  207. //in this case we need to create an instance
  208. if (empty($instanceoptionnames)) {
  209. $instanceoptions = array();
  210. if (empty($this->_options['pluginname'])) {
  211. // when moodle trying to install some repo plugin automatically
  212. // this option will be empty, get it from language string when display
  213. $instanceoptions['name'] = '';
  214. } else {
  215. // when admin trying to add a plugin manually, he will type a name
  216. // for it
  217. $instanceoptions['name'] = $this->_options['pluginname'];
  218. }
  219. repository::static_function($this->_typename, 'create', $this->_typename, 0, context_system::instance(), $instanceoptions);
  220. }
  221. //run plugin_init function
  222. if (!repository::static_function($this->_typename, 'plugin_init')) {
  223. $this->update_visibility(false);
  224. if (!$silent) {
  225. throw new repository_exception('cannotinitplugin', 'repository');
  226. }
  227. }
  228. cache::make('core', 'repositories')->purge();
  229. if(!empty($plugin_id)) {
  230. // return plugin_id if create successfully
  231. return $plugin_id;
  232. } else {
  233. return false;
  234. }
  235. } else {
  236. if (!$silent) {
  237. throw new repository_exception('existingrepository', 'repository');
  238. }
  239. // If plugin existed, return false, tell caller no new plugins were created.
  240. return false;
  241. }
  242. }
  243. /**
  244. * Update plugin options into the config_plugin table
  245. *
  246. * @param array $options
  247. * @return bool
  248. */
  249. public function update_options($options = null) {
  250. global $DB;
  251. $classname = 'repository_' . $this->_typename;
  252. $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
  253. if (empty($instanceoptions)) {
  254. // update repository instance name if this plugin type doesn't have muliti instances
  255. $params = array();
  256. $params['type'] = $this->_typename;
  257. $instances = repository::get_instances($params);
  258. $instance = array_pop($instances);
  259. if ($instance) {
  260. $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
  261. }
  262. unset($options['pluginname']);
  263. }
  264. if (!empty($options)) {
  265. $this->_options = $options;
  266. }
  267. foreach ($this->_options as $name => $value) {
  268. set_config($name, $value, $this->_typename);
  269. }
  270. cache::make('core', 'repositories')->purge();
  271. return true;
  272. }
  273. /**
  274. * Update visible database field with the value given as parameter
  275. * or with the visible value of this object
  276. * This function is private.
  277. * For public access, have a look to switch_and_update_visibility()
  278. *
  279. * @param bool $visible
  280. * @return bool
  281. */
  282. private function update_visible($visible = null) {
  283. global $DB;
  284. if (!empty($visible)) {
  285. $this->_visible = $visible;
  286. }
  287. else if (!isset($this->_visible)) {
  288. throw new repository_exception('updateemptyvisible', 'repository');
  289. }
  290. cache::make('core', 'repositories')->purge();
  291. return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
  292. }
  293. /**
  294. * Update database sortorder field with the value given as parameter
  295. * or with the sortorder value of this object
  296. * This function is private.
  297. * For public access, have a look to move_order()
  298. *
  299. * @param int $sortorder
  300. * @return bool
  301. */
  302. private function update_sortorder($sortorder = null) {
  303. global $DB;
  304. if (!empty($sortorder) && $sortorder!=0) {
  305. $this->_sortorder = $sortorder;
  306. }
  307. //if sortorder is not set, we set it as the ;ast position in the list
  308. else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
  309. $sql = "SELECT MAX(sortorder) FROM {repository}";
  310. $this->_sortorder = 1 + $DB->get_field_sql($sql);
  311. }
  312. cache::make('core', 'repositories')->purge();
  313. return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
  314. }
  315. /**
  316. * Change order of the type with its adjacent upper or downer type
  317. * (database fields are updated)
  318. * Algorithm details:
  319. * 1. retrieve all types in an array. This array is sorted by sortorder,
  320. * and the array keys start from 0 to X (incremented by 1)
  321. * 2. switch sortorder values of this type and its adjacent type
  322. *
  323. * @param string $move "up" or "down"
  324. */
  325. public function move_order($move) {
  326. global $DB;
  327. $types = repository::get_types(); // retrieve all types
  328. // retrieve this type into the returned array
  329. $i = 0;
  330. while (!isset($indice) && $i<count($types)) {
  331. if ($types[$i]->get_typename() == $this->_typename) {
  332. $indice = $i;
  333. }
  334. $i++;
  335. }
  336. // retrieve adjacent indice
  337. switch ($move) {
  338. case "up":
  339. $adjacentindice = $indice - 1;
  340. break;
  341. case "down":
  342. $adjacentindice = $indice + 1;
  343. break;
  344. default:
  345. throw new repository_exception('movenotdefined', 'repository');
  346. }
  347. //switch sortorder of this type and the adjacent type
  348. //TODO: we could reset sortorder for all types. This is not as good in performance term, but
  349. //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
  350. //it worth to change the algo.
  351. if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
  352. $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
  353. $this->update_sortorder($types[$adjacentindice]->get_sortorder());
  354. }
  355. }
  356. /**
  357. * 1. Change visibility to the value chosen
  358. * 2. Update the type
  359. *
  360. * @param bool $visible
  361. * @return bool
  362. */
  363. public function update_visibility($visible = null) {
  364. if (is_bool($visible)) {
  365. $this->_visible = $visible;
  366. } else {
  367. $this->_visible = !$this->_visible;
  368. }
  369. return $this->update_visible();
  370. }
  371. /**
  372. * Delete a repository_type (general options are removed from config_plugin
  373. * table, and all instances are deleted)
  374. *
  375. * @param bool $downloadcontents download external contents if exist
  376. * @return bool
  377. */
  378. public function delete($downloadcontents = false) {
  379. global $DB;
  380. //delete all instances of this type
  381. $params = array();
  382. $params['context'] = array();
  383. $params['onlyvisible'] = false;
  384. $params['type'] = $this->_typename;
  385. $instances = repository::get_instances($params);
  386. foreach ($instances as $instance) {
  387. $instance->delete($downloadcontents);
  388. }
  389. //delete all general options
  390. foreach ($this->_options as $name => $value) {
  391. set_config($name, null, $this->_typename);
  392. }
  393. cache::make('core', 'repositories')->purge();
  394. try {
  395. $DB->delete_records('repository', array('type' => $this->_typename));
  396. } catch (dml_exception $ex) {
  397. return false;
  398. }
  399. return true;
  400. }
  401. /**
  402. * Prepares the repository type to be cached. Implements method from cacheable_object interface.
  403. *
  404. * @return array
  405. */
  406. public function prepare_to_cache() {
  407. return array(
  408. 'typename' => $this->_typename,
  409. 'typeoptions' => $this->_options,
  410. 'visible' => $this->_visible,
  411. 'sortorder' => $this->_sortorder
  412. );
  413. }
  414. /**
  415. * Restores repository type from cache. Implements method from cacheable_object interface.
  416. *
  417. * @return array
  418. */
  419. public static function wake_from_cache($data) {
  420. return new repository_type($data['typename'], $data['typeoptions'], $data['visible'], $data['sortorder']);
  421. }
  422. }
  423. /**
  424. * This is the base class of the repository class.
  425. *
  426. * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
  427. * See an example: {@link repository_boxnet}
  428. *
  429. * @package core_repository
  430. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  431. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  432. */
  433. abstract class repository implements cacheable_object {
  434. /**
  435. * Timeout in seconds for downloading the external file into moodle
  436. * @deprecated since Moodle 2.7, please use $CFG->repositorygetfiletimeout instead
  437. */
  438. const GETFILE_TIMEOUT = 30;
  439. /**
  440. * Timeout in seconds for syncronising the external file size
  441. * @deprecated since Moodle 2.7, please use $CFG->repositorysyncfiletimeout instead
  442. */
  443. const SYNCFILE_TIMEOUT = 1;
  444. /**
  445. * Timeout in seconds for downloading an image file from external repository during syncronisation
  446. * @deprecated since Moodle 2.7, please use $CFG->repositorysyncimagetimeout instead
  447. */
  448. const SYNCIMAGE_TIMEOUT = 3;
  449. // $disabled can be set to true to disable a plugin by force
  450. // example: self::$disabled = true
  451. /** @var bool force disable repository instance */
  452. public $disabled = false;
  453. /** @var int repository instance id */
  454. public $id;
  455. /** @var stdClass current context */
  456. public $context;
  457. /** @var array repository options */
  458. public $options;
  459. /** @var bool Whether or not the repository instance is editable */
  460. public $readonly;
  461. /** @var int return types */
  462. public $returntypes;
  463. /** @var stdClass repository instance database record */
  464. public $instance;
  465. /** @var string Type of repository (webdav, google_docs, dropbox, ...). Read from $this->get_typename(). */
  466. protected $typename;
  467. /**
  468. * Constructor
  469. *
  470. * @param int $repositoryid repository instance id
  471. * @param int|stdClass $context a context id or context object
  472. * @param array $options repository options
  473. * @param int $readonly indicate this repo is readonly or not
  474. */
  475. public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
  476. global $DB;
  477. $this->id = $repositoryid;
  478. if (is_object($context)) {
  479. $this->context = $context;
  480. } else {
  481. $this->context = context::instance_by_id($context);
  482. }
  483. $cache = cache::make('core', 'repositories');
  484. if (($this->instance = $cache->get('i:'. $this->id)) === false) {
  485. $this->instance = $DB->get_record_sql("SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
  486. FROM {repository} r, {repository_instances} i
  487. WHERE i.typeid = r.id and i.id = ?", array('id' => $this->id));
  488. $cache->set('i:'. $this->id, $this->instance);
  489. }
  490. $this->readonly = $readonly;
  491. $this->options = array();
  492. if (is_array($options)) {
  493. // The get_option() method will get stored options in database.
  494. $options = array_merge($this->get_option(), $options);
  495. } else {
  496. $options = $this->get_option();
  497. }
  498. foreach ($options as $n => $v) {
  499. $this->options[$n] = $v;
  500. }
  501. $this->name = $this->get_name();
  502. $this->returntypes = $this->supported_returntypes();
  503. $this->super_called = true;
  504. }
  505. /**
  506. * Get repository instance using repository id
  507. *
  508. * Note that this function does not check permission to access repository contents
  509. *
  510. * @throws repository_exception
  511. *
  512. * @param int $repositoryid repository instance ID
  513. * @param context|int $context context instance or context ID where this repository will be used
  514. * @param array $options additional repository options
  515. * @return repository
  516. */
  517. public static function get_repository_by_id($repositoryid, $context, $options = array()) {
  518. global $CFG, $DB;
  519. $cache = cache::make('core', 'repositories');
  520. if (!is_object($context)) {
  521. $context = context::instance_by_id($context);
  522. }
  523. $cachekey = 'rep:'. $repositoryid. ':'. $context->id. ':'. serialize($options);
  524. if ($repository = $cache->get($cachekey)) {
  525. return $repository;
  526. }
  527. if (!$record = $cache->get('i:'. $repositoryid)) {
  528. $sql = "SELECT i.*, r.type AS repositorytype, r.visible, r.sortorder
  529. FROM {repository_instances} i
  530. JOIN {repository} r ON r.id = i.typeid
  531. WHERE i.id = ?";
  532. if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
  533. throw new repository_exception('invalidrepositoryid', 'repository');
  534. }
  535. $cache->set('i:'. $record->id, $record);
  536. }
  537. $type = $record->repositorytype;
  538. if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
  539. require_once($CFG->dirroot . "/repository/$type/lib.php");
  540. $classname = 'repository_' . $type;
  541. $options['type'] = $type;
  542. $options['typeid'] = $record->typeid;
  543. $options['visible'] = $record->visible;
  544. if (empty($options['name'])) {
  545. $options['name'] = $record->name;
  546. }
  547. $repository = new $classname($repositoryid, $context, $options, $record->readonly);
  548. if (empty($repository->super_called)) {
  549. // to make sure the super construct is called
  550. debugging('parent::__construct must be called by '.$type.' plugin.');
  551. }
  552. $cache->set($cachekey, $repository);
  553. return $repository;
  554. } else {
  555. throw new repository_exception('invalidplugin', 'repository');
  556. }
  557. }
  558. /**
  559. * Returns the type name of the repository.
  560. *
  561. * @return string type name of the repository.
  562. * @since Moodle 2.5
  563. */
  564. public function get_typename() {
  565. if (empty($this->typename)) {
  566. $matches = array();
  567. if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
  568. throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
  569. 'e.g. repository_dropbox');
  570. }
  571. $this->typename = $matches[1];
  572. }
  573. return $this->typename;
  574. }
  575. /**
  576. * Get a repository type object by a given type name.
  577. *
  578. * @static
  579. * @param string $typename the repository type name
  580. * @return repository_type|bool
  581. */
  582. public static function get_type_by_typename($typename) {
  583. global $DB;
  584. $cache = cache::make('core', 'repositories');
  585. if (($repositorytype = $cache->get('typename:'. $typename)) === false) {
  586. $repositorytype = null;
  587. if ($record = $DB->get_record('repository', array('type' => $typename))) {
  588. $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
  589. $cache->set('typeid:'. $record->id, $repositorytype);
  590. }
  591. $cache->set('typename:'. $typename, $repositorytype);
  592. }
  593. return $repositorytype;
  594. }
  595. /**
  596. * Get the repository type by a given repository type id.
  597. *
  598. * @static
  599. * @param int $id the type id
  600. * @return object
  601. */
  602. public static function get_type_by_id($id) {
  603. global $DB;
  604. $cache = cache::make('core', 'repositories');
  605. if (($repositorytype = $cache->get('typeid:'. $id)) === false) {
  606. $repositorytype = null;
  607. if ($record = $DB->get_record('repository', array('id' => $id))) {
  608. $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
  609. $cache->set('typename:'. $record->type, $repositorytype);
  610. }
  611. $cache->set('typeid:'. $id, $repositorytype);
  612. }
  613. return $repositorytype;
  614. }
  615. /**
  616. * Return all repository types ordered by sortorder field
  617. * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
  618. *
  619. * @static
  620. * @param bool $visible can return types by visiblity, return all types if null
  621. * @return array Repository types
  622. */
  623. public static function get_types($visible=null) {
  624. global $DB, $CFG;
  625. $cache = cache::make('core', 'repositories');
  626. if (!$visible) {
  627. $typesnames = $cache->get('types');
  628. } else {
  629. $typesnames = $cache->get('typesvis');
  630. }
  631. $types = array();
  632. if ($typesnames === false) {
  633. $typesnames = array();
  634. $vistypesnames = array();
  635. if ($records = $DB->get_records('repository', null ,'sortorder')) {
  636. foreach($records as $type) {
  637. if (($repositorytype = $cache->get('typename:'. $type->type)) === false) {
  638. // Create new instance of repository_type.
  639. if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
  640. $repositorytype = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
  641. $cache->set('typeid:'. $type->id, $repositorytype);
  642. $cache->set('typename:'. $type->type, $repositorytype);
  643. }
  644. }
  645. if ($repositorytype) {
  646. if (empty($visible) || $repositorytype->get_visible()) {
  647. $types[] = $repositorytype;
  648. $vistypesnames[] = $repositorytype->get_typename();
  649. }
  650. $typesnames[] = $repositorytype->get_typename();
  651. }
  652. }
  653. }
  654. $cache->set('types', $typesnames);
  655. $cache->set('typesvis', $vistypesnames);
  656. } else {
  657. foreach ($typesnames as $typename) {
  658. $types[] = self::get_type_by_typename($typename);
  659. }
  660. }
  661. return $types;
  662. }
  663. /**
  664. * Checks if user has a capability to view the current repository.
  665. *
  666. * @return bool true when the user can, otherwise throws an exception.
  667. * @throws repository_exception when the user does not meet the requirements.
  668. */
  669. public final function check_capability() {
  670. global $USER;
  671. // The context we are on.
  672. $currentcontext = $this->context;
  673. // Ensure that the user can view the repository in the current context.
  674. $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext);
  675. // Context in which the repository has been created.
  676. $repocontext = context::instance_by_id($this->instance->contextid);
  677. // Prevent access to private repositories when logged in as.
  678. if ($can && \core\session\manager::is_loggedinas()) {
  679. if ($this->contains_private_data() || $repocontext->contextlevel == CONTEXT_USER) {
  680. $can = false;
  681. }
  682. }
  683. // We are going to ensure that the current context was legit, and reliable to check
  684. // the capability against. (No need to do that if we already cannot).
  685. if ($can) {
  686. if ($repocontext->contextlevel == CONTEXT_USER) {
  687. // The repository is a user instance, ensure we're the right user to access it!
  688. if ($repocontext->instanceid != $USER->id) {
  689. $can = false;
  690. }
  691. } else if ($repocontext->contextlevel == CONTEXT_COURSE) {
  692. // The repository is a course one. Let's check that we are on the right course.
  693. if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) {
  694. $coursecontext = $currentcontext->get_course_context();
  695. if ($coursecontext->instanceid != $repocontext->instanceid) {
  696. $can = false;
  697. }
  698. } else {
  699. // We are on a parent context, therefore it's legit to check the permissions
  700. // in the current context.
  701. }
  702. } else {
  703. // Nothing to check here, system instances can have different permissions on different
  704. // levels. We do not want to prevent URL hack here, because it does not make sense to
  705. // prevent a user to access a repository in a context if it's accessible in another one.
  706. }
  707. }
  708. if ($can) {
  709. return true;
  710. }
  711. throw new repository_exception('nopermissiontoaccess', 'repository');
  712. }
  713. /**
  714. * Check if file already exists in draft area.
  715. *
  716. * @static
  717. * @param int $itemid of the draft area.
  718. * @param string $filepath path to the file.
  719. * @param string $filename file name.
  720. * @return bool
  721. */
  722. public static function draftfile_exists($itemid, $filepath, $filename) {
  723. global $USER;
  724. $fs = get_file_storage();
  725. $usercontext = context_user::instance($USER->id);
  726. return $fs->file_exists($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename);
  727. }
  728. /**
  729. * Parses the moodle file reference and returns an instance of stored_file
  730. *
  731. * @param string $reference reference to the moodle internal file as retruned by
  732. * {@link repository::get_file_reference()} or {@link file_storage::pack_reference()}
  733. * @return stored_file|null
  734. */
  735. public static function get_moodle_file($reference) {
  736. $params = file_storage::unpack_reference($reference, true);
  737. $fs = get_file_storage();
  738. return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
  739. $params['itemid'], $params['filepath'], $params['filename']);
  740. }
  741. /**
  742. * Repository method to make sure that user can access particular file.
  743. *
  744. * This is checked when user tries to pick the file from repository to deal with
  745. * potential parameter substitutions is request
  746. *
  747. * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
  748. * @return bool whether the file is accessible by current user
  749. */
  750. public function file_is_accessible($source) {
  751. if ($this->has_moodle_files()) {
  752. $reference = $this->get_file_reference($source);
  753. try {
  754. $params = file_storage::unpack_reference($reference, true);
  755. } catch (file_reference_exception $e) {
  756. return false;
  757. }
  758. $browser = get_file_browser();
  759. $context = context::instance_by_id($params['contextid']);
  760. $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
  761. $params['itemid'], $params['filepath'], $params['filename']);
  762. return !empty($file_info);
  763. }
  764. return true;
  765. }
  766. /**
  767. * This function is used to copy a moodle file to draft area.
  768. *
  769. * It DOES NOT check if the user is allowed to access this file because the actual file
  770. * can be located in the area where user does not have access to but there is an alias
  771. * to this file in the area where user CAN access it.
  772. * {@link file_is_accessible} should be called for alias location before calling this function.
  773. *
  774. * @param string $source The metainfo of file, it is base64 encoded php serialized data
  775. * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
  776. * attributes of the new file
  777. * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
  778. * the limit, the file_exception is thrown.
  779. * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
  780. * new file will reach the limit.
  781. * @return array The information about the created file
  782. */
  783. public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED) {
  784. global $USER;
  785. $fs = get_file_storage();
  786. if ($this->has_moodle_files() == false) {
  787. throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
  788. }
  789. $user_context = context_user::instance($USER->id);
  790. $filerecord = (array)$filerecord;
  791. // make sure the new file will be created in user draft area
  792. $filerecord['component'] = 'user';
  793. $filerecord['filearea'] = 'draft';
  794. $filerecord['contextid'] = $user_context->id;
  795. $draftitemid = $filerecord['itemid'];
  796. $new_filepath = $filerecord['filepath'];
  797. $new_filename = $filerecord['filename'];
  798. // the file needs to copied to draft area
  799. $stored_file = self::get_moodle_file($source);
  800. if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
  801. $maxbytesdisplay = display_size($maxbytes);
  802. throw new file_exception('maxbytesfile', (object) array('file' => $filerecord['filename'],
  803. 'size' => $maxbytesdisplay));
  804. }
  805. // Validate the size of the draft area.
  806. if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
  807. throw new file_exception('maxareabytes');
  808. }
  809. if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
  810. // create new file
  811. $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
  812. $filerecord['filename'] = $unused_filename;
  813. $fs->create_file_from_storedfile($filerecord, $stored_file);
  814. $event = array();
  815. $event['event'] = 'fileexists';
  816. $event['newfile'] = new stdClass;
  817. $event['newfile']->filepath = $new_filepath;
  818. $event['newfile']->filename = $unused_filename;
  819. $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
  820. $event['existingfile'] = new stdClass;
  821. $event['existingfile']->filepath = $new_filepath;
  822. $event['existingfile']->filename = $new_filename;
  823. $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
  824. return $event;
  825. } else {
  826. $fs->create_file_from_storedfile($filerecord, $stored_file);
  827. $info = array();
  828. $info['itemid'] = $draftitemid;
  829. $info['file'] = $new_filename;
  830. $info['title'] = $new_filename;
  831. $info['contextid'] = $user_context->id;
  832. $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
  833. $info['filesize'] = $stored_file->get_filesize();
  834. return $info;
  835. }
  836. }
  837. /**
  838. * Get an unused filename from the current draft area.
  839. *
  840. * Will check if the file ends with ([0-9]) and increase the number.
  841. *
  842. * @static
  843. * @param int $itemid draft item ID.
  844. * @param string $filepath path to the file.
  845. * @param string $filename name of the file.
  846. * @return string an unused file name.
  847. */
  848. public static function get_unused_filename($itemid, $filepath, $filename) {
  849. global $USER;
  850. $contextid = context_user::instance($USER->id)->id;
  851. $fs = get_file_storage();
  852. return $fs->get_unused_filename($contextid, 'user', 'draft', $itemid, $filepath, $filename);
  853. }
  854. /**
  855. * Append a suffix to filename.
  856. *
  857. * @static
  858. * @param string $filename
  859. * @return string
  860. * @deprecated since 2.5
  861. */
  862. public static function append_suffix($filename) {
  863. debugging('The function repository::append_suffix() has been deprecated. Use repository::get_unused_filename() instead.',
  864. DEBUG_DEVELOPER);
  865. $pathinfo = pathinfo($filename);
  866. if (empty($pathinfo['extension'])) {
  867. return $filename . RENAME_SUFFIX;
  868. } else {
  869. return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
  870. }
  871. }
  872. /**
  873. * Return all types that you a user can create/edit and which are also visible
  874. * Note: Mostly used in order to know if at least one editable type can be set
  875. *
  876. * @static
  877. * @param stdClass $context the context for which we want the editable types
  878. * @return array types
  879. */
  880. public static function get_editable_types($context = null) {
  881. if (empty($context)) {
  882. $context = context_system::instance();
  883. }
  884. $types= repository::get_types(true);
  885. $editabletypes = array();
  886. foreach ($types as $type) {
  887. $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
  888. if (!empty($instanceoptionnames)) {
  889. if ($type->get_contextvisibility($context)) {
  890. $editabletypes[]=$type;
  891. }
  892. }
  893. }
  894. return $editabletypes;
  895. }
  896. /**
  897. * Return repository instances
  898. *
  899. * @static
  900. * @param array $args Array containing the following keys:
  901. * currentcontext : instance of context (default system context)
  902. * context : array of instances of context (default empty array)
  903. * onlyvisible : bool (default true)
  904. * type : string return instances of this type only
  905. * accepted_types : string|array return instances that contain files of those types (*, web_image, .pdf, ...)
  906. * return_types : int combination of FILE_INTERNAL & FILE_EXTERNAL & FILE_REFERENCE.
  907. * 0 means every type. The default is FILE_INTERNAL | FILE_EXTERNAL.
  908. * userid : int if specified, instances belonging to other users will not be returned
  909. *
  910. * @return array repository instances
  911. */
  912. public static function get_instances($args = array()) {
  913. global $DB, $CFG, $USER;
  914. // Fill $args attributes with default values unless specified
  915. if (!isset($args['currentcontext']) || !($args['currentcontext'] instanceof context)) {
  916. $current_context = context_system::instance();
  917. } else {
  918. $current_context = $args['currentcontext'];
  919. }
  920. $args['currentcontext'] = $current_context->id;
  921. $contextids = array();
  922. if (!empty($args['context'])) {
  923. foreach ($args['context'] as $context) {
  924. $contextids[] = $context->id;
  925. }
  926. }
  927. $args['context'] = $contextids;
  928. if (!isset($args['onlyvisible'])) {
  929. $args['onlyvisible'] = true;
  930. }
  931. if (!isset($args['return_types'])) {
  932. $args['return_types'] = FILE_INTERNAL | FILE_EXTERNAL;
  933. }
  934. if (!isset($args['type'])) {
  935. $args['type'] = null;
  936. }
  937. if (empty($args['disable_types']) || !is_array($args['disable_types'])) {
  938. $args['disable_types'] = null;
  939. }
  940. if (empty($args['userid']) || !is_numeric($args['userid'])) {
  941. $args['userid'] = null;
  942. }
  943. if (!isset($args['accepted_types']) || (is_array($args['accepted_types']) && in_array('*', $args['accepted_types']))) {
  944. $args['accepted_types'] = '*';
  945. }
  946. ksort($args);
  947. $cachekey = 'all:'. serialize($args);
  948. // Check if we have cached list of repositories with the same query
  949. $cache = cache::make('core', 'repositories');
  950. if (($cachedrepositories = $cache->get($cachekey)) !== false) {
  951. // convert from cacheable_object_array to array
  952. $repositories = array();
  953. foreach ($cachedrepositories as $repository) {
  954. $repositories[$repository->id] = $repository;
  955. }
  956. return $repositories;
  957. }
  958. // Prepare DB SQL query to retrieve repositories
  959. $params = array();
  960. $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
  961. FROM {repository} r, {repository_instances} i
  962. WHERE i.typeid = r.id ";
  963. if ($args['disable_types']) {
  964. list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_NAMED, 'distype', false);
  965. $sql .= " AND r.type $types";
  966. $params = array_merge($params, $p);
  967. }
  968. if ($args['userid']) {
  969. $sql .= " AND (i.userid = 0 or i.userid = :userid)";
  970. $params['userid'] = $args['userid'];
  971. }
  972. if ($args['context']) {
  973. list($ctxsql, $p2) = $DB->get_in_or_equal($args['context'], SQL_PARAMS_NAMED, 'ctx');
  974. $sql .= " AND i.contextid $ctxsql";
  975. $params = array_merge($params, $p2);
  976. }
  977. if ($args['onlyvisible'] == true) {
  978. $sql .= " AND r.visible = 1";
  979. }
  980. if ($args['type'] !== null) {
  981. $sql .= " AND r.type = :type";
  982. $params['type'] = $args['type'];
  983. }
  984. $sql .= " ORDER BY r.sortorder, i.name";
  985. if (!$records = $DB->get_records_sql($sql, $params)) {
  986. $records = array();
  987. }
  988. $repositories = array();
  989. // Sortorder should be unique, which is not true if we use $record->sortorder
  990. // and there are multiple instances of any repository type
  991. $sortorder = 1;
  992. foreach ($records as $record) {
  993. $cache->set('i:'. $record->id, $record);
  994. if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
  995. continue;
  996. }
  997. $repository = self::get_repository_by_id($record->id, $current_context);
  998. $repository->options['sortorder'] = $sortorder++;
  999. $is_supported = true;
  1000. // check mimetypes
  1001. if ($args['accepted_types'] !== '*' and $repository->supported_filetypes() !== '*') {
  1002. $accepted_ext = file_get_typegroup('extension', $args['accepted_types']);
  1003. $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
  1004. $valid_ext = array_intersect($accepted_ext, $supported_ext);
  1005. $is_supported = !empty($valid_ext);
  1006. }
  1007. // Check return values.
  1008. if (!empty($args['return_types']) && !($repository->supported_returntypes() & $args['return_types'])) {
  1009. $is_supported = false;
  1010. }
  1011. if (!$args['onlyvisible'] || ($repository->is_visible() && !$repository->disabled)) {
  1012. // check capability in current context
  1013. $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
  1014. if ($record->repositorytype == 'coursefiles') {
  1015. // coursefiles plugin needs managefiles permission
  1016. $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
  1017. }
  1018. if ($is_supported && $capability) {
  1019. $repositories[$repository->id] = $repository;
  1020. }
  1021. }
  1022. }
  1023. $cache->set($cachekey, new cacheable_object_array($repositories));
  1024. return $repositories;
  1025. }
  1026. /**
  1027. * Get single repository instance for administrative actions
  1028. *
  1029. * Do not use this function to access repository contents, because it
  1030. * does not set the current context
  1031. *
  1032. * @see repository::get_repository_by_id()
  1033. *
  1034. * @static
  1035. * @param integer $id repository instance id
  1036. * @return repository
  1037. */
  1038. public static function get_instance($id) {
  1039. return self::get_repository_by_id($id, context_system::instance());
  1040. }
  1041. /**
  1042. * Call a static function. Any additional arguments than plugin and function will be passed through.
  1043. *
  1044. * @static
  1045. * @param string $plugin repository plugin name
  1046. * @param string $function function name
  1047. * @return mixed
  1048. */
  1049. public static function static_function($plugin, $function) {
  1050. global $CFG;
  1051. //check that the plugin exists
  1052. $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
  1053. if (!file_exists($typedirectory)) {
  1054. //throw new repository_exception('invalidplugin', 'repository');
  1055. return false;
  1056. }
  1057. $args = func_get_args();
  1058. if (count($args) <= 2) {
  1059. $args = array();
  1060. } else {
  1061. array_shift($args);
  1062. array_shift($args);
  1063. }
  1064. require_once($typedirectory);
  1065. return call_user_func_array(array('repository_' . $plugin, $function), $args);
  1066. }
  1067. /**
  1068. * Scan file, throws exception in case of infected file.
  1069. *
  1070. * Please note that the scanning engine must be able to access the file,
  1071. * permissions of the file are not modified here!
  1072. *
  1073. * @static
  1074. * @deprecated since Moodle 3.0
  1075. * @param string $thefile
  1076. * @param string $filename name of the file
  1077. * @param bool $deleteinfected
  1078. */
  1079. public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
  1080. debugging('Please upgrade your code to use \core\antivirus\manager::scan_file instead', DEBUG_DEVELOPER);
  1081. \core\antivirus\manager::scan_file($thefile, $filename, $deleteinfected);
  1082. }
  1083. /**
  1084. * Repository method to serve the referenced file
  1085. *
  1086. * @see send_stored_file
  1087. *
  1088. * @param stored_file $storedfile the file that contains the reference
  1089. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  1090. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  1091. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  1092. * @param array $options additional options affecting the file serving
  1093. */
  1094. public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
  1095. if ($this->has_moodle_files()) {
  1096. $fs = get_file_storage();
  1097. $params = file_storage::unpack_reference($storedfile->get_reference(), true);
  1098. $srcfile = null;
  1099. if (is_array($params)) {
  1100. $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
  1101. $params['itemid'], $params['filepath'], $params['filename']);
  1102. }
  1103. if (empty($options)) {
  1104. $options = array();
  1105. }
  1106. if (!isset($options['filename'])) {
  1107. $options['filename'] = $storedfile->get_filename();
  1108. }
  1109. if (!$srcfile) {
  1110. send_file_not_found();
  1111. } else {
  1112. send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
  1113. }
  1114. } else {
  1115. throw new coding_exception("Repository plugin must implement send_file() method.");
  1116. }
  1117. }
  1118. /**
  1119. * Return human readable reference information
  1120. *
  1121. * @param string $reference value of DB field files_reference.reference
  1122. * @param int $filestatus status of the file, 0 - ok, 666 - source missing
  1123. * @return string
  1124. */
  1125. public function get_reference_details($reference, $filestatus = 0) {
  1126. if ($this->has_moodle_files()) {
  1127. $fileinfo = null;
  1128. $params = file_storage::unpack_reference($reference, true);
  1129. if (is_array($params)) {
  1130. $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
  1131. if ($context) {
  1132. $browser = get_file_browser();
  1133. $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
  1134. }
  1135. }
  1136. if (empty($fileinfo)) {
  1137. if ($filestatus == 666) {
  1138. if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
  1139. return get_string('lostsource', 'repository',
  1140. $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
  1141. } else {
  1142. return get_string('lostsource', 'repository', '');
  1143. }
  1144. }
  1145. return get_string('undisclosedsource', 'repository');
  1146. } else {
  1147. return $fileinfo->get_readable_fullname();
  1148. }
  1149. }
  1150. return '';
  1151. }
  1152. /**
  1153. * Cache file from external repository by reference
  1154. * {@link repository::get_file_reference()}
  1155. * {@link repository::get_file()}
  1156. * Invoked at MOODLE/repository/repository_ajax.php
  1157. *
  1158. * @param string $reference this reference is generated by
  1159. * repository::get_file_reference()
  1160. * @param stored_file $storedfile created file reference
  1161. */
  1162. public function cache_file_by_reference($reference, $storedfile) {
  1163. }
  1164. /**
  1165. * Return the source information
  1166. *
  1167. * The result of the function is stored in files.source field. It may be analysed
  1168. * when the source file is lost or repository may use it to display human-readable
  1169. * location of reference original.
  1170. *
  1171. * This method is called when file is picked for the first time only. When file
  1172. * (either copy or a reference) is already in moodle and it is being picked
  1173. * again to another file area (also as a copy or as a reference), the value of
  1174. * files.source is copied.
  1175. *
  1176. * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
  1177. * @return string|null
  1178. */
  1179. public function get_file_source_info($source) {
  1180. if ($this->has_moodle_files()) {
  1181. $reference = $this->get_file_reference($source);
  1182. return $this->get_reference_details($reference, 0);
  1183. }
  1184. return $source;
  1185. }
  1186. /**
  1187. * Move file from download folder to file pool using FILE API
  1188. *
  1189. * @todo MDL-28637
  1190. * @static
  1191. * @param string $thefile file path in download folder
  1192. * @param stdClass $record
  1193. * @return array containing the following keys:
  1194. * icon
  1195. * file
  1196. * id
  1197. * url
  1198. */
  1199. public static function move_to_filepool($thefile, $record) {
  1200. global $DB, $CFG, $USER, $OUTPUT;
  1201. // scan for viruses if possible, throws exception if problem found
  1202. // TODO: MDL-28637 this repository_no_delete is a bloody hack!
  1203. \core\antivirus\manager::scan_file($thefile, $record->filename, empty($CFG->repository_no_delete));
  1204. $fs = get_file_storage();
  1205. // If file name being used.
  1206. if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
  1207. $draftitemid = $record->itemid;
  1208. $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
  1209. $old_filename = $record->filename;
  1210. // Create a tmp file.
  1211. $record->filename = $new_filename;
  1212. $newfile = $fs->create_file_from_pathname($record, $thefile);
  1213. $event = array();
  1214. $event['event'] = 'fileexists';
  1215. $event['newfile'] = new stdClass;
  1216. $event['newfile']->filepath = $record->filepath;
  1217. $event['newfile']->filename = $new_filename;
  1218. $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
  1219. $event['existingfile'] = new stdClass;
  1220. $event['existingfile']->filepath = $record->filepath;
  1221. $event['existingfile']->filename = $old_filename;
  1222. $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();
  1223. return $event;
  1224. }
  1225. if ($file = $fs->create_file_from_pathname($record, $thefile)) {
  1226. if (empty($CFG->repository_no_delete)) {
  1227. $delete = unlink($thefile);
  1228. unset($CFG->repository_no_delete);
  1229. }
  1230. return array(
  1231. 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
  1232. 'id'=>$file->get_itemid(),
  1233. 'file'=>$file->get_filename(),
  1234. 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
  1235. );
  1236. } else {
  1237. return null;
  1238. }
  1239. }
  1240. /**
  1241. * Builds a tree of files This function is then called recursively.
  1242. *
  1243. * @static
  1244. * @todo take $search into account, and respect a threshold for dynamic loading
  1245. * @param file_info $fileinfo an object returned by file_browser::get_file_info()
  1246. * @param string $search searched string
  1247. * @param bool $dynamicmode no recursive call is done when in dynamic mode
  1248. * @param array $list the array containing the files under the passed $fileinfo
  1249. * @return int the number of files found
  1250. */
  1251. public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
  1252. global $CFG, $OUTPUT;
  1253. $filecount = 0;
  1254. $children = $fileinfo->get_children();
  1255. foreach ($children as $child) {
  1256. $filename = $child->get_visible_name();
  1257. $filesize = $child->get_filesize();
  1258. $filesize = $filesize ? display_size($filesize) : '';
  1259. $filedate = $child->get_timemodified();
  1260. $filedate = $filedate ? userdate($filedate) : '';
  1261. $filetype = $child->get_mimetype();
  1262. if ($child->is_directory()) {
  1263. $path = array();
  1264. $level = $child->get_parent();
  1265. while ($level) {
  1266. $params = $level->get_params();
  1267. $path[] = array($params['filepath'], $level->get_visible_name());
  1268. $level = $level->get_parent();
  1269. }
  1270. $tmp = array(
  1271. 'title' => $child->get_visible_name(),
  1272. 'size' => 0,
  1273. 'date' => $filedate,
  1274. 'path' => array_reverse($path),
  1275. 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
  1276. );
  1277. //if ($dynamicmode && $child->is_writable()) {
  1278. // $tmp['children'] = array();
  1279. //} else {
  1280. // if folder name matches search, we send back all files contained.
  1281. $_search = $search;
  1282. if ($search && stristr($tmp['title'], $search) !== false) {
  1283. $_search = false;
  1284. }
  1285. $tmp['children'] = array();
  1286. $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
  1287. if ($search && $_filecount) {
  1288. $tmp['expanded'] = 1;
  1289. }
  1290. //}
  1291. if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
  1292. $filecount += $_filecount;
  1293. $list[] = $tmp;
  1294. }
  1295. } else { // not a directory
  1296. // skip the file, if we're in search mode and it's not a match
  1297. if ($search && (stristr($filename, $search) === false)) {
  1298. continue;
  1299. }
  1300. $params = $child->get_params();
  1301. $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
  1302. $list[] = array(
  1303. 'title' => $filename,
  1304. 'size' => $filesize,
  1305. 'date' => $filedate,
  1306. //'source' => $child->get_url(),
  1307. 'source' => base64_encode($source),
  1308. 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
  1309. 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
  1310. );
  1311. $filecount++;
  1312. }
  1313. }
  1314. return $filecount;
  1315. }
  1316. /**
  1317. * Display a repository instance list (with edit/delete/create links)
  1318. *
  1319. * @static
  1320. * @param stdClass $context the context for which we display the instance
  1321. * @param string $typename if set, we display only one type of instance
  1322. */
  1323. public static function display_instances_list($context, $typename = null) {
  1324. global $CFG, $USER, $OUTPUT;
  1325. $output = $OUTPUT->box_start('generalbox');
  1326. //if the context is SYSTEM, so we call it from administration page
  1327. $admin = ($context->id == SYSCONTEXTID) ? true : false;
  1328. if ($admin) {
  1329. $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
  1330. $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
  1331. } else {
  1332. $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
  1333. }
  1334. $namestr = get_string('name');
  1335. $pluginstr = get_string('plugin', 'repository');
  1336. $settingsstr = get_string('settings');
  1337. $deletestr = get_string('delete');
  1338. // Retrieve list of instances. In administration context we want to display all
  1339. // instances of a type, even if this type is not visible. In course/user context we
  1340. // want to display only visible instances, but for every type types. The repository::get_instances()
  1341. // third parameter displays only visible type.
  1342. $params = array();
  1343. $params['context'] = array($context);
  1344. $params['currentcontext'] = $context;
  1345. $params['return_types'] = 0;
  1346. $params['onlyvisible'] = !$admin;
  1347. $params['type'] = $typename;
  1348. $instances = repository::get_instances($params);
  1349. $instancesnumber = count($instances);
  1350. $alreadyplugins = array();
  1351. $table = new html_table();
  1352. $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
  1353. $table->align = array('left', 'left', 'center','center');
  1354. $table->data = array();
  1355. $updowncount = 1;
  1356. foreach ($instances as $i) {
  1357. $settings = '';
  1358. $delete = '';
  1359. $type = repository::get_type_by_id($i->options['typeid']);
  1360. if ($type->get_contextvisibility($context)) {
  1361. if (!$i->readonly) {
  1362. $settingurl = new moodle_url($baseurl);
  1363. $settingurl->param('type', $i->options['type']);
  1364. $settingurl->param('edit', $i->id);
  1365. $settings .= html_writer::link($settingurl, $settingsstr);
  1366. $deleteurl = new moodle_url($baseurl);
  1367. $deleteurl->param('delete', $i->id);
  1368. $deleteurl->param('type', $i->options['type']);
  1369. $delete .= html_writer::link($deleteurl, $deletestr);
  1370. }
  1371. }
  1372. $type = repository::get_type_by_id($i->options['typeid']);
  1373. $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
  1374. //display a grey row if the type is defined as not visible
  1375. if (isset($type) && !$type->get_visible()) {
  1376. $table->rowclasses[] = 'dimmed_text';
  1377. } else {
  1378. $table->rowclasses[] = '';
  1379. }
  1380. if (!in_array($i->name, $alreadyplugins)) {
  1381. $alreadyplugins[] = $i->name;
  1382. }
  1383. }
  1384. $output .= html_writer::table($table);
  1385. $instancehtml = '<div>';
  1386. $addable = 0;
  1387. //if no type is set, we can create all type of instance
  1388. if (!$typename) {
  1389. $instancehtml .= '<h3>';
  1390. $instancehtml .= get_string('createrepository', 'repository');
  1391. $instancehtml .= '</h3><ul>';
  1392. $types = repository::get_editable_types($context);
  1393. foreach ($types as $type) {
  1394. if (!empty($type) && $type->get_visible()) {
  1395. // If the user does not have the permission to view the repository, it won't be displayed in
  1396. // the list of instances. Hiding the link to create new instances will prevent the
  1397. // user from creating them without being able to find them afterwards, which looks like a bug.
  1398. if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
  1399. continue;
  1400. }
  1401. $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
  1402. if (!empty($instanceoptionnames)) {
  1403. $baseurl->param('new', $type->get_typename());
  1404. $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
  1405. $baseurl->remove_params('new');
  1406. $addable++;
  1407. }
  1408. }
  1409. }
  1410. $instancehtml .= '</ul>';
  1411. } else {
  1412. $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
  1413. if (!empty($instanceoptionnames)) { //create a unique type of instance
  1414. $addable = 1;
  1415. $baseurl->param('new', $typename);
  1416. $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
  1417. $baseurl->remove_params('new');
  1418. }
  1419. }
  1420. if ($addable) {
  1421. $instancehtml .= '</div>';
  1422. $output .= $instancehtml;
  1423. }
  1424. $output .= $OUTPUT->box_end();
  1425. //print the list + creation links
  1426. print($output);
  1427. }
  1428. /**
  1429. * Prepare file reference information
  1430. *
  1431. * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
  1432. * @return string file reference, ready to be stored
  1433. */
  1434. public function get_file_reference($source) {
  1435. if ($source && $this->has_moodle_files()) {
  1436. $params = @json_decode(base64_decode($source), true);
  1437. if (!is_array($params) || empty($params['contextid'])) {
  1438. throw new repository_exception('invalidparams', 'repository');
  1439. }
  1440. $params = array(
  1441. 'component' => empty($params['component']) ? '' : clean_param($params['component'], PARAM_COMPONENT),
  1442. 'filearea' => empty($params['filearea']) ? '' : clean_param($params['filearea'], PARAM_AREA),
  1443. 'itemid' => empty($params['itemid']) ? 0 : clean_param($params['itemid'], PARAM_INT),
  1444. 'filename' => empty($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE),
  1445. 'filepath' => empty($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH),
  1446. 'contextid' => clean_param($params['contextid'], PARAM_INT)
  1447. );
  1448. // Check if context exists.
  1449. if (!context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
  1450. throw new repository_exception('invalidparams', 'repository');
  1451. }
  1452. return file_storage::pack_reference($params);
  1453. }
  1454. return $source;
  1455. }
  1456. /**
  1457. * Get a unique file path in which to save the file.
  1458. *
  1459. * The filename returned will be removed at the end of the request and
  1460. * should not be relied upon to exist in subsequent requests.
  1461. *
  1462. * @param string $filename file name
  1463. * @return file path
  1464. */
  1465. public function prepare_file($filename) {
  1466. if (empty($filename)) {
  1467. $filename = 'file';
  1468. }
  1469. return sprintf('%s/%s', make_request_directory(), $filename);
  1470. }
  1471. /**
  1472. * Does this repository used to browse moodle files?
  1473. *
  1474. * @return bool
  1475. */
  1476. public function has_moodle_files() {
  1477. return false;
  1478. }
  1479. /**
  1480. * Return file URL, for most plugins, the parameter is the original
  1481. * url, but some plugins use a file id, so we need this function to
  1482. * convert file id to original url.
  1483. *
  1484. * @param string $url the url of file
  1485. * @return string
  1486. */
  1487. public function get_link($url) {
  1488. return $url;
  1489. }
  1490. /**
  1491. * Downloads a file from external repository and saves it in temp dir
  1492. *
  1493. * Function get_file() must be implemented by repositories that support returntypes
  1494. * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
  1495. * to moodle. This function is not called for moodle repositories, the function
  1496. * {@link repository::copy_to_area()} is used instead.
  1497. *
  1498. * This function can be overridden by subclass if the files.reference field contains
  1499. * not just URL or if request should be done differently.
  1500. *
  1501. * @see curl
  1502. * @throws file_exception when error occured
  1503. *
  1504. * @param string $url the content of files.reference field, in this implementaion
  1505. * it is asssumed that it contains the string with URL of the file
  1506. * @param string $filename filename (without path) to save the downloaded file in the
  1507. * temporary directory, if omitted or file already exists the new filename will be generated
  1508. * @return array with elements:
  1509. * path: internal location of the file
  1510. * url: URL to the source (from parameters)
  1511. */
  1512. public function get_file($url, $filename = '') {
  1513. global $CFG;
  1514. $path = $this->prepare_file($filename);
  1515. $c = new curl;
  1516. $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => $CFG->repositorygetfiletimeout));
  1517. if ($result !== true) {
  1518. throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
  1519. }
  1520. return array('path'=>$path, 'url'=>$url);
  1521. }
  1522. /**
  1523. * Downloads the file from external repository and saves it in moodle filepool.
  1524. * This function is different from {@link repository::sync_reference()} because it has
  1525. * bigger request timeout and always downloads the content.
  1526. *
  1527. * This function is invoked when we try to unlink the file from the source and convert
  1528. * a reference into a true copy.
  1529. *
  1530. * @throws exception when file could not be imported
  1531. *
  1532. * @param stored_file $file
  1533. * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
  1534. */
  1535. public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
  1536. if (!$file->is_external_file()) {
  1537. // nothing to import if the file is not a reference
  1538. return;
  1539. } else if ($file->get_repository_id() != $this->id) {
  1540. // error
  1541. debugging('Repository instance id does not match');
  1542. return;
  1543. } else if ($this->has_moodle_files()) {
  1544. // files that are references to local files are already in moodle filepool
  1545. // just validate the size
  1546. if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
  1547. $maxbytesdisplay = display_size($maxbytes);
  1548. throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
  1549. 'size' => $maxbytesdisplay));
  1550. }
  1551. return;
  1552. } else {
  1553. if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
  1554. // note that stored_file::get_filesize() also calls synchronisation
  1555. $maxbytesdisplay = display_size($maxbytes);
  1556. throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
  1557. 'size' => $maxbytesdisplay));
  1558. }
  1559. $fs = get_file_storage();
  1560. $contentexists = $fs->content_exists($file->get_contenthash());
  1561. if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
  1562. // even when 'file_storage::content_exists()' returns true this may be an empty
  1563. // content for the file that was not actually downloaded
  1564. $contentexists = false;
  1565. }
  1566. if (!$file->get_status() && $contentexists) {
  1567. // we already have the content in moodle filepool and it was synchronised recently.
  1568. // Repositories may overwrite it if they want to force synchronisation anyway!
  1569. return;
  1570. } else {
  1571. // attempt to get a file
  1572. try {
  1573. $fileinfo = $this->get_file($file->get_reference());
  1574. if (isset($fileinfo['path'])) {
  1575. list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
  1576. // set this file and other similar aliases synchronised
  1577. $file->set_synchronized($contenthash, $filesize);
  1578. } else {
  1579. throw new moodle_exception('errorwhiledownload', 'repository', '', '');
  1580. }
  1581. } catch (Exception $e) {
  1582. if ($contentexists) {
  1583. // better something than nothing. We have a copy of file. It's sync time
  1584. // has expired but it is still very likely that it is the last version
  1585. } else {
  1586. throw($e);
  1587. }
  1588. }
  1589. }
  1590. }
  1591. }
  1592. /**
  1593. * Return size of a file in bytes.
  1594. *
  1595. * @param string $source encoded and serialized data of file
  1596. * @return int file size in bytes
  1597. */
  1598. public function get_file_size($source) {
  1599. // TODO MDL-33297 remove this function completely?
  1600. $browser = get_file_browser();
  1601. $params = unserialize(base64_decode($source));
  1602. $contextid = clean_param($params['contextid'], PARAM_INT);
  1603. $fileitemid = clean_param($params['itemid'], PARAM_INT);
  1604. $filename = clean_param($params['filename'], PARAM_FILE);
  1605. $filepath = clean_param($params['filepath'], PARAM_PATH);
  1606. $filearea = clean_param($params['filearea'], PARAM_AREA);
  1607. $component = clean_param($params['component'], PARAM_COMPONENT);
  1608. $context = context::instance_by_id($contextid);
  1609. $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
  1610. if (!empty($file_info)) {
  1611. $filesize = $file_info->get_filesize();
  1612. } else {
  1613. $filesize = null;
  1614. }
  1615. return $filesize;
  1616. }
  1617. /**
  1618. * Return is the instance is visible
  1619. * (is the type visible ? is the context enable ?)
  1620. *
  1621. * @return bool
  1622. */
  1623. public function is_visible() {
  1624. $type = repository::get_type_by_id($this->options['typeid']);
  1625. $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
  1626. if ($type->get_visible()) {
  1627. //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
  1628. if (empty($instanceoptions) || $type->get_contextvisibility(context::instance_by_id($this->instance->contextid))) {
  1629. return true;
  1630. }
  1631. }
  1632. return false;
  1633. }
  1634. /**
  1635. * Can the instance be edited by the current user?
  1636. *
  1637. * The property $readonly must not be used within this method because
  1638. * it only controls if the options from self::get_instance_option_names()
  1639. * can be edited.
  1640. *
  1641. * @return bool true if the user can edit the instance.
  1642. * @since Moodle 2.5
  1643. */
  1644. public final function can_be_edited_by_user() {
  1645. global $USER;
  1646. // We need to be able to explore the repository.
  1647. try {
  1648. $this->check_capability();
  1649. } catch (repository_exception $e) {
  1650. return false;
  1651. }
  1652. $repocontext = context::instance_by_id($this->instance->contextid);
  1653. if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
  1654. // If the context of this instance is a user context, we need to be this user.
  1655. return false;
  1656. } else if ($repocontext->contextlevel == CONTEXT_MODULE && !has_capability('moodle/course:update', $repocontext)) {
  1657. // We need to have permissions on the course to edit the instance.
  1658. return false;
  1659. } else if ($repocontext->contextlevel == CONTEXT_SYSTEM && !has_capability('moodle/site:config', $repocontext)) {
  1660. // Do not meet the requirements for the context system.
  1661. return false;
  1662. }
  1663. return true;
  1664. }
  1665. /**
  1666. * Return the name of this instance, can be overridden.
  1667. *
  1668. * @return string
  1669. */
  1670. public function get_name() {
  1671. if ($name = $this->instance->name) {
  1672. return $name;
  1673. } else {
  1674. return get_string('pluginname', 'repository_' . $this->get_typename());
  1675. }
  1676. }
  1677. /**
  1678. * Is this repository accessing private data?
  1679. *
  1680. * This function should return true for the repositories which access external private
  1681. * data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
  1682. * which authenticate the user and then store the auth token.
  1683. *
  1684. * Of course, many repositories store 'private data', but we only want to set
  1685. * contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
  1686. * to by the users having the capability to 'login as' someone else. For instance, the repository
  1687. * 'Private files' is not considered as private because it's part of Moodle.
  1688. *
  1689. * You should not set contains_private_data() to true on repositories which allow different types
  1690. * of instances as the levels other than 'user' are, by definition, not private. Also
  1691. * the user instances will be protected when they need to.
  1692. *
  1693. * @return boolean True when the repository accesses private external data.
  1694. * @since Moodle 2.5
  1695. */
  1696. public function contains_private_data() {
  1697. return true;
  1698. }
  1699. /**
  1700. * What kind of files will be in this repository?
  1701. *
  1702. * @return array return '*' means this repository support any files, otherwise
  1703. * return mimetypes of files, it can be an array
  1704. */
  1705. public function supported_filetypes() {
  1706. // return array('text/plain', 'image/gif');
  1707. return '*';
  1708. }
  1709. /**
  1710. * Tells how the file can be picked from this repository
  1711. *
  1712. * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
  1713. *
  1714. * @return int
  1715. */
  1716. public function supported_returntypes() {
  1717. return (FILE_INTERNAL | FILE_EXTERNAL);
  1718. }
  1719. /**
  1720. * Provide repository instance information for Ajax
  1721. *
  1722. * @return stdClass
  1723. */
  1724. final public function get_meta() {
  1725. global $CFG, $OUTPUT;
  1726. $meta = new stdClass();
  1727. $meta->id = $this->id;
  1728. $meta->name = format_string($this->get_name());
  1729. $meta->type = $this->get_typename();
  1730. $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
  1731. $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
  1732. $meta->return_types = $this->supported_returntypes();
  1733. $meta->sortorder = $this->options['sortorder'];
  1734. return $meta;
  1735. }
  1736. /**
  1737. * Create an instance for this plug-in
  1738. *
  1739. * @static
  1740. * @param string $type the type of the repository
  1741. * @param int $userid the user id
  1742. * @param stdClass $context the context
  1743. * @param array $params the options for this instance
  1744. * @param int $readonly whether to create it readonly or not (defaults to not)
  1745. * @return mixed
  1746. */
  1747. public static function create($type, $userid, $context, $params, $readonly=0) {
  1748. global $CFG, $DB;
  1749. $params = (array)$params;
  1750. require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
  1751. $classname = 'repository_' . $type;
  1752. if ($repo = $DB->get_record('repository', array('type'=>$type))) {
  1753. $record = new stdClass();
  1754. $record->name = $params['name'];
  1755. $record->typeid = $repo->id;
  1756. $record->timecreated = time();
  1757. $record->timemodified = time();
  1758. $record->contextid = $context->id;
  1759. $record->readonly = $readonly;
  1760. $record->userid = $userid;
  1761. $id = $DB->insert_record('repository_instances', $record);
  1762. cache::make('core', 'repositories')->purge();
  1763. $options = array();
  1764. $configs = call_user_func($classname . '::get_instance_option_names');
  1765. if (!empty($configs)) {
  1766. foreach ($configs as $config) {
  1767. if (isset($params[$config])) {
  1768. $options[$config] = $params[$config];
  1769. } else {
  1770. $options[$config] = null;
  1771. }
  1772. }
  1773. }
  1774. if (!empty($id)) {
  1775. unset($options['name']);
  1776. $instance = repository::get_instance($id);
  1777. $instance->set_option($options);
  1778. return $id;
  1779. } else {
  1780. return null;
  1781. }
  1782. } else {
  1783. return null;
  1784. }
  1785. }
  1786. /**
  1787. * delete a repository instance
  1788. *
  1789. * @param bool $downloadcontents
  1790. * @return bool
  1791. */
  1792. final public function delete($downloadcontents = false) {
  1793. global $DB;
  1794. if ($downloadcontents) {
  1795. $this->convert_references_to_local();
  1796. }
  1797. cache::make('core', 'repositories')->purge();
  1798. try {
  1799. $DB->delete_records('repository_instances', array('id'=>$this->id));
  1800. $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
  1801. } catch (dml_exception $ex) {
  1802. return false;
  1803. }
  1804. return true;
  1805. }
  1806. /**
  1807. * Delete all the instances associated to a context.
  1808. *
  1809. * This method is intended to be a callback when deleting
  1810. * a course or a user to delete all the instances associated
  1811. * to their context. The usual way to delete a single instance
  1812. * is to use {@link self::delete()}.
  1813. *
  1814. * @param int $contextid context ID.
  1815. * @param boolean $downloadcontents true to convert references to hard copies.
  1816. * @return void
  1817. */
  1818. final public static function delete_all_for_context($contextid, $downloadcontents = true) {
  1819. global $DB;
  1820. $repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
  1821. if ($downloadcontents) {
  1822. foreach ($repoids as $repoid) {
  1823. $repo = repository::get_repository_by_id($repoid, $contextid);
  1824. $repo->convert_references_to_local();
  1825. }
  1826. }
  1827. cache::make('core', 'repositories')->purge();
  1828. $DB->delete_records_list('repository_instances', 'id', $repoids);
  1829. $DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
  1830. }
  1831. /**
  1832. * Hide/Show a repository
  1833. *
  1834. * @param string $hide
  1835. * @return bool
  1836. */
  1837. final public function hide($hide = 'toggle') {
  1838. global $DB;
  1839. if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
  1840. if ($hide === 'toggle' ) {
  1841. if (!empty($entry->visible)) {
  1842. $entry->visible = 0;
  1843. } else {
  1844. $entry->visible = 1;
  1845. }
  1846. } else {
  1847. if (!empty($hide)) {
  1848. $entry->visible = 0;
  1849. } else {
  1850. $entry->visible = 1;
  1851. }
  1852. }
  1853. return $DB->update_record('repository', $entry);
  1854. }
  1855. return false;
  1856. }
  1857. /**
  1858. * Save settings for repository instance
  1859. * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
  1860. *
  1861. * @param array $options settings
  1862. * @return bool
  1863. */
  1864. public function set_option($options = array()) {
  1865. global $DB;
  1866. if (!empty($options['name'])) {
  1867. $r = new stdClass();
  1868. $r->id = $this->id;
  1869. $r->name = $options['name'];
  1870. $DB->update_record('repository_instances', $r);
  1871. unset($options['name']);
  1872. }
  1873. foreach ($options as $name=>$value) {
  1874. if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
  1875. $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
  1876. } else {
  1877. $config = new stdClass();
  1878. $config->instanceid = $this->id;
  1879. $config->name = $name;
  1880. $config->value = $value;
  1881. $DB->insert_record('repository_instance_config', $config);
  1882. }
  1883. }
  1884. cache::make('core', 'repositories')->purge();
  1885. return true;
  1886. }
  1887. /**
  1888. * Get settings for repository instance.
  1889. *
  1890. * @param string $config a specific option to get.
  1891. * @return mixed returns an array of options. If $config is not empty, then it returns that option,
  1892. * or null if the option does not exist.
  1893. */
  1894. public function get_option($config = '') {
  1895. global $DB;
  1896. $cache = cache::make('core', 'repositories');
  1897. if (($entries = $cache->get('ops:'. $this->id)) === false) {
  1898. $entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id));
  1899. $cache->set('ops:'. $this->id, $entries);
  1900. }
  1901. $ret = array();
  1902. foreach($entries as $entry) {
  1903. $ret[$entry->name] = $entry->value;
  1904. }
  1905. if (!empty($config)) {
  1906. if (isset($ret[$config])) {
  1907. return $ret[$config];
  1908. } else {
  1909. return null;
  1910. }
  1911. } else {
  1912. return $ret;
  1913. }
  1914. }
  1915. /**
  1916. * Filter file listing to display specific types
  1917. *
  1918. * @param array $value
  1919. * @return bool
  1920. */
  1921. public function filter(&$value) {
  1922. $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
  1923. if (isset($value['children'])) {
  1924. if (!empty($value['children'])) {
  1925. $value['children'] = array_filter($value['children'], array($this, 'filter'));
  1926. }
  1927. return true; // always return directories
  1928. } else {
  1929. if ($accepted_types == '*' or empty($accepted_types)
  1930. or (is_array($accepted_types) and in_array('*', $accepted_types))) {
  1931. return true;
  1932. } else {
  1933. foreach ($accepted_types as $ext) {
  1934. if (preg_match('#'.$ext.'$#i', $value['title'])) {
  1935. return true;
  1936. }
  1937. }
  1938. }
  1939. }
  1940. return false;
  1941. }
  1942. /**
  1943. * Given a path, and perhaps a search, get a list of files.
  1944. *
  1945. * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
  1946. *
  1947. * @param string $path this parameter can a folder name, or a identification of folder
  1948. * @param string $page the page number of file list
  1949. * @return array the list of files, including meta infomation, containing the following keys
  1950. * manage, url to manage url
  1951. * client_id
  1952. * login, login form
  1953. * repo_id, active repository id
  1954. * login_btn_action, the login button action
  1955. * login_btn_label, the login button label
  1956. * total, number of results
  1957. * perpage, items per page
  1958. * page
  1959. * pages, total pages
  1960. * issearchresult, is it a search result?
  1961. * list, file list
  1962. * path, current path and parent path
  1963. */
  1964. public function get_listing($path = '', $page = '') {
  1965. }
  1966. /**
  1967. * Prepare the breadcrumb.
  1968. *
  1969. * @param array $breadcrumb contains each element of the breadcrumb.
  1970. * @return array of breadcrumb elements.
  1971. * @since Moodle 2.3.3
  1972. */
  1973. protected static function prepare_breadcrumb($breadcrumb) {
  1974. global $OUTPUT;
  1975. $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
  1976. $len = count($breadcrumb);
  1977. for ($i = 0; $i < $len; $i++) {
  1978. if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
  1979. $breadcrumb[$i]['icon'] = $foldericon;
  1980. } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
  1981. $breadcrumb[$i]->icon = $foldericon;
  1982. }
  1983. }
  1984. return $breadcrumb;
  1985. }
  1986. /**
  1987. * Prepare the file/folder listing.
  1988. *
  1989. * @param array $list of files and folders.
  1990. * @return array of files and folders.
  1991. * @since Moodle 2.3.3
  1992. */
  1993. protected static function prepare_list($list) {
  1994. global $OUTPUT;
  1995. $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
  1996. // Reset the array keys because non-numeric keys will create an object when converted to JSON.
  1997. $list = array_values($list);
  1998. $len = count($list);
  1999. for ($i = 0; $i < $len; $i++) {
  2000. if (is_object($list[$i])) {
  2001. $file = (array)$list[$i];
  2002. $converttoobject = true;
  2003. } else {
  2004. $file =& $list[$i];
  2005. $converttoobject = false;
  2006. }
  2007. if (isset($file['size'])) {
  2008. $file['size'] = (int)$file['size'];
  2009. $file['size_f'] = display_size($file['size']);
  2010. }
  2011. if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
  2012. $file['license_f'] = get_string($file['license'], 'license');
  2013. }
  2014. if (isset($file['image_width']) && isset($file['image_height'])) {
  2015. $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
  2016. $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
  2017. }
  2018. foreach (array('date', 'datemodified', 'datecreated') as $key) {
  2019. if (!isset($file[$key]) && isset($file['date'])) {
  2020. $file[$key] = $file['date'];
  2021. }
  2022. if (isset($file[$key])) {
  2023. // must be UNIX timestamp
  2024. $file[$key] = (int)$file[$key];
  2025. if (!$file[$key]) {
  2026. unset($file[$key]);
  2027. } else {
  2028. $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
  2029. $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
  2030. }
  2031. }
  2032. }
  2033. $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
  2034. $filename = null;
  2035. if (isset($file['title'])) {
  2036. $filename = $file['title'];
  2037. }
  2038. else if (isset($file['fullname'])) {
  2039. $filename = $file['fullname'];
  2040. }
  2041. if (!isset($file['mimetype']) && !$isfolder && $filename) {
  2042. $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
  2043. }
  2044. if (!isset($file['icon'])) {
  2045. if ($isfolder) {
  2046. $file['icon'] = $foldericon;
  2047. } else if ($filename) {
  2048. $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
  2049. }
  2050. }
  2051. // Recursively loop over children.
  2052. if (isset($file['children'])) {
  2053. $file['children'] = self::prepare_list($file['children']);
  2054. }
  2055. // Convert the array back to an object.
  2056. if ($converttoobject) {
  2057. $list[$i] = (object)$file;
  2058. }
  2059. }
  2060. return $list;
  2061. }
  2062. /**
  2063. * Prepares list of files before passing it to AJAX, makes sure data is in the correct
  2064. * format and stores formatted values.
  2065. *
  2066. * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
  2067. * @return array
  2068. */
  2069. public static function prepare_listing($listing) {
  2070. $wasobject = false;
  2071. if (is_object($listing)) {
  2072. $listing = (array) $listing;
  2073. $wasobject = true;
  2074. }
  2075. // Prepare the breadcrumb, passed as 'path'.
  2076. if (isset($listing['path']) && is_array($listing['path'])) {
  2077. $listing['path'] = self::prepare_breadcrumb($listing['path']);
  2078. }
  2079. // Prepare the listing of objects.
  2080. if (isset($listing['list']) && is_array($listing['list'])) {
  2081. $listing['list'] = self::prepare_list($listing['list']);
  2082. }
  2083. // Convert back to an object.
  2084. if ($wasobject) {
  2085. $listing = (object) $listing;
  2086. }
  2087. return $listing;
  2088. }
  2089. /**
  2090. * Search files in repository
  2091. * When doing global search, $search_text will be used as
  2092. * keyword.
  2093. *
  2094. * @param string $search_text search key word
  2095. * @param int $page page
  2096. * @return mixed see {@link repository::get_listing()}
  2097. */
  2098. public function search($search_text, $page = 0) {
  2099. $list = array();
  2100. $list['list'] = array();
  2101. return false;
  2102. }
  2103. /**
  2104. * Logout from repository instance
  2105. * By default, this function will return a login form
  2106. *
  2107. * @return string
  2108. */
  2109. public function logout(){
  2110. return $this->print_login();
  2111. }
  2112. /**
  2113. * To check whether the user is logged in.
  2114. *
  2115. * @return bool
  2116. */
  2117. public function check_login(){
  2118. return true;
  2119. }
  2120. /**
  2121. * Show the login screen, if required
  2122. *
  2123. * @return string
  2124. */
  2125. public function print_login(){
  2126. return $this->get_listing();
  2127. }
  2128. /**
  2129. * Show the search screen, if required
  2130. *
  2131. * @return string
  2132. */
  2133. public function print_search() {
  2134. global $PAGE;
  2135. $renderer = $PAGE->get_renderer('core', 'files');
  2136. return $renderer->repository_default_searchform();
  2137. }
  2138. /**
  2139. * For oauth like external authentication, when external repository direct user back to moodle,
  2140. * this function will be called to set up token and token_secret
  2141. */
  2142. public function callback() {
  2143. }
  2144. /**
  2145. * is it possible to do glboal search?
  2146. *
  2147. * @return bool
  2148. */
  2149. public function global_search() {
  2150. return false;
  2151. }
  2152. /**
  2153. * Defines operations that happen occasionally on cron
  2154. *
  2155. * @return bool
  2156. */
  2157. public function cron() {
  2158. return true;
  2159. }
  2160. /**
  2161. * function which is run when the type is created (moodle administrator add the plugin)
  2162. *
  2163. * @return bool success or fail?
  2164. */
  2165. public static function plugin_init() {
  2166. return true;
  2167. }
  2168. /**
  2169. * Edit/Create Admin Settings Moodle form
  2170. *
  2171. * @param moodleform $mform Moodle form (passed by reference)
  2172. * @param string $classname repository class name
  2173. */
  2174. public static function type_config_form($mform, $classname = 'repository') {
  2175. $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
  2176. if (empty($instnaceoptions)) {
  2177. // this plugin has only one instance
  2178. // so we need to give it a name
  2179. // it can be empty, then moodle will look for instance name from language string
  2180. $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
  2181. $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
  2182. $mform->setType('pluginname', PARAM_TEXT);
  2183. }
  2184. }
  2185. /**
  2186. * Validate Admin Settings Moodle form
  2187. *
  2188. * @static
  2189. * @param moodleform $mform Moodle form (passed by reference)
  2190. * @param array $data array of ("fieldname"=>value) of submitted data
  2191. * @param array $errors array of ("fieldname"=>errormessage) of errors
  2192. * @return array array of errors
  2193. */
  2194. public static function type_form_validation($mform, $data, $errors) {
  2195. return $errors;
  2196. }
  2197. /**
  2198. * Edit/Create Instance Settings Moodle form
  2199. *
  2200. * @param moodleform $mform Moodle form (passed by reference)
  2201. */
  2202. public static function instance_config_form($mform) {
  2203. }
  2204. /**
  2205. * Return names of the general options.
  2206. * By default: no general option name
  2207. *
  2208. * @return array
  2209. */
  2210. public static function get_type_option_names() {
  2211. return array('pluginname');
  2212. }
  2213. /**
  2214. * Return names of the instance options.
  2215. * By default: no instance option name
  2216. *
  2217. * @return array
  2218. */
  2219. public static function get_instance_option_names() {
  2220. return array();
  2221. }
  2222. /**
  2223. * Validate repository plugin instance form
  2224. *
  2225. * @param moodleform $mform moodle form
  2226. * @param array $data form data
  2227. * @param array $errors errors
  2228. * @return array errors
  2229. */
  2230. public static function instance_form_validation($mform, $data, $errors) {
  2231. return $errors;
  2232. }
  2233. /**
  2234. * Create a shorten filename
  2235. *
  2236. * @param string $str filename
  2237. * @param int $maxlength max file name length
  2238. * @return string short filename
  2239. */
  2240. public function get_short_filename($str, $maxlength) {
  2241. if (core_text::strlen($str) >= $maxlength) {
  2242. return trim(core_text::substr($str, 0, $maxlength)).'...';
  2243. } else {
  2244. return $str;
  2245. }
  2246. }
  2247. /**
  2248. * Overwrite an existing file
  2249. *
  2250. * @param int $itemid
  2251. * @param string $filepath
  2252. * @param string $filename
  2253. * @param string $newfilepath
  2254. * @param string $newfilename
  2255. * @return bool
  2256. */
  2257. public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
  2258. global $USER;
  2259. $fs = get_file_storage();
  2260. $user_context = context_user::instance($USER->id);
  2261. if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
  2262. if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
  2263. // Remember original file source field.
  2264. $source = @unserialize($file->get_source());
  2265. // Remember the original sortorder.
  2266. $sortorder = $file->get_sortorder();
  2267. if ($tempfile->is_external_file()) {
  2268. // New file is a reference. Check that existing file does not have any other files referencing to it
  2269. if (isset($source->original) && $fs->search_references_count($source->original)) {
  2270. return (object)array('error' => get_string('errordoublereference', 'repository'));
  2271. }
  2272. }
  2273. // delete existing file to release filename
  2274. $file->delete();
  2275. // create new file
  2276. $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
  2277. // Preserve original file location (stored in source field) for handling references
  2278. if (isset($source->original)) {
  2279. if (!($newfilesource = @unserialize($newfile->get_source()))) {
  2280. $newfilesource = new stdClass();
  2281. }
  2282. $newfilesource->original = $source->original;
  2283. $newfile->set_source(serialize($newfilesource));
  2284. }
  2285. $newfile->set_sortorder($sortorder);
  2286. // remove temp file
  2287. $tempfile->delete();
  2288. return true;
  2289. }
  2290. }
  2291. return false;
  2292. }
  2293. /**
  2294. * Updates a file in draft filearea.
  2295. *
  2296. * This function can only update fields filepath, filename, author, license.
  2297. * If anything (except filepath) is updated, timemodified is set to current time.
  2298. * If filename or filepath is updated the file unconnects from it's origin
  2299. * and therefore all references to it will be converted to copies when
  2300. * filearea is saved.
  2301. *
  2302. * @param int $draftid
  2303. * @param string $filepath path to the directory containing the file, or full path in case of directory
  2304. * @param string $filename name of the file, or '.' in case of directory
  2305. * @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
  2306. * @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
  2307. */
  2308. public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
  2309. global $USER;
  2310. $fs = get_file_storage();
  2311. $usercontext = context_user::instance($USER->id);
  2312. // make sure filename and filepath are present in $updatedata
  2313. $updatedata = $updatedata + array('filepath' => $filepath, 'filename' => $filename);
  2314. $filemodified = false;
  2315. if (!$file = $fs->get_file($usercontext->id, 'user', 'draft', $draftid, $filepath, $filename)) {
  2316. if ($filename === '.') {
  2317. throw new moodle_exception('foldernotfound', 'repository');
  2318. } else {
  2319. throw new moodle_exception('filenotfound', 'error');
  2320. }
  2321. }
  2322. if (!$file->is_directory()) {
  2323. // This is a file
  2324. if ($updatedata['filepath'] !== $filepath || $updatedata['filename'] !== $filename) {
  2325. // Rename/move file: check that target file name does not exist.
  2326. if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
  2327. throw new moodle_exception('fileexists', 'repository');
  2328. }
  2329. if (($filesource = @unserialize($file->get_source())) && isset($filesource->original)) {
  2330. unset($filesource->original);
  2331. $file->set_source(serialize($filesource));
  2332. }
  2333. $file->rename($updatedata['filepath'], $updatedata['filename']);
  2334. // timemodified is updated only when file is renamed and not updated when file is moved.
  2335. $filemodified = $filemodified || ($updatedata['filename'] !== $filename);
  2336. }
  2337. if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
  2338. // Update license and timemodified.
  2339. $file->set_license($updatedata['license']);
  2340. $filemodified = true;
  2341. }
  2342. if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
  2343. // Update author and timemodified.
  2344. $file->set_author($updatedata['author']);
  2345. $filemodified = true;
  2346. }
  2347. // Update timemodified:
  2348. if ($filemodified) {
  2349. $file->set_timemodified(time());
  2350. }
  2351. } else {
  2352. // This is a directory - only filepath can be updated for a directory (it was moved).
  2353. if ($updatedata['filepath'] === $filepath) {
  2354. // nothing to update
  2355. return;
  2356. }
  2357. if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
  2358. // bad luck, we can not rename if something already exists there
  2359. throw new moodle_exception('folderexists', 'repository');
  2360. }
  2361. $xfilepath = preg_quote($filepath, '|');
  2362. if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
  2363. // we can not move folder to it's own subfolder
  2364. throw new moodle_exception('folderrecurse', 'repository');
  2365. }
  2366. // If directory changed the name, update timemodified.
  2367. $filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
  2368. // Now update directory and all children.
  2369. $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid);
  2370. foreach ($files as $f) {
  2371. if (preg_match("|^$xfilepath|", $f->get_filepath())) {
  2372. $path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
  2373. if (($filesource = @unserialize($f->get_source())) && isset($filesource->original)) {
  2374. // unset original so the references are not shown any more
  2375. unset($filesource->original);
  2376. $f->set_source(serialize($filesource));
  2377. }
  2378. $f->rename($path, $f->get_filename());
  2379. if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
  2380. $f->set_timemodified(time());
  2381. }
  2382. }
  2383. }
  2384. }
  2385. }
  2386. /**
  2387. * Delete a temp file from draft area
  2388. *
  2389. * @param int $draftitemid
  2390. * @param string $filepath
  2391. * @param string $filename
  2392. * @return bool
  2393. */
  2394. public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
  2395. global $USER;
  2396. $fs = get_file_storage();
  2397. $user_context = context_user::instance($USER->id);
  2398. if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
  2399. $file->delete();
  2400. return true;
  2401. } else {
  2402. return false;
  2403. }
  2404. }
  2405. /**
  2406. * Find all external files in this repo and import them
  2407. */
  2408. public function convert_references_to_local() {
  2409. $fs = get_file_storage();
  2410. $files = $fs->get_external_files($this->id);
  2411. foreach ($files as $storedfile) {
  2412. $fs->import_external_file($storedfile);
  2413. }
  2414. }
  2415. /**
  2416. * Function repository::reset_caches() is deprecated, cache is handled by MUC now.
  2417. * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
  2418. */
  2419. public static function reset_caches() {
  2420. throw new coding_exception('Function repository::reset_caches() can not be used any more, cache is handled by MUC now.');
  2421. }
  2422. /**
  2423. * Function repository::sync_external_file() is deprecated. Use repository::sync_reference instead
  2424. *
  2425. * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
  2426. * @see repository::sync_reference()
  2427. */
  2428. public static function sync_external_file($file, $resetsynchistory = false) {
  2429. throw new coding_exception('Function repository::sync_external_file() can not be used any more. ' .
  2430. 'Use repository::sync_reference instead.');
  2431. }
  2432. /**
  2433. * Performs synchronisation of an external file if the previous one has expired.
  2434. *
  2435. * This function must be implemented for external repositories supporting
  2436. * FILE_REFERENCE, it is called for existing aliases when their filesize,
  2437. * contenthash or timemodified are requested. It is not called for internal
  2438. * repositories (see {@link repository::has_moodle_files()}), references to
  2439. * internal files are updated immediately when source is modified.
  2440. *
  2441. * Referenced files may optionally keep their content in Moodle filepool (for
  2442. * thumbnail generation or to be able to serve cached copy). In this
  2443. * case both contenthash and filesize need to be synchronized. Otherwise repositories
  2444. * should use contenthash of empty file and correct filesize in bytes.
  2445. *
  2446. * Note that this function may be run for EACH file that needs to be synchronised at the
  2447. * moment. If anything is being downloaded or requested from external sources there
  2448. * should be a small timeout. The synchronisation is performed to update the size of
  2449. * the file and/or to update image and re-generated image preview. There is nothing
  2450. * fatal if syncronisation fails but it is fatal if syncronisation takes too long
  2451. * and hangs the script generating a page.
  2452. *
  2453. * Note: If you wish to call $file->get_filesize(), $file->get_contenthash() or
  2454. * $file->get_timemodified() make sure that recursion does not happen.
  2455. *
  2456. * Called from {@link stored_file::sync_external_file()}
  2457. *
  2458. * @uses stored_file::set_missingsource()
  2459. * @uses stored_file::set_synchronized()
  2460. * @param stored_file $file
  2461. * @return bool false when file does not need synchronisation, true if it was synchronised
  2462. */
  2463. public function sync_reference(stored_file $file) {
  2464. if ($file->get_repository_id() != $this->id) {
  2465. // This should not really happen because the function can be called from stored_file only.
  2466. return false;
  2467. }
  2468. if ($this->has_moodle_files()) {
  2469. // References to local files need to be synchronised only once.
  2470. // Later they will be synchronised automatically when the source is changed.
  2471. if ($file->get_referencelastsync()) {
  2472. return false;
  2473. }
  2474. $fs = get_file_storage();
  2475. $params = file_storage::unpack_reference($file->get_reference(), true);
  2476. if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
  2477. $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
  2478. $params['filename']))) {
  2479. $file->set_missingsource();
  2480. } else {
  2481. $file->set_synchronized($storedfile->get_contenthash(), $storedfile->get_filesize(), 0, $storedfile->get_timemodified());
  2482. }
  2483. return true;
  2484. }
  2485. return false;
  2486. }
  2487. /**
  2488. * Build draft file's source field
  2489. *
  2490. * {@link file_restore_source_field_from_draft_file()}
  2491. * XXX: This is a hack for file manager (MDL-28666)
  2492. * For newly created draft files we have to construct
  2493. * source filed in php serialized data format.
  2494. * File manager needs to know the original file information before copying
  2495. * to draft area, so we append these information in mdl_files.source field
  2496. *
  2497. * @param string $source
  2498. * @return string serialised source field
  2499. */
  2500. public static function build_source_field($source) {
  2501. $sourcefield = new stdClass;
  2502. $sourcefield->source = $source;
  2503. return serialize($sourcefield);
  2504. }
  2505. /**
  2506. * Prepares the repository to be cached. Implements method from cacheable_object interface.
  2507. *
  2508. * @return array
  2509. */
  2510. public function prepare_to_cache() {
  2511. return array(
  2512. 'class' => get_class($this),
  2513. 'id' => $this->id,
  2514. 'ctxid' => $this->context->id,
  2515. 'options' => $this->options,
  2516. 'readonly' => $this->readonly
  2517. );
  2518. }
  2519. /**
  2520. * Restores the repository from cache. Implements method from cacheable_object interface.
  2521. *
  2522. * @return array
  2523. */
  2524. public static function wake_from_cache($data) {
  2525. $classname = $data['class'];
  2526. return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
  2527. }
  2528. /**
  2529. * Gets a file relative to this file in the repository and sends it to the browser.
  2530. * Used to allow relative file linking within a repository without creating file records
  2531. * for linked files
  2532. *
  2533. * Repositories that overwrite this must be very careful - see filesystem repository for example.
  2534. *
  2535. * @param stored_file $mainfile The main file we are trying to access relative files for.
  2536. * @param string $relativepath the relative path to the file we are trying to access.
  2537. *
  2538. */
  2539. public function send_relative_file(stored_file $mainfile, $relativepath) {
  2540. // This repository hasn't implemented this so send_file_not_found.
  2541. send_file_not_found();
  2542. }
  2543. /**
  2544. * helper function to check if the repository supports send_relative_file.
  2545. *
  2546. * @return true|false
  2547. */
  2548. public function supports_relative_file() {
  2549. return false;
  2550. }
  2551. /**
  2552. * Helper function to indicate if this repository uses post requests for uploading files.
  2553. *
  2554. * @deprecated since Moodle 3.2, 3.1.1, 3.0.5
  2555. * @return bool
  2556. */
  2557. public function uses_post_requests() {
  2558. debugging('The method repository::uses_post_requests() is deprecated and must not be used anymore.', DEBUG_DEVELOPER);
  2559. return false;
  2560. }
  2561. }
  2562. /**
  2563. * Exception class for repository api
  2564. *
  2565. * @since Moodle 2.0
  2566. * @package core_repository
  2567. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2568. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2569. */
  2570. class repository_exception extends moodle_exception {
  2571. }
  2572. /**
  2573. * This is a class used to define a repository instance form
  2574. *
  2575. * @since Moodle 2.0
  2576. * @package core_repository
  2577. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2578. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2579. */
  2580. final class repository_instance_form extends moodleform {
  2581. /** @var stdClass repository instance */
  2582. protected $instance;
  2583. /** @var string repository plugin type */
  2584. protected $plugin;
  2585. /**
  2586. * Added defaults to moodle form
  2587. */
  2588. protected function add_defaults() {
  2589. $mform =& $this->_form;
  2590. $strrequired = get_string('required');
  2591. $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
  2592. $mform->setType('edit', PARAM_INT);
  2593. $mform->addElement('hidden', 'new', $this->plugin);
  2594. $mform->setType('new', PARAM_ALPHANUMEXT);
  2595. $mform->addElement('hidden', 'plugin', $this->plugin);
  2596. $mform->setType('plugin', PARAM_PLUGIN);
  2597. $mform->addElement('hidden', 'typeid', $this->typeid);
  2598. $mform->setType('typeid', PARAM_INT);
  2599. $mform->addElement('hidden', 'contextid', $this->contextid);
  2600. $mform->setType('contextid', PARAM_INT);
  2601. $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
  2602. $mform->addRule('name', $strrequired, 'required', null, 'client');
  2603. $mform->setType('name', PARAM_TEXT);
  2604. }
  2605. /**
  2606. * Define moodle form elements
  2607. */
  2608. public function definition() {
  2609. global $CFG;
  2610. // type of plugin, string
  2611. $this->plugin = $this->_customdata['plugin'];
  2612. $this->typeid = $this->_customdata['typeid'];
  2613. $this->contextid = $this->_customdata['contextid'];
  2614. $this->instance = (isset($this->_customdata['instance'])
  2615. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2616. ? $this->_customdata['instance'] : null;
  2617. $mform =& $this->_form;
  2618. $this->add_defaults();
  2619. // Add instance config options.
  2620. $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
  2621. if ($result === false) {
  2622. // Remove the name element if no other config options.
  2623. $mform->removeElement('name');
  2624. }
  2625. if ($this->instance) {
  2626. $data = array();
  2627. $data['name'] = $this->instance->name;
  2628. if (!$this->instance->readonly) {
  2629. // and set the data if we have some.
  2630. foreach ($this->instance->get_instance_option_names() as $config) {
  2631. if (!empty($this->instance->options[$config])) {
  2632. $data[$config] = $this->instance->options[$config];
  2633. } else {
  2634. $data[$config] = '';
  2635. }
  2636. }
  2637. }
  2638. $this->set_data($data);
  2639. }
  2640. if ($result === false) {
  2641. $mform->addElement('cancel');
  2642. } else {
  2643. $this->add_action_buttons(true, get_string('save','repository'));
  2644. }
  2645. }
  2646. /**
  2647. * Validate moodle form data
  2648. *
  2649. * @param array $data form data
  2650. * @param array $files files in form
  2651. * @return array errors
  2652. */
  2653. public function validation($data, $files) {
  2654. global $DB;
  2655. $errors = array();
  2656. $plugin = $this->_customdata['plugin'];
  2657. $instance = (isset($this->_customdata['instance'])
  2658. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2659. ? $this->_customdata['instance'] : null;
  2660. if (!$instance) {
  2661. $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
  2662. } else {
  2663. $errors = $instance->instance_form_validation($this, $data, $errors);
  2664. }
  2665. $sql = "SELECT count('x')
  2666. FROM {repository_instances} i, {repository} r
  2667. WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
  2668. $params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
  2669. if ($instance) {
  2670. $sql .= ' AND i.id != :instanceid';
  2671. $params['instanceid'] = $instance->id;
  2672. }
  2673. if ($DB->count_records_sql($sql, $params) > 0) {
  2674. $errors['name'] = get_string('erroruniquename', 'repository');
  2675. }
  2676. return $errors;
  2677. }
  2678. }
  2679. /**
  2680. * This is a class used to define a repository type setting form
  2681. *
  2682. * @since Moodle 2.0
  2683. * @package core_repository
  2684. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2685. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2686. */
  2687. final class repository_type_form extends moodleform {
  2688. /** @var stdClass repository instance */
  2689. protected $instance;
  2690. /** @var string repository plugin name */
  2691. protected $plugin;
  2692. /** @var string action */
  2693. protected $action;
  2694. /**
  2695. * Definition of the moodleform
  2696. */
  2697. public function definition() {
  2698. global $CFG;
  2699. // type of plugin, string
  2700. $this->plugin = $this->_customdata['plugin'];
  2701. $this->instance = (isset($this->_customdata['instance'])
  2702. && is_a($this->_customdata['instance'], 'repository_type'))
  2703. ? $this->_customdata['instance'] : null;
  2704. $this->action = $this->_customdata['action'];
  2705. $this->pluginname = $this->_customdata['pluginname'];
  2706. $mform =& $this->_form;
  2707. $strrequired = get_string('required');
  2708. $mform->addElement('hidden', 'action', $this->action);
  2709. $mform->setType('action', PARAM_TEXT);
  2710. $mform->addElement('hidden', 'repos', $this->plugin);
  2711. $mform->setType('repos', PARAM_PLUGIN);
  2712. // let the plugin add its specific fields
  2713. $classname = 'repository_' . $this->plugin;
  2714. require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
  2715. //add "enable course/user instances" checkboxes if multiple instances are allowed
  2716. $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
  2717. $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
  2718. if (!empty($instanceoptionnames)) {
  2719. $sm = get_string_manager();
  2720. $component = 'repository';
  2721. if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
  2722. $component .= ('_' . $this->plugin);
  2723. }
  2724. $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
  2725. $mform->setType('enablecourseinstances', PARAM_BOOL);
  2726. $component = 'repository';
  2727. if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
  2728. $component .= ('_' . $this->plugin);
  2729. }
  2730. $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
  2731. $mform->setType('enableuserinstances', PARAM_BOOL);
  2732. }
  2733. // set the data if we have some.
  2734. if ($this->instance) {
  2735. $data = array();
  2736. $option_names = call_user_func(array($classname,'get_type_option_names'));
  2737. if (!empty($instanceoptionnames)){
  2738. $option_names[] = 'enablecourseinstances';
  2739. $option_names[] = 'enableuserinstances';
  2740. }
  2741. $instanceoptions = $this->instance->get_options();
  2742. foreach ($option_names as $config) {
  2743. if (!empty($instanceoptions[$config])) {
  2744. $data[$config] = $instanceoptions[$config];
  2745. } else {
  2746. $data[$config] = '';
  2747. }
  2748. }
  2749. // XXX: set plugin name for plugins which doesn't have muliti instances
  2750. if (empty($instanceoptionnames)){
  2751. $data['pluginname'] = $this->pluginname;
  2752. }
  2753. $this->set_data($data);
  2754. }
  2755. $this->add_action_buttons(true, get_string('save','repository'));
  2756. }
  2757. /**
  2758. * Validate moodle form data
  2759. *
  2760. * @param array $data moodle form data
  2761. * @param array $files
  2762. * @return array errors
  2763. */
  2764. public function validation($data, $files) {
  2765. $errors = array();
  2766. $plugin = $this->_customdata['plugin'];
  2767. $instance = (isset($this->_customdata['instance'])
  2768. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2769. ? $this->_customdata['instance'] : null;
  2770. if (!$instance) {
  2771. $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
  2772. } else {
  2773. $errors = $instance->type_form_validation($this, $data, $errors);
  2774. }
  2775. return $errors;
  2776. }
  2777. }
  2778. /**
  2779. * Generate all options needed by filepicker
  2780. *
  2781. * @param array $args including following keys
  2782. * context
  2783. * accepted_types
  2784. * return_types
  2785. *
  2786. * @return array the list of repository instances, including meta infomation, containing the following keys
  2787. * externallink
  2788. * repositories
  2789. * accepted_types
  2790. */
  2791. function initialise_filepicker($args) {
  2792. global $CFG, $USER, $PAGE, $OUTPUT;
  2793. static $templatesinitialized = array();
  2794. require_once($CFG->libdir . '/licenselib.php');
  2795. $return = new stdClass();
  2796. $licenses = array();
  2797. if (!empty($CFG->licenses)) {
  2798. $array = explode(',', $CFG->licenses);
  2799. foreach ($array as $license) {
  2800. $l = new stdClass();
  2801. $l->shortname = $license;
  2802. $l->fullname = get_string($license, 'license');
  2803. $licenses[] = $l;
  2804. }
  2805. }
  2806. if (!empty($CFG->sitedefaultlicense)) {
  2807. $return->defaultlicense = $CFG->sitedefaultlicense;
  2808. }
  2809. $return->licenses = $licenses;
  2810. $return->author = fullname($USER);
  2811. if (empty($args->context)) {
  2812. $context = $PAGE->context;
  2813. } else {
  2814. $context = $args->context;
  2815. }
  2816. $disable_types = array();
  2817. if (!empty($args->disable_types)) {
  2818. $disable_types = $args->disable_types;
  2819. }
  2820. $user_context = context_user::instance($USER->id);
  2821. list($context, $course, $cm) = get_context_info_array($context->id);
  2822. $contexts = array($user_context, context_system::instance());
  2823. if (!empty($course)) {
  2824. // adding course context
  2825. $contexts[] = context_course::instance($course->id);
  2826. }
  2827. $externallink = (int)get_config(null, 'repositoryallowexternallinks');
  2828. $repositories = repository::get_instances(array(
  2829. 'context'=>$contexts,
  2830. 'currentcontext'=> $context,
  2831. 'accepted_types'=>$args->accepted_types,
  2832. 'return_types'=>$args->return_types,
  2833. 'disable_types'=>$disable_types
  2834. ));
  2835. $return->repositories = array();
  2836. if (empty($externallink)) {
  2837. $return->externallink = false;
  2838. } else {
  2839. $return->externallink = true;
  2840. }
  2841. $return->userprefs = array();
  2842. $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
  2843. $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
  2844. $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
  2845. user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
  2846. user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
  2847. user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
  2848. // provided by form element
  2849. $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
  2850. $return->return_types = $args->return_types;
  2851. $templates = array();
  2852. foreach ($repositories as $repository) {
  2853. $meta = $repository->get_meta();
  2854. // Please note that the array keys for repositories are used within
  2855. // JavaScript a lot, the key NEEDS to be the repository id.
  2856. $return->repositories[$repository->id] = $meta;
  2857. // Register custom repository template if it has one
  2858. if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
  2859. $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
  2860. $templatesinitialized['uploadform_' . $meta->type] = true;
  2861. }
  2862. }
  2863. if (!array_key_exists('core', $templatesinitialized)) {
  2864. // we need to send each filepicker template to the browser just once
  2865. $fprenderer = $PAGE->get_renderer('core', 'files');
  2866. $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
  2867. $templatesinitialized['core'] = true;
  2868. }
  2869. if (sizeof($templates)) {
  2870. $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
  2871. }
  2872. return $return;
  2873. }