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

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

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

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

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

53
54
    public static function group_tabs($groupid) {
        return array(
55
            'files' => array(
56
                'path' => 'groups/files',
57
58
                'url' => 'artefact/file/groupfiles.php?group='.$groupid,
                'title' => get_string('Files', 'artefact.file'),
59
                'weight' => 80,
60
61
62
63
            ),
        );
    }

64
65
66
67
68
69
70
    public static function get_event_subscriptions() {
        $subscriptions = array(
            (object)array(
                'plugin'       => 'file',
                'event'        => 'createuser',
                'callfunction' => 'newuser',
            ),
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
            (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',
            ),
91
92
93
94
95
        );

        return $subscriptions;
    }

96
97
    public static function postinst($prevversion) {
        if ($prevversion == 0) {
Hugh Davenport's avatar
Hugh Davenport committed
98
            // Set default quotas to 50MB
99
            set_config_plugin('artefact', 'file', 'defaultquota', 52428800);
Hugh Davenport's avatar
Hugh Davenport committed
100
            set_config_plugin('artefact', 'file', 'defaultgroupquota', 52428800);
101
102
            set_config_plugin('artefact', 'file', 'folderdownloadzip', 1);
            set_config_plugin('artefact', 'file', 'folderdownloadkeepzipfor', 3600);
103
            self::set_quota_triggers();
104
        }
105
        set_config_plugin('artefact', 'file', 'commentsallowedimage', 1);
106
        self::resync_filetype_list();
107
108
    }

109
110
111
112
113
114
    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()) {
115
116
            $sql = "DROP FUNCTION IF EXISTS {unmark_quota_exeed_upd_set}() CASCADE;";
            execute_sql($sql);
117
118

            db_create_trigger(
119
                'unmark_quota_exceed_upd_usr_set',
120
121
122
123
124
125
126
127
128
129
130
                '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 {
131
132
133
            $sql = "DROP TRIGGER IF EXISTS {unmark_quota_exceed_upd_set}";
            execute_sql($sql);

134
            db_create_trigger(
135
                'unmark_quota_exceed_upd_usr_set',
136
137
138
139
140
141
142
143
144
145
146
147
                '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;"
            );
        }
    }

148
    public static function newuser($event, $user) {
149
        if (empty($user['quota'])) {
150
151
            update_record('usr', array('quota' => get_config_plugin('artefact', 'file', 'defaultquota')), array('id' => $user['id']));
        }
152
    }
Aaron Wells's avatar
Aaron Wells committed
153

Richard Mansfield's avatar
Richard Mansfield committed
154

155
156
157
158
159
160
161
162
163
    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
164

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

202
203
    public static function jshelp($type) {
        static $jshelp = array(
204
            'filebrowser' => array(
205
206
207
208
                'artefact.file' => array(
                    'notice',
                    'quota_message',
                    'uploadfile',
209
                    'tags',
210
211
212
213
214
215
                ),
            ),
        );
        return $jshelp[$type];
    }

216
217
218
219
220
221
222

    /**
     * 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.
     */
223
    public static function resync_filetype_list() {
224
225
226
        require_once('xmlize.php');
        db_begin();

227
228
        delete_records('artefact_file_mime_types');

229
        $newlist     = xmlize(file_get_contents(get_config('docroot') . 'artefact/file/filetypes.xml'));
230
        $filetypes   = $newlist['filetypes']['#']['filetype'];
231

232
        foreach ($filetypes as $filetype) {
233
234
235
            $description = $filetype['#']['description'][0]['#'];
            foreach ($filetype['#']['mimetypes'][0]['#']['mimetype'] as $type) {
                $mimetype = $type['#'];
236
                execute_sql("INSERT INTO {artefact_file_mime_types} (mimetype, description) VALUES (?,?)", array($mimetype, $description));
237
238
            }
        }
Aaron Wells's avatar
Aaron Wells committed
239

240
        db_commit();
241
242

        log_info('Synced filetype list with filetypes.xml');
243
244
    }

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
    public static function get_mimetypes_from_description($description=null, $getrecords=false) {
        static $allmimetypes = null;

        if (is_null($allmimetypes)) {
            $allmimetypes = get_records_assoc('artefact_file_mime_types');
        }

        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;
                }
            }
267
        }
268
269

        return $mimetypes;
270
271
    }

272
273
274
    public static function can_be_disabled() {
        return false;
    }
