Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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