filebrowser.php 43.3 KB
Newer Older
1
2
3
<?php
/**
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *
 * 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.
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    mahara
 * @subpackage artefact-file
 * @author     Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
25
26
27
28
29
30
31
32
33
34
35
36
37
 *
 */

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

/**
 * Browser for files area.
 *
 * @param Pieform  $form    The form to render the element for
 * @param array    $element The element to render
 * @return string           The HTML for the element
 */
function pieform_element_filebrowser(Pieform $form, $element) {
38
    global $USER, $_PIEFORM_FILEBROWSERS;
39
    $smarty = smarty_core();
40

41
42
43
    $group = $form->get_property('group');
    $institution = $form->get_property('institution');

44
45
46
    if (!empty($element['tabs'])) {
        $tabdata = pieform_element_filebrowser_configure_tabs($element['tabs']);
        $smarty->assign('tabs', $tabdata);
47
        if (!$group && $tabdata['owner'] == 'group') {
48
            $group = $tabdata['ownerid'];
49
50
51
52
53
54
        } else if (!$institution) {
            if ($tabdata['owner'] == 'institution') {
                $institution = $tabdata['ownerid'];
            } else if ($tabdata['owner'] == 'site') {
                $institution = 'mahara';
            }
55
56
57
58
        }
    }

    $userid = ($group || $institution) ? null : $USER->get('id');
59

60
61
62
63
64
    // refresh quotas
    if ($userid) {
        $USER->quota_refresh();
    }

65
66
67
68
69
70
    $folder = $element['folder'];
    $path = pieform_element_filebrowser_get_path($folder);
    $smarty->assign('folder', $folder);
    $smarty->assign('foldername', $path[0]->title);
    $smarty->assign('path', array_reverse($path));
    $smarty->assign('highlight', $element['highlight'][0]);
71
    $smarty->assign('edit', !empty($element['edit']) ? $element['edit'] : -1);
72
73
74
    if (isset($element['browse'])) {
        $smarty->assign('browse', (int) $element['browse']);
    }
75

76
    $config = array_map('intval', $element['config']);
77

78
79
80
81
    if ($group && $config['edit']) {
        $smarty->assign('groupinfo', pieform_element_filebrowser_get_groupinfo($group));
    }

82
83
84
    $formid = $form->get_name();
    $prefix = $formid . '_' . $element['name'];

85
    if ($config['select']) {
86
87
88
89
90
91
92
93
94
95
96
        if (function_exists($element['selectlistcallback'])) {
            if ($form->is_submitted() && $form->has_errors() && isset($_POST[$prefix . '_selected']) && is_array($_POST[$prefix . '_selected'])) {
                $value = array_keys($_POST[$prefix . '_selected']);
            }
            else if (isset($element['defaultvalue'])) {
                $value = $element['defaultvalue'];
            }
            else {
                $value = null;
            }
            $selected = $element['selectlistcallback']($value);
97
        }
98
99
100
        $smarty->assign('selectedlist', $selected);
        $selectedliststr = json_encode($selected);
    }
101

102
    if ($config['uploadagreement']) {
103
104
        if (get_config_plugin('artefact', 'file', 'usecustomagreement')) {
            $smarty->assign('agreementtext', get_field('site_content', 'content', 'name', 'uploadcopyright'));
105
106
        }
        else {
107
            $smarty->assign('agreementtext', get_string('uploadcopyrightdefaultcontent', 'install'));
108
109
        }
    }
110
    if ($config['upload']) {
111
        $maxuploadsize = display_size(get_max_upload_size(!$institution && !$group));
112
        $smarty->assign('maxuploadsize', $maxuploadsize);
113
        $smarty->assign('phpmaxfilesize', get_max_upload_size(false));
114
    }
115

Richard Mansfield's avatar
Richard Mansfield committed
116
    if (!empty($element['browsehelp'])) {
117
118
119
120
        $config['plugintype'] = $form->get_property('plugintype');
        $config['pluginname'] = $form->get_property('pluginname');
        $config['browsehelp'] = $element['browsehelp'];
    }
121

122
123
124
    $config['showtags'] = !empty($config['tag']) ? (int) $userid : 0;
    $config['editmeta'] = (int) ($userid && !$config['edit'] && !empty($config['tag']));

125
126
    $smarty->assign('config', $config);

127
128
    $filters = isset($element['filters']) ? $element['filters'] : null;
    $filedata = ArtefactTypeFileBase::get_my_files_data($folder, $userid, $group, $institution, $filters);
129
130
131
132
133
    $smarty->assign('filelist', $filedata);

    $configstr = json_encode($config);
    $fileliststr = json_encode($filedata);

134
135
    $smarty->assign('prefix', $prefix);

136
    $initjs = "{$prefix} = new FileBrowser('{$prefix}', {$folder}, {$configstr}, config);
137
138
139
140
{$prefix}.filedata = {$fileliststr};";
    if ($config['select']) {
        $initjs .= "{$prefix}.selecteddata = {$selectedliststr};";
    }
141
142
143

    $_PIEFORM_FILEBROWSERS[$prefix]['views_js'] = $initjs;

144
    $initjs .= "addLoadEvent({$prefix}.init);";
145
146

    $smarty->assign('initjs', $initjs);
147
148
    $smarty->assign('querybase', $element['page'] . (strpos($element['page'], '?') === false ? '?' : '&'));

149
150
151
    return $smarty->fetch('artefact:file:form/filebrowser.tpl');
}