275
276
277
278
279

    public static function get_artefact_type_content_types() {
        return array(
            'file'        => array('file'),
            'image'       => array('file', 'image'),
280
            'profileicon' => array('file', 'image'),
281
            'archive'     => array('file'),
282
283
            'video'       => array('file'),
            'audio'       => array('file'),
284
285
        );
    }
286
287

    public static function get_attachment_types() {
288
289
290
291
292
293
294
        return array(
            'file',
            'image',
            'archive',
            'video',
            'audio'
        );
295
    }
296
297
298

    public static function recalculate_quota() {
        $data = get_records_sql_assoc("
299
            SELECT a.owner, SUM(f.size) AS bytes
300
            FROM {artefact} a JOIN {artefact_file_files} f ON a.id = f.artefact
301
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', PluginArtefactFile::get_artefact_types())) . ")
302
303
304
305
            AND a.owner IS NOT NULL
            GROUP BY a.owner", array()
        );
        if ($data) {
306
            return array_map(create_function('$a', 'return $a->bytes;'), $data);
307
308
309
        }
        return array();
    }
310
311

    public static function recalculate_group_quota() {
312

313
314
315
        $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
316
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', PluginArtefactFile::get_artefact_types())) . ")
317
318
319
320
321
322
323
324
            AND a.group IS NOT NULL
            GROUP BY a.group", array()
        );
        if ($data) {
            return array_map(create_function('$a', 'return $a->bytes;'), $data);
        }
        return array();
    }
325
326
327
328
329
330
331
332
333
334

    public static function progressbar_link($artefacttype) {
        switch ($artefacttype) {
         case 'profileicon':
            return 'artefact/file/profileicons.php';
            break;
         default:
            return 'artefact/file/index.php';
        }
    }
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353

    /**
     * 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;
        }
    }
354
355
356
357
358
359
360
361
362
363
364

    /**
     * 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) {
365
        $userid = $group = null;
366
367
368
369
370
        $owner = null;
        $addsize = 0;

        safe_require('notification', 'internal');

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

405
406
407
408
409
        $quotanotifylimit = get_config_plugin('artefact', 'file', 'quotanotifylimit');
        if ($quotanotifylimit <= 0 || $quotanotifylimit >= 100) {
            $quotanotifylimit = 100;
        }

410
411
        if ($userid !== null) {
            $userdata = get_user($userid);
412
            $userdata->quotausedpercent = empty($userdata->quota) ? 0 : (($userdata->quotaused + $filesize ) / $userdata->quota) * 100;
413
414
415
            $overlimit = false;
            if ($quotanotifylimit <= $userdata->quotausedpercent) {
                $overlimit = true;
416
417
418
419
            }

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

420
            if ($overlimit && '1' !== $notified) {
421
                $notifyadmin = get_config_plugin('artefact', 'file', 'quotanotifyadmin');
422
                ArtefactTypeFile::notify_users_threshold_exceeded(array($userdata), $notifyadmin);
423
            }
424
            else if ($notified && !$overlimit) {
425
426
427
                set_account_preference($userid, 'quota_exceeded_notified', false);
            }
        }
428
429
430
        else if ($group !== null) {
            $groupdata = get_record('group', 'id', $group);

431
            $groupdata->quotausedpercent = empty($groupdata->quota) ? 0 : (($groupdata->quotaused + $filesize ) / $groupdata->quota) * 100;
432
433
434
435
436
437
438
439
440
            $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));
            }
        }
441
    }
442
443
}

Martyn Smith's avatar
Martyn Smith committed
444
abstract class ArtefactTypeFileBase extends ArtefactType {
445

446
447
448
449
450
451
452
453
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);

        if (empty($this->id)) {
            $this->allowcomments = get_config_plugin('artefact', 'file', 'commentsallowed' . $this->artefacttype);
        }
    }

Nigel McNie's avatar
Nigel McNie committed
454
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
455
456
457
        return false;
    }

458
459
460
461
462
463
464
    /**
     * This function checks if a artefact can be deleted
     */
    public function can_be_deleted() {
        return true;
    }

465
    public static function get_icon($options=null) {
466
467
468
469
470
471
472

    }

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

Richard Mansfield's avatar
Richard Mansfield committed
473
474
475
476
477
478
    public function move($newparentid) {
        $this->set('parent', $newparentid);
        $this->commit();
        return true;
    }

479
480


Richard Mansfield's avatar
Richard Mansfield committed
481
482
    // 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
