lib.php 86.3 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
6
 *
Francois Marier's avatar
Francois Marier committed
7
8
9
10
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
11
 *
Francois Marier's avatar
Francois Marier committed
12
13
14
15
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
16
 *
Francois Marier's avatar
Francois Marier committed
17
18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21
 *
 * @package    mahara
 * @subpackage artefact-internal
22
 * @author     Catalyst IT Ltd
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
25
26
27
28
29
 *
 */

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

30
31
32
class PluginArtefactFile extends PluginArtefact {

    public static function get_artefact_types() {
33
34
35
36
        return array(
            'file',
            'folder',
            'image',
37
            'profileicon',
38
            'archive',
39
40
            'video',
            'audio',
41
        );
42
    }
43
44
    
    public static function get_block_types() {
45
        return array('image');
46
    }
47
48
49
50
51
52

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

    public static function menu_items() {
Richard Mansfield's avatar
Richard Mansfield committed
53
        return array(
54
            'content/files' => array(
55
                'path' => 'content/files',
56
                'url' => 'artefact/file/',
57
                'title' => get_string('Files', 'artefact.file'),
58
                'weight' => 30,
59
            ),
60
            'content/profileicons' => array(
61
                'path' => 'content/profileicons',
62
63
                'url' => 'artefact/file/profileicons.php',
                'title' => get_string('profileicons', 'artefact.file'),
64
                'weight' => 20,
65
            ),
Richard Mansfield's avatar
Richard Mansfield committed
66
        );
67
    }
68

69
70
    public static function group_tabs($groupid) {
        return array(
71
            'files' => array(
72
                'path' => 'groups/files',
73
74
                'url' => 'artefact/file/groupfiles.php?group='.$groupid,
                'title' => get_string('Files', 'artefact.file'),
Richard Mansfield's avatar
Richard Mansfield committed
75
                'weight' => 70,
76
77
78
79
            ),
        );
    }

80
81
82
83
84
85
86
87
88
89
90
91
    public static function get_event_subscriptions() {
        $subscriptions = array(
            (object)array(
                'plugin'       => 'file',
                'event'        => 'createuser',
                'callfunction' => 'newuser',
            ),
        );

        return $subscriptions;
    }

92
93
    public static function postinst($prevversion) {
        if ($prevversion == 0) {
Hugh Davenport's avatar
Hugh Davenport committed
94
            // Set default quotas to 50MB
95
            set_config_plugin('artefact', 'file', 'defaultquota', 52428800);
Hugh Davenport's avatar
Hugh Davenport committed
96
            set_config_plugin('artefact', 'file', 'defaultgroupquota', 52428800);
97
        }
98
        set_config_plugin('artefact', 'file', 'commentsallowedimage', 1);
99
        self::resync_filetype_list();
100
101
    }

102
    public static function newuser($event, $user) {
103
        if (empty($user['quota'])) {
104
105
            update_record('usr', array('quota' => get_config_plugin('artefact', 'file', 'defaultquota')), array('id' => $user['id']));
        }
106
    }
107
    
Richard Mansfield's avatar
Richard Mansfield committed
108

109
110
111
112
113
114
115
116
117
    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
118

119
120
    public static function jsstrings($type) {
        static $jsstrings = array(
121
122
123
124
125
            'filebrowser' => array(
                'mahara' => array(
                    'remove',
                ),
                'artefact.file' => array(
126
127
128
                    'confirmdeletefile',
                    'confirmdeletefolder',
                    'confirmdeletefolderandcontents',
129
                    'defaultprofileicon',
130
131
                    'editfile',
                    'editfolder',
132
                    'fileappearsinviews',
133
                    'fileattachedtoportfolioitems',
134
                    'filewithnameexists',
135
                    'folderappearsinviews',
136
                    'foldercontainsprofileicons',
137
                    'foldernamerequired',
138
                    'foldernotempty',
139
                    'maxuploadsize',
140
141
                    'nametoolong',
                    'namefieldisrequired',
142
                    'upload',
143
144
145
146
                    'uploadingfiletofolder',
                    'youmustagreetothecopyrightnotice',
                ),
            ),
147
148
149
        );
        return $jsstrings[$type];
    }
150

151
152
    public static function jshelp($type) {
        static $jshelp = array(
153
            'filebrowser' => array(
154
155
156
157
                'artefact.file' => array(
                    'notice',
                    'quota_message',
                    'uploadfile',
158
                    'tags',
159
160
161
162
163
164
                ),
            ),
        );
        return $jshelp[$type];
    }

165
166
167
168
169
170
171
172
173
174
175

