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
            if ($tags) {
719
720
                require_once(get_config('docroot') . 'lib/form/elements/tags.php');
                $alltags = get_all_tags_for_user();
Richard Mansfield's avatar
Richard Mansfield committed
721
                foreach ($tags as $t) {
722
723
                    $tagname = remove_prefix($t->tag);
                    $filedata[$t->resourceid]->tags[$tagname] = display_tag($tagname, $alltags['tags']);
Richard Mansfield's avatar
Richard Mansfield committed
724
725
                }
            }
726
            $where = 'artefact IN (' . join(',', array_keys($filedata)) . ')';
Richard Mansfield's avatar
Richard Mansfield committed
727
728
729
730
731
732
733
734
735
736
            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
                        );
                    }
737
                }
738
739
740
            }
        }

Richard Mansfield's avatar
Richard Mansfield committed
741
742
        // Add parent folder to the list
        if (!empty($parentfolderid)) {
743
744
745
            $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
746
747
748
                'artefacttype' => 'folder',
                'description'  => get_string('parentfolder', 'artefact.file'),
                'isparent'     => true,
749
                'id'           => $grandparentid
Richard Mansfield's avatar
Richard Mansfield committed
750
751
752
            );
        }

753
        uasort($filedata, array("ArtefactTypeFileBase", "my_files_cmp"));
754

755
756
        return $filedata;
    }
757

758
759
760
761

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

766
767
768
769
770
771
772
773
774
775
776
777
        $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
        }

778
779
780
781
782
783
784
785
786
787
        // 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;
        }

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

822
    public static function files_js() {
823
        return "function files_callback(form, data) { files_filebrowser.callback(form, data); }";
824
825
    }

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

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

842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
    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;
            }
        }

857
        $folderdata = self::artefactchooser_folder_data($artefact);
858
859

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

        return $artefact;
    }

870
    public static function artefactchooser_folder_data(&$artefact) {
871
872
873
874
875
876
877
878
        // 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);
879
            $folderdata[$ownerkey] = new stdClass();
880
881
882
883
884
885
            $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') {
886
                    $folderdata[$ownerkey]->ownername = get_config('sitename') . ':';
887
888
889
890
891
892
893
894
895
896
897
898
899
900
                }
                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
901
     * Works out a full path to a folder, given an ID. Implemented this way so
902
903
     * only one query is made.
     */
904
    public static function get_full_path($id, &$folderdata) {
905
906
907
908
909
910
911
912
        $path = '';
        while (!empty($id)) {
            $path = $folderdata[$id]->title . '/' . $path;
            $id = $folderdata[$id]->parent;
        }
        return $path;
    }

913
    public function default_parent_for_copy(&$view, &$template, $artefactstoignore) {
914
        static $folderids;
915

916
917
918
919
        $viewid = $view->get('id');

        if (isset($folderids[$viewid])) {
            return $folderids[$viewid];
920
921
922
        }

        $viewfilesfolder = ArtefactTypeFolder::get_folder_id(get_string('viewfilesdirname', 'view'), get_string('viewfilesdirdesc', 'view'),
923
                                                             null, true, $view->get('owner'), $view->get('group'), $view->get('institution'), $artefactstoignore);
924
        $foldername = $viewid;
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
        $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();

948
        $folderids[$viewid] = $folder->get('id');
949

950
        return $folderids[$viewid];
951
952
    }

953
    /**
954
955
956
957
958
     * 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
959
     *
960
961
962
963
964
965
     * @param string $desired
     * @param integer $parent
     * @param integer $owner
     * @param integer $group
     * @param string $institution
     */
966
    public static function get_new_file_title($desired, $parent, $owner=null, $group=null, $institution=null) {
967
        $bits = explode('\.', $desired);
968
        if (count($bits) > 1 && preg_match('/[^0-9]/', end($bits))) {
969
970
971
972
973
974
975
976
            $start = join('.', array_slice($bits, 0, count($bits)-1));
            $end = '.' . end($bits);
        }
        else {
            $start = $desired;
            $end = '';
        }

977
        $where = ($parent && is_int($parent)) ? "parent = $parent" : 'parent IS NULL';
978
        $where .=  ' AND ' . artefact_owner_sql($owner, $group, $institution);
979

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

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

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

1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
    /**
     * 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();
    }
1035
1036
}

1037

1038
class ArtefactTypeFile extends ArtefactTypeFileBase {
1039

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

1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
    // 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;
1066

1067
1068
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
Aaron Wells's avatar
Aaron Wells committed
1069

1070
1071
1072
1073