lib.php 35.1 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
67
68
69

    public static function get_event_subscriptions() {
        $subscriptions = array(
            (object)array(
                'plugin'       => 'file',
                'event'        => 'createuser',
                'callfunction' => 'newuser',
            ),
        );

        return $subscriptions;
    }

70
71
    public static function postinst() {
        set_config_plugin('artefact', 'file', 'defaultquota', 10485760);
72
        self::resync_filetype_list();
73
74
    }

75
    public static function newuser($event, $user) {
76
77
78
        if (empty($user->quota)) {
            update_record('usr', array('quota' => get_config_plugin('artefact', 'file', 'defaultquota')), array('id' => $user['id']));
        }
79
    }
80
    
Richard Mansfield's avatar
Richard Mansfield committed
81

82
83
84
85
86
87
88
89
90
    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
91

Martyn Smith's avatar
Martyn Smith committed
92
93
94
95
96
97
98
99
100
101
102
    public static function themepaths($type) {
        static $themepaths = array(
            'file' => array(
                'images/file.gif',
                'images/folder.gif',
                'images/image.gif',
            ),
        );
        return $themepaths[$type];
    }

103
104
    public static function jsstrings($type) {
        static $jsstrings = array(
105
            'file' => array(
106
107
108
109
                'mahara' => array(
                    'cancel',
                    'delete',
                    'edit',
110
                    'tags',
111
112
                ),
                'artefact.file' => array(
113
                    'copyrightnotice',
114
115
116
117
                    'create',
                    'createfolder',
                    'deletefile?',
                    'deletefolder?',
118
                    'Description',
119
120
121
                    'destination',
                    'editfile',
                    'editfolder',
122
                    'File',
123
                    'fileexistsoverwritecancel',
124
                    'filenamefieldisrequired',
125
                    'home',
126
                    'Name',
127
128
129
130
                    'namefieldisrequired',
                    'nofilesfound',
                    'overwrite',
                    'savechanges',
131
                    'timeouterror',
132
133
                    'title',
                    'titlefieldisrequired',
134
                    'unlinkthisfilefromblogposts?',
135
136
137
138
139
                    'upload',
                    'uploadfile',
                    'uploadfileexistsoverwritecancel',
                    'uploadingfiletofolder',
                    'youmustagreetothecopyrightnotice',
140
                ),
141
            ),
142
143
144
        );
        return $jsstrings[$type];
    }
145

146
147
148
149
150
151
152
    public static function jshelp($type) {
        static $jshelp = array(
            'file' => array(
                'artefact.file' => array(
                    'notice',
                    'quota_message',
                    'uploadfile',
153
                    'tags',
154
155
156
157
158
159
                ),
            ),
        );
        return $jshelp[$type];
    }

160
161
162
163
164
165
166
167
168
169
170
171

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

172
        $currentlist = get_column('artefact_file_file_types', 'description');
173
174
175
176
177
178
179
180
181
182
183
184
185
186
        $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]['#'];
187
                insert_record('artefact_file_file_types', $record);
188
189
190
191
192
193
194
195
196
197
            }
            $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]);
198
199
                delete_records('artefact_file_mime_types', 'description', $type);
                delete_records('artefact_file_file_types', 'description', $type);
200
201
202
203
204
205
            }
        }


        // Get a list of all current mimetypes for each file type
        $currentmimetypes = array();
206
        $dbmimetypes = get_records_array('artefact_file_mime_types');
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
        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);
238
                delete_records('artefact_file_mime_types', 'description', $description);
239
240
241
242
                foreach ($newmimetypes as $newmimetype) {
                    $record = new StdClass;
                    $record->mimetype    = $newmimetype;
                    $record->description = $description;
243
                    insert_record('artefact_file_mime_types', $record);
244
245
246
247
248
249
250
251
                }
            }
        }
       
        db_commit();
        //db_rollback();
    }

252
253
}