    /**
     * 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.
     */
    function resync_filetype_list() {
        require_once('xmlize.php');
        db_begin();

176
        $currentlist = get_records_assoc('artefact_file_mime_types');
177
        $newlist     = xmlize(file_get_contents(get_config('docroot') . 'artefact/file/filetypes.xml'));
178
179
        $filetypes   = $newlist['filetypes']['#']['filetype'];
        $newtypes    = array();
180

181
182
        $count = array('added' => 0, 'updated' => 0, 'removed' => 0);

183
        // Step one: if a mimetype is in the new list that is not in the current
184
185
        // list, add it to the current list.
        foreach ($filetypes as $filetype) {
186
187
188
189
190
            $description = $filetype['#']['description'][0]['#'];
            foreach ($filetype['#']['mimetypes'][0]['#']['mimetype'] as $type) {
                $mimetype = $type['#'];
                if (!isset($currentlist[$mimetype])) {
                    execute_sql("INSERT INTO {artefact_file_mime_types} (mimetype, description) VALUES (?,?)", array($mimetype, $description));
191
                    $count['added']++;
192
193
194
                }
                else if ($currentlist[$mimetype]->description != $description) {
                    execute_sql("UPDATE {artefact_file_mime_types} SET description = ? WHERE mimetype = ?", array($description, $mimetype));
195
                    $count['updated']++;
196
                }
197
                $newtypes[$mimetype] = true;
198
199
200
201
                $currentlist[$mimetype] = (object) array(
                    'mimetype'    => $mimetype,
                    'description' => $description,
                );
202
203
204
            }
        }

205
        // Step two: If a mimetype is in the current list that is not in the
206
        // new list, remove it from the current list.
207
208
209
        foreach ($currentlist as $mimetype => $type) {
            if (!isset($newtypes[$mimetype])) {
                delete_records('artefact_file_mime_types', 'mimetype', $mimetype);
210
                $count['removed']++;
211
212
213
214
            }
        }
       
        db_commit();
215
216
217
218
219
220
221
        $changes = array();
        foreach (array_filter($count) as $k => $v) {
            $changes[] = "$v $k";
        }
        if ($changes) {
            log_info('Updated filetype list: ' . join(', ', $changes) . '.');
        }
222
223
    }

224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    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;
                }
            }
246
        }
247
248

        return $mimetypes;
249
250
    }

251
252
253
    public static function can_be_disabled() {
        return false;
    }
254
255
256
257
258

    public static function get_artefact_type_content_types() {
        return array(
            'file'        => array('file'),
            'image'       => array('file', 'image'),
259
            'profileicon' => array('file', 'image'),
260
            'archive'     => array('file'),
261
262
            'video'       => array('file'),
            'audio'       => array('file'),
263
264
        );
    }
265
266

    public static function get_attachment_types() {
267
268
269
270
271
272
273
        return array(
            'file',
            'image',
            'archive',
            'video',
            'audio'
        );
274
    }
275
276
277

    public static function recalculate_quota() {
        $data = get_records_sql_assoc("
278
            SELECT a.owner, SUM(f.size) AS bytes
279
            FROM {artefact} a JOIN {artefact_file_files} f ON a.id = f.artefact
280
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', PluginArtefactFile::get_artefact_types())) . ")
281
282
283
284
            AND a.owner IS NOT NULL
            GROUP BY a.owner", array()
        );
        if ($data) {
285
            return array_map(create_function('$a', 'return $a->bytes;'), $data);
286
287
288
        }
        return array();
    }
