lib.php 40.8 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
60
61
62
63
64
65
66
    public static function group_tabs($groupid) {
        return array(
            'files' => array(
                'url' => 'artefact/file/groupfiles.php?group='.$groupid,
                'title' => get_string('Files', 'artefact.file'),
            ),
        );
    }

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

        return $subscriptions;
    }

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

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

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

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

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

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

177
178
179
180
181
182
183
184
185
186
187
188

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

189
        $currentlist = get_column('artefact_file_file_types', 'description');
190
191
192
193
194
195
196
197
198
199
200
201
202
203
        $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]['#'];
204
                insert_record('artefact_file_file_types', $record);
205
206
207
208
209
210
211
212
213
214
            }
            $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]);
215
216
                delete_records('artefact_file_mime_types', 'description', $type);
                delete_records('artefact_file_file_types', 'description', $type);
217
218
219
220
221
222
            }
        }


        // Get a list of all current mimetypes for each file type
        $currentmimetypes = array();
223
        $dbmimetypes = get_records_array('artefact_file_mime_types');
224
225
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
        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);
255
                delete_records('artefact_file_mime_types', 'description', $description);
256
257
258
259
                foreach ($newmimetypes as $newmimetype) {
                    $record = new StdClass;
                    $record->mimetype    = $newmimetype;
                    $record->description = $description;
260
                    insert_record('artefact_file_mime_types', $record);
261
262
263
264
265
266
267
268
                }
            }
        }
       
        db_commit();
        //db_rollback();
    }

269
270
}

Martyn Smith's avatar
Martyn Smith committed
271
abstract class ArtefactTypeFileBase extends ArtefactType {
272

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

    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)) {
291
                    $this->{$name} = $value;
Richard Mansfield's avatar
Richard Mansfield committed
292
293
294
295
296
297
                }
            }
        }

    }

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

310
311
312
        $smarty = smarty_core();
        $smarty->assign('iconpath', $this->get_icon($options));
        $smarty->assign('downloadpath', $downloadpath);
313
        $smarty->assign('filetype', $filetype);
314
        $smarty->assign('owner', $this->display_owner());