152
153

function pieform_element_filebrowser_get_groupinfo($group) {
154
    require_once('group.php');
155
156
157
158
159
160
161
162
163
164
165
166
    $groupinfo = array(
        'roles' => group_get_role_info($group),
        'perms' => group_get_default_artefact_permissions($group),
        'perm'  => array(),
    );
    foreach (current($groupinfo['perms']) as $k => $v) {
        $groupinfo['perm'][$k] = get_string($k);
    }
    return $groupinfo;
}


167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
function pieform_element_filebrowser_get_path($folder) {
    $path = array();
    if ($folder) {
        $folders = ArtefactTypeFileBase::artefactchooser_folder_data(artefact_instance_from_id($folder))->data;
        $f = $folder;
        while ($f) {
            $path[] = (object) array('title' => $folders[$f]->title, 'id' => $f);
            $f = $folders[$f]->parent;
        }
    }

    $path[] = (object) array('title' => get_string('home'), 'id' => 0);
    return $path;
}

182

183
function pieform_element_filebrowser_build_path($form, $element, $folder, $owner=null, $ownerid=null) {
184
185
186
    if (!$form->submitted_by_js()) {
        return;
    }
187
    $querybase = $element['page'] . (strpos($element['page'], '?') === false ? '?' : '&');
188

189
190
191
192
193
    $path = pieform_element_filebrowser_get_path($folder);
    $foldername = $path[0]->title;

    $smarty = smarty_core();
    $smarty->assign('path', array_reverse($path));
194
195
    $smarty->assign('owner', $owner);
    $smarty->assign('ownerid', $ownerid);
196
    $smarty->assign('querybase', $querybase);
197
198
199
    return array('html' => $smarty->fetch('artefact:file:form/folderpath.tpl'), 'foldername' => $foldername);
}

200

201
function pieform_element_filebrowser_build_filelist($form, $element, $folder, $highlight=null, $user=null, $group=null, $institution=null) {
202
203
204
205
206
    if (!$form->submitted_by_js()) {
        // We're going to rebuild the page from scratch anyway.
        return;
    }

207
208
    global $USER;

209
    $smarty = smarty_core();
210
    $userid = null;
211
    if (is_null($group) && is_null($user)) {
212
213
        $group = $form->get_property('group');
    }
214
215
216
217
218
    else if ($user) {
        $userid = $USER->get('id');
        $smarty->assign('owner', 'user');
        $smarty->assign('ownerid', $userid);
    }
219
220
221
222
223
224
225
226
227
228
229
    else {
        $smarty->assign('owner', 'group');
        $smarty->assign('ownerid', $group);
    }
    if (is_null($institution)) {
        $institution = $form->get_property('institution');
    }
    else {
        $smarty->assign('owner', 'institution');
        $smarty->assign('ownerid', $institution);
    }
230
231
232
233

    if (is_null($userid)) {
        $userid = ($group || $institution) ? null : $USER->get('id');
    }
234
235
    $editable = (int) $element['config']['edit'];
    $selectable = (int) $element['config']['select'];
236
    $selectfolders = (int) !empty($element['config']['selectfolders']);
237
    $publishing = (int) !empty($element['config']['publishing']);
238
239
    $showtags = !empty($element['config']['tag']) ? (int) $userid : 0;
    $editmeta = (int) ($userid && !$editable && !empty($element['config']['tag']));
240
241
242
    $querybase = $element['page'] . (strpos($element['page'], '?') === false ? '?' : '&');
    $prefix = $form->get_name() . '_' . $element['name'];

243
244
    $filters = isset($element['filters']) ? $element['filters'] : null;
    $filedata = ArtefactTypeFileBase::get_my_files_data($folder, $userid, $group, $institution, $filters);
245
246
247

    $smarty->assign('edit', -1);
    $smarty->assign('highlight', $highlight);
248
249
    $smarty->assign('editable', $editable);
    $smarty->assign('selectable', $selectable);
250
    $smarty->assign('selectfolders', $selectfolders);
251
    $smarty->assign('publishing', $publishing);
252
253
    $smarty->assign('showtags', $showtags);
    $smarty->assign('editmeta', $editmeta);
254
    $smarty->assign('filelist', $filedata);
255
256
    $smarty->assign('querybase', $querybase);
    $smarty->assign('prefix', $prefix);
257
258
259
260
261
262
263

    return array(
        'data' => $filedata,
        'html' => $smarty->fetch('artefact:file:form/filelist.tpl'),
    );
}