289
290

    public static function recalculate_group_quota() {
291

292
293
294
        $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
295
            WHERE a.artefacttype IN (" . join(',',  array_map('db_quote', PluginArtefactFile::get_artefact_types())) . ")
296
297
298
299
300
301
302
303
            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();
    }
304
305
}

Martyn Smith's avatar
Martyn Smith committed
306
abstract class ArtefactTypeFileBase extends ArtefactType {
307

308
309
310
311
312
313
314
315
    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
316
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
317
318
319
        return false;
    }

320
    public static function get_icon($options=null) {
321
322
323
324
325
326
327

    }

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

Richard Mansfield's avatar
Richard Mansfield committed
328
329
330
331
332
333
    public function move($newparentid) {
        $this->set('parent', $newparentid);
        $this->commit();
        return true;
    }

Richard Mansfield's avatar
Richard Mansfield committed
334
335
    // 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
336
    public static function file_exists($title, $owner, $folder, $institution=null, $group=null) {
337
        $filetypesql = "('" . join("','", PluginArtefactFile::get_artefact_types()) . "')";
338
        $ownersql = artefact_owner_sql($owner, $group, $institution);
339
340
        return get_field_sql('SELECT a.id FROM {artefact} a
            LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
341
            WHERE a.title = ?
342
            AND a.' . $ownersql . '
343
            AND a.parent ' . (empty($folder) ? ' IS NULL' : ' = ' . (int)$folder) . '
344
            AND a.artefacttype IN ' . $filetypesql, array($title));
345
346
    }

347
348
349

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


355
356
357
358
359
360
361
362
363
364
365
    /**
     * 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
     */
366
    public static function get_my_files_data($parentfolderid, $userid, $group=null, $institution=null, $filters=null) {
367
        global $USER;
Richard Mansfield's avatar
Richard Mansfield committed
368
        $select = '
Richard Mansfield's avatar
Richard Mansfield committed
369
            SELECT
370
371
372
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description, a.locked, a.allowcomments, u.profileicon AS defaultprofileicon,
                COUNT(DISTINCT c.id) AS childcount, COUNT (DISTINCT aa.artefact) AS attachcount, COUNT(DISTINCT va.view) AS viewcount,
                COUNT(DISTINCT api.id) AS profileiconcount';
Richard Mansfield's avatar
Richard Mansfield committed
373
        $from = '
374
375
            FROM {artefact} a
                LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
376
377
                LEFT OUTER JOIN {artefact} c ON c.parent = a.id
                LEFT OUTER JOIN {artefact} api ON api.parent = a.id AND api.artefacttype = \'profileicon\'
378
                LEFT OUTER JOIN {view_artefact} va ON va.artefact = a.id
379
380
                LEFT OUTER JOIN {artefact_attachment} aa ON aa.attachment = a.id
                LEFT OUTER JOIN {usr} u ON a.id = u.profileicon AND a.owner = u.id';
381
382

        if (!empty($filters['artefacttype'])) {
383
384
385
386
            $artefacttypes = $filters['artefacttype'];
            $artefacttypes[] = 'folder';
        }
        else {
387
            $artefacttypes = PluginArtefactFile::get_artefact_types();
388
        }
Richard Mansfield's avatar
Richard Mansfield committed
389
        $where = "
390
391
392
393
394
395
            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
396
        $groupby = '
397
            GROUP BY
398
399
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description, a.locked, a.allowcomments,
                u.profileicon';
Richard Mansfield's avatar
Richard Mansfield committed
400
401

        $phvals = array();
402

Richard Mansfield's avatar
Richard Mansfield committed
403
        if ($institution) {
404
405
406
407
408
409
410
411
412
            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();
                $from .= '
                LEFT OUTER JOIN {artefact_parent_cache} pub ON (a.id = pub.artefact AND pub.parent = ?)';
                $where .= '
                AND (pub.parent = ? OR a.id = ?)';
                $phvals = array($publicfolder, $publicfolder, $publicfolder);
            }
Richard Mansfield's avatar
Richard Mansfield committed
413
414
415
416
417
418
            $where .= '
            AND a.institution = ? AND a.owner IS NULL';
            $phvals[] = $institution;
        }
        else if ($group) {
            $select .= ',
419
                r.can_edit, r.can_view, r.can_republish, a.author';
Richard Mansfield's avatar
Richard Mansfield committed
420
421
            $from .= '
                LEFT OUTER JOIN (
422
                    SELECT ar.artefact, ar.can_edit, ar.can_view, ar.can_republish
Richard Mansfield's avatar
Richard Mansfield committed
423
424
425
426
427
428
429
                    FROM {artefact_access_role} ar
                    INNER JOIN {group_member} gm ON ar.role = gm.role
                    WHERE gm.group = ? AND gm.member = ? 
                ) r ON r.artefact = a.id';
            $phvals[] = $group;
            $phvals[] = $USER->get('id');
            $where .= '
430
            AND a.group = ? AND a.owner IS NULL AND (r.can_view = 1 OR a.author = ?)';
Richard Mansfield's avatar
Richard Mansfield committed
431
            $phvals[] = $group;
432
433
            $phvals[] = $USER->get('id');
            $groupby .= ', r.can_edit, r.can_view, r.can_republish, a.author';
Richard Mansfield's avatar
Richard Mansfield committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
        }
        else {
            $where .= '
            AND a.institution IS NULL AND a.owner = ?';
            $phvals[] = $userid;
        }

        if ($parentfolderid) {
            $where .= '
            AND a.parent = ? ';
            $phvals[] = $parentfolderid;
        }
        else {
            $where .= '
            AND a.parent IS NULL';
        }
450

Richard Mansfield's avatar
Richard Mansfield committed
451
        $filedata = get_records_sql_assoc($select . $from . $where . $groupby, $phvals);
452
453
454
455
456
        if (!$filedata) {
            $filedata = array();
        }
        else {
            foreach ($filedata as $item) {
Richard Mansfield's avatar
Richard Mansfield committed
457
                $item->mtime = format_date(strtotime($item->mtime), 'strfdaymonthyearshort');
Richard Mansfield's avatar
Richard Mansfield committed
458
                $item->tags = array();
459
                $item->allowcomments = (bool) $item->allowcomments;
460
                $item->icon = call_static_method(generate_artefact_class_name($item->artefacttype), 'get_icon', array('id' => $item->id));
461
462
463
                if ($item->size) { // Doing this here now for non-js users
                    $item->size = ArtefactTypeFile::short_size($item->size, true);
                }
464
465
466
                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
                }
Richard Mansfield's avatar
Richard Mansfield committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
            }
            $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
                        );
                    }