483
    public static function file_exists($title, $owner, $folder, $institution=null, $group=null) {
484
        $filetypesql = "('" . join("','", PluginArtefactFile::get_artefact_types()) . "')";
485
        $ownersql = artefact_owner_sql($owner, $group, $institution);
486
487
        return get_field_sql('SELECT a.id FROM {artefact} a
            LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
488
            WHERE a.title = ?
489
            AND a.' . $ownersql . '
490
            AND a.parent ' . (empty($folder) ? ' IS NULL' : ' = ' . (int)$folder) . '
491
            AND a.artefacttype IN ' . $filetypesql, array($title));
492
493
    }

494
495
496

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

501
502
503
504
505
    // 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);
    }
506

507
508
509
510
511
512
513
514
515
516
517
    /**
     * 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
     */
518
    public static function get_my_files_data($parentfolderid, $userid, $group=null, $institution=null, $filters=null) {
519
        global $USER;
Richard Mansfield's avatar
Richard Mansfield committed
520
        $select = '
Richard Mansfield's avatar
Richard Mansfield committed
521
            SELECT
522
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description, a.license, a.licensor, a.licensorurl, a.locked, a.allowcomments, u.profileicon AS defaultprofileicon,
523
                COUNT(DISTINCT c.id) AS childcount, COUNT (DISTINCT aa.artefact) AS attachcount, COUNT(DISTINCT va.view) AS viewcount, COUNT(DISTINCT s.id) AS skincount,
524
                COUNT(DISTINCT api.id) AS profileiconcount';
Richard Mansfield's avatar
Richard Mansfield committed
525
        $from = '
526
527
            FROM {artefact} a
                LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
528
529
                LEFT OUTER JOIN {artefact} c ON c.parent = a.id
                LEFT OUTER JOIN {artefact} api ON api.parent = a.id AND api.artefacttype = \'profileicon\'
530
                LEFT OUTER JOIN {view_artefact} va ON va.artefact = a.id
531
                LEFT OUTER JOIN {artefact_attachment} aa ON aa.attachment = a.id
532
                LEFT OUTER JOIN {skin} s ON (s.bodybgimg = a.id OR s.viewbgimg = a.id)
533
                LEFT OUTER JOIN {usr} u ON a.id = u.profileicon AND a.owner = u.id';
534
535

        if (!empty($filters['artefacttype'])) {
536
537
538
539
            $artefacttypes = $filters['artefacttype'];
            $artefacttypes[] = 'folder';
        }
        else {
540
            $artefacttypes = PluginArtefactFile::get_artefact_types();
541
        }
Richard Mansfield's avatar
Richard Mansfield committed
542
        $where = "
543
544
545
546
547
548
            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
549
        $groupby = '
550
            GROUP BY
551
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description, a.license, a.licensor, a.licensorurl, a.locked, a.allowcomments,
552
                u.profileicon';
Richard Mansfield's avatar
Richard Mansfield committed
553
554

        $phvals = array();
555

Richard Mansfield's avatar
Richard Mansfield committed
556
        if ($institution) {
557
558
559
560
            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 .= '
561
562
563
564
565
566
567
568
569
570
571
572
573
                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');
                }
574
            }
Richard Mansfield's avatar
Richard Mansfield committed
575
576
577
        }
        else if ($group) {
            $select .= ',
578
                r.can_edit, r.can_view, r.can_republish, a.author';
Richard Mansfield's avatar
Richard Mansfield committed
579
580
            $from .= '
                LEFT OUTER JOIN (
581
                    SELECT ar.artefact, ar.can_edit, ar.can_view, ar.can_republish
Richard Mansfield's avatar
Richard Mansfield committed
582
583
                    FROM {artefact_access_role} ar
                    INNER JOIN {group_member} gm ON ar.role = gm.role
584
                    WHERE gm.group = ? AND gm.member = ?
Richard Mansfield's avatar
Richard Mansfield committed
585
586
587
588
                ) r ON r.artefact = a.id';
            $phvals[] = $group;
            $phvals[] = $USER->get('id');
            $where .= '
589
            AND a.group = ? AND (r.can_view = 1 OR a.author = ?)';
Richard Mansfield's avatar
Richard Mansfield committed
590
            $phvals[] = $group;
591
592
            $phvals[] = $USER->get('id');
            $groupby .= ', r.can_edit, r.can_view, r.can_republish, a.author';
Richard Mansfield's avatar
Richard Mansfield committed
593
594
595
596
597
598
599
600
601
602
603
        }
        else {
            $where .= '
            AND a.institution IS NULL AND a.owner = ?';
            $phvals[] = $userid;
        }

        if ($parentfolderid) {
            $where .= '
            AND a.parent = ? ';
            $phvals[] = $parentfolderid;
604
605
606
607
608
609
            $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
610
611
612
613
        }
        else {
            $where .= '
            AND a.parent IS NULL';
614
615
            $can_edit_parent = true;
            $can_view_parent = true;
Richard Mansfield's avatar
Richard Mansfield committed
616
        }