Martyn Smith's avatar
Martyn Smith committed
254
abstract class ArtefactTypeFileBase extends ArtefactType {
255

256
    protected $adminfiles = 0;
Richard Mansfield's avatar
Richard Mansfield committed
257
    protected $size;
258
259
260
261
262
    // 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.
263
    protected $oldextension;
Richard Mansfield's avatar
Richard Mansfield committed
264
265
266
267
268
269
270
271
272
273
274

    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)) {
275
                    $this->{$name} = $value;
Richard Mansfield's avatar
Richard Mansfield committed
276
277
278
279
280
281
                }
            }
        }

    }

282
283
284
285
286
    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'])) {
287
            $downloadpath .= '&view=' . $options['viewid'];
288
        }
289
290
291
292
293
        $filetype = get_string($this->get('oldextension'), 'artefact.file');
        if (substr($filetype, 0, 2) == '[[') {
            $filetype = $this->get('oldextension') . ' ' . get_string('file', 'artefact.file');
        }

294
295
296
        $smarty = smarty_core();
        $smarty->assign('iconpath', $this->get_icon($options));
        $smarty->assign('downloadpath', $downloadpath);
297
        $smarty->assign('filetype', $filetype);
298
299
300
301
302
303
304
305
306
307
308
309
        $smarty->assign('owner', display_name($this->get('owner')));
        $smarty->assign('created', strftime(get_string('strftimedaydatetime'), $this->get('ctime')));
        $smarty->assign('modified', strftime(get_string('strftimedaydatetime'), $this->get('mtime')));
        $smarty->assign('size', $this->describe_size() . ' (' . $this->get('size') . ' ' . get_string('bytes', 'artefact.file') . ')');

        foreach (array('title', 'description', 'artefacttype') 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
    /**
     * 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'),
335
336
            'adminfiles'    => $this->get('adminfiles'),
            'oldextension'  => $this->get('oldextension')
Richard Mansfield's avatar
Richard Mansfield committed
337
338
339
340
341
342
343
344
345
346
347
348
        );

        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
349
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
350
351
352
        return false;
    }

353
    public static function get_icon($options=null) {
354
355
356
357
358
359
360

    }

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

Richard Mansfield's avatar
Richard Mansfield committed
361
362
363
364
365
366
    public function move($newparentid) {
        $this->set('parent', $newparentid);
        $this->commit();
        return true;
    }

367
368
    public function delete() {
        if (empty($this->id)) {
Richard Mansfield's avatar
Richard Mansfield committed
369
            return; 
370
        }
371
372
373
374
        try {
            delete_records('artefact_blog_blogpost_file', 'file', $this->id);
        } 
        catch ( Exception $e ) {}
375
376
377
378
        delete_records('artefact_file_files', 'artefact', $this->id);
        parent::delete();
    }

Richard Mansfield's avatar
Richard Mansfield committed
379
380
381
    // Check if something exists in the db with a given title and parent,
    // either in adminfiles or with a specific owner.
    public static function file_exists($title, $owner, $folder, $adminfiles=false) {
382
        $filetypesql = "('" . join("','", PluginArtefactFile::get_artefact_types()) . "')";
383
384
        return get_field_sql('SELECT a.id FROM {artefact} a
            LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
Richard Mansfield's avatar
Richard Mansfield committed
385
386
387
388
            WHERE ' . ($adminfiles ? 'f.adminfiles = 1' : 'f.adminfiles <> 1 AND a.owner = ' . $owner) . '
            AND a.title = ?
            AND a.parent ' . (empty($folder) ? ' IS NULL' : ' = ' . $folder) . '
            AND a.artefacttype IN ' . $filetypesql, array($title));
389
390
    }

391
392
393
394
395
396
397
398

    // 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
399
    public static function get_my_files_data($parentfolderid, $userid, $adminfiles=false) {
400

401
402
403
404
        $foldersql = $parentfolderid ? ' = ' . $parentfolderid : ' IS NULL';

        // if blogs are installed then also return the number of blog
        // posts each file is attached to
405
        $bloginstalled = !$adminfiles && get_field('artefact_installed', 'active', 'name', 'blog');
406

407
        $filetypesql = "('" . join("','", PluginArtefactFile::get_artefact_types()) . "')";
Richard Mansfield's avatar
Richard Mansfield committed
408
409
        $filedata = get_records_sql_array('
            SELECT
410
                a.id, a.artefacttype, a.mtime, f.size, a.title, a.description,
Penny Leach's avatar
Penny Leach committed
411
412
                COUNT(c.id) AS childcount ' 
                . ($bloginstalled ? ', COUNT (b.blogpost) AS attachcount' : '') . '
413
414
415
416
417
            FROM {artefact} a
                LEFT OUTER JOIN {artefact_file_files} f ON f.artefact = a.id
                LEFT OUTER JOIN {artefact} c ON c.parent = a.id '
                . ($bloginstalled ? ('LEFT OUTER JOIN
                                     {artefact_blog_blogpost_file} b ON b.file = a.id') : '') . '
418
            WHERE a.parent' . $foldersql . '
Richard Mansfield's avatar
Richard Mansfield committed
419
                AND ' . ($adminfiles ? 'f.adminfiles = 1' : ('f.adminfiles = 0 AND a.owner = ' . $userid)) . '
420
421
422
                AND a.artefacttype IN ' . $filetypesql . '
            GROUP BY
                1, 2, 3, 4, 5, 6;', '');
423
424
425
426
427
428

        if (!$filedata) {
            $filedata = array();
        }
        else {
            foreach ($filedata as $item) {
Richard Mansfield's avatar
Richard Mansfield committed
429
                $item->mtime = format_date(strtotime($item->mtime), 'strfdaymonthyearshort');
430
431
432
433
                $item->tags = get_column('artefact_tag', 'tag', 'artefact', $item->id);
                if (!is_array($item->tags)) {
                    $item->tags = array();
                }
434
435
436
            }
        }

Richard Mansfield's avatar
Richard Mansfield committed
437
438
439
440
441
442
443
444
445
446
447
448
        // 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
            );
        }

449
        usort($filedata, array("ArtefactTypeFileBase", "my_files_cmp"));
450
451
        return $filedata;
    }
452
453
}

454
class ArtefactTypeFile extends ArtefactTypeFileBase {
455

456
457
458
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
        
Richard Mansfield's avatar
Richard Mansfield committed
459
460
        if (empty($this->id)) {
            $this->container = 0;
461
        }
462

463
464
    }

465
    public static function get_file_directory($id) {
466
        return "artefact/file/originals/" . ($id % 256);
467
468
    }

469
470
    public function get_path() {
        return get_config('dataroot') . self::get_file_directory($this->id) . '/' .  $this->id;
471
472
    }

473
474
475
476
477
478
479
480
    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';
    }

481
482
483
484
    /**
     * Test file type and return a new Image or File.
     */
    public static function new_file($path, $data) {
Richard Mansfield's avatar
Richard Mansfield committed
485
486
        require_once('file.php');
        $type = get_mime_type($path);
487
        if (ArtefactTypeImage::is_image_mime_type($type)) {
488
            list($data->width, $data->height) = getimagesize($path);
489
490
491
492
493
            return new ArtefactTypeImage(0, $data);
        }
        return new ArtefactTypeFile(0, $data);
    }

494
495
496
497
498
    /**
     * 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
499
    public static function save_file($pathname, $data) {
500
501
502
        // 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. 
503
504
505
506
507
        $dataroot = get_config('dataroot');
        $pathname = $dataroot . $pathname;
        if (!$size = filesize($pathname)) {
            return false;
        }
508
        $f = self::new_file($pathname, $data);
Richard Mansfield's avatar
Richard Mansfield committed
509
510
511
512
513
        $f->set('size', $size);
        $f->commit();
        $id = $f->get('id');

        $newdir = $dataroot . self::get_file_directory($id);
514
        check_dir_exists($newdir);
Richard Mansfield's avatar
Richard Mansfield committed
515
        $newname = $newdir . '/' . $id;
516
        if (!rename($pathname, $newname)) {
Richard Mansfield's avatar
Richard Mansfield committed
517
            $f->delete();
518
            return false;
519
        }
520
521
        global $USER;
        $USER->quota_add($size);
522
        $USER->commit();
Richard Mansfield's avatar
Richard Mansfield committed
523
        return $id;
524
    }
Richard Mansfield's avatar
Richard Mansfield committed
525

526
    /**
Richard Mansfield's avatar
Richard Mansfield committed
527
528
     * Processes a newly uploaded file, copies it to disk, and creates
     * a new artefact object.
529
530
531
532
533
534
535
536
537
     * 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
538
        $size = $um->file['size'];
539
        global $USER;
Richard Mansfield's avatar
Richard Mansfield committed
540
541
542
543
        if (!$USER->quota_allowed($size) && !$data->adminfiles) {
            return get_string('uploadexceedsquota');
        }
        $f = self::new_file($um->file['tmp_name'], $data);
544
        $f->set('owner', $USER->id);
Richard Mansfield's avatar
Richard Mansfield committed
545
        $f->set('size', $size);
546
        $f->set('oldextension', $um->original_filename_extension());
547
548
549
550
551
552
553
        $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
554
555
        else {
            $USER->quota_add($size);
556
            $USER->commit();
Richard Mansfield's avatar
Richard Mansfield committed
557
        }
558
559
        return $error;
    }
Richard Mansfield's avatar
Richard Mansfield committed
560

561

562
563
564
565
566
567
568
569
570
571
572
    // 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;
    }

573

574
    public static function get_admin_files($public) {
575
        $pubfolder = ArtefactTypeFolder::admin_public_folder_id();
576
        $artefacts = get_records_sql_assoc('
577
            SELECT
578
                a.id, a.title, a.parent, a.artefacttype
579
580
            FROM {artefact} a
                INNER JOIN {artefact_file_files} f ON f.artefact = a.id
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
            WHERE f.adminfiles = 1', array());

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

606
607
608
609
    public function delete() {
        if (empty($this->id)) {
            return; 
        }
Richard Mansfield's avatar
Richard Mansfield committed
610
        $file = $this->get_path();
611
612
        // Detach this file from any view feedback
        set_field('view_feedback', 'attachment', null, 'attachment', $this->id);
613
614
615
616
617
        if (is_file($file)) {
            $size = filesize($file);
            unlink($file);
            global $USER;
            // Deleting other users' files won't lower their quotas yet...
618
619
620
            if (!$this->adminfiles && $USER->id == $this->get('owner')) {
                $USER->quota_remove($size);
                $USER->commit();
621
            }
Richard Mansfield's avatar
Richard Mansfield committed
622
        }
623
624
625
        parent::delete();
    }

626
627
628
629
    public static function has_config() {
        return true;
    }

630
    public static function get_icon($options=null) {
631
        return theme_get_url('images/file.gif');
632
633
    }

634
    public static function get_config_options() {
635
        $elements = array();
636
637
638
639
        $defaultquota = get_config_plugin('artefact', 'file', 'defaultquota');
        if (empty($defaultquota)) {
            $defaultquota = 1024 * 1024 * 10;
        }
640
641
642
        $elements['quotafieldset'] = array(
            'type' => 'fieldset',
            'legend' => get_string('defaultquota', 'artefact.file'),
643
            'elements' => array(
644
645
646
                'defaultquotadescription' => array(
                    'value' => '<tr><td colspan="2">' . get_string('defaultquotadescription', 'artefact.file') . '</td></tr>'
                ),
647
648
649
650
                'defaultquota' => array(
                    'title'        => get_string('defaultquota', 'artefact.file'), 
                    'type'         => 'bytes',
                    'defaultvalue' => $defaultquota,
651
                )
652
            ),
653
654
655
656
657
658
            'collapsible' => true
        );


        // Allowed file types
        $filetypes = array();
659
        foreach (get_records_array('artefact_file_file_types', null, null, 'description') as $filetype) {
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
            $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'
684
685
686
687
688
        );
    }

    public static function save_config_options($values) {
        set_config_plugin('artefact', 'file', 'defaultquota', $values['defaultquota']);
689
        foreach (get_records_array('artefact_file_file_types') as $filetype) {
690
691
            $key = preg_replace('/[^a-zA-Z0-9_]/', '_', $filetype->description);
            $filetype->enabled = intval($values[$key]);
692
            update_record('artefact_file_file_types', $filetype, 'description');
693
        }
694
    }
695

Richard Mansfield's avatar
Richard Mansfield committed
696
    public function describe_size() {
697
698
699
700
701
        $bytes = $this->get('size');
        if ($bytes < 1024) {
            return $bytes <= 0 ? '0' : ($bytes . ' ' . get_string('bytes', 'artefact.file'));
        }
        if ($bytes < 1048576) {
702
            return floor(($bytes / 1024) * 10 + 0.5) / 10 . 'K';
703
704
705
706
        }
        return floor(($bytes / 1048576) * 10 + 0.5) / 10 . 'M';
    }

Martyn Smith's avatar
Martyn Smith committed
707
708
709
710
711
712
713
714
    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,
        );
    }
715
716
717
718
719
720
721
722
723
724
725
726
727
728

    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;
    }
729
}
730
731
732

class ArtefactTypeFolder extends ArtefactTypeFileBase {

733
734
735
736
    public function __construct($id = 0, $data = null) {

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

Richard Mansfield's avatar
Richard Mansfield committed
737
738
739
740
        if (empty($this->id)) {
            $this->container = 1;
            $this->size = null;
        }
741
742
743

    }

744
    public function folder_contents() {
745
        return get_records_array('artefact', 'parent', $this->get('id'));
746
747
    }

748
749
750
751
752
    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']);
753
        $smarty->assign('simpledisplay', isset($options['simpledisplay']) ? $options['simpledisplay'] : false);
754
755
756
757
758
759
760

        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);
761
762
763
764
                $child->title = $child->hovertitle = $c->get('title');
                if (!empty($options['simpledisplay'])) {
                    $child->title = str_shorten($child->title, 20);
                }
765
766
767
768
769
770
771
772
773
                $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
774
775
776
777
    public function describe_size() {
        return $this->count_children() . ' ' . get_string('files', 'artefact.file');
    }

778
    public static function get_icon($options=null) {
779
        return theme_get_url('images/folder.gif');
780
781
782
783
784
785
    }

    public static function collapse_config() {
        return 'file';
    }
    
786
    public static function admin_public_folder_id() {
787
788
789
790
        // 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');
791
792
793
        $folderid = get_field_sql('
           SELECT
             a.id
794
795
           FROM {artefact} a
             INNER JOIN {artefact_file_files} f ON a.id = f.artefact
796
797
798
799
800
801
           WHERE a.title = ?
             AND a.artefacttype = ?
             AND f.adminfiles = 1
             AND a.parent IS NULL', array($name, 'folder'));
        if (!$folderid) {
            global $USER;
802
            if (get_field('usr', 'admin', 'id', $USER->id)) {
803
804
                $description = get_string_from_language(get_config('lang'), 
                                                        'adminpublicdirdescription', 'admin');
805
806
807
808
809
810
811
812
813
814
                $data = (object) array('title' => $name,
                                       'description' => $description,
                                       'owner' => $USER->id,
                                       'adminfiles' => 1);
                $f = new ArtefactTypeFolder(0, $data);
                $f->commit();
                $folderid = $f->get('id');
            } else {
                return false;
            }
815
816
817
818
        }
        return $folderid;
    }

819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
    public static function change_public_folder_name($oldlang, $newlang) {
        $oldname = get_string_from_language($oldlang, 'adminpublicdirname', 'admin');
        $folderid = get_field_sql('
           SELECT
             a.id
           FROM {artefact} a
             INNER JOIN {artefact_file_files} f ON a.id = f.artefact
           WHERE a.title = ?
             AND a.artefacttype = ?
             AND f.adminfiles = 1
             AND a.parent IS NULL', array($oldname, 'folder'));

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

845
846
847
    public static function get_folder_by_name($name, $parentfolderid=null, $userid=null) {
        if (empty($userid)) {
            global $USER;
848
            $userid = $USER->id;
849
        }
850
        $parentclause = $parentfolderid ? 'parent = ' . $parentfolderid : 'parent IS NULL';
851
        return get_record_sql('SELECT * FROM {artefact}
852
           WHERE title = ? AND ' . $parentclause . ' AND owner = ' . $userid . "
853
854
855
856
           AND artefacttype = 'folder'", array($name));
    }

    // Get the id of a folder, creating the folder if necessary
857
    public static function get_folder_id($name, $description, $parentfolderid=null, $userid=null, $create=true) {
858
859
        if (empty($userid)) {
            global $USER;
860
            $userid = $USER->id;
861
862
        }
        if (!$record = self::get_folder_by_name($name, $parentfolderid, $userid)) {
863
864
865
            if (!$create) {
                return false;
            }
866
867
868
869
            $data = new StdClass;
            $data->title = $name;
            $data->description = $description;
            $f = new ArtefactTypeFolder(0, $data);
870
            $f->set('owner', $userid);
871
872
873
874
875
876
877
            $f->set('parent', $parentfolderid);
            $f->commit();
            return $f->get('id');
        }
        return $record->id;
    }

Martyn Smith's avatar
Martyn Smith committed
878
879
880
881
882
883
884
    public static function get_links($id) {
        $wwwroot = get_config('wwwroot');

        return array(
            '_default' => $wwwroot . 'artefact/file/?folder=' . $id,
        );
    }
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902

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

903
904
}

905
class ArtefactTypeImage extends ArtefactTypeFile {
906
907
908
909
910
911
912
913
914
915

    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)) {
916
                    $this->{$name} = $value;
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
                }
            }
        }
    }

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

960
961
    public static function collapse_config() {
        return 'file';
962
   } 
963

964
965
966
    /**
     * err... wtf. Let's find where this method is called and change the call eh?
     */
967
    public static function is_image_mime_type($type) {
Richard Mansfield's avatar
Richard Mansfield committed
968
969
        require_once('file.php');
        return is_image_mime_type($type);
970
971
    }

972
973
974
975
    public static function get_icon($options=null) {
        $url = get_config('wwwroot') . 'artefact/file/download.php?';
        $url .= 'file=' . $options['id'];

976
977
        if (isset($options['viewid'])) {
            $url .= '&view=' . $options['viewid'];
978
979
980
981
982
        }
        if (isset($options['size'])) {
            $url .= '&size=' . $options['size'];
        }
        else {
983
            $url .= '&maxheight=20&maxwidth=20';
984
985
986
        }

        return $url;
987
988
989
    }

    public function get_path($data=array()) {
990
        require_once('file.php');
991
        $result = get_dataroot_image_path('artefact/file/', $this->id, $data);
992
993
994
        return $result;
    }

995
996
997
998
999
1000
1001
1002
    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
1003
    public function render_self($options) {
1004
        $result = parent::render_self($options);
1005
        $result['html'] = '<div class="fr filedata-icon" style="text-align: center;"><h4>' . get_string('Preview', 'artefact.file') . '</h4><img src="'
1006
            . hsc(get_config('wwwroot') . 'artefact/file/download.php?file=' . $this->id . '&view=' . $options['viewid'] . '&maxwidth=400&maxheight=180')
1007
1008
            . '" alt=""></div>' . $result['html'];
        return $result;
Penny Leach's avatar
Penny Leach committed
1009
    }
1010
1011
1012
}

?>