485
                }
486
487
488
            }
        }

Richard Mansfield's avatar
Richard Mansfield committed
489
490
        // Add parent folder to the list
        if (!empty($parentfolderid)) {
491
492
493
            $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
494
495
496
                'artefacttype' => 'folder',
                'description'  => get_string('parentfolder', 'artefact.file'),
                'isparent'     => true,
497
498
                'id'           => $grandparentid,
                'icon'         => ArtefactTypeFolder::get_icon(),
Richard Mansfield's avatar
Richard Mansfield committed
499
500
501
            );
        }

502
        uasort($filedata, array("ArtefactTypeFileBase", "my_files_cmp"));
503
504
        return $filedata;
    }
505

506
507
508
509

    /**
     * Creates pieforms definition for forms on the my files, group files, etc. pages.
     */
510
    public static function files_form($page='', $group=null, $institution=null, $folder=null, $highlight=null, $edit=null) {
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
        $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
        }

        $form = array(
            'name'               => 'files',
            'jsform'             => true,
            'newiframeonsubmit'  => true,
527
528
            'jssuccesscallback'  => 'files_callback',
            'jserrorcallback'    => 'files_callback',
529
530
531
532
            'renderer'           => 'oneline',
            'plugintype'         => 'artefact',
            'pluginname'         => 'file',
            'configdirs'         => array(get_config('libroot') . 'form/', get_config('docroot') . 'artefact/file/form/'),
533
534
            'group'              => $group,
            'institution'        => $institution,
535
536
537
538
539
540
            'elements'           => array(
                'filebrowser' => array(
                    'type'         => 'filebrowser',
                    'folder'       => $folder,
                    'highlight'    => $highlight,
                    'edit'         => $edit,
541
                    'page'         => $page,
542
543
                    'config'       => array(
                        'upload'          => true,
544
                        'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
545
546
547
548
549
550
551
552
553
                        'createfolder'    => true,
                        'edit'            => true,
                        'select'          => false,
                    ),
                ),
            ),
        );
        return $form;
    }
