lib.php 124 KB
Newer Older
1
2
3
4
5
<?php
/**
 *
 * @package    mahara
 * @subpackage artefact-internal
6
 * @author     Catalyst IT Ltd
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9
10
11
12
13
 *
 */

defined('INTERNAL') || die();

14
15
require_once('file.php');

16
17
class PluginArtefactFile extends PluginArtefact {

18
19
20
21
    public static function is_active() {
        return get_field('artefact_installed', 'active', 'name', 'file');
    }

22
    public static function get_artefact_types() {
23
24
25
26
        return array(
            'file',
            'folder',
            'image',
27
            'profileicon',
28
            'archive',
29
30
            'video',
            'audio',
31
        );
32
    }
Aaron Wells's avatar
Aaron Wells committed
33

34
    public static function get_block_types() {
35
        return array('image');
36
    }
37
38
39
40
41
42

    public static function get_plugin_name() {
        return 'file';
    }

    public static function menu_items() {
Richard Mansfield's avatar
Richard Mansfield committed
43
        return array(
44
45
            'create/files' => array(
                'path' => 'create/files',
46
                'url' => 'artefact/file/index.php',
47
                'title' => get_string('Files', 'artefact.file'),
48
                'weight' => 20,
49
            ),
50
51
52
53
54
55
56
        );
    }

    public static function right_nav_menu_items() {
        return array(
            'profileicons' => array(
                'path' => 'profileicons',
57
58
                'url' => 'artefact/file/profileicons.php',
                'title' => get_string('profileicons', 'artefact.file'),
59
60
                'weight' => 15,
                'iconclass' => 'id-badge',
61
            ),
Richard Mansfield's avatar
Richard Mansfield committed
62
        );
63
    }
64

65
66
67
68
69
70
71
72
73
74
75
76
77
78
    public static function group_tabs($groupid, $role) {
        if ($role) {
            return array(
                'files' => array(
                    'path' => 'groups/files',
                    'url' => 'artefact/file/groupfiles.php?group='.$groupid,
                    'title' => get_string('Files', 'artefact.file'),
                    'weight' => 80,
                ),
            );
        }
        else {
            return array();
        }
79
80
    }

81
82
83
84
85
86
87
    public static function get_event_subscriptions() {
        $subscriptions = array(
            (object)array(
                'plugin'       => 'file',
                'event'        => 'createuser',
                'callfunction' => 'newuser',
            ),
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
            (object)array(
                'plugin'        => 'file',
                'event'         => 'saveartefact',
                'callfunction'  => 'eventlistener_savedeleteartefact',
            ),
            (object)array(
                'plugin'        => 'file',
                'event'         => 'deleteartefact',
                'callfunction'  => 'eventlistener_savedeleteartefact',
            ),
            (object)array(
                'plugin'        => 'file',
                'event'         => 'deleteartefacts',
                'callfunction'  => 'eventlistener_savedeleteartefact',
            ),
            (object)array(
                'plugin'        => 'file',
                'event'         => 'updateuser',
                'callfunction'  => 'eventlistener_savedeleteartefact',
            ),
108
109
110
111
112
        );

        return $subscriptions;
    }

113
114
    public static function postinst($prevversion) {
        if ($prevversion == 0) {
Hugh Davenport's avatar
Hugh Davenport committed
115
            // Set default quotas to 50MB
116
            set_config_plugin('artefact', 'file', 'defaultquota', 52428800);
Hugh Davenport's avatar
Hugh Davenport committed
117
            set_config_plugin('artefact', 'file', 'defaultgroupquota', 52428800);
118
119
            set_config_plugin('artefact', 'file', 'folderdownloadzip', 1);
            set_config_plugin('artefact', 'file', 'folderdownloadkeepzipfor', 3600);
120
            self::set_quota_triggers();
121
        }
122
        set_config_plugin('artefact', 'file', 'commentsallowedimage', 1);
123
        self::resync_filetype_list();
124
125
    }

126
127
128
129
130
131
    public static function set_quota_triggers() {
        set_config_plugin('artefact', 'file', 'quotanotifylimit', 80);
        set_config_plugin('artefact', 'file', 'quotanotifyadmin', false);

        // Create triggers to reset the quota notification flag
        if (is_postgres()) {
132
133
            $sql = "DROP FUNCTION IF EXISTS {unmark_quota_exeed_upd_set}() CASCADE;";
            execute_sql($sql);
134
135

            db_create_trigger(
136
                'unmark_quota_exceed_upd_usr_set',
137
138
139
140
141
142
143
144
145
146
147
                'AFTER', 'UPDATE', 'usr', "
                UPDATE {usr_account_preference}
                SET value = 0 FROM {artefact_config}
                WHERE {usr_account_preference}.field = 'quota_exceeded_notified'
                AND {usr_account_preference}.usr = NEW.id
                AND {artefact_config}.plugin = 'file'
                AND {artefact_config}.field = 'quotanotifylimit'
                AND CAST(NEW.quotaused AS float)/CAST(NEW.quota AS float) < CAST({artefact_config}.value AS float)/100;"
            );
        }
        else {
148
149
150
            $sql = "DROP TRIGGER IF EXISTS {unmark_quota_exceed_upd_set}";
            execute_sql($sql);

151
            db_create_trigger(
152
                'unmark_quota_exceed_upd_usr_set',
153
154
155
156
157
158
159
160
161
162
163
164
                'AFTER', 'UPDATE', 'usr', "
                UPDATE {usr_account_preference}, {artefact_config}
                SET {usr_account_preference}.value = 0
                WHERE {usr_account_preference}.field = 'quota_exceeded_notified'
                AND {usr_account_preference}.usr = NEW.id
                AND {artefact_config}.plugin = 'file'
                AND {artefact_config}.field = 'quotanotifylimit'
                AND NEW.quotaused/NEW.quota < {artefact_config}.value/100;"
            );
        }
    }

165
    public static function newuser($event, $user) {
166
        $user = is_object($user) ? (array)$user : $user;
167
        if (empty($user['quota'])) {
168
169
            update_record('usr', array('quota' => get_config_plugin('artefact', 'file', 'defaultquota')), array('id' => $user['id']));
        }
170
    }
Aaron Wells's avatar
Aaron Wells committed
171

Richard Mansfield's avatar
Richard Mansfield committed
172

173
174
175
176
177
178
179
180
181
    public static function sort_child_data($a, $b) {
        if ($a->container && !$b->container) {
            return -1;
        }
        else if (!$a->container && $b->container) {
            return 1;
        }
        return strnatcasecmp($a->text, $b->text);
    }
Richard Mansfield's avatar
Richard Mansfield committed
182

183
184
    public static function jsstrings($type) {
        static $jsstrings = array(
185
186
187
            'filebrowser' => array(
                'mahara' => array(
                    'remove',
188
                    'cancel',
189
                    'defaulthint',
190
191
                ),
                'artefact.file' => array(
192
193
194
                    'confirmdeletefile',
                    'confirmdeletefolder',
                    'confirmdeletefolderandcontents',
195
                    'defaultprofileicon',
196
197
                    'editfile',
                    'editfolder',
198
                    'fileappearsinviews',
199
                    'fileattachedtoportfolioitems',
200
                    'fileappearsinskins',
201
                    'filewithnameexists',
202
                    'folderappearsinviews',
203
                    'foldercontainsprofileicons',
204
                    'foldernamerequired',
205
                    'foldernotempty',
206
                    'maxuploadsize',
207
                    'fileisfolder',
208
209
                    'nametoolong',
                    'namefieldisrequired',
210
                    'upload',
211
212
                    'uploadingfiletofolder',
                    'youmustagreetothecopyrightnotice',
213
                    'moveto',
214
215
                ),
            ),
216
217
218
        );
        return $jsstrings[$type];
    }
219

220
221
    public static function jshelp($type) {
        static $jshelp = array(
222
            'filebrowser' => array(
223
224
225
226
                'artefact.file' => array(
                    'notice',
                    'quota_message',
                    'uploadfile',
227
                    'tags',
228
229
230
231
232
233
                ),
            ),
        );
        return $jshelp[$type];
    }

234
235
236
237
238
239
240