617

Richard Mansfield's avatar
Richard Mansfield committed
618
        $filedata = get_records_sql_assoc($select . $from . $where . $groupby, $phvals);
619
620
621
622
623
        if (!$filedata) {
            $filedata = array();
        }
        else {
            foreach ($filedata as $item) {
Richard Mansfield's avatar
Richard Mansfield committed
624
                $item->mtime = format_date(strtotime($item->mtime), 'strfdaymonthyearshort');
Richard Mansfield's avatar
Richard Mansfield committed
625
                $item->tags = array();
626
                $item->allowcomments = (bool) $item->allowcomments;
627
                $item->icon = call_static_method(generate_artefact_class_name($item->artefacttype), 'get_icon', array('id' => $item->id));
628
629
630
                if ($item->size) { // Doing this here now for non-js users
                    $item->size = ArtefactTypeFile::short_size($item->size, true);
                }
631
                if ($group) {
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
                  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;
                  }
654
                }
655
656
657
658
                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
                    }
659
                }
660
661
662
663
664
665
666
667
668
669
                if ($item->artefacttype == 'folder') {
                    if ($item->childcount > 0) {
                        $foldersize = get_record_sql("SELECT SUM(aff.size) FROM {artefact} a
                                                      JOIN {artefact_file_files} aff ON aff.artefact = a.id
                                                      WHERE a.path LIKE ?", array('%/' . $item->id . '/%'));
                        $item->foldersize = ArtefactTypeFile::short_size($foldersize->sum, true);
                    }
                    else {
                        $item->foldersize = ArtefactTypeFile::short_size(0, true);
                    }
670
                }
Richard Mansfield's avatar
Richard Mansfield committed
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
            }
            $where = 'artefact IN (' . join(',', array_keys($filedata)) . ')';
            $tags = get_records_select_array('artefact_tag', $where);
            if ($tags) {
                foreach ($tags as $t) {
                    $filedata[$t->artefact]->tags[] = $t->tag;
                }
            }
            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
                        );
                    }
689
                }
690
691
692
            }
        }

Richard Mansfield's avatar
Richard Mansfield committed
693
694
        // Add parent folder to the list
        if (!empty($parentfolderid)) {
695
696
697
            $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
698
699
700
                'artefacttype' => 'folder',
                'description'  => get_string('parentfolder', 'artefact.file'),
                'isparent'     => true,
701
                'id'           => $grandparentid
Richard Mansfield's avatar
Richard Mansfield committed
702
703
704
            );
        }

705
        uasort($filedata, array("ArtefactTypeFileBase", "my_files_cmp"));
706

707
708
        return $filedata;
    }
709

710
711
712
713

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

718
719
720
721
722
723
724
725
726
727
728
729
        $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
        }

730
731
732
733
734
735
736
737
738
739
        // 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;
        }

740
741
742
743
        $form = array(
            'name'               => 'files',
            'jsform'             => true,
            'newiframeonsubmit'  => true,
744
745
            'jssuccesscallback'  => 'files_callback',
            'jserrorcallback'    => 'files_callback',
746
            'renderer'           => 'div',
747
748
749
            'plugintype'         => 'artefact',
            'pluginname'         => 'file',
            'configdirs'         => array(get_config('libroot') . 'form/', get_config('docroot') . 'artefact/file/form/'),
750
751
            'group'              => $group,
            'institution'        => $institution,
752
753
754
755
756
757
            'elements'           => array(
                'filebrowser' => array(
                    'type'         => 'filebrowser',
                    'folder'       => $folder,
                    'highlight'    => $highlight,
                    'edit'         => $edit,
758
                    'page'         => $page,
759
                    'config'       => array(
760
                        'upload'          => $editfilesfolders,
761
                        'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
Mike Kelly's avatar
Mike Kelly committed
762
763
                        'resizeonuploaduseroption' => get_config_plugin('artefact', 'file', 'resizeonuploaduseroption'),
                        'resizeonuploaduserdefault' => $resizeonuploaduserdefault,
764
765
                        'createfolder'    => $editfilesfolders,
                        'edit'            => $editfilesfolders,
766
767
768
769
770
771
772
                        'select'          => false,
                    ),
                ),
            ),
        );
        return $form;
    }