264

265
266
267
268
269
270
271
272
273
274
275
276
function pieform_element_filebrowser_configure_tabs($viewowner) {
    if ($viewowner['type'] == 'institution' && $viewowner['id'] == 'mahara') {
        // No filebrowser tabs for site views
        return null;
    }

    $tabs = array();
    $subtabs = array();

    $upload = null;
    $selectedsubtab = null;
    if ($viewowner['type'] == 'institution') {
277
        $selectedtab = param_variable('owner', 'institution');
278
279
280
281
        $upload = $selectedtab == 'institution';
        $tabs['institution'] = get_string('institutionfiles', 'admin');
    }
    else if ($viewowner['type'] == 'group') {
282
        $selectedtab = param_variable('owner', 'group');
283
        $upload = $selectedtab == 'group';
284
        $tabs['user'] = get_string('myfiles', 'artefact.file');
285
286
287
288
        $tabs['group'] = get_string('groupfiles', 'artefact.file');
    }
    else { // $viewowner['type'] == 'user'
        global $USER;
289
        $selectedtab = param_variable('owner', 'user');
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        $upload = $selectedtab == 'user';
        $tabs['user'] = get_string('myfiles', 'artefact.file');
        if ($groups = $USER->get('grouproles')) {
            $tabs['group'] = get_string('groupfiles', 'artefact.file');
            require_once(get_config('libroot') . 'group.php');
            $groups = group_get_user_groups($USER->get('id'));
            if ($selectedtab == 'group') {
                if (!$selectedsubtab = (int) param_variable('ownerid', 0)) {
                    $selectedsubtab = $groups[0]->id;
                }
                foreach ($groups as &$g) {
                    $subtabs[$g->id] = $g->name;
                }
            }
        }
        if ($institutions = $USER->get('institutions')) {
            $tabs['institution'] = get_string('institutionfiles', 'admin');
            $institutions = get_records_select_array('institution', 'name IN (' 
                . join(',', array_map('db_quote', array_keys($institutions))) . ')');
            if ($selectedtab == 'institution') {
                if (!$selectedsubtab = param_variable('ownerid', '')) {
                    $selectedsubtab = $institutions[0]->name;
                }
                $selectedsubtab = hsc($selectedsubtab);
                foreach ($institutions as &$i) {
                    $subtabs[$i->name] = $i->displayname;
                }
            }
        }
    }
    $tabs['site'] = get_string('sitefiles', 'admin');
    return array('tabs' => $tabs, 'subtabs' => $subtabs, 'owner' => $selectedtab, 'ownerid' => $selectedsubtab, 'upload' => $upload);
}
323

324

325
function pieform_element_filebrowser_get_value(Pieform $form, $element) {
326
327
328
329
330
331
332
333
    $prefix = $form->get_name() . '_' . $element['name'];


    // The value of this element is the list of selected artefact ids
    $selected = param_variable($prefix . '_selected', null);
    if (is_array($selected)) {
        $selected = array_keys($selected);
    }
334
335


336
337
338
    // Process actions that must occur before form validation and
    // which can safely occur without affecting the element's value
    $result = pieform_element_filebrowser_doupdate($form, $element);
339

340
341
342
343
344
345
346
347
348
    if (is_array($result)) {
        // We did something.  If js, replace the filebrowser now and
        // don't continue form submission.
        if (!isset($result['folder'])) {
            $result['folder'] = $element['folder'];
        }
        if ($form->submitted_by_js()) {
            $replacehtml = false; // Don't replace the entire form when replying with json data.
            $result['formelement'] = $prefix;
349
            if (!empty($result['error'])) {
350
                $result['formelementerror'] = $prefix . '.callback';
Richard Mansfield's avatar
Richard Mansfield committed
351
            }
352
            else {
353
                $result['formelementsuccess'] = $prefix . '.callback';
354
            }
355
            $form->json_reply(empty($result['error']) ? PIEFORM_OK : PIEFORM_ERR, $result, $replacehtml);
356
        }
357

358
359
360
361
362
363
364
365
366
367
368
369
370
        // Not js. Add some params & redirect back to the page
        $params = array();
        if (!empty($result['folder'])) {
            $params[] = 'folder=' . $result['folder'];
        }
        if (!empty($result['edit'])) {
            $params[] = 'edit=' . $result['edit'];
        }
        if (!empty($result['highlight'])) {
            $params[] = 'file=' . $result['highlight'];
        }
        if (!empty($result['browse'])) {
            $params[] = 'browse=1';
371
        }
372

373
374
375
376
377
378
379
380
381
382
383
        $result['goto'] = $element['page'];
        if (!empty($params)) { 
            $result['goto'] .= (strpos($element['page'], '?') === false ? '?' : '&') . join('&', $params);
        }

        if (empty($result['select']) && empty($result['unselect'])) {
            $form->reply(empty($result['error']) ? PIEFORM_OK : PIEFORM_ERR, $result);
        }

        // If we got to this point, the doupdate function couldn't select or unselect a file,
        // so we need to let it go through to the form's submit function to deal with.
384
        if (!empty($result['select'])) {
385
386
            if ($element['config']['selectone']) {
                $selected = array($result['select']);
387
            }
388
389
            else {
                $selected = is_array($selected) ? $selected : array();
390
391
392
                if (!in_array($result['select'], $selected)) {
                    $selected[] = $result['select'];
                }
393
            }
394
        }
395
        else if (!empty($result['unselect'])) {
396
            $selected = is_array($selected) ? array_diff($selected, array($result['unselect'])) : array();
397
        }
398
    }
399

400
    if (is_array($selected) && !empty($selected)) {
401
        if (!empty($element['config']['selectone'])) {
402
403
404
            return $selected[0];
        }
        return $selected;
405
    }
406
    return null;
407
408
}