    /**
     * Resyncs the allowed filetypes list with the XML configuration file.
     *
     * This can be called on install (and is, in the postinst method above),
     * and every time an upgrade is made that changes the file.
     */
241
    public static function resync_filetype_list() {
242
243
244
        require_once('xmlize.php');
        db_begin();

245
246
        delete_records('artefact_file_mime_types');

247
        $newlist     = xmlize(file_get_contents(get_config('docroot') . 'artefact/file/filetypes.xml'));
248
        $filetypes   = $newlist['filetypes']['#']['filetype'];
249

250
        foreach ($filetypes as $filetype) {
251
252
253
            $description = $filetype['#']['description'][0]['#'];
            foreach ($filetype['#']['mimetypes'][0]['#']['mimetype'] as $type) {
                $mimetype = $type['#'];
254
                execute_sql("INSERT INTO {artefact_file_mime_types} (mimetype, description) VALUES (?,?)", array($mimetype, $description));
255
256
            }
        }
Aaron Wells's avatar
Aaron Wells committed
257

258
        db_commit();
259
260

        log_info('Synced filetype list with filetypes.xml');
261
262
    }

263
264
265
266
    public static function get_mimetypes_from_description($description=null, $getrecords=false) {
        static $allmimetypes = null;

        if (is_null($allmimetypes)) {
267
            $allmimetypes = get_records_array('artefact_file_mime_types');
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        }

        if (is_string($description)) {
            $description = array($description);
        }

        $mimetypes = array();

        foreach ($allmimetypes as $r) {
            if (is_null($description) || in_array($r->description, $description)) {
                if ($getrecords) {
                    $mimetypes[$r->mimetype] = $r;
                }
                else {
                    $mimetypes[] = $r->mimetype;
                }
            }
285
        }
286
287

        return $mimetypes;
288
289
    }

290
291
292
    public static function can_be_disabled() {
        return false;
    }
293
294
295
296

    public static function get_artefact_type_content_types() {
        return array(
            'file'        => array('file'),
297
298
            'image'       => array('image'),
            'profileicon' => array('image'),
299
            'archive'     => array('file'),
300
301
            'video'       => array('file'),
            'audio'       => array('file'),
302
303
        );
    }
304
305

    public static function get_attachment_types() {
306
307
308
309
310
311
312
        return array(
            'file',
            'image',
            'archive',
            'video',
            'audio'
        );
313
    }
314
315
316

    public static function recalculate_quota() {
        $data = get_records_sql_assoc("
317
            SELECT a.owner, SUM(f.size) AS bytes
318
            FROM {artefact} a JOIN {artefact_file_files} f ON a.id = f.artefact
319
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', PluginArtefactFile::get_artefact_types())) . ")
320
321
322
323
            AND a.owner IS NOT NULL
            GROUP BY a.owner", array()
        );
        if ($data) {
324
            return array_map(function($a) { return $a->bytes; }, $data);
325
326
327
        }
        return array();
    }
328
329

