lib.php 44 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
5
 *
Francois Marier's avatar
Francois Marier committed
6
7
8
9
 * 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.
10
 *
Francois Marier's avatar
Francois Marier committed
11
12
13
14
 * 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.
15
 *
Francois Marier's avatar
Francois Marier committed
16
17
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19
20
 *
 * @package    mahara
 * @subpackage artefact-internal
21
 * @author     Catalyst IT Ltd
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
24
25
26
27
28
 *
 */

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

29
30
31
class PluginArtefactFile extends PluginArtefact {

    public static function get_artefact_types() {
32
33
34
35
36
        return array(
            'file',
            'folder',
            'image',
        );
37
    }
38
39
    
    public static function get_block_types() {
40
        return array('image');
41
    }
42
43
44
45
46
47

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

    public static function menu_items() {
Richard Mansfield's avatar
Richard Mansfield committed
48
49
        return array(
            array(
50
51
                'path' => 'myportfolio/files',
                'url' => 'artefact/file/',
52
                'title' => get_string('myfiles', 'artefact.file'),
53
54
                'weight' => 20,
            ),
Richard Mansfield's avatar
Richard Mansfield committed
55
        );
56
    }
57

58
59
    public static function group_tabs($groupid) {
        return array(
60
            'files' => array(
61
                'path' => 'groups/files',
62
63
                'url' => 'artefact/file/groupfiles.php?group='.$groupid,
                'title' => get_string('Files', 'artefact.file'),
64
                'weight' => 60,
65
66
67
68
            ),
        );
    }

69
70
71
72
73
74
75
76
77
78
79
80
    public static function get_event_subscriptions() {
        $subscriptions = array(
            (object)array(
                'plugin'       => 'file',
                'event'        => 'createuser',
                'callfunction' => 'newuser',
            ),
        );

        return $subscriptions;
    }

81
82
    public static function postinst($prevversion) {
        if ($prevversion == 0) {
83
            set_config_plugin('artefact', 'file', 'defaultquota', 52428800);
84
        }
85
        self::resync_filetype_list();
86
87
    }

88
    public static function newuser($event, $user) {
89
90
91
        if (empty($user->quota)) {
            update_record('usr', array('quota' => get_config_plugin('artefact', 'file', 'defaultquota')), array('id' => $user['id']));
        }
92
    }
93
    
Richard Mansfield's avatar
Richard Mansfield committed
94

95
96
97
98
99
100
101
102
103
    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
104

Martyn Smith's avatar
Martyn Smith committed
105
106
107
108
109
110
111
112
113
114
115
    public static function themepaths($type) {
        static $themepaths = array(
            'file' => array(
                'images/file.gif',
                'images/folder.gif',
                'images/image.gif',
            ),
        );
        return $themepaths[$type];
    }

116
117
    public static function jsstrings($type) {
        static $jsstrings = array(
118
            'file' => array(
119
120
121
122
                'mahara' => array(
                    'cancel',
                    'delete',
                    'edit',
Richard Mansfield's avatar
Richard Mansfield committed
123
124
                    'Permissions',
                    'republish',
125
                    'tags',
Richard Mansfield's avatar
Richard Mansfield committed
126
                    'view',
127
128
                ),
                'artefact.file' => array(
129
                    'copyrightnotice',
130
131
132
133
                    'create',
                    'createfolder',
                    'deletefile?',
                    'deletefolder?',
134
                    'Description',
135
136
137
                    'destination',
                    'editfile',
                    'editfolder',
138
                    'File',
139
                    'fileexistsoverwritecancel',
140
                    'filenamefieldisrequired',
141
                    'home',
142
                    'Name',
143
144
145
146
                    'namefieldisrequired',
                    'nofilesfound',
                    'overwrite',
                    'savechanges',
147
                    'timeouterror',
148
149
                    'title',
                    'titlefieldisrequired',
150
                    'unlinkthisfilefromblogposts?',
151
152
153
154
155
                    'upload',
                    'uploadfile',
                    'uploadfileexistsoverwritecancel',
                    'uploadingfiletofolder',
                    'youmustagreetothecopyrightnotice',
156
                ),
Richard Mansfield's avatar
Richard Mansfield committed
157
158
159
                'group' => array(
                    'Role',
                ),
160
            ),
161
162
163
        );
        return $jsstrings[$type];
    }
164

165
166
167
168
169
170
171
    public static function jshelp($type) {
        static $jshelp = array(
            'file' => array(
                'artefact.file' => array(
                    'notice',
                    'quota_message',
                    'uploadfile',
172
                    'tags',
173
174
175
176
177
178
                ),
            ),
        );
        return $jshelp[$type];
    }

179
180
181
182
183
184
185
186
187
188
189
190