554

555
    public static function files_js() {
556
        return "function files_callback(form, data) { files_filebrowser.callback(form, data); }";
557
558
    }

559
    public static function count_user_files($owner=null, $group=null, $institution=null) {
560
        $filetypes = PluginArtefactFile::get_artefact_types();
561
562
563
564
565
566
567
        foreach ($filetypes as $k => $v) {
            if ($v == 'folder') {
                unset($filetypes[$k]);
            }
        }
        $filetypesql = "('" . join("','", $filetypes) . "')";

568
        $ownersql = artefact_owner_sql($owner, $group, $institution);
569
        return (object) array(
570
571
            'files'   => count_records_select('artefact', "artefacttype IN $filetypesql AND $ownersql", array()),
            'folders' => count_records_select('artefact', "artefacttype = 'folder' AND $ownersql", array())
572
573
574
        );
    }

575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
    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;
            }
        }

590
        $folderdata = self::artefactchooser_folder_data($artefact);
591
592

        if ($artefact->artefacttype == 'profileicon') {
593
            $artefact->description = str_shorten_text($artefact->title, 30);
594
595
596
        }
        else {
            $path = $artefact->parent ? self::get_full_path($artefact->parent, $folderdata->data) : '';
597
            $artefact->description = str_shorten_text($folderdata->ownername . $path . $artefact->title, 30);
598
599
600
601
602
        }

        return $artefact;
    }

603
    public static function artefactchooser_folder_data(&$artefact) {
604
605
606
607
608
609
610
611
        // 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);
612
            $folderdata[$ownerkey] = new stdClass();
613
614
615
616
617
618
            $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') {
619
                    $folderdata[$ownerkey]->ownername = get_config('sitename') . ':';
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
                }
                else {
                    $folderdata[$ownerkey]->ownername = get_field('institution', 'displayname', 'name', $artefact->institution) . ':';
                }
            }
            else {
                $folderdata[$ownerkey]->ownername = '';
            }
        }

        return $folderdata[$ownerkey];
    }

    /**
     * Works out a full path to a folder, given an ID. Implemented this way so 
     * only one query is made.
     */
637
    public static function get_full_path($id, &$folderdata) {
638
639
640
641
642
643
644
645
        $path = '';
        while (!empty($id)) {
            $path = $folderdata[$id]->title . '/' . $path;
            $id = $folderdata[$id]->parent;
        }
        return $path;
    }

646
    public function default_parent_for_copy(&$view, &$template, $artefactstoignore) {
647
        static $folderids;
648

649
650
651
652
        $viewid = $view->get('id');

        if (isset($folderids[$viewid])) {
            return $folderids[$viewid];
653
654
655
        }

        $viewfilesfolder = ArtefactTypeFolder::get_folder_id(get_string('viewfilesdirname', 'view'), get_string('viewfilesdirdesc', 'view'),
656
                                                             null, true, $view->get('owner'), $view->get('group'), $view->get('institution'), $artefactstoignore);
657
        $foldername = $viewid;
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
        $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();

681
        $folderids[$viewid] = $folder->get('id');
682

683
        return $folderids[$viewid];
684
685
    }

686
    /**
687
688
689
690
691
     * 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.
692
693
694
695
696
697
698
     * 
     * @param string $desired
     * @param integer $parent
     * @param integer $owner
     * @param integer $group
     * @param string $institution
     */
