lib.php 123 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
18
class PluginArtefactFile extends PluginArtefact {

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

30
    public static function get_block_types() {
31
        return array('image');
32
    }
33
34
35
36
37
38

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

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

55
56
57
58
59
60
61
62
63
64
65
66
67
68
    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();
        }
69
70
    }

71
72
73
74
75
76
77
    public static function get_event_subscriptions() {
        $subscriptions = array(
            (object)array(
                'plugin'       => 'file',
                'event'        => 'createuser',
                'callfunction' => 'newuser',
            ),
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
            (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',
            ),
98
99
100
101
102
        );

        return $subscriptions;
    }

103
104
    public static function postinst($prevversion) {
        if ($prevversion == 0) {
Hugh Davenport's avatar
Hugh Davenport committed
105
            // Set default quotas to 50MB
106
            set_config_plugin('artefact', 'file', 'defaultquota', 52428800);
Hugh Davenport's avatar
Hugh Davenport committed
107
            set_config_plugin('artefact', 'file', 'defaultgroupquota', 52428800);
108
109
            set_config_plugin('artefact', 'file', 'folderdownloadzip', 1);
            set_config_plugin('artefact', 'file', 'folderdownloadkeepzipfor', 3600);
110
            self::set_quota_triggers();
111
        }
112
        set_config_plugin('artefact', 'file', 'commentsallowedimage', 1);
113
        self::resync_filetype_list();
114
115
    }

116
117
118
119
120
121
    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()) {
122
123
            $sql = "DROP FUNCTION IF EXISTS {unmark_quota_exeed_upd_set}() CASCADE;";
            execute_sql($sql);
124
125

            db_create_trigger(
126
                'unmark_quota_exceed_upd_usr_set',
127
128
129
130
131
132
133
134
135
136
137
                '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 {
138
139
140
            $sql = "DROP TRIGGER IF EXISTS {unmark_quota_exceed_upd_set}";
            execute_sql($sql);

141
            db_create_trigger(
142
                'unmark_quota_exceed_upd_usr_set',
143
144
145
146
147
148
149
150
151
152
153
154
                '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;"
            );
        }
    }

155
    public static function newuser($event, $user) {
156
        $user = is_object($user) ? (array)$user : $user;
157
        if (empty($user['quota'])) {
158
159
            update_record('usr', array('quota' => get_config_plugin('artefact', 'file', 'defaultquota')), array('id' => $user['id']));
        }
160
    }
Aaron Wells's avatar
Aaron Wells committed
161

Richard Mansfield's avatar
Richard Mansfield committed
162

163
164
165
166
167
168
169
170
171
    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
172

173
174
    public static function jsstrings($type) {
        static $jsstrings = array(
175
176
177
            'filebrowser' => array(
                'mahara' => array(
                    'remove',
178
                    'cancel',
179
                    'defaulthint',
180
181
                ),
                'artefact.file' => array(
182
183
184
                    'confirmdeletefile',
                    'confirmdeletefolder',
                    'confirmdeletefolderandcontents',
185
                    'defaultprofileicon',
186
187
                    'editfile',
                    'editfolder',
188
                    'fileappearsinviews',
189
                    'fileattachedtoportfolioitems',
190
                    'fileappearsinskins',
191
                    'filewithnameexists',
192
                    'folderappearsinviews',
193
                    'foldercontainsprofileicons',
194
                    'foldernamerequired',
195
                    'foldernotempty',
196
                    'maxuploadsize',
197
                    'fileisfolder',
198
199
                    'nametoolong',
                    'namefieldisrequired',
200
                    'upload',
201
202
                    'uploadingfiletofolder',
                    'youmustagreetothecopyrightnotice',
203
                    'moveto',
204
205
                ),
            ),
206
207
208
        );
        return $jsstrings[$type];
    }
209

210
211
    public static function jshelp($type) {
        static $jshelp = array(
212
            'filebrowser' => array(
213
214
215
216
                'artefact.file' => array(
                    'notice',
                    'quota_message',
                    'uploadfile',
217
                    'tags',
218
219
220
221
222
223
                ),
            ),
        );
        return $jshelp[$type];
    }