409

Richard Mansfield's avatar
Richard Mansfield committed
410
function pieform_element_filebrowser_doupdate(Pieform $form, $element) {
411
412
    $result = null;

413
414
415
    $prefix = $form->get_name() . '_' . $element['name'];

    $delete = param_variable($prefix . '_delete', null);
Richard Mansfield's avatar
Richard Mansfield committed
416
417
418
    if (is_array($delete)) {
        $keys = array_keys($delete);
        return pieform_element_filebrowser_delete($form, $element, (int) ($keys[0]));
419
    }
Richard Mansfield's avatar
Richard Mansfield committed
420

421
    $update = param_variable($prefix . '_update', null);
Richard Mansfield's avatar
Richard Mansfield committed
422
    if (is_array($update)) {
423
        $edit_title = param_variable($prefix . '_edit_title');
424
425
        $namelength = strlen($edit_title);
        if (!$namelength) {
426
427
428
429
430
            return array(
                'error'   => true,
                'message' => get_string('filenamefieldisrequired', 'artefact.file')
            );
        }
431
432
433
434
435
436
        else if ($namelength > 1024) {
            return array(
                'error'   => true,
                'message' => get_string('nametoolong', 'artefact.file'),
            );
        }
Richard Mansfield's avatar
Richard Mansfield committed
437
        $keys = array_keys($update);
438
439
        $data = array(
            'artefact'    => (int) ($keys[0]),
Richard Mansfield's avatar
Richard Mansfield committed
440
            'title'       => $edit_title,
441
442
            'description' => param_variable($prefix . '_edit_description'),
            'tags'        => param_variable($prefix . '_edit_tags'),
Richard Mansfield's avatar
Richard Mansfield committed
443
            'folder'      => $element['folder'],
444
445
446
        );
        if ($form->get_property('group')) {
            $data['permissions']  = array('admin' => (object) array('view' => true, 'edit' => true, 'republish' => true));
447
            foreach ($_POST as $k => $v) {
448
                if (preg_match('/^' . $prefix . '_permission:([a-z]+):([a-z]+)$/', $k, $m)) {
449
                    $data['permissions'][$m[1]]->{$m[2]} = (bool) $v;
450
451
452
                }
            }
        }
Richard Mansfield's avatar
Richard Mansfield committed
453
        return pieform_element_filebrowser_update($form, $element, $data);
454
    }
Richard Mansfield's avatar
Richard Mansfield committed
455

456
    $move = param_variable($prefix . '_move', null);
Richard Mansfield's avatar
Richard Mansfield committed
457
458
459
    if (!empty($move)) {
        return pieform_element_filebrowser_move($form, $element, array(
            'artefact'  => (int) $move,
460
            'newparent' => param_integer($prefix . '_moveto'),
Richard Mansfield's avatar
Richard Mansfield committed
461
            'folder'    => $element['folder'],
462
        ));
463
    }
Richard Mansfield's avatar
Richard Mansfield committed
464

465
    $createfolder = param_variable($prefix . '_createfolder', null);
Richard Mansfield's avatar
Richard Mansfield committed
466
    if (!empty($createfolder)) {
467
468
469
        $createfolder_name = param_variable($prefix . '_createfolder_name');
        $namelength = strlen($createfolder_name);
        if (!$namelength) {
470
471
472
473
            return array(
                'error'   => true,
                'message' => get_string('foldernamerequired', 'artefact.file'),
            );
474
        }
475
476
477
478
479
480
        else if ($namelength > 1024) {
            return array(
                'error'   => true,
                'message' => get_string('nametoolong', 'artefact.file'),
            );
        }
Richard Mansfield's avatar
Richard Mansfield committed
481
482
483
        return pieform_element_filebrowser_createfolder($form, $element, array(
            'title'  => $createfolder_name,
            'folder' => $element['folder'],
484
        ));
485
    }
Richard Mansfield's avatar
Richard Mansfield committed
486

487
488
    // {$prefix}_upload is set in all browsers except safari when javascript is
    // on (and set in all browsers when it's not)
489
    $upload = param_variable($prefix . '_upload', null);
Richard Mansfield's avatar
Richard Mansfield committed
490
    if (!empty($upload)) {
491
        if (empty($_FILES['userfile']['name'])) {
492
493
494
            return array(
                'error'   => true,
                'message' => get_string('filenamefieldisrequired', 'artefact.file'),
495
                'browse'  => 1,
496
            );
497
        }
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
    }

    if (!empty($_FILES['userfile']['name'])) {
        if (strlen($_FILES['userfile']['name']) > 1024) {
            return array(
                'error'   => true,
                'message' => get_string('nametoolong', 'artefact.file'),
            );
        }
        else if ($element['config']['uploadagreement'] && !param_boolean($prefix . '_notice', false)) {
            return array(
                'error'   => true,
                'message' => get_string('youmustagreetothecopyrightnotice', 'artefact.file'),
                'browse'  => 1,
            );
        }
        $result = pieform_element_filebrowser_upload($form, $element, array(
            'userfile'         => $_FILES['userfile'],
            'uploadnumber'     => param_integer($prefix . '_uploadnumber'),
            'uploadfolder'     => $element['folder'] ? $element['folder'] : null,
            'uploadfoldername' => param_variable($prefix . '_foldername'),
        ));
        // If it's a non-js upload, automatically select the newly uploaded file.
        $result['browse'] = 1;
        if (!$form->submitted_by_js() && !$result['error'] && !empty($element['config']['select'])) {
            if (isset($element['selectcallback']) && is_callable($element['selectcallback'])) {
                $element['selectcallback']($result['highlight']);
525
            }
526
527
            else {
                $result['select'] = $result['highlight'];
528
            }
529
        }
530
        return $result;
531
    }
Richard Mansfield's avatar
Richard Mansfield committed
532

533
534
535
536
537
538
539
    if (!$form->submitted_by_js()) {

        $select = param_variable($prefix . '_select', null);
        if (is_array($select)) {
            $keys = array_keys($select);
            $add = (int) $keys[0];
            if (isset($element['selectcallback']) && is_callable($element['selectcallback'])) {
540
541
542
543
544
545
546
547
548
549
                try {
                    $element['selectcallback']($add);
                }
                catch (ArtefactNotFoundException $e) {
                    $result = array(
                        'error' => true,
                        'message' => get_string('selectingfailed', 'artefact.file'),
                    );
                    return $result;
                }
550
551
552
553
554
555
556
            }
            else {
                $result['select'] = $add;
            }
            $result['message'] = get_string('fileadded', 'artefact.file');
            $result['browse'] = 1;
            return $result;
557
558
        }

559
560
561
562
563
        $unselect = param_variable($prefix . '_unselect', null);
        if (is_array($unselect)) {
            $keys = array_keys($unselect);
            $del = (int) $keys[0];
            if (isset($element['unselectcallback']) && is_callable($element['unselectcallback'])) {
564
565
566
567
568
569
570
571
572
573
                try {
                    $element['unselectcallback']($del);
                }
                catch (ArtefactNotFoundException $e) {
                    $result = array(
                        'error' => true,
                        'message' => get_string('removingfailed', 'artefact.file'),
                    );
                    return $result;
                }
574
575
576
577
578
579
            }
            else {
                $result['unselect'] = $del;
            }
            $result['message'] = get_string('fileremoved', 'artefact.file');
            return $result;
580
        }
581
582
583
584
585
586

        $edit = param_variable($prefix . '_edit', null);
        if (is_array($edit)) {
            $keys = array_keys($edit);
            $result['edit'] = (int) $keys[0];
            return $result;
587
588
        }

589
590
591
592
        if (param_variable('browse', 0) && !param_variable($prefix . '_cancelbrowse', 0)) {
            $result['browse'] = 1;
            return $result;
        }
593
594
595

    }

596
597
    $changeowner = param_variable($prefix . '_changeowner', null);
    if (!empty($changeowner)) {
598
        $result = pieform_element_filebrowser_changeowner($form, $element);
599
600
601
602
        $result['browse'] = 1;
        return $result;
    }

603
    $newfolder = param_variable($prefix . '_changefolder', null);
Richard Mansfield's avatar
Richard Mansfield committed
604
    if (!is_null($newfolder) && is_numeric($newfolder)) {
605
        $result = pieform_element_filebrowser_changefolder($form, $element, $newfolder);
606
        $result['browse'] = 1;
Richard Mansfield's avatar
Richard Mansfield committed
607
608
        $result['folder'] = $newfolder;
        return $result;
609
610
611
612
    }

}