    /**
     * 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();
        log_info('Beginning resync of filetype list');

191
        $currentlist = get_column('artefact_file_file_types', 'description');
192
193
194
195
196
197
198
199
200
201
202
203
204
205
        $newlist     = xmlize(file_get_contents(get_config('docroot') . 'artefact/file/filetypes.xml'));
        $filetypes = $newlist['filetypes']['#']['filetype'];
        $newfiletypes = array();

        // Step one: if a filetype is in the new list that is not in the current
        // list, add it to the current list.
        foreach ($filetypes as $filetype) {
            $type = $filetype['#']['description'][0]['#'];
            if (!in_array($type, $currentlist)) {
                log_debug('Adding filetype: ' . $type);
                $currentlist[] = $type;
                $record = new StdClass;
                $record->description = $type;
                $record->enabled     = $filetype['#']['enabled'][0]['#'];
206
                insert_record('artefact_file_file_types', $record);
207
208
209
210
211
212
213
214
215
216
            }
            $newfiletypes[] = $type;
        }

        // Step two: If a filetype is in the current list that is not in the
        // new list, remove it from the current list.
        foreach ($currentlist as $key => $type) {
            if (!in_array($type, $newfiletypes)) {
                log_debug('Removing filetype: ' . $type);
                unset($currentlist[$key]);
217
218
                delete_records('artefact_file_mime_types', 'description', $type);
                delete_records('artefact_file_file_types', 'description', $type);
219
220
221
222
223
224
            }
        }


        // Get a list of all current mimetypes for each file type
        $currentmimetypes = array();
225
        $dbmimetypes = get_records_array('artefact_file_mime_types');
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
        if ($dbmimetypes) {
            foreach ($dbmimetypes as $mimetype) {
                $currentmimetypes[$mimetype->description][] = $mimetype->mimetype;
            }
        }
        unset($dbmimetypes);

        // Step three: For each filetype in the current list, update the mime
        // types allowed for it if necessary
        foreach ($currentlist as $description) {
            // Get the new mime types
            $newmimetypes = array();
            foreach ($filetypes as $filetype) {
                if ($filetype['#']['description'][0]['#'] == $description) {
                    foreach ($filetype['#']['mimetypes'][0]['#']['mimetype'] as $mimetype) {
                        $newmimetypes[] = $mimetype['#'];
                    }
                }
            }

            // Roll up roll up to see the famous array_equals implementation!
            // You'd think PHP would have a way to do this, but I couldn't find
            // it...
            sort($newmimetypes);
            if (isset($currentmimetypes[$description])) {
                sort($currentmimetypes[$description]);
            }

            if ((!isset($currentmimetypes[$description]) && $newmimetypes)
                || ((join('', $currentmimetypes[$description]) != join('', $newmimetypes)))) {
                log_debug('Need to update mime types for ' . $description);
257
                delete_records('artefact_file_mime_types', 'description', $description);
258
259
260
261
                foreach ($newmimetypes as $newmimetype) {
                    $record = new StdClass;
                    $record->mimetype    = $newmimetype;
                    $record->description = $description;
262
                    insert_record('artefact_file_mime_types', $record);
263
264
265
266
267
268
269
270
                }
            }
        }
       
        db_commit();
        //db_rollback();
    }

271
272
}

Martyn Smith's avatar
Martyn Smith committed
273
abstract class ArtefactTypeFileBase extends ArtefactType {
274

Richard Mansfield's avatar
Richard Mansfield committed
275
    protected $size;
276
277
278
279
280
    // 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.
281
    protected $oldextension;
Richard Mansfield's avatar
Richard Mansfield committed
282
283
284
285
286
287
288
289
290
291
292

    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
        
        if (empty($this->id)) {
            $this->locked = 0;
        }

        if ($this->id && ($filedata = get_record('artefact_file_files', 'artefact', $this->id))) {
            foreach($filedata as $name => $value) {
                if (property_exists($this, $name)) {
293
                    $this->{$name} = $value;
Richard Mansfield's avatar
Richard Mansfield committed
294
295
296
297
298
299
                }
            }
        }

    }

300
301
302
303
304
    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'])) {
305
            $downloadpath .= '&view=' . $options['viewid'];
306
        }
307
308
309
310
311
        $filetype = get_string($this->get('oldextension'), 'artefact.file');
        if (substr($filetype, 0, 2) == '[[') {
            $filetype = $this->get('oldextension') . ' ' . get_string('file', 'artefact.file');
        }

312
313
314
        $smarty = smarty_core();
        $smarty->assign('iconpath', $this->get_icon($options));
        $smarty->assign('downloadpath', $downloadpath);
315
        $smarty->assign('filetype', $filetype);
316
        $smarty->assign('owner', $this->display_owner());
317
318
319
320
321
322
323
324
325
326
327
        $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') as $field) {
            $smarty->assign($field, $this->get($field));
        }

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

Richard Mansfield's avatar
Richard Mansfield committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
    /**
     * 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);

        $this->mtime = time();

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

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

        $data = (object)array(
            'artefact'      => $this->get('id'),
            'size'          => $this->get('size'),
353
            'oldextension'  => $this->get('oldextension')
Richard Mansfield's avatar
Richard Mansfield committed
354
355
356
357
358
359
360
361
362
363
364
365
        );

        if ($new) {
            insert_record('artefact_file_files', $data);
        }
        else {
            update_record('artefact_file_files', $data, 'artefact');
        }

        $this->dirty = false;
    }

Nigel McNie's avatar
Nigel McNie committed
366
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
367
368
369
        return false;
    }

370
    public static function get_icon($options=null) {
371
372
373
374
375
376
377

    }

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

Richard Mansfield's avatar
Richard Mansfield committed
378
379
380
381
382
383
    public function move($newparentid) {
        $this->set('parent', $newparentid);
        $this->commit();
        return true;
    }

384
385
    public function delete() {
        if (empty($this->id)) {
Richard Mansfield's avatar
Richard Mansfield committed
386
            return; 
387
        }
388
389
390
391
        try {
            delete_records('artefact_blog_blogpost_file', 'file', $this->id);
        } 
        catch ( Exception $e ) {}
392
393
394
395
        delete_records('artefact_file_files', 'artefact', $this->id);
        parent::delete();
    }

Richard Mansfield's avatar
Richard Mansfield committed
396
397
    // 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
398
    public static function file_exists($title, $owner, $folder, $institution=null, $group=null) {
399
        $filetypesql = "('" . join("','", PluginArtefactFile::get_artefact_types()) . "')";
400
        $ownersql = artefact_owner_sql($owner, $group, $institution);
401
402
        return get_field_sql('SELECT a.id FROM {artefact} a
            LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
403
            WHERE a.title = ?
404
            AND a.' . $ownersql . '
Richard Mansfield's avatar
Richard Mansfield committed
405
            AND a.parent ' . (empty($folder) ? ' IS NULL' : ' = ' . $folder) . '
406
            AND a.artefacttype IN ' . $filetypesql, array($title));
407
408
    }

409
410
411
412
413
414
415
416

    // Sort folders before files; then use nat sort order.
    public static function my_files_cmp($a, $b) {
        return strnatcasecmp((int)($a->artefacttype != 'folder') . $a->title,
                             (int)($b->artefacttype != 'folder') . $b->title);
    }


Richard Mansfield's avatar
Richard Mansfield committed
417
    public static function get_my_files_data($parentfolderid, $userid, $institution=null, $group=null) {
418

Richard Mansfield's avatar
Richard Mansfield committed
419
        $select = '
Richard Mansfield's avatar
Richard Mansfield committed
420
            SELECT
421
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description,
Richard Mansfield's avatar
Richard Mansfield committed
422
423
                COUNT(c.id) AS childcount, COUNT (b.blogpost) AS attachcount';
        $from = '
424
425
            FROM {artefact} a
                LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
Richard Mansfield's avatar
Richard Mansfield committed
426
427
428
429
430
                LEFT OUTER JOIN {artefact} c ON c.parent = a.id 
                LEFT OUTER JOIN {artefact_blog_blogpost_file} b ON b.file = a.id';
        $where = "
            WHERE a.artefacttype IN ('" . join("','", PluginArtefactFile::get_artefact_types()) . "')";
        $groupby = '
431
            GROUP BY
Richard Mansfield's avatar
Richard Mansfield committed
432
433
434
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description';

        $phvals = array();
435

Richard Mansfield's avatar
Richard Mansfield committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
        if ($institution) {
            $where .= '
            AND a.institution = ? AND a.owner IS NULL';
            $phvals[] = $institution;
        }
        else if ($group) {
            global $USER;
            $select .= ',
                r.can_edit, r.can_view';
            $from .= '
                LEFT OUTER JOIN (
                    SELECT ar.artefact, ar.can_edit, ar.can_view
                    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 .= '
            AND a.group = ? AND a.owner IS NULL AND r.can_view = 1';
            $phvals[] = $group;
            $groupby .= ', r.can_edit, r.can_view';
        }
        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';
        }
474

Richard Mansfield's avatar
Richard Mansfield committed
475
        $filedata = get_records_sql_assoc($select . $from . $where . $groupby, $phvals);
476
477
478
479
480
        if (!$filedata) {
            $filedata = array();
        }
        else {
            foreach ($filedata as $item) {
Richard Mansfield's avatar
Richard Mansfield committed
481
                $item->mtime = format_date(strtotime($item->mtime), 'strfdaymonthyearshort');
Richard Mansfield's avatar
Richard Mansfield committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
                $item->tags = array();
            }
            $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
                        );
                    }
501
                }
502
            }
Richard Mansfield's avatar
Richard Mansfield committed
503
            $filedata = array_values($filedata);
504
505
        }

Richard Mansfield's avatar
Richard Mansfield committed
506
507
508
509
510
511
512
513
514
515
516
517
        // Add parent folder to the list
        if (!empty($parentfolderid)) {
            $grandparentid = get_field('artefact', 'parent', 'id', $parentfolderid);
            $filedata[] = (object) array(
                'title'        => '..',
                'artefacttype' => 'folder',
                'description'  => get_string('parentfolder', 'artefact.file'),
                'isparent'     => true,
                'id'           => (int) $grandparentid
            );
        }

518
        usort($filedata, array("ArtefactTypeFileBase", "my_files_cmp"));
519
520
        return $filedata;
    }
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569


    public static function get_my_files_js($folder_id=null) {

        global $USER;

        if ($folder_id) {
            $folder_list = array();

            $current_folder = artefact_instance_from_id($folder_id);

            if ($USER->can_view_artefact($current_folder)) {

                if ($current_folder->get('artefacttype') == 'folder') {
                    $folder_list[] = array(
                        'id'   => $current_folder->get('id'),
                        'name' => $current_folder->get('title'),
                    );
                }

                while ($p = $current_folder->get('parent')) {
                    $current_folder = artefact_instance_from_id($p);

                    $folder_list[] = array(
                        'id'   => $current_folder->get('id'),
                        'name' => $current_folder->get('title'),
                    );
                }
            }

            $enc_folders = json_encode(array_reverse($folder_list));
        }
        else {
            $enc_folders = json_encode(array());
        }

        $copyright = get_field('site_content', 'content', 'name', 'uploadcopyright');

        $javascript = <<<JAVASCRIPT
var copyrightnotice = '{$copyright}';
var browser = new FileBrowser('filelist', 'myfiles.json.php', null, null, null, null, {$enc_folders});
var uploader = new FileUploader('uploader', 'upload.php', {}, null, null, browser.refresh, browser.fileexists);
browser.changedircallback = uploader.updatedestination;

JAVASCRIPT;

        return $javascript;
    }

570
    public static function count_user_files($owner=null, $group=null, $institution=null) {
571
572
573
574
575
576
577
578
        $filetypes = PluginArtefactFile::get_artefact_types();
        foreach ($filetypes as $k => $v) {
            if ($v == 'folder') {
                unset($filetypes[$k]);
            }
        }
        $filetypesql = "('" . join("','", $filetypes) . "')";

579
        $ownersql = artefact_owner_sql($owner, $group, $institution);
580
        return (object) array(
581
582
            'files'   => count_records_select('artefact', "artefacttype IN $filetypesql AND $ownersql", array()),
            'folders' => count_records_select('artefact', "artefacttype = 'folder' AND $ownersql", array())
583
584
585
        );
    }

586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
    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;
            }
        }

601
        $folderdata = self::artefactchooser_folder_data($artefact);
602
603

        if ($artefact->artefacttype == 'profileicon') {
604
            $artefact->description = str_shorten($artefact->title, 30);
605
606
607
        }
        else {
            $path = $artefact->parent ? self::get_full_path($artefact->parent, $folderdata->data) : '';
608
            $artefact->description = str_shorten($folderdata->ownername . $path . $artefact->title, 30);
609
610
611
612
613
        }

        return $artefact;
    }

614
    public static function artefactchooser_folder_data(&$artefact) {
615
616
617
618
619
620
621
622
623
624
625
626
627
628
        // 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);
            $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') {
629
                    $folderdata[$ownerkey]->ownername = get_config('sitename') . ':';
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
                }
                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.
     */
647
    public static function get_full_path($id, &$folderdata) {
648
649
650
651
652
653
654
655
        $path = '';
        while (!empty($id)) {
            $path = $folderdata[$id]->title . '/' . $path;
            $id = $folderdata[$id]->parent;
        }
        return $path;
    }

656
657
}