699
    public static function get_new_file_title($desired, $parent, $owner=null, $group=null, $institution=null) {
700
        $bits = split('\.', $desired);
701
        if (count($bits) > 1 && preg_match('/[^0-9]/', end($bits))) {
702
703
704
705
706
707
708
709
            $start = join('.', array_slice($bits, 0, count($bits)-1));
            $end = '.' . end($bits);
        }
        else {
            $start = $desired;
            $end = '';
        }

710
        $where = ($parent && is_int($parent)) ? "parent = $parent" : 'parent IS NULL';
711
        $where .=  ' AND ' . artefact_owner_sql($owner, $group, $institution);
712

713
714
        $taken = get_column_sql("
            SELECT title FROM {artefact}
715
            WHERE artefacttype IN ('" . join("','", PluginArtefactFile::get_artefact_types()) . "')
716
            AND title LIKE ? || '%' || ? AND " . $where, array($start, $end));
717
        $taken = array_flip($taken);
718
719
720

        $i = 0;
        $newname = $start . $end;
721
722
        while (isset($taken[$newname])) {
            $i++;
723
            $newname = $start . '.' . $i . $end;
724
725
726
        }
        return $newname;
    }
727

728
729
    public static function blockconfig_filebrowser_element(&$instance, $default=array()) {
        return array(
730
731
732
733
734
735
            'name'         => 'filebrowser',
            'type'         => 'filebrowser',
            'title'        => get_string('file', 'artefact.file'),
            'folder'       => (int) param_variable('folder', 0),
            'highlight'    => null,
            'browse'       => true,
736
            'page'         => get_config('wwwroot') . 'view/blocks.php' . View::make_base_url(),
737
738
739
740
741
            'config'       => array(
                'upload'          => true,
                'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
                'createfolder'    => false,
                'edit'            => false,
742
                'tag'             => true,
743
744
                'select'          => true,
                'alwaysopen'      => true,
745
                'publishing'      => true,
746
747
            ),
            'tabs'         => $instance->get_view()->ownership(),
748
749
            'defaultvalue' => $default,
            'selectlistcallback' => 'artefact_get_records_by_id',
750
751
752
        );
    }

753
754
}

755

756
class ArtefactTypeFile extends ArtefactTypeFileBase {
757

758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
    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

774
775
776
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
        
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
        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;
                }
            }
        }
    }

    /**
     * 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;
805

806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
        $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;
825
826
    }

827
    public static function get_file_directory($id) {
828
        return "artefact/file/originals/" . ($id % 256);
829
830
    }

831
    public function get_path() {
832
        return get_config('dataroot') . self::get_file_directory($this->fileid) . '/' .  $this->fileid;
833
834
    }

835

836
837
838
839
    /**
     * Test file type and return a new Image or File.
     */
    public static function new_file($path, $data) {
840
841
842
843
844
845
846
        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];
847
848
            return new ArtefactTypeImage(0, $data);
        }
849
850
851
852
853
854
855
856
857
858
859
860
861

        // If $data->filetype is set here, it's probably the claim made by the
        // browser during upload or by a Leap2a file.  Generally we believe this
        // claim, because it gives better results when serving the file on
        // download.  If there's no claimed mimetype, use file_mime_type to make
        // a guess, and give each file artefact type access to both the claimed
        // and guessed mimetypes.
        $data->guess = file_mime_type($path);

        if (empty($data->filetype) || $data->filetype == 'application/octet-stream') {
            $data->filetype = $data->guess;
        }

862
863
864
865
866
        foreach (array('video', 'audio', 'archive') as $artefacttype) {
            $classname = 'ArtefactType' . ucfirst($artefacttype);
            if (call_static_method($classname, 'is_valid_file', $path, &$data)) {
                return new $classname(0, $data);
            }
867
        }
868

869
870
871
        return new ArtefactTypeFile(0, $data);
    }

872
873
874
875
    /**
     * Moves a file into the myfiles area.
     * Takes the name of a file outside the myfiles area.
     * Returns a boolean indicating success or failure.
876
877
878
879
     *
     * Note: this method is crappy because it returns false instead of throwing 
     * exceptions. It's not used in many places, and should probably die in a 
     * future version. So think twice before using it :)
880
     */