613

614
function pieform_element_filebrowser_upload(Pieform $form, $element, $data) {
615
616
    global $USER;

617
618
619
    $parentfolder     = $data['uploadfolder'] ? (int) $data['uploadfolder'] : null;
    $institution      = $form->get_property('institution');
    $group            = $form->get_property('group');
620
621
622
623
624
625
626
    $uploadnumber     = (int) $data['uploadnumber'];
    $editable         = (int) $element['config']['edit'];
    $selectable       = (int) $element['config']['select'];
    $querybase        = $element['page'] . (strpos($element['page'], '?') === false ? '?' : '&');
    $prefix           = $form->get_name() . '_' . $element['name'];

    $result = array('error' => false, 'uploadnumber' => $uploadnumber);
627

628
629
630
    if ($parentfolder == 0) {
        $parentfolder = null;
    }
631

632
633
634
    $data             = new StdClass;
    $data->parent     = $parentfolder;
    $data->owner      = null;
635

636
637
638
639
640
641
642
    if ($parentfolder) {
        $parentartefact = artefact_instance_from_id($parentfolder);
        if (!$USER->can_edit_artefact($parentartefact)) {
            $result['error'] = true;
            $result['message'] = get_string('cannoteditfolder', 'artefact.file');
            return $result;
        }
643
644
645
646
647
        else if ($parentartefact->get('locked')) {
            $result['error'] = true;
            $result['message'] = get_string('cannoteditfoldersubmitted', 'artefact.file');
            return $result;
        }
648
649
650
651
        $parentfoldername = $parentartefact->get('title');
    }
    else {
        $parentfoldername = null;
652
653
    }
    if ($institution) {
654
655
656
657
658
        if (!$USER->can_edit_institution($institution)) {
            $result['error'] = true;
            $result['message'] = get_string('notadminforinstitution', 'admin');
            return $result;
        }
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
        $data->institution = $institution;
    } else if ($group) {
        require_once(get_config('libroot') . 'group.php');
        if (!$parentfolder) {
            $role = group_user_access($group);
            if (!$role) {
                $result['error'] = true;
                $result['message'] = get_string('usernotingroup', 'mahara');
                return $result;
            }
            // Use default grouptype artefact permissions to check if the
            // user can upload a file to the group's root directory
            $permissions = group_get_default_artefact_permissions($group);
            if (!$permissions[$role]->edit) {
                $result['error'] = true;
                $result['message'] = get_string('cannoteditfolder', 'artefact.file');
                return $result;
            }
        }
        $data->group = $group;
    } else {
        $data->owner = $USER->get('id');
    }

    $data->container = 0;

    $originalname = $_FILES['userfile']['name'];
    $originalname = $originalname ? basename($originalname) : get_string('file', 'artefact.file');
    $data->title = ArtefactTypeFileBase::get_new_file_title($originalname, $parentfolder, $data->owner, $group, $institution);

    try {
        $newid = ArtefactTypeFile::save_uploaded_file('userfile', $data);
    }
    catch (QuotaExceededException $e) {
        prepare_upload_failed_message($result, $e, $parentfoldername, $originalname);
694
695
696
697
        // update the file listing
        $result['quota'] = $USER->get('quota');
        $result['quotaused'] = $USER->get('quotaused');
        $result['newlist'] = pieform_element_filebrowser_build_filelist($form, $element, $parentfolder);
698
699
700
701
702
703
704
705
        return $result;
    }
    catch (UploadException $e) {
        prepare_upload_failed_message($result, $e, $parentfoldername, $originalname);
        return $result;
    }

    // Upload succeeded
706
707

    if (isset($element['filters'])) {
708
709
        $artefacttypes = isset($element['filters']['artefacttype']) ? $element['filters']['artefacttype'] : null;
        $filetypes = isset($element['filters']['filetype']) ? $element['filters']['filetype'] : null;
710
711
712
713
714
715
        if (!empty($artefacttypes) || !empty($filetypes)) {
            // Need to check the artefacttype or filetype (mimetype) of the uploaded file.
            $file = artefact_instance_from_id($newid);
            if (is_array($artefacttypes) && !in_array($file->get('artefacttype'), $artefacttypes)
                || is_array($filetypes) && !in_array($file->get('filetype'), $filetypes)) {
                $result['error'] = true;
716
                $result['uploaded'] = true;
717
718
719
720
721
722
                $result['message'] = get_string('wrongfiletypeforblock', 'artefact.file');
                return $result;
            }
        }
    }

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
    if ($parentfoldername) {
        if ($data->title == $originalname) {
            $result['message'] = get_string('uploadoffiletofoldercomplete', 'artefact.file', 
                                            $originalname, $parentfoldername);
        }
        else {
            $result['message'] = get_string('fileuploadedtofolderas', 'artefact.file', 
                                            $originalname, $parentfoldername, $data->title);
        }
    }
    else if ($data->title == $originalname) {
        $result['message'] = get_string('uploadoffilecomplete', 'artefact.file', $originalname);
    }
    else {
        $result['message'] = get_string('fileuploadedas', 'artefact.file', $originalname, $data->title);
    }

    $result['highlight'] = $newid;
741
742
    $result['uploaded'] = true;
    $result['newlist'] = pieform_element_filebrowser_build_filelist($form, $element, $parentfolder, $newid);
743
744
    $result['quota'] = $USER->get('quota');
    $result['quotaused'] = $USER->get('quotaused');
745
    $result['maxuploadsize'] = display_size(get_max_upload_size(!$institution && !$group));
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
    return $result;
}