658
class ArtefactTypeFile extends ArtefactTypeFileBase {
659

660
661
662
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
        
Richard Mansfield's avatar
Richard Mansfield committed
663
664
        if (empty($this->id)) {
            $this->container = 0;
665
        }
666

667
668
    }

669
    public static function get_file_directory($id) {
670
        return "artefact/file/originals/" . ($id % 256);
671
672
    }

673
674
    public function get_path() {
        return get_config('dataroot') . self::get_file_directory($this->id) . '/' .  $this->id;
675
676
    }

677
678
679
680
681
682
683
684
    public static function detect_artefact_type($file) {
        require_once('file.php');
        if (ArtefactTypeImage::is_image_mime_type(get_mime_type(get_config('dataroot') . $file))) {
            return 'image';
        }
        return 'file';
    }

685
686
687
688
    /**
     * Test file type and return a new Image or File.
     */
    public static function new_file($path, $data) {
Richard Mansfield's avatar
Richard Mansfield committed
689
690
        require_once('file.php');
        $type = get_mime_type($path);
691
        if (ArtefactTypeImage::is_image_mime_type($type)) {
692
            list($data->width, $data->height) = getimagesize($path);
693
694
695
696
697
            return new ArtefactTypeImage(0, $data);
        }
        return new ArtefactTypeFile(0, $data);
    }