881
    public static function save_file($pathname, $data, User &$user=null, $outsidedataroot=false) {
Hugh Davenport's avatar
Hugh Davenport committed
882
883
        global $USER;

884
        $dataroot = get_config('dataroot');
885
886
887
        if (!$outsidedataroot) {
            $pathname = $dataroot . $pathname;
        }
888
        if (!file_exists($pathname) || !is_readable($pathname)) {
889
890
            return false;
        }
891
        $size = filesize($pathname);
892
        $f = self::new_file($pathname, $data);
Richard Mansfield's avatar
Richard Mansfield committed
893
        $f->set('size', $size);
894
895
896
897
898
899

        // if an extension has been provided (only from self::extract() at this stage), use it
        if (!empty($data->extension)) {
            $f->set('oldextension', $data->extension);
        }

Richard Mansfield's avatar
Richard Mansfield committed
900
901
902
903
        $f->commit();
        $id = $f->get('id');

        $newdir = $dataroot . self::get_file_directory($id);
904
        check_dir_exists($newdir);
Richard Mansfield's avatar
Richard Mansfield committed
905
        $newname = $newdir . '/' . $id;
906
        if (!rename($pathname, $newname)) {
Richard Mansfield's avatar
Richard Mansfield committed
907
            $f->delete();
908
909
            return false;
        }
Hugh Davenport's avatar
Hugh Davenport committed
910
911
912
913
914
915
916
917
918
919
920
        $owner = null;
        if ($user) {
            $owner = $user;
        }
        else if ($data->owner == $USER->get('id')) {
            $owner = $USER;
            $owner->quota_refresh();
        }
        else if (!empty($data->owner)) {
            $owner = new User;
            $owner->find_by_id($data->owner);
921
922
        }
        try {
Hugh Davenport's avatar
Hugh Davenport committed
923
924
925
926
927
928
929
930
            if ($owner) {
                $owner->quota_add($size);
                $owner->commit();
            }
            else if (!empty($data->group)) {
                require_once('group.php');
                group_quota_add($data->group, $size);
            }
931
932
933
934
            return $id;
        }
        catch (QuotaExceededException $e) {
            $f->delete();
935
            return false;
936
937
        }
    }
Richard Mansfield's avatar
Richard Mansfield committed
938

939

940
    /**
Richard Mansfield's avatar
Richard Mansfield committed
941
942
     * Processes a newly uploaded file, copies it to disk, and creates
     * a new artefact object.
943
944
945
     * Takes the name of a file input.
     * Returns false for no errors, or a string describing the error.
     */
946
    public static function save_uploaded_file($inputname, $data, $inputindex=null) {
947
        require_once('uploadmanager.php');
948
        $um = new upload_manager($inputname, false, $inputindex);
949
        if ($error = $um->preprocess_file()) {
950
            throw new UploadException($error);
951
        }
952
953
954
955
956
957
958
959
960
961
        if (isset($inputindex)) {
            $size = $um->file['size'][$inputindex];
            $tmpname = $um->file['tmp_name'][$inputindex];
            $filetype = $um->file['type'][$inputindex];
        }
        else {
            $size = $um->file['size'];
            $tmpname = $um->file['tmp_name'];
            $filetype = $um->file['type'];
        }
962
963
964
965
        if (!empty($data->owner)) {
            global $USER;
            if ($data->owner == $USER->get('id')) {
                $owner = $USER;
966
                $owner->quota_refresh();
967
968
969
970
971
972
973
974
            }
            else {
                $owner = new User;
                $owner->find_by_id($data->owner);
            }
            if (!$owner->quota_allowed($size)) {
                throw new QuotaExceededException(get_string('uploadexceedsquota', 'artefact.file'));
            }
Richard Mansfield's avatar
Richard Mansfield committed
975
        }
Hugh Davenport's avatar
Hugh Davenport committed
976
977
978
979
980
981
        if (!empty($data->group)) {
            require_once('group.php');
            if (!group_quota_allowed($data->group, $size)) {
                throw new QuotaExceededException(get_string('uploadexceedsquota', 'artefact.file'));
            }
        }
982
        $data->size = $size;
983
        $data->filetype = $filetype;
984
        $data->oldextension = $um->original_filename_extension();
985
        $f = self::new_file($tmpname, $data);
986
987
988
989
990
991
        $f->commit();
        $id = $f->get('id');
        // Save the file using its id as the filename, and use its id modulo
        // the number of subdirectories as the directory name.
        if ($error = $um->save_file(self::get_file_directory($id) , $id)) {
            $f->delete();
992
            throw new UploadException($error);
993
        }
994
        else if (isset($owner)) {
995
996
            $owner->quota_add($size);
            $owner->commit();
Richard Mansfield's avatar
Richard Mansfield committed
997
        }
Hugh Davenport's avatar
Hugh Davenport committed
998
999
1000
        else if (!empty($data->group)) {
            group_quota_add($data->group, $size);
        }
1001
        return $id;
1002
    }