/**
 * Helper function used above to minimise code duplication
 */
function prepare_upload_failed_message(&$result, $exception, $parentfoldername, $title) {
    $result['error'] = true;
    if ($parentfoldername) {
        $result['message'] = get_string('uploadoffiletofolderfailed', 'artefact.file', 
                                        $title, $parentfoldername);
    }
    else {
        $result['message'] = get_string('uploadoffilefailed', 'artefact.file',  $title);
    }
    $result['message'] .= ': ' . $exception->getMessage();
}

765

766
function pieform_element_filebrowser_createfolder(Pieform $form, $element, $data) {
767
768
    global $USER;

769
770
771
    $parentfolder     = $data['folder'] ? (int) $data['folder'] : null;
    $institution      = $form->get_property('institution');
    $group            = $form->get_property('group');
772
773
774

    $result = array();

775
776
777
778
779
    $data = (object) array(
        'parent'      => $parentfolder,
        'owner'       => null,
        'title'       => $data['title'],
    );
780

781
782
783
784
785
786
787
788
    if ($parentfolder) {
        $parentartefact = artefact_instance_from_id($parentfolder);
        if (!$USER->can_edit_artefact($parentartefact)) {
            return array('error' => true, 'message' => get_string('cannoteditfolder', 'artefact.file'));
        }
        else if ($parentartefact->get('locked')) {
            return array('error' => true, 'message' => get_string('cannoteditfoldersubmitted', 'artefact.file'));
        }
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
    }
    if ($institution) {
        $data->institution = $institution;
    } else if ($group) {
        require_once(get_config('libroot') . 'group.php');
        if (!$parentfolder) {
            $role = group_user_access($group);
            if (!$role) {
                return array('error' => true, 'message' => get_string('usernotingroup', 'mahara'));
            }
            // Use default grouptype artefact permissions to check if the
            // user can create a folder in the group's root directory
            $permissions = group_get_default_artefact_permissions($group);
            if (!$permissions[$role]->edit) {
                return array('error' => true, 'message' => get_string('cannoteditfolder', 'artefact.file'));
            }
        }
        $data->group = $group;
    } else {
        $data->owner = $USER->get('id');
    }

    if ($oldid = ArtefactTypeFileBase::file_exists($data->title, $data->owner, $parentfolder, $institution, $group)) {
        return array('error' => true, 'message' => get_string('fileexists', 'artefact.file'));
    }

    $f = new ArtefactTypeFolder(0, $data);
    $f->set('dirty', true);
    $f->commit();

    return array(
        'error'     => false,
        'message'   => get_string('foldercreated', 'artefact.file'),
        'highlight' => $f->get('id'),
823
        'newlist'   => pieform_element_filebrowser_build_filelist($form, $element, $parentfolder, $f->get('id')),
824
825
826
    );
}