698
699
700
701
702
    /**
     * Moves a file into the myfiles area.
     * Takes the name of a file outside the myfiles area.
     * Returns a boolean indicating success or failure.
     */
703
    public static function save_file($pathname, $data, User &$user=null) {
704
705
706
        // This is only used when blog posts are saved: Files which
        // have been uploaded to the post are moved to a permanent
        // location in the files area using this function. 
707
708
709
710
711
        $dataroot = get_config('dataroot');
        $pathname = $dataroot . $pathname;
        if (!$size = filesize($pathname)) {
            return false;
        }
712
        $f = self::new_file($pathname, $data);
Richard Mansfield's avatar
Richard Mansfield committed
713
714
715
716
717
        $f->set('size', $size);
        $f->commit();
        $id = $f->get('id');

        $newdir = $dataroot . self::get_file_directory($id);
718
        check_dir_exists($newdir);
Richard Mansfield's avatar
Richard Mansfield committed
719
        $newname = $newdir . '/' . $id;
720
        if (!rename($pathname, $newname)) {
Richard Mansfield's avatar
Richard Mansfield committed
721
            $f->delete();
722
723
724
725
726
727
728
729
730
731
732
733
734
            return false;
        }
        if (empty($user)) {
            global $USER;
            $user = $USER;
        }
        try {
            $user->quota_add($size);
            $user->commit();
            return $id;
        }
        catch (QuotaExceededException $e) {
            $f->delete();
735
            return false;
736
737
        }
    }