773

774
    public static function files_js() {
775
        return "function files_callback(form, data) { files_filebrowser.callback(form, data); }";
776
777
    }

778
    public static function count_user_files($owner=null, $group=null, $institution=null) {
779
        $filetypes = PluginArtefactFile::get_artefact_types();
780
781
782
783
784
785
786
        foreach ($filetypes as $k => $v) {
            if ($v == 'folder') {
                unset($filetypes[$k]);
            }
        }
        $filetypesql = "('" . join("','", $filetypes) . "')";

787
        $ownersql = artefact_owner_sql($owner, $group, $institution);
788
        return (object) array(
789
790
            'files'   => count_records_select('artefact', "artefacttype IN $filetypesql AND $ownersql", array()),
            'folders' => count_records_select('artefact', "artefacttype = 'folder' AND $ownersql", array())
791
792
793
        );
    }

794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
    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;
            }
        }

809
        $folderdata = self::artefactchooser_folder_data($artefact);
810
811

        if ($artefact->artefacttype == 'profileicon') {
812
            $artefact->description = str_shorten_text($artefact->title, 30);
813
814
815
        }
        else {
            $path = $artefact->parent ? self::get_full_path($artefact->parent, $folderdata->data) : '';
816
            $artefact->description = str_shorten_text($folderdata->ownername . $path . $artefact->title, 30);
817
818
819
820
821
        }

        return $artefact;
    }

822
    public static function artefactchooser_folder_data(&$artefact) {
823
824
825
826
827
828
829
830
        // 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);
831
            $folderdata[$ownerkey] = new stdClass();
832
833
834
835
836
837
            $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') {
838
                    $folderdata[$ownerkey]->ownername = get_config('sitename') . ':';
839
840
841
842
843
844
845
846
847
848
849
850
851
852
                }
                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
853
     * Works out a full path to a folder, given an ID. Implemented this way so
854
855
     * only one query is made.
     */
856
    public static function get_full_path($id, &$folderdata) {
857
858
859
860
861
862
863
864
        $path = '';
        while (!empty($id)) {
            $path = $folderdata[$id]->title . '/' . $path;
            $id = $folderdata[$id]->parent;
        }
        return $path;
    }

865
    public function default_parent_for_copy(&$view, &$template, $artefactstoignore) {
866
        static $folderids;
867

868
869
870
871
        $viewid = $view->get('id');

        if (isset($folderids[$viewid])) {
            return $folderids[$viewid];
872
873
874
        }

        $viewfilesfolder = ArtefactTypeFolder::get_folder_id(get_string('viewfilesdirname', 'view'), get_string('viewfilesdirdesc', 'view'),
875
                                                             null, true, $view->get('owner'), $view->get('group'), $view->get('institution'), $artefactstoignore);
876
        $foldername = $viewid;
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
        $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();

900
        $folderids[$viewid] = $folder->get('id');
901

902
        return $folderids[$viewid];
903
904
    }

905
    /**
906
907
908
909
910
     * 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
911
     *
912
913
914
915
916
917
     * @param string $desired
     * @param integer $parent
     * @param integer $owner
     * @param integer $group
     * @param string $institution
     */