    public static function recalculate_group_quota() {
330

331
332
333
        $data = get_records_sql_assoc("
            SELECT a.group, SUM(f.size) AS bytes
            FROM {artefact} a JOIN {artefact_file_files} f ON a.id = f.artefact
334
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', PluginArtefactFile::get_artefact_types())) . ")
335
336
337
338
            AND a.group IS NOT NULL
            GROUP BY a.group", array()
        );
        if ($data) {
339
            return array_map(function($a) { return $a->bytes; }, $data);
340
341
342
        }
        return array();
    }
343
344
345
346
347
348
349
350
351
352

    public static function progressbar_link($artefacttype) {
        switch ($artefacttype) {
         case 'profileicon':
            return 'artefact/file/profileicons.php';
            break;
         default:
            return 'artefact/file/index.php';
        }
    }
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371

    /**
     * The "file" artefact type should count uploads of all file types.
     * @param object $plugin
     * @return object
     */
    public static function progressbar_metaartefact_count($name) {
        global $USER;
        if ($name == 'file') {
            $meta = new stdClass();
            $meta->artefacttype = $name;
            $count = count_records_select('artefact', "owner=? and artefacttype in ('file','image','archive','video','audio')", array($USER->get('id')));
            $meta->completed = $count;
            return $meta;
        }
        else {
            return false;
        }
    }
372
373
374
375
376
377
378
379
380
381
382

    /**
     * eventlistener to respond to saveartefact, deleteartefact and
     * deleteartefacts.
     * Check if the user just passed the critical amount of his quota with a new
     * artefact or just deleted an artefact and now is below the critical percentage
     *
     * @param type $event
     * @param type $eventdata
     */
    public static function eventlistener_savedeleteartefact($event, $eventdata) {
383
        $userid = $group = null;
384
385
386
387
388
        $owner = null;
        $addsize = 0;

        safe_require('notification', 'internal');

389
390
        $filesize = 0;
        $quotatypes = array('file','audio','video','image','archive','profileicon');
391
392
        if (('saveartefact' === $event) && in_array($eventdata->get('artefacttype'), $quotatypes)) {
            $owner = array($eventdata->get('owner'));
393
394
            $group = $eventdata->get('group');
            $filesize = $eventdata->get('size');
395
        }
396
        else if (('deleteartefact' === $event) && in_array($eventdata->get('artefacttype'), $quotatypes)) {
397
            $owner = array($eventdata->get('owner'));
398
399
400
            $group = $eventdata->get('group');
            // we want to remove the size of the file from the quota check so we make it a negative integer
            $filesize = intval('-' . $eventdata->get('size'));
401
402
403
        }
        else if ('updateuser' === $event) {
            $userid = $eventdata;
404
405
406
            if (is_array($userid)) {
                $userid = reset($userid);
            }
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
        }
        else if (is_array($eventdata)) {
            foreach ($eventdata as $artefactid) {
                if (!is_int($artefactid)) {
                    continue;
                }
                $artefact = artefact_instance_from_id($artefactid);
                $owner = $artefact->get('owner');
                break;
            }
        }

        if (is_array($owner)) {
            $userid = reset($owner);
        }

423
424
425
426
427
        $quotanotifylimit = get_config_plugin('artefact', 'file', 'quotanotifylimit');
        if ($quotanotifylimit <= 0 || $quotanotifylimit >= 100) {
            $quotanotifylimit = 100;
        }

428
429
        if ($userid !== null) {
            $userdata = get_user($userid);
430
            $userdata->quotausedpercent = empty($userdata->quota) ? 0 : (($userdata->quotaused + $filesize ) / $userdata->quota) * 100;
431
432
433
            $overlimit = false;
            if ($quotanotifylimit <= $userdata->quotausedpercent) {
                $overlimit = true;
434
435
436
437
            }

            $notified = get_field('usr_account_preference', 'value', 'field', 'quota_exceeded_notified', 'usr', $userid);

438
            if ($overlimit && '1' !== $notified) {
439
                $notifyadmin = get_config_plugin('artefact', 'file', 'quotanotifyadmin');
440
                ArtefactTypeFile::notify_users_threshold_exceeded(array($userdata), $notifyadmin);
441
            }
442
            else if ($notified && !$overlimit) {
443
444
445
                set_account_preference($userid, 'quota_exceeded_notified', false);
            }
        }
446
        else if ($group !== null) {
447
            $groupdata = get_group_by_id($group, true);
448

449
            $groupdata->quotausedpercent = empty($groupdata->quota) ? 0 : (($groupdata->quotaused + $filesize ) / $groupdata->quota) * 100;
450
451
452
453
454
455
456
457
458
            $overlimit = false;
            if ($quotanotifylimit <= $groupdata->quotausedpercent) {
                $overlimit = true;
            }
            if ($overlimit) {
                require_once(get_config('docroot') . 'artefact/file/lib.php');
                ArtefactTypeFile::notify_groups_threshold_exceeded(array($groupdata));
            }
        }
459
    }
460
461
}

Martyn Smith's avatar
Martyn Smith committed
462
abstract class ArtefactTypeFileBase extends ArtefactType {
463

464
465
466
467
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);

        if (empty($this->id)) {
468
469
            $allowcomments = get_config_plugin('artefact', 'file', 'commentsallowed' . $this->artefacttype);
            $this->allowcomments = !is_null($allowcomments) ? $allowcomments : $this->allowcomments;
470
471
472
        }
    }

Nigel McNie's avatar
Nigel McNie committed
473
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
474
475
476
        return false;
    }

477
478
479
480
481
482
483
    /**
     * This function checks if a artefact can be deleted
     */
    public function can_be_deleted() {
        return true;
    }