224
225
226
227
228
229
230

    /**
     * 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.
     */
231
    public static function resync_filetype_list() {
232
233
234
        require_once('xmlize.php');
        db_begin();

235
236
        delete_records('artefact_file_mime_types');

237
        $newlist     = xmlize(file_get_contents(get_config('docroot') . 'artefact/file/filetypes.xml'));
238
        $filetypes   = $newlist['filetypes']['#']['filetype'];
239

240
        foreach ($filetypes as $filetype) {
241
242
243
            $description = $filetype['#']['description'][0]['#'];
            foreach ($filetype['#']['mimetypes'][0]['#']['mimetype'] as $type) {
                $mimetype = $type['#'];
244
                execute_sql("INSERT INTO {artefact_file_mime_types} (mimetype, description) VALUES (?,?)", array($mimetype, $description));
245
246
            }
        }
Aaron Wells's avatar
Aaron Wells committed
247

248
        db_commit();
249
250

        log_info('Synced filetype list with filetypes.xml');
251
252
    }

253
254
255
256
    public static function get_mimetypes_from_description($description=null, $getrecords=false) {
        static $allmimetypes = null;

        if (is_null($allmimetypes)) {
257
            $allmimetypes = get_records_array('artefact_file_mime_types');
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
        }

        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;
                }
            }
275
        }
276
277

        return $mimetypes;
278
279
    }

280
281
282
    public static function can_be_disabled() {
        return false;
    }
283
284
285
286

    public static function get_artefact_type_content_types() {
        return array(
            'file'        => array('file'),
287
288
            'image'       => array('image'),
            'profileicon' => array('image'),
289
            'archive'     => array('file'),
290
291
            'video'       => array('file'),
            'audio'       => array('file'),
292
293
        );
    }
294
295

    public static function get_attachment_types() {
296
297
298
299
300
301
302
        return array(
            'file',
            'image',
            'archive',
            'video',
            'audio'
        );
303
    }
304
305
306

    public static function recalculate_quota() {
        $data = get_records_sql_assoc("
307
            SELECT a.owner, SUM(f.size) AS bytes
308
            FROM {artefact} a JOIN {artefact_file_files} f ON a.id = f.artefact
309
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', PluginArtefactFile::get_artefact_types())) . ")
310
311
312
313
            AND a.owner IS NOT NULL
            GROUP BY a.owner", array()
        );
        if ($data) {
314
            return array_map(function($a) { return $a->bytes; }, $data);
315
316
317
        }
        return array();
    }
318
319

    public static function recalculate_group_quota() {
320

321
322
323
        $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
324
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', PluginArtefactFile::get_artefact_types())) . ")
325
326
327
328
            AND a.group IS NOT NULL
            GROUP BY a.group", array()
        );
        if ($data) {
329
            return array_map(function($a) { return $a->bytes; }, $data);
330
331
332
        }
        return array();
    }