827

828
function pieform_element_filebrowser_update(Pieform $form, $element, $data) {
829
    global $USER;
830
    $collide = !empty($data['collide']) ? $data['collide'] : 'fail';
831

832
833
834
835
836
837
838
839
840
841
842
843
844
    try {
        $artefact = artefact_instance_from_id($data['artefact']);
    }
    catch (ArtefactNotFoundException $e) {
        $parentfolder = $element['folder'] ? $element['folder'] : null;
        $result = array(
            'error'   => true,
            'message' => get_string('editingfailed', 'artefact.file'),
            'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $parentfolder),
        );
        return $result;
    }

845
    if (!$USER->can_edit_artefact($artefact) || $artefact->get('locked')) {
846
847
848
        return array('error' => true, 'message' => get_string('noeditpermission', 'mahara'));
    }

849
    if ($existingid = ArtefactTypeFileBase::file_exists($data['title'], $artefact->get('owner'), $data['folder'],
850
                                                        $artefact->get('institution'), $artefact->get('group'))) {
851
852
        if ($existingid != $data['artefact']) {
            if ($collide == 'replace') {
853
854
855
856
857
858
859
860
861
862
                log_debug('deleting ' . $existingid);
                $copy = artefact_instance_from_id($existingid);
                $copy->delete();
            }
            else {
                return array('error' => true, 'message' => get_string('fileexists', 'artefact.file'));
            }
        }
    }

863
864
    $artefact->set('title', $data['title']);
    $artefact->set('description', $data['description']);
865
866
867
868
869
870
871
872

    $oldtags = $artefact->get('tags');
    $newtags = preg_split("/\s*,\s*/", trim($data['tags']));
    $updatetags = $oldtags != $newtags;
    if ($updatetags) {
        $artefact->set('tags', $newtags);
    }

873
874
    if ($form->get_property('group') && $data['permissions']) {
        $artefact->set('rolepermissions', $data['permissions']);
875
876
877
    }
    $artefact->commit();

878
    $returndata = array(
879
880
        'error' => false,
        'message' => get_string('changessaved', 'artefact.file'),
881
        'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $artefact->get('parent')),
882
    );
883
884
885
886

    if ($updatetags && $form->submitted_by_js()) {
        $smarty = smarty_core();
        $tagdata = tags_sideblock();
887
        $smarty->assign('sbdata', $tagdata);
888
889
890
891
        $returndata['tagblockhtml'] = $smarty->fetch('sideblocks/tags.tpl');
    }

    return $returndata;
892
893
}