315
316
317
318
319
320
321
322
323
324
325
        $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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
    /**
     * 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'),
351
            'oldextension'  => $this->get('oldextension')
Richard Mansfield's avatar
Richard Mansfield committed
352
353
354
355
356
357
358
359
360
361
362
363
        );

        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
364
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
365
366
367
        return false;
    }

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

    }

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

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

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

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

419
420
421
422
423
424
425
426

    // 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
427
    public static function get_my_files_data($parentfolderid, $userid, $institution=null, $group=null) {
428

Richard Mansfield's avatar
Richard Mansfield committed
429
        $select = '
Richard Mansfield's avatar
Richard Mansfield committed
430
            SELECT
431
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description,
Richard Mansfield's avatar
Richard Mansfield committed
432
433
                COUNT(c.id) AS childcount, COUNT (b.blogpost) AS attachcount';
        $from = '
434
435
            FROM {artefact} a
                LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
Richard Mansfield's avatar
Richard Mansfield committed
436
437
438
439
440
                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 = '
441
            GROUP BY
Richard Mansfield's avatar
Richard Mansfield committed
442
443
444
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description';

        $phvals = array();
445

Richard Mansfield's avatar
Richard Mansfield committed
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
474
475
476
477
478
479
480
481
482
483
        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';
        }
484

Richard Mansfield's avatar
Richard Mansfield committed
485
        $filedata = get_records_sql_assoc($select . $from . $where . $groupby, $phvals);
486
487
488
489
490
        if (!$filedata) {
            $filedata = array();
        }
        else {
            foreach ($filedata as $item) {
Richard Mansfield's avatar
Richard Mansfield committed
491
                $item->mtime = format_date(strtotime($item->mtime), 'strfdaymonthyearshort');
Richard Mansfield's avatar
Richard Mansfield committed
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
                $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
                        );
                    }
511
                }
512
            }
Richard Mansfield's avatar
Richard Mansfield committed
513
            $filedata = array_values($filedata);
514
515
        }

Richard Mansfield's avatar
Richard Mansfield committed
516
517
518
519
520
521
522
523
524
525
526
527
        // 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
            );
        }

528
        usort($filedata, array("ArtefactTypeFileBase", "my_files_cmp"));
529
530
        return $filedata;
    }
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
570
571
572
573
574
575
576
577
578
579


    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;
    }

580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
    public static function count_user_files($owner=null, $institution=null, $group=null) {
        $filetypes = PluginArtefactFile::get_artefact_types();
        foreach ($filetypes as $k => $v) {
            if ($v == 'folder') {
                unset($filetypes[$k]);
            }
        }
        $filetypesql = "('" . join("','", $filetypes) . "')";

        $phvals = array();
        if ($institution) {
            $ownersql = 'institution = ? AND "group" IS NULL AND owner IS NULL';
            $phvals[] = $institution;
        }
        else if ($group) {
            $ownersql = '"group" = ? AND institution IS NULL AND owner IS NULL';
            $phvals[] = $group;
        }
        else {
            if (!$owner) {
                global $USER;
                $owner = $USER->get('id');
            }
            $ownersql = 'institution IS NULL AND "group" IS NULL AND owner = ?';
            $phvals[] = $owner;
        }
        return (object) array(
            'files'   => count_records_select('artefact', "artefacttype IN $filetypesql AND $ownersql", $phvals),
608
            'folders' => count_records_select('artefact', "artefacttype = 'folder' AND $ownersql", $phvals)
609
610
611
        );
    }

612
613
}

614
class ArtefactTypeFile extends ArtefactTypeFileBase {
615

616
617
618
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
        
Richard Mansfield's avatar
Richard Mansfield committed
619
620
        if (empty($this->id)) {
            $this->container = 0;
621
        }
622

623
624
    }

625
    public static function get_file_directory($id) {
626
        return "artefact/file/originals/" . ($id % 256);
627
628
    }

629
630
    public function get_path() {
        return get_config('dataroot') . self::get_file_directory($this->id) . '/' .  $this->id;
631
632
    }

633
634
635
636
637
638
639
640
    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';
    }

641
642
643
644
    /**
     * Test file type and return a new Image or File.
     */
    public static function new_file($path, $data) {
Richard Mansfield's avatar
Richard Mansfield committed
645
646
        require_once('file.php');
        $type = get_mime_type($path);
647
        if (ArtefactTypeImage::is_image_mime_type($type)) {
648
            list($data->width, $data->height) = getimagesize($path);
649
650
651
652
653
            return new ArtefactTypeImage(0, $data);
        }
        return new ArtefactTypeFile(0, $data);
    }

654
655
656
657
658
    /**
     * Moves a file into the myfiles area.
     * Takes the name of a file outside the myfiles area.
     * Returns a boolean indicating success or failure.
     */
Richard Mansfield's avatar
Richard Mansfield committed
659
    public static function save_file($pathname, $data) {
660
661
662
        // 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. 
663
664
665
666
667
        $dataroot = get_config('dataroot');
        $pathname = $dataroot . $pathname;
        if (!$size = filesize($pathname)) {
            return false;
        }
668
        $f = self::new_file($pathname, $data);
Richard Mansfield's avatar
Richard Mansfield committed
669
670
671
672
673
        $f->set('size', $size);
        $f->commit();
        $id = $f->get('id');

        $newdir = $dataroot . self::get_file_directory($id);
674
        check_dir_exists($newdir);
Richard Mansfield's avatar
Richard Mansfield committed
675
        $newname = $newdir . '/' . $id;
676
        if (!rename($pathname, $newname)) {
Richard Mansfield's avatar
Richard Mansfield committed
677
            $f->delete();
678
            return false;
679
        }
680
681
        global $USER;
        $USER->quota_add($size);
682
        $USER->commit();
Richard Mansfield's avatar
Richard Mansfield committed
683
        return $id;
684
    }