333
334
335
336
337
338
339
340
341
342

    public static function progressbar_link($artefacttype) {
        switch ($artefacttype) {
         case 'profileicon':
            return 'artefact/file/profileicons.php';
            break;
         default:
            return 'artefact/file/index.php';
        }
    }
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361

    /**
     * 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;
        }
    }
362
363
364
365
366
367
368
369
370
371
372

    /**
     * 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) {
373
        $userid = $group = null;
374
375
376
377
378
        $owner = null;
        $addsize = 0;

        safe_require('notification', 'internal');

379
380
        $filesize = 0;
        $quotatypes = array('file','audio','video','image','archive','profileicon');
381
382
        if (('saveartefact' === $event) && in_array($eventdata->get('artefacttype'), $quotatypes)) {
            $owner = array($eventdata->get('owner'));
383
384
            $group = $eventdata->get('group');
            $filesize = $eventdata->get('size');
385
        }
386
        else if (('deleteartefact' === $event) && in_array($eventdata->get('artefacttype'), $quotatypes)) {
387
            $owner = array($eventdata->get('owner'));
388
389
390
            $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'));
391
392
393
        }
        else if ('updateuser' === $event) {
            $userid = $eventdata;
394
395
396
            if (is_array($userid)) {
                $userid = reset($userid);
            }
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
        }
        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);
        }

413
414
415
416
417
        $quotanotifylimit = get_config_plugin('artefact', 'file', 'quotanotifylimit');
        if ($quotanotifylimit <= 0 || $quotanotifylimit >= 100) {
            $quotanotifylimit = 100;
        }

418
419
        if ($userid !== null) {
            $userdata = get_user($userid);
420
            $userdata->quotausedpercent = empty($userdata->quota) ? 0 : (($userdata->quotaused + $filesize ) / $userdata->quota) * 100;
421
422
423
            $overlimit = false;
            if ($quotanotifylimit <= $userdata->quotausedpercent) {
                $overlimit = true;
424
425
426
427
            }

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

428
            if ($overlimit && '1' !== $notified) {
429
                $notifyadmin = get_config_plugin('artefact', 'file', 'quotanotifyadmin');
430
                ArtefactTypeFile::notify_users_threshold_exceeded(array($userdata), $notifyadmin);
431
            }
432
            else if ($notified && !$overlimit) {
433
434
435
                set_account_preference($userid, 'quota_exceeded_notified', false);
            }
        }
436
        else if ($group !== null) {
437
            $groupdata = get_group_by_id($group, true);
438

439
            $groupdata->quotausedpercent = empty($groupdata->quota) ? 0 : (($groupdata->quotaused + $filesize ) / $groupdata->quota) * 100;
440
441
442
443
444
445
446
447
448
            $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));
            }
        }
449
    }
450
451
}

Martyn Smith's avatar
Martyn Smith committed
452
abstract class ArtefactTypeFileBase extends ArtefactType {
453

454
455
456
457
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);

        if (empty($this->id)) {
458
459
            $allowcomments = get_config_plugin('artefact', 'file', 'commentsallowed' . $this->artefacttype);
            $this->allowcomments = !is_null($allowcomments) ? $allowcomments : $this->allowcomments;
460
461
462
        }
    }

Nigel McNie's avatar
Nigel McNie committed
463
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
464
465
466
        return false;
    }

467
468
469
470
471
472
473
    /**
     * This function checks if a artefact can be deleted
     */
    public function can_be_deleted() {
        return true;
    }

474
    public static function get_icon($options=null) {
475
476
477
478
479
480
481

    }

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

Richard Mansfield's avatar
Richard Mansfield committed
482
483
484
485
486
487
    public function move($newparentid) {
        $this->set('parent', $newparentid);
        $this->commit();
        return true;
    }

488
489
490
491
492
493
494
    /**
     * 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;
495

496
497
498
499
500
501
502
        if (is_using_external_filesystem()) {
            $classname = $CFG->externalfilesystem['class'];
            return new $classname();
        }

        return false;
    }
503

Richard Mansfield's avatar
Richard Mansfield committed
504
505
    // 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
506
    public static function file_exists($title, $owner, $folder, $institution=null, $group=null) {
507
        $filetypesql = "('" . join("','", PluginArtefactFile::get_artefact_types()) . "')";
508
        $ownersql = artefact_owner_sql($owner, $group, $institution);
509
510
        return get_field_sql('SELECT a.id FROM {artefact} a
            LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
511
            WHERE a.title = ?
512
            AND a.' . $ownersql . '
513
            AND a.parent ' . (empty($folder) ? ' IS NULL' : ' = ' . (int)$folder) . '
514
            AND a.artefacttype IN ' . $filetypesql, array($title));
515
516
    }

517
518
519

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

524
525
526
527
528
    // 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);
    }
529

530
531
532
533
534
535
536
537
538
539
540
    /**
     * 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
     */