Richard Mansfield's avatar
Richard Mansfield committed
1003

1004

1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
    // Return the title with the original extension appended to it if
    // it's not already there.
    public function download_title() {
        $extn = $this->get('oldextension');
        $name = $this->get('title');
        if (substr($name, -1-strlen($extn)) == '.' . $extn) {
            return $name;
        }
        return $name . (substr($name, -1) == '.' ? '' : '.') . $extn;
    }

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
    public function render_self($options) {
        $options['id'] = $this->get('id');

        $downloadpath = get_config('wwwroot') . 'artefact/file/download.php?file=' . $this->get('id');
        if (isset($options['viewid'])) {
            $downloadpath .= '&view=' . $options['viewid'];
        }
        $filetype = get_string($this->get('oldextension'), 'artefact.file');
        if (substr($filetype, 0, 2) == '[[') {
            $filetype = $this->get('oldextension') . ' ' . get_string('file', 'artefact.file');
        }

        $smarty = smarty_core();
        $smarty->assign('iconpath', $this->get_icon($options));
        $smarty->assign('downloadpath', $downloadpath);
        $smarty->assign('filetype', $filetype);
        $smarty->assign('ownername', $this->display_owner());
        $smarty->assign('created', strftime(get_string('strftimedaydatetime'), $this->get('ctime')));
        $smarty->assign('modified', strftime(get_string('strftimedaydatetime'), $this->get('mtime')));
        $smarty->assign('size', $this->describe_size() . ' (' . $this->get('size') . ' ' . get_string('bytes', 'artefact.file') . ')');

        foreach (array('title', 'description', 'artefacttype', 'owner', 'tags') as $field) {
            $smarty->assign($field, $this->get($field));
        }

        return array('html' => $smarty->fetch('artefact:file:file_render_self.tpl'), 'javascript' => '');
    }

1044

1045
    public static function get_admin_files($public) {
1046
        $pubfolder = ArtefactTypeFolder::admin_public_folder_id();
1047
        $artefacts = get_records_sql_assoc("
1048
            SELECT
1049
                a.id, a.title, a.parent, a.artefacttype
1050
            FROM {artefact} a
1051
                LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
1052
            WHERE a.institution = 'mahara'", array());
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074

        $files = array();
        if (!empty($artefacts)) {
            foreach ($artefacts as $a) {
                if ($a->artefacttype != 'folder') {
                    $title = $a->title;
                    $parent = $a->parent;
                    while (!empty($parent)) {
                        if ($public && $parent == $pubfolder) {
                            $files[] = array('name' => $title, 'id' => $a->id);
                            continue 2;
                        }
                        $title = $artefacts[$parent]->title . '/' . $title;
                        $parent = $artefacts[$parent]->parent;
                    }
                    if (!$public) {
                        $files[] = array('name' => $title, 'id' => $a->id);
                    }
                }
            }
        }
        return $files;
1075
    }
Richard Mansfield's avatar
Richard Mansfield committed
1076

1077
1078
1079
1080
    public function delete() {
        if (empty($this->id)) {
            return; 
        }
Richard Mansfield's avatar
Richard Mansfield committed
1081
        $file = $this->get_path();
1082
1083
        if (is_file($file)) {
            $size = filesize($file);
1084
1085
1086
1087
            // Only delete the file on disk if no other artefacts point to it
            if (count_records('artefact_file_files', 'fileid', $this->get('id')) == 1) {
                unlink($file);
            }