Richard Mansfield's avatar
Richard Mansfield committed
685

686
    /**
Richard Mansfield's avatar
Richard Mansfield committed
687
688
     * Processes a newly uploaded file, copies it to disk, and creates
     * a new artefact object.
689
690
691
692
693
694
695
696
697
     * 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
698
        $size = $um->file['size'];
699
        global $USER;
700
        if (!$USER->quota_allowed($size) && !$data->institution) {
701
            return get_string('uploadexceedsquota', 'artefact.file');
Richard Mansfield's avatar
Richard Mansfield committed
702
703
704
        }
        $f = self::new_file($um->file['tmp_name'], $data);
        $f->set('size', $size);
705
        $f->set('oldextension', $um->original_filename_extension());
706
707
708
709
710
711
712
        $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
713
714
        else {
            $USER->quota_add($size);
715
            $USER->commit();
Richard Mansfield's avatar
Richard Mansfield committed
716
        }
717
718
        return $error;
    }
Richard Mansfield's avatar
Richard Mansfield committed
719

720

721
722
723
724
725
726
727
728
729
730
731
    // 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;
    }

732

733
    public static function get_admin_files($public) {
734
        $pubfolder = ArtefactTypeFolder::admin_public_folder_id();
735
        $artefacts = get_records_sql_assoc("
736
            SELECT
737
                a.id, a.title, a.parent, a.artefacttype
738
739
            FROM {artefact} a
                INNER JOIN {artefact_file_files} f ON f.artefact = a.id
740
            WHERE a.institution = 'mahara'", array());
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762

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

765
766
767
768
    public function delete() {
        if (empty($this->id)) {
            return; 
        }
Richard Mansfield's avatar
Richard Mansfield committed
769
        $file = $this->get_path();
770
771
        // Detach this file from any view feedback
        set_field('view_feedback', 'attachment', null, 'attachment', $this->id);
772
773
774
775
776
        if (is_file($file)) {
            $size = filesize($file);
            unlink($file);
            global $USER;
            // Deleting other users' files won't lower their quotas yet...
777
            if (!$this->institution && $USER->id == $this->get('owner')) {
778
779
                $USER->quota_remove($size);
                $USER->commit();
780
            }
Richard Mansfield's avatar
Richard Mansfield committed
781
        }
782
783
784
        parent::delete();
    }

785
786
787
788
    public static function has_config() {
        return true;
    }

789
    public static function get_icon($options=null) {
790
        return theme_get_url('images/file.gif');
791
792
    }

793
    public static function get_config_options() {
794
        $elements = array();
795
796
797
798
        $defaultquota = get_config_plugin('artefact', 'file', 'defaultquota');
        if (empty($defaultquota)) {
            $defaultquota = 1024 * 1024 * 10;
        }
799
800
801
        $elements['quotafieldset'] = array(
            'type' => 'fieldset',
            'legend' => get_string('defaultquota', 'artefact.file'),
802
            'elements' => array(
803
804
805
                'defaultquotadescription' => array(
                    'value' => '<tr><td colspan="2">' . get_string('defaultquotadescription', 'artefact.file') . '</td></tr>'
                ),
806
807
808
809
                'defaultquota' => array(
                    'title'        => get_string('defaultquota', 'artefact.file'), 
                    'type'         => 'bytes',
                    'defaultvalue' => $defaultquota,
810
                )
811
            ),
812
813
814
815
816
817
            'collapsible' => true
        );


        // Allowed file types
        $filetypes = array();
818
        foreach (get_records_array('artefact_file_file_types', null, null, 'description') as $filetype) {
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
            $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'
843
844
845
846
847
        );
    }

    public static function save_config_options($values) {
        set_config_plugin('artefact', 'file', 'defaultquota', $values['defaultquota']);
848
        foreach (get_records_array('artefact_file_file_types') as $filetype) {
849
850
            $key = preg_replace('/[^a-zA-Z0-9_]/', '_', $filetype->description);
            $filetype->enabled = intval($values[$key]);
851
            update_record('artefact_file_file_types', $filetype, 'description');
852
        }
853
    }
854

Richard Mansfield's avatar
Richard Mansfield committed
855
    public function describe_size() {
856
857
858
859
860
        $bytes = $this->get('size');
        if ($bytes < 1024) {
            return $bytes <= 0 ? '0' : ($bytes . ' ' . get_string('bytes', 'artefact.file'));
        }
        if ($bytes < 1048576) {
861
            return floor(($bytes / 1024) * 10 + 0.5) / 10 . 'K';
862
863
864
865
        }
        return floor(($bytes / 1048576) * 10 + 0.5) / 10 . 'M';
    }

Martyn Smith's avatar
Martyn Smith committed
866
867
868
869
870
871
872
873
    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,
        );
    }
874
875
876
877
878
879
880
881
882
883
884
885
886
887

    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;
    }
888
889
890
891

    public static function get_quota_usage($artefact) {
        return get_field('artefact_file_files', 'size', 'artefact', $artefact);
    }
892
}
893
894
895

class ArtefactTypeFolder extends ArtefactTypeFileBase {

896
897
898
899
    public function __construct($id = 0, $data = null) {

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

Richard Mansfield's avatar
Richard Mansfield committed
900
901
902
903
        if (empty($this->id)) {
            $this->container = 1;
            $this->size = null;
        }
904
905
906

    }

907
    public function folder_contents() {
908
        return get_records_array('artefact', 'parent', $this->get('id'));
909
910
    }

911
912
913
914
915
    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']);
916
        $smarty->assign('simpledisplay', isset($options['simpledisplay']) ? $options['simpledisplay'] : false);
917
918
919
920
921
922
923

        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);
924
925
926
927
                $child->title = $child->hovertitle = $c->get('title');
                if (!empty($options['simpledisplay'])) {
                    $child->title = str_shorten($child->title, 20);
                }
928
929
930
931
932
933
934
935
936
                $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
937
938
939
940
    public function describe_size() {
        return $this->count_children() . ' ' . get_string('files', 'artefact.file');
    }

941
    public static function get_icon($options=null) {
942
        return theme_get_url('images/folder.gif');
943
944
945
946
947
948
    }

    public static function collapse_config() {
        return 'file';
    }
    
949
    public static function admin_public_folder_id() {
950
951
952
953
        // 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');
954
        $folderid = get_field_sql("
955
956
           SELECT
             a.id
957
958
           FROM {artefact} a
             INNER JOIN {artefact_file_files} f ON a.id = f.artefact
959
960
           WHERE a.title = ?
             AND a.artefacttype = ?
961
962
             AND a.institution = 'mahara'
             AND a.parent IS NULL", array($name, 'folder'));
963
964
        if (!$folderid) {
            global $USER;
965
            if ($USER->get('admin')) {
966
967
                $description = get_string_from_language(get_config('lang'), 
                                                        'adminpublicdirdescription', 'admin');
968
969
                $data = (object) array('title' => $name,
                                       'description' => $description,
970
                                       'institution' => 'mahara');
971
972
973
974
975
976
                $f = new ArtefactTypeFolder(0, $data);
                $f->commit();
                $folderid = $f->get('id');
            } else {
                return false;
            }
977
978
979
980
        }
        return $folderid;
    }

981
982
    public static function change_public_folder_name($oldlang, $newlang) {
        $oldname = get_string_from_language($oldlang, 'adminpublicdirname', 'admin');
983
        $folderid = get_field_sql("
984
985
986
987
988
989
           SELECT
             a.id
           FROM {artefact} a
             INNER JOIN {artefact_file_files} f ON a.id = f.artefact
           WHERE a.title = ?
             AND a.artefacttype = ?
990
991
             AND a.institution = 'mahara'
             AND a.parent IS NULL", array($oldname, 'folder'));
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006

        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();
        }
    }

1007
1008
1009
    public static function get_folder_by_name($name, $parentfolderid=null, $userid=null) {
        if (empty($userid)) {
            global $USER;
1010
            $userid = $USER->id;
1011
        }
1012
        $parentclause = $parentfolderid ? 'parent = ' . $parentfolderid : 'parent IS NULL';
1013
        return get_record_sql('SELECT * FROM {artefact}
1014
           WHERE title = ? AND ' . $parentclause . ' AND owner = ' . $userid . "
1015
1016
1017
1018
           AND artefacttype = 'folder'", array($name));
    }

    // Get the id of a folder, creating the folder if necessary
1019
    public static function get_folder_id($name, $description, $parentfolderid=null, $userid=null, $create=true) {
1020
1021
        if (empty($userid)) {
            global $USER;
1022
            $userid = $USER->id;
1023
1024
        }
        if (!$record = self::get_folder_by_name($name, $parentfolderid, $userid)) {
1025
1026
1027
            if (!$create) {
                return false;
            }
1028
1029
1030
1031
            $data = new StdClass;
            $data->title = $name;
            $data->description = $description;
            $f = new ArtefactTypeFolder(0, $data);
1032
            $f->set('owner', $userid);
1033
1034
1035
1036
1037
1038
1039
            $f->set('parent', $parentfolderid);
            $f->commit();
            return $f->get('id');
        }
        return $record->id;
    }

1040
1041
1042
1043
1044
1045
1046
1047
1048
    // 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
1049
1050
1051
1052
1053
1054
1055
    public static function get_links($id) {
        $wwwroot = get_config('wwwroot');

        return array(
            '_default' => $wwwroot . 'artefact/file/?folder=' . $id,
        );
    }
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073

    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();
        }
    }

1074
1075
}

1076
class ArtefactTypeImage extends ArtefactTypeFile {
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086

    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)) {
1087
                    $this->{$name} = $value;
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
                }
            }
        }
    }

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

1131
1132
    public static function collapse_config() {
        return 'file';
1133
   } 
1134

1135
1136
1137
    /**
     * err... wtf. Let's find where this method is called and change the call eh?
     */