541
    public static function get_my_files_data($parentfolderid, $userid, $group=null, $institution=null, $filters=null) {
542
        global $USER;
Richard Mansfield's avatar
Richard Mansfield committed
543
        $select = '
Richard Mansfield's avatar
Richard Mansfield committed
544
            SELECT
545
                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,
546
                COUNT(DISTINCT c.id) AS childcount, COUNT (DISTINCT aa.artefact) AS attachcount, COUNT(DISTINCT va.view) AS viewcount, COUNT(DISTINCT s.id) AS skincount,
547
                COUNT(DISTINCT api.id) AS profileiconcount';
Richard Mansfield's avatar
Richard Mansfield committed
548
        $from = '
549
550
            FROM {artefact} a
                LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
551
                LEFT OUTER JOIN {artefact_file_image} fi ON fi.artefact = a.id
552
553
                LEFT OUTER JOIN {artefact} c ON c.parent = a.id
                LEFT OUTER JOIN {artefact} api ON api.parent = a.id AND api.artefacttype = \'profileicon\'
554
                LEFT OUTER JOIN {view_artefact} va ON va.artefact = a.id
555
                LEFT OUTER JOIN {artefact_attachment} aa ON aa.attachment = a.id
556
                LEFT OUTER JOIN {skin} s ON (s.bodybgimg = a.id OR s.viewbgimg = a.id)
557
                LEFT OUTER JOIN {usr} u ON a.id = u.profileicon AND a.owner = u.id';
558
559

        if (!empty($filters['artefacttype'])) {
560
561
562
563
            $artefacttypes = $filters['artefacttype'];
            $artefacttypes[] = 'folder';
        }
        else {
564
            $artefacttypes = PluginArtefactFile::get_artefact_types();
565
        }
Richard Mansfield's avatar
Richard Mansfield committed
566
        $where = "
567
568
569
570
571
572
            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
573
        $groupby = '
574
            GROUP BY
575
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description, a.license, a.licensor, a.licensorurl, a.locked, a.allowcomments,
576
                u.profileicon, fi.orientation';
Richard Mansfield's avatar
Richard Mansfield committed
577
578

        $phvals = array();
579

Richard Mansfield's avatar
Richard Mansfield committed
580
        if ($institution) {
581
582
583
584
            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 .= '
585
586
587
588
589
590
591
592
593
594
595
596
597
                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');
                }
598
            }
Richard Mansfield's avatar
Richard Mansfield committed
599
600
601
        }
        else if ($group) {
            $select .= ',
602
                r.can_edit, r.can_view, r.can_republish, a.author';
Richard Mansfield's avatar
Richard Mansfield committed
603
604
            $from .= '
                LEFT OUTER JOIN (
605
                    SELECT ar.artefact, ar.can_edit, ar.can_view, ar.can_republish
Richard Mansfield's avatar
Richard Mansfield committed
606
607
                    FROM {artefact_access_role} ar
                    INNER JOIN {group_member} gm ON ar.role = gm.role
608
                    WHERE gm.group = ? AND gm.member = ?
Richard Mansfield's avatar
Richard Mansfield committed
609
610
611
612
                ) r ON r.artefact = a.id';
            $phvals[] = $group;
            $phvals[] = $USER->get('id');
            $where .= '
613
            AND a.group = ? AND (r.can_view = 1 OR a.author = ?)';
Richard Mansfield's avatar
Richard Mansfield committed
614
            $phvals[] = $group;
615
616
            $phvals[] = $USER->get('id');
            $groupby .= ', r.can_edit, r.can_view, r.can_republish, a.author';
Richard Mansfield's avatar
Richard Mansfield committed
617
618
619
620
621
622
623
624
625
626
627
        }
        else {
            $where .= '
            AND a.institution IS NULL AND a.owner = ?';
            $phvals[] = $userid;
        }

        if ($parentfolderid) {
            $where .= '
            AND a.parent = ? ';
            $phvals[] = $parentfolderid;
628
629
630
631
632
633
            $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
634
635
636
637
        }
        else {
            $where .= '
            AND a.parent IS NULL';
638
639
            $can_edit_parent = true;
            $can_view_parent = true;
Richard Mansfield's avatar
Richard Mansfield committed
640
        }