Richard Mansfield's avatar
Richard Mansfield committed
738

739

740
    /**
Richard Mansfield's avatar
Richard Mansfield committed
741
742
     * Processes a newly uploaded file, copies it to disk, and creates
     * a new artefact object.
743
744
745
746
747
748
749
750
751
     * Takes the name of a file input.
     * Returns false for no errors, or a string describing the error.
     */
    public static function save_uploaded_file($inputname, $data) {
        require_once('uploadmanager.php');
        $um = new upload_manager($inputname);
        if ($error = $um->preprocess_file()) {
            return $error;
        }
Richard Mansfield's avatar
Richard Mansfield committed
752
        $size = $um->file['size'];
753
        global $USER;
754
        if (!$USER->quota_allowed($size) && !$data->institution) {
755
            return get_string('uploadexceedsquota', 'artefact.file');
Richard Mansfield's avatar
Richard Mansfield committed
756
757
758
        }
        $f = self::new_file($um->file['tmp_name'], $data);
        $f->set('size', $size);
759
        $f->set('oldextension', $um->original_filename_extension());
760
761
762
763
764
765
766
        $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();
        }
Richard Mansfield's avatar
Richard Mansfield committed
767
768
        else {
            $USER->quota_add($size);
769
            $USER->commit();
Richard Mansfield's avatar
Richard Mansfield committed
770
        }
771
772
        return $error;
    }
Richard Mansfield's avatar
Richard Mansfield committed
773

774

775
776
777
778
779
780
781
782
783
784
785
    // 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;
    }

786