1138
    public static function is_image_mime_type($type) {
Richard Mansfield's avatar
Richard Mansfield committed
1139
1140
        require_once('file.php');
        return is_image_mime_type($type);
1141
1142
    }

1143
1144
1145
1146
    public static function get_icon($options=null) {
        $url = get_config('wwwroot') . 'artefact/file/download.php?';
        $url .= 'file=' . $options['id'];

1147
1148
        if (isset($options['viewid'])) {
            $url .= '&view=' . $options['viewid'];
1149
1150
1151
1152
1153
        }
        if (isset($options['size'])) {
            $url .= '&size=' . $options['size'];
        }
        else {
1154
            $url .= '&maxheight=20&maxwidth=20';
1155
1156
1157
        }

        return $url;
1158
1159
1160
    }

    public function get_path($data=array()) {
1161
        require_once('file.php');
1162
        $result = get_dataroot_image_path('artefact/file/', $this->id, $data);
1163
1164
1165
        return $result;
    }

1166
1167
1168
1169
1170
1171
1172
1173
    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
1174
    public function render_self($options) {
1175
        $result = parent::render_self($options);
1176
        $result['html'] = '<div class="fr filedata-icon" style="text-align: center;"><h4>' . get_string('Preview', 'artefact.file') . '</h4><img src="'
1177
            . hsc(get_config('wwwroot') . 'artefact/file/download.php?file=' . $this->id . '&view=' . $options['viewid'] . '&maxwidth=400&maxheight=180')
1178
1179
            . '" alt=""></div>' . $result['html'];
        return $result;
Penny Leach's avatar
Penny Leach committed
1180
    }
1181
1182
1183
}

?>