641

Richard Mansfield's avatar
Richard Mansfield committed
642
        $filedata = get_records_sql_assoc($select . $from . $where . $groupby, $phvals);
643
644
645
646
647
        if (!$filedata) {
            $filedata = array();
        }
        else {
            foreach ($filedata as $item) {
Richard Mansfield's avatar
Richard Mansfield committed
648
                $item->mtime = format_date(strtotime($item->mtime), 'strfdaymonthyearshort');
Richard Mansfield's avatar
Richard Mansfield committed
649
                $item->tags = array();
650
                $item->allowcomments = (bool) $item->allowcomments;
651
                $item->icon = call_static_method(generate_artefact_class_name($item->artefacttype), 'get_icon', array('id' => $item->id));
652
653
654
                if ($item->size) { // Doing this here now for non-js users
                    $item->size = ArtefactTypeFile::short_size($item->size, true);
                }
655
                if ($group) {
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
                  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;
                  }
678
                }
679
680
681
682
                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
                    }
683
                }
684
                if ($item->artefacttype == 'folder') {
685
                    if ($item->childcount > 0 && defined('FOLDER_SIZE')) {
686
                        $foldersize = get_record_sql("SELECT SUM(aff.size) AS size FROM {artefact} a
687
688
                                                      JOIN {artefact_file_files} aff ON aff.artefact = a.id
                                                      WHERE a.path LIKE ?", array('%/' . $item->id . '/%'));
689
                        $item->foldersize = ArtefactTypeFile::short_size($foldersize->size, true);
690
691
692
693
                    }
                    else {
                        $item->foldersize = ArtefactTypeFile::short_size(0, true);
                    }
694
                }
Richard Mansfield's avatar
Richard Mansfield committed
695
            }
696
            $tagwhere = "'" . join("','", array_keys($filedata)) . "'";
697
698
699
700
701
702
703
704
705
706
707
            $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
708
709
            if ($tags) {
                foreach ($tags as $t) {
710
                    $filedata[$t->resourceid]->tags[] = $t->tag;
Richard Mansfield's avatar
Richard Mansfield committed
711
712
                }
            }
713
            $where = 'artefact IN (' . join(',', array_keys($filedata)) . ')';
Richard Mansfield's avatar
Richard Mansfield committed
714
715
716
717
718
719
720
721
722
723
            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
                        );
                    }
724
                }
725
726
727
            }
        }

Richard Mansfield's avatar
Richard Mansfield committed
728
729
        // Add parent folder to the list
        if (!empty($parentfolderid)) {
730
731
732
            $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
733
734
735
                'artefacttype' => 'folder',
                'description'  => get_string('parentfolder', 'artefact.file'),
                'isparent'     => true,
736
                'id'           => $grandparentid
Richard Mansfield's avatar
Richard Mansfield committed
737
738
739
            );
        }

740
        uasort($filedata, array("ArtefactTypeFileBase", "my_files_cmp"));
741

742
743
        return $filedata;
    }
744

745
746
747
748

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

753
754
755
756
757
758
759
760
761
762
763
764
        $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
        }

765
766
767
768
769
770
771
772
773
774
        // 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;
        }

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

809
    public static function files_js() {
810
        return "function files_callback(form, data) { files_filebrowser.callback(form, data); }";
811
812
    }

813
    public static function count_user_files($owner=null, $group=null, $institution=null) {
814
        $filetypes = PluginArtefactFile::get_artefact_types();
815
816
817
818
819
820
821
        foreach ($filetypes as $k => $v) {
            if ($v == 'folder') {
                unset($filetypes[$k]);
            }
        }
        $filetypesql = "('" . join("','", $filetypes) . "')";

822
        $ownersql = artefact_owner_sql($owner, $group, $institution);
823
        return (object) array(
824
825
            'files'   => count_records_select('artefact', "artefacttype IN $filetypesql AND $ownersql", array()),
            'folders' => count_records_select('artefact', "artefacttype = 'folder' AND $ownersql", array())
826
827
828
        );
    }