787
    public static function get_admin_files($public) {
788
        $pubfolder = ArtefactTypeFolder::admin_public_folder_id();
789
        $artefacts = get_records_sql_assoc("
790
            SELECT
791
                a.id, a.title, a.parent, a.artefacttype
792
793
            FROM {artefact} a
                INNER JOIN {artefact_file_files} f ON f.artefact = a.id
794
            WHERE a.institution = 'mahara'", array());
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816

        $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;
817
    }
Richard Mansfield's avatar
Richard Mansfield committed
818

819
820
821
822
    public function delete() {
        if (empty($this->id)) {
            return; 
        }
Richard Mansfield's avatar
Richard Mansfield committed
823
        $file = $this->get_path();
824
825
        // Detach this file from any view feedback
        set_field('view_feedback', 'attachment', null, 'attachment', $this->id);
826
827
828
829
830
        if (is_file($file)) {
            $size = filesize($file);
            unlink($file);
            global $USER;
            // Deleting other users' files won't lower their quotas yet...
831
            if (!$this->institution && $USER->id == $this->get('owner')) {
832
833
                $USER->quota_remove($size);
                $USER->commit();
834
            }
Richard Mansfield's avatar
Richard Mansfield committed
835
        }
836
837
838
        parent::delete();
    }

839
840
841
842
    public static function has_config() {
        return true;
    }

843
    public static function get_icon($options=null) {
844
        return theme_get_url('images/file.gif');
845
846
    }

847
    public static function get_config_options() {
848
        $elements = array();
849
850
851
852
        $defaultquota = get_config_plugin('artefact', 'file', 'defaultquota');
        if (empty($defaultquota)) {
            $defaultquota = 1024 * 1024 * 10;
        }
853
854
855
        $elements['quotafieldset'] = array(
            'type' => 'fieldset',
            'legend' => get_string('defaultquota', 'artefact.file'),
856
            'elements' => array(
857
858
859
                'defaultquotadescription' => array(
                    'value' => '<tr><td colspan="2">' . get_string('defaultquotadescription', 'artefact.file') . '</td></tr>'
                ),
860
861
862
863
                'defaultquota' => array(
                    'title'        => get_string('defaultquota', 'artefact.file'), 
                    'type'         => 'bytes',
                    'defaultvalue' => $defaultquota,
864
                )
865
            ),
866
867
868
869
870
871
            'collapsible' => true
        );


        // Allowed file types
        $filetypes = array();
872
        foreach (get_records_array('artefact_file_file_types', null, null, 'description') as $filetype) {
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
            $filetype->description = preg_replace('/[^a-zA-Z0-9_]/', '_', $filetype->description);
            $filetypes[$filetype->description] = array(
                'type'  => 'checkbox',
                'title' => get_string($filetype->description, 'artefact.file'),
                'defaultvalue' => $filetype->enabled
            );
        }
        uasort($filetypes, create_function('$a, $b', 'return $a["title"] > $b["title"];'));
        $filetypes = array_merge(array(
            'filetypedescription' => array(
                'value' => '<tr><td colspan="2">' . get_string('filetypedescription', 'artefact.file') . '</td></tr>'
            )
        ), $filetypes);
        $elements['filetypes'] = array(
            'type' => 'fieldset',
            'legend' => get_string('filetypes', 'artefact.file'),
            'elements' => $filetypes,
            'collapsible' => true,
            'collapsed' => true
        );
 
        return array(
            'elements' => $elements,
            'renderer' => 'table'
897
898
899
900
901
        );
    }

    public static function save_config_options($values) {
        set_config_plugin('artefact', 'file', 'defaultquota', $values['defaultquota']);
902
        foreach (get_records_array('artefact_file_file_types') as $filetype) {
903
904
            $key = preg_replace('/[^a-zA-Z0-9_]/', '_', $filetype->description);
            $filetype->enabled = intval($values[$key]);
905
            update_record('artefact_file_file_types', $filetype, 'description');
906
        }
907
    }
908

Richard Mansfield's avatar
Richard Mansfield committed
909
    public function describe_size() {
910
911
912
913
914
        $bytes = $this->get('size');
        if ($bytes < 1024) {
            return $bytes <= 0 ? '0' : ($bytes . ' ' . get_string('bytes', 'artefact.file'));
        }
        if ($bytes < 1048576) {
915
            return floor(($bytes / 1024) * 10 + 0.5) / 10 . 'K';
916
917
918
919
        }
        return floor(($bytes / 1048576) * 10 + 0.5) / 10 . 'M';
    }

Martyn Smith's avatar
Martyn Smith committed
920
921
922
923
924
925
926
927
    public static function get_links($id) {
        $wwwroot = get_config('wwwroot');

        return array(
            '_default' => $wwwroot . 'artefact/file/download.php?file=' . $id,
            get_string('folder', 'artefact.file') => $wwwroot . 'artefact/file/?folder=' . $id,
        );
    }
928
929
930
931
932
933
934
935
936
937
938
939
940
941

    public function override_content_type() {
        static $extensions;
        if (empty($extensions)) {
            $extensions = array(
                'wmv' => 'video/x-ms-wmv',
                'flv' => 'video/x-flv',
            );
        }
        if (array_key_exists($this->get('oldextension'), $extensions)) {
            return $extensions[$this->get('oldextension')];
        }
        return false;
    }
942
943
944
945

    public static function get_quota_usage($artefact) {
        return get_field('artefact_file_files', 'size', 'artefact', $artefact);
    }
Richard Mansfield's avatar
Richard Mansfield committed
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964

    public function copy_extra($new) {
        $oldid = $this->get('id');
        $dataroot = get_config('dataroot');
        $oldfile = $dataroot . self::get_file_directory($oldid) . '/' . $oldid;
        $newid = $new->get('id');
        $newdir = $dataroot . self::get_file_directory($newid);
        check_dir_exists($newdir);
        if (!copy($oldfile, $newdir . '/' . $newid)) {
            throw new SystemException('failed copying file artefact');
        }
        global $USER;
        if ($new->get('owner') && $new->get('owner') == $USER->get('id')) {
            $USER->quota_add($new->get('size'));
            $USER->commit();
        }
        return;
    }

Richard Mansfield's avatar
Richard Mansfield committed
965
966
967
968
    // Only changes to group files get put in the artefact_log table
    public function can_be_logged() {
        return (bool) $this->get('group');
    }
969
}
970
971
972