484
    public static function get_icon($options=null) {
485
486
487
488
489
490
491

    }

    public static function collapse_config() {
        return 'file';
    }

Richard Mansfield's avatar
Richard Mansfield committed
492
493
494
495
496
497
    public function move($newparentid) {
        $this->set('parent', $newparentid);
        $this->commit();
        return true;
    }

498
499
500
501
502
503
504
    /**
     * Return an instance of external filesystem class or False if not configured.
     *
     * @return external_file_system
     */
    final public static function get_external_filesystem_instance() {
        global $CFG;
505

506
507
508
509
510
511
512
        if (is_using_external_filesystem()) {
            $classname = $CFG->externalfilesystem['class'];
            return new $classname();
        }

        return false;
    }
513

Richard Mansfield's avatar
Richard Mansfield committed
514
515
    // Check if something exists in the db with a given title and parent,
    // either in adminfiles or with a specific owner.
Richard Mansfield's avatar
Richard Mansfield committed
516
    public static function file_exists($title, $owner, $folder, $institution=null, $group=null) {
517
        $filetypesql = "('" . join("','", PluginArtefactFile::get_artefact_types()) . "')";
518
        $ownersql = artefact_owner_sql($owner, $group, $institution);
519
520
        return get_field_sql('SELECT a.id FROM {artefact} a
            LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
521
            WHERE a.title = ?
522
            AND a.' . $ownersql . '
523
            AND a.parent ' . (empty($folder) ? ' IS NULL' : ' = ' . (int)$folder) . '
524
            AND a.artefacttype IN ' . $filetypesql, array($title));
525
526
    }

527
528
529

    // Sort folders before files; then use nat sort order.
    public static function my_files_cmp($a, $b) {
530
531
        return strnatcasecmp((-2 * isset($a->isparent) + ($a->artefacttype != 'folder')) . 'a' . $a->title,
                             (-2 * isset($b->isparent) + ($b->artefacttype != 'folder')) . 'a' . $b->title);
532
533
    }

534
535
536
537
538
    // Sort folders before files in descending order; then use nat sort order descending.
    public static function my_files_cmp_desc($a, $b) {
        return strnatcasecmp((+2 * isset($b->isparent) + ($b->artefacttype == 'folder')) . 'a' . $b->title,
                             (+2 * isset($a->isparent) + ($a->artefacttype == 'folder')) . 'a' . $a->title);
    }
539

540
541
542
543
544
545
546
547
548
549
550
    /**
     * Gets a list of files in one folder
     *
     * @param integer $parentfolderid    Artefact id of the folder
     * @param integer $userid            Id of the owner, if the owner is a user
     * @param integer $group             Id of the owner, if the owner is a group
     * @param string  $institution       Id of the owner, if the owner is a institution
     * @param array   $filters           Filters to apply to the results. An array with keys 'artefacttype', 'filetype',
     *                                   where array values are arrays of artefacttype or mimetype strings.
     * @return array  A list of artefacts
     */
551
    public static function get_my_files_data($parentfolderid, $userid, $group=null, $institution=null, $filters=null) {
552
        global $USER;
Richard Mansfield's avatar
Richard Mansfield committed
553
        $select = '
Richard Mansfield's avatar
Richard Mansfield committed
554
            SELECT
555
                a.id, a.artefacttype, a.mtime, f.size, fi.orientation, a.title, a.description, a.license, a.licensor, a.licensorurl, a.locked, a.allowcomments, u.profileicon AS defaultprofileicon,
556
                COUNT(DISTINCT c.id) AS childcount, COUNT (DISTINCT aa.artefact) AS attachcount, COUNT(DISTINCT va.view) AS viewcount, COUNT(DISTINCT s.id) AS skincount,
557
                COUNT(DISTINCT api.id) AS profileiconcount';
Richard Mansfield's avatar
Richard Mansfield committed
558
        $from = '
559
560
            FROM {artefact} a
                LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
561
                LEFT OUTER JOIN {artefact_file_image} fi ON fi.artefact = a.id
562
563
                LEFT OUTER JOIN {artefact} c ON c.parent = a.id
                LEFT OUTER JOIN {artefact} api ON api.parent = a.id AND api.artefacttype = \'profileicon\'
564
                LEFT OUTER JOIN {view_artefact} va ON va.artefact = a.id
565
                LEFT OUTER JOIN {artefact_attachment} aa ON aa.attachment = a.id
566
                LEFT OUTER JOIN {skin} s ON (s.bodybgimg = a.id OR s.viewbgimg = a.id)
567
                LEFT OUTER JOIN {usr} u ON a.id = u.profileicon AND a.owner = u.id';
568
569

        if (!empty($filters['artefacttype'])) {
570
571
572
573
            $artefacttypes = $filters['artefacttype'];
            $artefacttypes[] = 'folder';
        }
        else {
574
            $artefacttypes = PluginArtefactFile::get_artefact_types();
575
        }
Richard Mansfield's avatar
Richard Mansfield committed
576
        $where = "
577
578
579
580
581
582
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', $artefacttypes)) . ")";
        if (!empty($filters['filetype']) && is_array($filters['filetype'])) {
            $where .= "
            AND (a.artefacttype = 'folder' OR f.filetype IN (" . join(',',  array_map('db_quote', $filters['filetype'])) . '))';
        }

Richard Mansfield's avatar
Richard Mansfield committed
583
        $groupby = '
584
            GROUP BY
585
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description, a.license, a.licensor, a.licensorurl, a.locked, a.allowcomments,
586
                u.profileicon, fi.orientation';
Richard Mansfield's avatar
Richard Mansfield committed
587
588

        $phvals = array();
589

Richard Mansfield's avatar
Richard Mansfield committed
590
        if ($institution) {
591
592
593
594
            if ($institution == 'mahara' && !$USER->get('admin')) {
                // If non-admins are browsing site files, only let them see the public folder & its contents
                $publicfolder = ArtefactTypeFolder::admin_public_folder_id();
                $where .= '
595
596
597
598
599
600
601
602
603
604
605
606
607
                AND (a.path = ? OR a.path LIKE ?)';
                $phvals = array("/$publicfolder", "/$publicfolder/%");
            }
            else {
                $from .= '
                    LEFT OUTER JOIN {usr_institution} ui ON ui.institution = a.institution';
                $where .= ' AND a.institution = ? ';
                $phvals[] = $institution;
                // Check if user is an admin in this institution.
                if (!$USER->get('admin')) {
                    $where .= ' AND ui.admin = 1 AND ui.usr = ? ';
                    $phvals[] = $USER->get('id');
                }
608
            }
Richard Mansfield's avatar
Richard Mansfield committed
609
610
611
        }
        else if ($group) {
            $select .= ',
612
                r.can_edit, r.can_view, r.can_republish, a.author';
Richard Mansfield's avatar
Richard Mansfield committed
613
614
            $from .= '
                LEFT OUTER JOIN (
615
                    SELECT ar.artefact, ar.can_edit, ar.can_view, ar.can_republish
Richard Mansfield's avatar
Richard Mansfield committed
616
617
                    FROM {artefact_access_role} ar
                    INNER JOIN {group_member} gm ON ar.role = gm.role
618
                    WHERE gm.group = ? AND gm.member = ?
Richard Mansfield's avatar
Richard Mansfield committed
619
620
621
622
                ) r ON r.artefact = a.id';
            $phvals[] = $group;
            $phvals[] = $USER->get('id');
            $where .= '
623
            AND a.group = ? AND (r.can_view = 1 OR a.author = ?)';
Richard Mansfield's avatar
Richard Mansfield committed
624
            $phvals[] = $group;
625
626
            $phvals[] = $USER->get('id');
            $groupby .= ', r.can_edit, r.can_view, r.can_republish, a.author';
Richard Mansfield's avatar
Richard Mansfield committed
627
628
629
630
631
632
633
634
635
636
637
        }
        else {
            $where .= '
            AND a.institution IS NULL AND a.owner = ?';
            $phvals[] = $userid;
        }

        if ($parentfolderid) {
            $where .= '
            AND a.parent = ? ';
            $phvals[] = $parentfolderid;
638
639
640
641
642
643
            $parent = artefact_instance_from_id($parentfolderid);
            $can_view_parent = $USER->can_view_artefact($parent);
            if (!$can_view_parent) {
                return null;
            }
            $can_edit_parent = $USER->can_edit_artefact($parent);
Richard Mansfield's avatar
Richard Mansfield committed
644
645
646
647
        }
        else {
            $where .= '
            AND a.parent IS NULL';
648
649
            $can_edit_parent = true;
            $can_view_parent = true;
Richard Mansfield's avatar
Richard Mansfield committed
650
        }
651

Richard Mansfield's avatar
Richard Mansfield committed
652
        $filedata = get_records_sql_assoc($select . $from . $where . $groupby, $phvals);
653
654
655
656
657
        if (!$filedata) {
            $filedata = array();
        }
        else {
            foreach ($filedata as $item) {
Richard Mansfield's avatar
Richard Mansfield committed
658
                $item->mtime = format_date(strtotime($item->mtime), 'strfdaymonthyearshort');
Richard Mansfield's avatar
Richard Mansfield committed
659
                $item->tags = array();
660
                $item->allowcomments = (bool) $item->allowcomments;
661
                $item->icon = call_static_method(generate_artefact_class_name($item->artefacttype), 'get_icon', array('id' => $item->id));
662
663
664
                if ($item->size) { // Doing this here now for non-js users
                    $item->size = ArtefactTypeFile::short_size($item->size, true);
                }
665
                if ($group) {
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
                  if ( $institution == 'mahara' && $USER->get('admin')) {
                    //site files inside and outside public folder (only admin user)
                    $item->can_edit = 1;
                    $item->can_view = 1;
                    $item->can_republish = 1;
                  }
                  else if ($institution == 'mahara' && ArtefactTypeFolder::admin_public_folder_id() == $parentfolderid) {
                       // site public files, not admin user
                       $item->can_edit = 0;
                       $item->can_view = 1;
                       $item->can_republish = 1;
                  }
                  else if (!empty($item->author) && $item->author == $USER->get('id')) {
                      $item->can_edit = 1;
                      $item->can_view = 1;
                      $item->can_republish = 1;
                  }
                  else {
                      $item->can_edit = $can_edit_parent && $item->can_edit;
                      $item->can_view = $can_view_parent && $item->can_view;
                      $item->can_republish = $can_view_parent && $item->can_republish;
                  }
688
                }
689
690
691
692
                if (!empty($item->author)) {
                    if ($group && $item->author == $USER->get('id')) {
                        $item->can_edit = 1;    // This will show the delete, edit buttons in filelist, but doesn't change the actual permissions in the checkbox
                    }
693
                }
694
                if ($item->artefacttype == 'folder') {
695
                    if ($item->childcount > 0 && defined('FOLDER_SIZE')) {
696
                        $foldersize = get_record_sql("SELECT SUM(aff.size) AS size FROM {artefact} a
697
698
                                                      JOIN {artefact_file_files} aff ON aff.artefact = a.id
                                                      WHERE a.path LIKE ?", array('%/' . $item->id . '/%'));
699
                        $item->foldersize = ArtefactTypeFile::short_size($foldersize->size, true);
700
701
702
703
                    }
                    else {
                        $item->foldersize = ArtefactTypeFile::short_size(0, true);
                    }
704
                }
Richard Mansfield's avatar
Richard Mansfield committed
705
            }
706
            $tagwhere = "'" . join("','", array_keys($filedata)) . "'";
707
708
709
710
711
712
713
714
715
716
717
            $typecast = is_postgres() ? '::varchar' : '';
            $tags = get_records_sql_array("
                SELECT
                    (CASE
                        WHEN t.tag LIKE 'tagid_%' THEN CONCAT(i.displayname, ': ', t2.tag)
                        ELSE t.tag
                    END) AS tag, t.resourceid
                FROM {tag} t
                LEFT JOIN {tag} t2 ON t2.id" . $typecast . " = SUBSTRING(t.tag, 7)
                LEFT JOIN {institution} i ON i.name = t2.ownerid
                WHERE t.resourcetype = 'artefact' AND t.resourceid IN (" . $tagwhere . ")");
Richard Mansfield's avatar
Richard Mansfield committed
718
719
            if ($tags) {
                foreach ($tags as $t) {
720
                    $filedata[$t->resourceid]->tags[] = $t->tag;
Richard Mansfield's avatar
Richard Mansfield committed
721
722
                }
            }
723
            $where = 'artefact IN (' . join(',', array_keys($filedata)) . ')';
Richard Mansfield's avatar
Richard Mansfield committed
724
725
726
727
728
729
730
731
732
733
            if ($group) {  // Fetch permissions for each artefact
                $perms = get_records_select_array('artefact_access_role', $where);
                if ($perms) {
                    foreach ($perms as $perm) {
                        $filedata[$perm->artefact]->permissions[$perm->role] = array(
                            'view' => $perm->can_view,
                            'edit' => $perm->can_edit,
                            'republish' => $perm->can_republish
                        );
                    }
734
                }
735
736
737
            }
        }

Richard Mansfield's avatar
Richard Mansfield committed
738
739
        // Add parent folder to the list
        if (!empty($parentfolderid)) {
740
741
742
            $grandparentid = (int) get_field('artefact', 'parent', 'id', $parentfolderid);
            $filedata[$grandparentid] = (object) array(
                'title'        => get_string('parentfolder', 'artefact.file'),
Richard Mansfield's avatar
Richard Mansfield committed
743
744
745
                'artefacttype' => 'folder',
                'description'  => get_string('parentfolder', 'artefact.file'),
                'isparent'     => true,
746
                'id'           => $grandparentid
Richard Mansfield's avatar
Richard Mansfield committed
747
748
749
            );
        }

750
        uasort($filedata, array("ArtefactTypeFileBase", "my_files_cmp"));
751

752
753
        return $filedata;
    }
754

755
756
757
758

    /**
     * Creates pieforms definition for forms on the my files, group files, etc. pages.
     */
759
    public static function files_form($page='', $group=null, $institution=null, $folder=null, $highlight=null, $edit=null) {
Mike Kelly's avatar
Mike Kelly committed
760
761
762
        global $USER;
        $resizeonuploaduserdefault = $USER->get_account_preference('resizeonuploaduserdefault');

763
764
765
766
767
768
769
770
771
772
773
774
        $folder = param_integer('folder', 0);
        $edit = param_variable('edit', 0);
        if (is_array($edit)) {
            $edit = array_keys($edit);
            $edit = $edit[0];
        }
        $edit = (int) $edit;
        $highlight = null;
        if ($file = param_integer('file', 0)) {
            $highlight = array($file); // todo convert to file1=1&file2=2 etc
        }

775
776
777
778
779
780
781
782
783
784
        // Check whether the user may upload files; either the group needs to
        // be within its edit window (if one is set) or the user needs to be
        // the group admin.
        if (!empty($group)) {
            $editfilesfolders = group_within_edit_window($group);
        }
        else {
            $editfilesfolders = true;
        }

785
786
787
788
        $form = array(
            'name'               => 'files',
            'jsform'             => true,
            'newiframeonsubmit'  => true,
789
790
            'jssuccesscallback'  => 'files_callback',
            'jserrorcallback'    => 'files_callback',
791
            'renderer'           => 'div',
792
793
794
            'plugintype'         => 'artefact',
            'pluginname'         => 'file',
            'configdirs'         => array(get_config('libroot') . 'form/', get_config('docroot') . 'artefact/file/form/'),
795
796
            'group'              => $group,
            'institution'        => $institution,
797
798
799
800
801
802
            'elements'           => array(
                'filebrowser' => array(
                    'type'         => 'filebrowser',
                    'folder'       => $folder,
                    'highlight'    => $highlight,
                    'edit'         => $edit,
803
                    'page'         => $page,
804
                    'config'       => array(
805
                        'upload'          => $editfilesfolders,
806
                        'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
Mike Kelly's avatar
Mike Kelly committed
807
808
                        'resizeonuploaduseroption' => get_config_plugin('artefact', 'file', 'resizeonuploaduseroption'),
                        'resizeonuploaduserdefault' => $resizeonuploaduserdefault,
809
810
                        'createfolder'    => $editfilesfolders,
                        'edit'            => $editfilesfolders,
811
812
813
814
815
816
817
                        'select'          => false,
                    ),
                ),
            ),
        );
        return $form;
    }
818

819
    public static function files_js() {
820
        return "function files_callback(form, data) { files_filebrowser.callback(form, data); }";
821
822
    }

823
    public static function count_user_files($owner=null, $group=null, $institution=null) {
824
        $filetypes = PluginArtefactFile::get_artefact_types();
825
826
827
828
829
830
831
        foreach ($filetypes as $k => $v) {
            if ($v == 'folder') {
                unset($filetypes[$k]);
            }
        }
        $filetypesql = "('" . join("','", $filetypes) . "')";

832
        $ownersql = artefact_owner_sql($owner, $group, $institution);
833
        return (object) array(
834
835
            'files'   => count_records_select('artefact', "artefacttype IN $filetypesql AND $ownersql", array()),
            'folders' => count_records_select('artefact', "artefacttype = 'folder' AND $ownersql", array())
836
837
838
        );
    }

839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
    public static function artefactchooser_get_file_data($artefact) {
        $artefact->icon = call_static_method(generate_artefact_class_name($artefact->artefacttype), 'get_icon', array('id' => $artefact->id));
        if ($artefact->artefacttype == 'profileicon') {
            $artefact->hovertitle  =  $artefact->note;
            if ($artefact->title) {
                $artefact->hovertitle .= ': ' . $artefact->title;
            }
        }
        else {
            $artefact->hovertitle  =  $artefact->title;
            if ($artefact->description) {
                $artefact->hovertitle .= ': ' . $artefact->description;
            }
        }

854
        $folderdata = self::artefactchooser_folder_data($artefact);
855
856

        if ($artefact->artefacttype == 'profileicon') {
857
            $artefact->description = str_shorten_text($artefact->title, 30);
858
859
860
        }
        else {
            $path = $artefact->parent ? self::get_full_path($artefact->parent, $folderdata->data) : '';
861
            $artefact->description = str_shorten_text($folderdata->ownername . $path . $artefact->title, 30);
862
863
864
865
866
        }

        return $artefact;
    }

867
    public static function artefactchooser_folder_data(&$artefact) {
868
869
870
871
872
873
874
875
        // Grab data about all folders the artefact owner has, so we
        // can make full paths to them, and show the artefact owner if
        // it's a group or institution.
        static $folderdata = array();

        $ownerkey = $artefact->owner . '::' . $artefact->group . '::' . $artefact->institution;
        if (!isset($folderdata[$ownerkey])) {
            $ownersql = artefact_owner_sql($artefact->owner, $artefact->group, $artefact->institution);
876
            $folderdata[$ownerkey] = new stdClass();
877
878
879
880
881
882
            $folderdata[$ownerkey]->data = get_records_select_assoc('artefact', "artefacttype='folder' AND $ownersql", array(), '', 'id, title, parent');
            if ($artefact->group) {
                $folderdata[$ownerkey]->ownername = get_field('group', 'name', 'id', $artefact->group) . ':';
            }
            else if ($artefact->institution) {
                if ($artefact->institution == 'mahara') {
883
                    $folderdata[$ownerkey]->ownername = get_config('sitename') . ':';
884
885
886
887
888
889
890
891
892
893
894
895
896
897
                }
                else {
                    $folderdata[$ownerkey]->ownername = get_field('institution', 'displayname', 'name', $artefact->institution) . ':';
                }
            }
            else {
                $folderdata[$ownerkey]->ownername = '';
            }
        }

        return $folderdata[$ownerkey];
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
898
     * Works out a full path to a folder, given an ID. Implemented this way so
899
900
     * only one query is made.
     */
901
    public static function get_full_path($id, &$folderdata) {
902
903
904
905
906
907
908
909
        $path = '';
        while (!empty($id)) {
            $path = $folderdata[$id]->title . '/' . $path;
            $id = $folderdata[$id]->parent;
        }
        return $path;
    }

910
    public function default_parent_for_copy(&$view, &$template, $artefactstoignore) {
911
        static $folderids;
912

913
914
915
916
        $viewid = $view->get('id');

        if (isset($folderids[$viewid])) {
            return $folderids[$viewid];
917
918
919
        }

        $viewfilesfolder = ArtefactTypeFolder::get_folder_id(get_string('viewfilesdirname', 'view'), get_string('viewfilesdirdesc', 'view'),
920
                                                             null, true, $view->get('owner'), $view->get('group'), $view->get('institution'), $artefactstoignore);
921
        $foldername = $viewid;
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
        $existing = get_column_sql("
            SELECT title
            FROM {artefact}
            WHERE parent = ? AND title LIKE ? || '%'", array($viewfilesfolder, $foldername));
        $sep = '';
        $ext = '';
        if ($existing) {
            while (in_array($foldername . $sep . $ext, $existing)) {
                $sep = '-';
                $ext++;
            }
        }
        $data = (object) array(
            'title'       => $foldername . $sep . $ext,
            'description' => get_string('filescopiedfromviewtemplate', 'view', $template->get('title')),
            'owner'       => $view->get('owner'),
            'group'       => $view->get('group'),
            'institution' => $view->get('institution'),
            'parent'      => $viewfilesfolder,
        );
        $folder = new ArtefactTypeFolder(0, $data);
        $folder->commit();

945
        $folderids[$viewid] = $folder->get('id');
946

947
        return $folderids[$viewid];
948
949
    }

950
    /**
951
952
953
954
955
     * Return a unique artefact title for a given owner & parent.
     *
     * Try to add digits before the filename extension: If the desired
     * title contains a ".", add "." plus digits before the final ".",
     * otherwise append "." and digits.
Aaron Wells's avatar
Aaron Wells committed
956
     *
957
958
959
960
961
962
     * @param string $desired
     * @param integer $parent
     * @param integer $owner
     * @param integer $group
     * @param string $institution
     */
963
    public static function get_new_file_title($desired, $parent, $owner=null, $group=null, $institution=null) {
964
        $bits = explode('\.', $desired);
965
        if (count($bits) > 1 && preg_match('/[^0-9]/', end($bits))) {
966
967
968
969
970
971
972
973
            $start = join('.', array_slice($bits, 0, count($bits)-1));
            $end = '.' . end($bits);
        }
        else {
            $start = $desired;
            $end = '';
        }

974
        $where = ($parent && is_int($parent)) ? "parent = $parent" : 'parent IS NULL';
975
        $where .=  ' AND ' . artefact_owner_sql($owner, $group, $institution);
976

977
978
        $taken = get_column_sql("
            SELECT title FROM {artefact}
979
            WHERE artefacttype IN ('" . join("','", PluginArtefactFile::get_artefact_types()) . "')
980
            AND title LIKE ? || '%' || ? AND " . $where, array($start, $end));
981
        $taken = array_flip($taken);
982
983
984

        $i = 0;
        $newname = $start . $end;
985
986
        while (isset($taken[$newname])) {
            $i++;
987
            $newname = $start . '.' . $i . $end;
988
989
990
        }
        return $newname;
    }
991

992
    public static function blockconfig_filebrowser_element(&$instance, $default=array()) {
Mike Kelly's avatar
Mike Kelly committed
993
994
        global $USER;
        $resizeonuploaduserdefault = $USER->get_account_preference('resizeonuploaduserdefault');
995
        return array(
996
997
998
999
1000
1001
            'name'         => 'filebrowser',
            'type'         => 'filebrowser',
            'title'        => get_string('file', 'artefact.file'),
            'folder'       => (int) param_variable('folder', 0),
            'highlight'    => null,
            'browse'       => true,
1002
            'page'         => get_config('wwwroot') . 'view/blocks.php' . View::make_base_url(),
1003
1004
            'config'       => array(
                'upload'          => true,
Mike Kelly's avatar
Mike Kelly committed
1005
1006
                'resizeonuploaduseroption' => get_config_plugin('artefact', 'file', 'resizeonuploaduseroption'),
                'resizeonuploaduserdefault' => $resizeonuploaduserdefault,
1007
1008
1009
                'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
                'createfolder'    => false,
                'edit'            => false,
1010
                'tag'             => true,
1011
1012
                'select'          => true,
                'alwaysopen'      => true,
1013
                'publishing'      => true,
1014
1015
            ),
            'tabs'         => $instance->get_view()->ownership(),
1016
1017
            'defaultvalue' => $default,
            'selectlistcallback' => 'artefact_get_records_by_id',
1018
1019
1020
        );
    }

1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
    /**
     * returns duplicated file/folder artefacts
     *
     * @param array $values
     */
    public static function get_duplicated_artefacts(array $values) {
        return array();
    }
    public static function get_existing_artefacts(array $values) {
        return array();
    }
1032
1033
}

1034

1035
class ArtefactTypeFile extends ArtefactTypeFileBase {
1036

1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
    protected $size;

    // The original filename extension (when the file is first
    // uploaded) is saved here.  This is used as a workaround for IE's
    // detecting filetypes by extension: when the file is downloaded,
    // the extension can be appended to the name if it's not there
    // already.
    protected $oldextension;

    // The id used for the filename on the filesystem.  Usually this
    // is the same as the artefact id, but it can be different if the
    // file is a copy of another file artefact.
    protected $fileid;

1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
    // Mime type
    protected $filetype;

    // File content hash. It could be used by external file systems.
    protected $contenthash;

    /**
     * Array with remote file system settings like 'includefilepath' and 'class'
     *
     * @var external_file_system
     */
    protected $externalfilesystem;
1063

1064
1065
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
Aaron Wells's avatar
Aaron Wells committed
1066

1067
1068
1069
1070
1071
1072
        if ($this->id && ($filedata = get_record('artefact_file_files', 'artefact', $this->id))) {
            foreach($filedata as $name => $value) {
                if (property_exists($this, $name)) {
                    $this->{$name} = $value;
                }
            }
1073
1074
1075
1076
1077

            // If contenthash is not set for some reason, set it now.
            if (empty($this->contenthash)) {
                $this->save_content_hash();
            }
1078
        }
1079
1080

        $this->externalfilesystem = ArtefactTypeFileBase::get_external_filesystem_instance();
1081
1082
    }

1083
1084
1085
1086
1087
1088
1089
    /**
     * This function checks if a file artefact can be deleted
     */
    public function can_be_deleted() {
        return !$this->get('locked');
    }

1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
    /**
     * This function updates or inserts the artefact.  This involves putting
     * some data in the artefact table (handled by parent::commit()), and then
     * some data in the artefact_file_files table.
     */
    public function commit() {
        // Just forget the whole thing when we're clean.
        if (empty($this->dirty)) {
            return;
        }

        // We need to keep track of newness before and after.
        $new = empty($this->id);

        // Commit to the artefact table.
        parent::commit();

        // Reset dirtyness for the time being.
        $this->dirty = true;
1109

1110
1111
1112
1113
1114
1115
        $data = (object)array(
            'artefact'      => $this->get('id'),
            'size'          => $this->get('size'),
            'oldextension'  => $this->get('oldextension'),
            'fileid'        => $this->get('fileid'),
            'filetype'      => $this->get('filetype'),
1116
            'contenthash'   => $this->get('contenthash'),
1117
1118
1119
1120
1121
1122
        );

        if ($new) {