894

895
function pieform_element_filebrowser_delete(Pieform $form, $element, $artefact) {
896
    global $USER;
897
898
    $institution = $form->get_property('institution');
    $group       = $form->get_property('group');
899
900
901
902
903
904
905
906
907
908
909
910
911
912

    try {
        $artefact = artefact_instance_from_id($artefact);
    }
    catch (ArtefactNotFoundException $e) {
        $parentfolder = $element['folder'] ? $element['folder'] : null;
        $result = array(
            'error'   => true,
            'message' => get_string('deletingfailed', 'artefact.file'),
            'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $parentfolder),
        );
        return $result;
    }

913
    if (!$USER->can_edit_artefact($artefact) || $artefact->get('locked')) {
914
915
916
917
918
        return array('error' => true, get_string('nodeletepermission', 'mahara'));
    }
    $parentfolder = $artefact->get('parent');
    $artefact->delete();
    return array(
919
920
921
        'error' => false,
        'deleted' => true,
        'message' => get_string('filethingdeleted', 'artefact.file',
922
                                get_string($artefact->get('artefacttype'), 'artefact.file') . ' ' . $artefact->get('title')),
923
924
        'quotaused' => $USER->get('quotaused'),
        'quota' => $USER->get('quota'),
925
        'maxuploadsize' => display_size(get_max_upload_size(!$institution && !$group)),
926
        'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $parentfolder),
927
928
929
    );
}

930

931
function pieform_element_filebrowser_move(Pieform $form, $element, $data) {
932
    global $USER;
933
934
    $artefactid  = $data['artefact'];    // Artefact being moved
    $newparentid = $data['newparent'];   // Folder to move it to
935

936
937
938
939
940
941
942
943
944
945
946
    try {
        $artefact = artefact_instance_from_id($artefactid);
    }
    catch (ArtefactNotFoundException $e) {
        $result = array(
            'error' => true,
            'message' => get_string('movingfailed', 'artefact.file'),
            'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $data['folder']),
        );
        return $result;
    }
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961

    if (!$USER->can_edit_artefact($artefact)) {
        return array('error' => true, 'message' => get_string('movefailednotowner', 'artefact.file'));
    }
    if (!in_array($artefact->get('artefacttype'), PluginArtefactFile::get_artefact_types())) {
        return array('error' => true, 'message' => get_string('movefailednotfileartefact', 'artefact.file'));
    }

    if ($newparentid > 0) {
        if ($newparentid == $artefactid) {
            return array('error' => true, 'message' => get_string('movefaileddestinationinartefact', 'artefact.file'));
        }
        if ($newparentid == $artefact->get('parent')) {
            return array('error' => false, 'message' => get_string('filealreadyindestination', 'artefact.file'));
        }
962
963
964
965
966
967
968
969
970
971
972
973
        try {
            $newparent = artefact_instance_from_id($newparentid);
        }
        catch (ArtefactNotFoundException $e) {
            $parentfolder = $element['folder'] ? $element['folder'] : null;
            $result = array(
                'error' => true,
                'message' => get_string('movingfailed', 'artefact.file'),
                'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $data['folder']),
            );
            return $result;
        }
974
975
976
        if (!$USER->can_edit_artefact($newparent)) {
            return array('error' => true, 'message' => get_string('movefailednotowner', 'artefact.file'));
        }
977
978
979
        else if ($newparent->get('locked')) {
            return array('error' => true, 'message' => get_string('cannoteditfoldersubmitted', 'artefact.file'));
        }
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        $group = $artefact->get('group');
        if ($group && $group !== $newparent->get('group')) {
            return array('error' => true, 'message' => get_string('movefailednotowner', 'artefact.file'));
        }
        if ($newparent->get('artefacttype') != 'folder') {
            return array('error' => true, 'message' => get_string('movefaileddestinationnotfolder', 'artefact.file'));
        }
        $nextparentid = $newparent->get('parent');
        while (!empty($nextparentid)) {
            if ($nextparentid != $artefactid) {
                $ancestor = artefact_instance_from_id($nextparentid);
                $nextparentid = $ancestor->get('parent');
            } else {
                return array('error' => true, 'message' => get_string('movefaileddestinationinartefact', 'artefact.file'));
            }
        }
    } else { // $newparentid === 0
        if ($artefact->get('parent') == null) {
            return array('error' => false, 'message' => get_string('filealreadyindestination', 'artefact.file'));
        }
        $group = $artefact->get('group');
For faster browsing, not all history is shown. View entire blame