class ArtefactTypeFolder extends ArtefactTypeFileBase {

973
974
975
976
    public function __construct($id = 0, $data = null) {

        parent::__construct($id, $data);

Richard Mansfield's avatar
Richard Mansfield committed
977
978
979
980
        if (empty($this->id)) {
            $this->container = 1;
            $this->size = null;
        }
981
982
983

    }

984
    public function folder_contents() {
985
        return get_records_array('artefact', 'parent', $this->get('id'));
986
987
    }

988
989
990
991
992
    public function render_self($options) {
        $smarty = smarty_core();
        $smarty->assign('title', $this->get('title'));
        $smarty->assign('description', $this->get('description'));
        $smarty->assign('viewid', $options['viewid']);
993
        $smarty->assign('simpledisplay', isset($options['simpledisplay']) ? $options['simpledisplay'] : false);
994
995
996
997
998
999
1000

        if ($childrecords = $this->folder_contents()) {
            $this->add_to_render_path($options);
            usort($childrecords, array('ArtefactTypeFileBase', 'my_files_cmp'));
            $children = array();
            foreach ($childrecords as &$child) {
                $c = artefact_instance_from_id($child->id);
1001
1002
1003
1004
                $child->title = $child->hovertitle = $c->get('title');
                if (!empty($options['simpledisplay'])) {
                    $child->title = str_shorten($child->title, 20);
                }
1005
1006
1007
1008
1009
1010
1011
1012
1013
                $child->date = format_date(strtotime($child->mtime), 'strfdaymonthyearshort');
                $child->iconsrc = call_static_method(generate_artefact_class_name($child->artefacttype), 'get_icon', array('id' => $child->id, 'viewid' => $options['viewid']));
            }
            $smarty->assign('children', $childrecords);
        }
        return array('html' => $smarty->fetch('artefact:file:folder_render_self.tpl'),
                     'javascript' => null);
    }

Richard Mansfield's avatar
Richard Mansfield committed
1014
1015
1016
1017
    public function describe_size() {
        return $this->count_children() . ' ' . get_string('files', 'artefact.file');
    }

1018
    public static function get_icon($options=null) {
1019
        return theme_get_url('images/folder.gif');
1020
1021
1022
1023
1024
1025
    }