829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
    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;
            }
        }

844
        $folderdata = self::artefactchooser_folder_data($artefact);
845
846

        if ($artefact->artefacttype == 'profileicon') {
847
            $artefact->description = str_shorten_text($artefact->title, 30);
848
849
850
        }
        else {
            $path = $artefact->parent ? self::get_full_path($artefact->parent, $folderdata->data) : '';
851
            $artefact->description = str_shorten_text($folderdata->ownername . $path . $artefact->title, 30);
852
853
854
855
856
        }

        return $artefact;
    }

857
    public static function artefactchooser_folder_data(&$artefact) {
858
859
860
861
862
863
864
865
        // 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);
866
            $folderdata[$ownerkey] = new stdClass();
867
868
869
870
871
872
            $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') {
873
                    $folderdata[$ownerkey]->ownername = get_config('sitename') . ':';
874
875
876
877
878
879
880
881
882
883
884
885
886
887
                }
                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
888
     * Works out a full path to a folder, given an ID. Implemented this way so
889
890
     * only one query is made.
     */
891
    public static function get_full_path($id, &$folderdata) {
892
893
894
895
896
897
898
899
        $path = '';
        while (!empty($id)) {
            $path = $folderdata[$id]->title . '/' . $path;
            $id = $folderdata[$id]->parent;
        }
        return $path;
    }

900
    public function default_parent_for_copy(&$view, &$template, $artefactstoignore) {
901
        static $folderids;
902

903
904
905
906
        $viewid = $view->get('id');

        if (isset($folderids[$viewid])) {
            return $folderids[$viewid];
907
908
909
        }

        $viewfilesfolder = ArtefactTypeFolder::get_folder_id(get_string('viewfilesdirname', 'view'), get_string('viewfilesdirdesc', 'view'),
910
                                                             null, true, $view->get('owner'), $view->get('group'), $view->get('institution'), $artefactstoignore);
911
        $foldername = $viewid;
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
        $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();

935
        $folderids[$viewid] = $folder->get('id');
936

937
        return $folderids[$viewid];
938
939
    }

940
    /**
941
942
943
944
945
     * 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
946
     *
947
948
949
950
951
952
     * @param string $desired
     * @param integer $parent
     * @param integer $owner
     * @param integer $group
     * @param string $institution
     */
953
    public static function get_new_file_title($desired, $parent, $owner=null, $group=null, $institution=null) {
954
        $bits = explode('\.', $desired);
955
        if (count($bits) > 1 && preg_match('/[^0-9]/', end($bits))) {
956
957
958
959
960
961
962
963
            $start = join('.', array_slice($bits, 0, count($bits)-1));
            $end = '.' . end($bits);
        }
        else {
            $start = $desired;
            $end = '';
        }

964
        $where = ($parent && is_int($parent)) ? "parent = $parent" : 'parent IS NULL';
965
        $where .=  ' AND ' . artefact_owner_sql($owner, $group, $institution);
966

967
968
        $taken = get_column_sql("
            SELECT title FROM {artefact}
969
            WHERE artefacttype IN ('" . join("','", PluginArtefactFile::get_artefact_types()) . "')
970
            AND title LIKE ? || '%' || ? AND " . $where, array($start, $end));
971
        $taken = array_flip($taken);
972
973
974

        $i = 0;
        $newname = $start . $end;
975
976
        while (isset($taken[$newname])) {
            $i++;
977
            $newname = $start . '.' . $i . $end;
978
979
980
        }
        return $newname;
    }
981

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

1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
    /**
     * 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();
    }
1022
1023
}

1024

1025
class ArtefactTypeFile extends ArtefactTypeFileBase {
1026

1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
    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;

1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
    // 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;
1053

1054
1055
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
Aaron Wells's avatar
Aaron Wells committed
1056

1057
1058
1059
1060
1061
1062
        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;
                }
            }
1063
1064
1065
1066
1067

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