918
    public static function get_new_file_title($desired, $parent, $owner=null, $group=null, $institution=null) {
919
        $bits = explode('\.', $desired);
920
        if (count($bits) > 1 && preg_match('/[^0-9]/', end($bits))) {
921
922
923
924
925
926
927
928
            $start = join('.', array_slice($bits, 0, count($bits)-1));
            $end = '.' . end($bits);
        }
        else {
            $start = $desired;
            $end = '';
        }

929
        $where = ($parent && is_int($parent)) ? "parent = $parent" : 'parent IS NULL';
930
        $where .=  ' AND ' . artefact_owner_sql($owner, $group, $institution);
931

932
933
        $taken = get_column_sql("
            SELECT title FROM {artefact}
934
            WHERE artefacttype IN ('" . join("','", PluginArtefactFile::get_artefact_types()) . "')
935
            AND title LIKE ? || '%' || ? AND " . $where, array($start, $end));
936
        $taken = array_flip($taken);
937
938
939

        $i = 0;
        $newname = $start . $end;
940
941
        while (isset($taken[$newname])) {
            $i++;
942
            $newname = $start . '.' . $i . $end;
943
944
945
        }
        return $newname;
    }
946

947
    public static function blockconfig_filebrowser_element(&$instance, $default=array()) {
Mike Kelly's avatar
Mike Kelly committed
948
949
        global $USER;
        $resizeonuploaduserdefault = $USER->get_account_preference('resizeonuploaduserdefault');
950
        return array(
951
952
953
954
955
956
            'name'         => 'filebrowser',
            'type'         => 'filebrowser',
            'title'        => get_string('file', 'artefact.file'),
            'folder'       => (int) param_variable('folder', 0),
            'highlight'    => null,
            'browse'       => true,
957
            'page'         => get_config('wwwroot') . 'view/blocks.php' . View::make_base_url(),
958
959
            'config'       => array(
                'upload'          => true,
Mike Kelly's avatar
Mike Kelly committed
960
961
                'resizeonuploaduseroption' => get_config_plugin('artefact', 'file', 'resizeonuploaduseroption'),
                'resizeonuploaduserdefault' => $resizeonuploaduserdefault,
962
963
964
                'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
                'createfolder'    => false,
                'edit'            => false,
965
                'tag'             => true,
966
967
                'select'          => true,
                'alwaysopen'      => true,
968
                'publishing'      => true,
969
970
            ),
            'tabs'         => $instance->get_view()->ownership(),
971
972
            'defaultvalue' => $default,
            'selectlistcallback' => 'artefact_get_records_by_id',
973
974
975
        );
    }

976
977
978
979
980
981
982
983
984
985
986
    /**
     * 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();
    }
987
988
}

989

990
class ArtefactTypeFile extends ArtefactTypeFileBase {
991

992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
    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;

    protected $filetype; // Mime type

1008
1009
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
Aaron Wells's avatar
Aaron Wells committed
1010

1011
1012
1013
1014
1015
1016
1017
1018
1019
        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;
                }
            }
        }
    }

1020
1021
1022
1023
1024
1025
1026
    /**
     * This function checks if a file artefact can be deleted
     */
    public function can_be_deleted() {
        return !$this->get('locked');
    }

1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
    /**
     * This function updates or inserts the artefact.  This involves putting
     * some data in the artefact table (handled by parent::commit()), and then
     * some data in the artefact_file_files table.
     */
    public function commit() {
        // Just forget the whole thing when we're clean.
        if (empty($this->dirty)) {
            return;
        }

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

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

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

1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
        $data = (object)array(
            'artefact'      => $this->get('id'),
            'size'          => $this->get('size'),
            'oldextension'  => $this->get('oldextension'),
            'fileid'        => $this->get('fileid'),
            'filetype'      => $this->get('filetype'),
        );

        if ($new) {
            if (empty($data->fileid)) {
                $data->fileid = $data->artefact;
            }
            insert_record('artefact_file_files', $data);
        }
        else {
            update_record('artefact_file_files', $data, 'artefact');
        }

        $this->dirty = false;
1066
1067
    }

1068
    public static function get_file_directory($id) {
1069
        return "artefact/file/originals/" . ($id % 256);
1070
1071
    }

1072
    public function get_path() {
1073
        return get_config('dataroot') . self::get_file_directory($this->fileid) . '/' .  $this->fileid;
1074
1075
    }

1076

1077
1078
1079
1080
    /**
     * Test file type and return a new Image or File.
     */
    public static function new_file($path, $data) {
1081
1082
1083
1084
1085
1086
1087
        require_once('file.php');
        if (is_image_file($path)) {
            // If it's detected as an image, overwrite the browser mime type
            $imageinfo      = getimagesize($path);
            $data->filetype = $imageinfo['mime'];
            $data->width    = $imageinfo[0];
            $data->height   = $imageinfo[1];
1088
1089
            return new ArtefactTypeImage(0, $data);
        }
1090

1091
        $data->guess = file_mime_type($path, "foo.{$data->oldextension}");
1092
1093
1094
1095
1096
        // The guessed mimetype tends to be more accurate than what the browser tells us.
        // Use the guess, unless it failed to find a match.
        // But if it failed to find a match *and* there is no browser-supplied mimetype,
        // then just use the guess.
        if ($data->guess != 'application/octet-stream' || empty($data->filetype)) {
1097
1098
1099
            $data->filetype