    public static function collapse_config() {
        return 'file';
    }
    
1026
    public static function admin_public_folder_id() {
1027
1028
1029
1030
        // There is one public files directory and many admins, so the
        // name of the directory uses the site language rather than
        // the language of the admin who first creates it.
        $name = get_string_from_language(get_config('lang'), 'adminpublicdirname', 'admin');
1031
        $folderid = get_field_sql("
1032
1033
           SELECT
             a.id
1034
1035
           FROM {artefact} a
             INNER JOIN {artefact_file_files} f ON a.id = f.artefact
1036
1037
           WHERE a.title = ?
             AND a.artefacttype = ?
1038
1039
             AND a.institution = 'mahara'
             AND a.parent IS NULL", array($name, 'folder'));
1040
1041
        if (!$folderid) {
            global $USER;
1042
            if ($USER->get('admin')) {
1043
1044
                $description = get_string_from_language(get_config('lang'), 
                                                        'adminpublicdirdescription', 'admin');
1045
1046
                $data = (object) array('title' => $name,
                                       'description' => $description,
1047
                                       'institution' => 'mahara');
1048
1049
1050
1051
1052
1053
                $f = new ArtefactTypeFolder(0, $data);
                $f->commit();
                $folderid = $f->get('id');
            } else {
                return false;
            }
1054
1055
1056
1057
        }
        return $folderid;
    }

1058
1059
    public static function change_public_folder_name($oldlang, $newlang) {
        $oldname = get_string_from_language($oldlang, 'adminpublicdirname', 'admin');
1060
        $folderid = get_field_sql("
1061
1062
1063
1064
1065
1066
           SELECT
             a.id
           FROM {artefact} a
             INNER JOIN {artefact_file_files} f ON a.id = f.artefact
           WHERE a.title = ?
             AND a.artefacttype = ?
1067
1068
             AND a.institution = 'mahara'
             AND a.parent IS NULL", array($oldname, 'folder'));
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083

        if (!$folderid) {
            return;
        }

        $name = get_string_from_language($newlang, 'adminpublicdirname', 'admin');
        $description = get_string_from_language($newlang, 'adminpublicdirdescription', 'admin');
        if (!empty($name)) {
            $artefact = artefact_instance_from_id($folderid);
            $artefact->set('title', $name);
            $artefact->set('description', $description);
            $artefact->commit();
        }
    }

1084
    public static function get_folder_by_name($name, $parentfolderid=null, $userid=null, $groupid=null, $institution=null) {
1085
        $parentclause = $parentfolderid ? 'parent = ' . $parentfolderid : 'parent IS NULL';
1086
        $ownerclause = artefact_owner_sql($userid, $groupid, $institution);
1087
        return get_record_sql('SELECT * FROM {artefact}
1088
           WHERE title = ? AND ' . $parentclause . ' AND ' . $ownerclause . "
1089
1090
1091
1092
           AND artefacttype = 'folder'", array($name));
    }

    // Get the id of a folder, creating the folder if necessary
1093
1094
    public static function get_folder_id($name, $description, $parentfolderid=null, $create=true, $userid=null, $groupid=null, $institution=null) {
        if (!$record = self::get_folder_by_name($name, $parentfolderid, $userid, $groupid, $institution)) {
1095
1096
1097
            if (!$create) {
                return false;
            }
1098
1099
1100
            $data = new StdClass;
            $data->title = $name;
            $data->description = $description;
1101
1102
1103
1104
            $data->owner = $userid;
            $data->group = $groupid;
            $data->institution = $institution;
            $data->parent = $parentfolderid;
1105
1106
1107
1108
1109
1110
1111
            $f = new ArtefactTypeFolder(0, $data);
            $f->commit();
            return $f->get('id');
        }
        return $record->id;
    }

1112
1113
1114
1115
1116
1117
1118
1119
1120
    // append the view id to to the end of image and anchor urls so they are visible to logged out users also
    public static function append_view_url($postcontent, $view_id) {
        $postcontent = preg_replace('#(<a[^>]+href="[^>]+artefact/file/download\.php\?file=\d+)#', '\1&amp;view=' . $view_id , $postcontent);
        $postcontent = preg_replace('#(<img[^>]+src="[^>]+artefact/file/download\.php\?file=\d+)#', '\1&amp;view=' . $view_id, $postcontent);
        $postcontent = preg_replace('#(<img[^>]+src="([^>]+artefact/file/download\.php\?file=\d+&amp;view=\d+)"[^>]*>)#', '<a href="\2">\1</a>', $postcontent);

        return $postcontent;
    }

Martyn Smith's avatar
Martyn Smith committed
1121
1122
1123
1124
1125
1126
1127
    public static function get_links($id) {
        $wwwroot = get_config('wwwroot');

        return array(
            '_default' => $wwwroot . 'artefact/file/?folder=' . $id,
        );
    }
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145

    public static function change_language($userid, $oldlang, $newlang) {
        $oldname = get_string_from_language($oldlang, 'feedbackattachdirname', 'view');
        $artefact = ArtefactTypeFolder::get_folder_by_name($oldname, null, $userid);
        if (empty($artefact)) {
            return;
        }

        $name = get_string_from_language($newlang, 'feedbackattachdirname', 'view');
        $description = get_string_from_language($newlang, 'feedbackattachdirdesc', 'view');
        if (!empty($name)) {
            $artefact = artefact_instance_from_id($artefact->id);
            $artefact->set('title', $name);
            $artefact->set('description', $description);
            $artefact->commit();
        }
    }

1146
1147
}

1148
class ArtefactTypeImage extends ArtefactTypeFile {
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158

    protected $width;
    protected $height;

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

        if ($this->id && ($filedata = get_record('artefact_file_image', 'artefact', $this->id))) {
            foreach($filedata as $name => $value) {
                if (property_exists($this, $name)) {
1159
                    $this->{$name} = $value;
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
                }
            }
        }
    }

    /**
     * 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_image 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);

        $this->mtime = time();

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

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

        $data = (object)array(
            'artefact'      => $this->get('id'),
            'width'         => $this->get('width'),
            'height'        => $this->get('height')
        );

        if ($new) {
            insert_record('artefact_file_image', $data);
        }
        else {
            update_record('artefact_file_image', $data, 'artefact');
        }

        $this->dirty = false;
    }

1203
1204
    public static function collapse_config() {
        return 'file';
1205
   } 
1206

1207
1208
1209
    /**
     * err... wtf. Let's find where this method is called and change the call eh?
     */
1210
    public static function is_image_mime_type($type) {
Richard Mansfield's avatar
Richard Mansfield committed
1211
1212
        require_once('file.php');
        return is_image_mime_type($type);
1213
1214
    }

1215
1216
1217
1218
    public static function get_icon($options=null) {
        $url = get_config('wwwroot') . 'artefact/file/download.php?';
        $url .= 'file=' . $options['id'];

1219
1220
        if (isset($options['viewid'])) {
            $url .= '&view=' . $options['viewid'];
1221
1222
1223
1224
1225
        }
        if (isset($options['size'])) {
            $url .= '&size=' . $options['size'];
        }
        else {
1226
            $url .= '&maxheight=20&maxwidth=20';
1227
1228
1229
        }

        return $url;
1230
1231
1232
    }

    public function get_path($data=array()) {
1233
        require_once('file.php');
1234
        $result = get_dataroot_image_path('artefact/file/', $this->id, $data);
1235
1236
1237
        return $result;
    }

1238
1239
1240
1241
1242
1243
1244
1245
    public function delete() {
        if (empty($this->id)) {
            return; 
        }
        delete_records('artefact_file_image', 'artefact', $this->id);
        parent::delete();
    }

Penny Leach's avatar
Penny Leach committed
1246
    public function render_self($options) {
1247
        $result = parent::render_self($options);
1248
        $result['html'] = '<div class="fr filedata-icon" style="text-align: center;"><h4>' . get_string('Preview', 'artefact.file') . '</h4><img src="'
1249
            . hsc(get_config('wwwroot') . 'artefact/file/download.php?file=' . $this->id . '&view=' . $options['viewid'] . '&maxwidth=400&maxheight=180')
1250
1251
            . '" alt=""></div>' . $result['html'];
        return $result;
Penny Leach's avatar
Penny Leach committed
1252
    }
1253
1254
1255
}

?>