filebrowser.php 43.5 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
111
112
113
    else if (!isset($config['simpleupload'])) {
        $config['simpleupload'] = 1;
    }

114
    if ($config['upload']) {
115
        $maxuploadsize = display_size(get_max_upload_size(!$institution && !$group));
116
        $smarty->assign('maxuploadsize', $maxuploadsize);
117
        $smarty->assign('phpmaxfilesize', get_max_upload_size(false));
118
119
120
        if ($group) {
            $smarty->assign('uploaddisabled', !pieform_element_filebrowser_edit_group_folder($group, $folder));
        }
121
    }
122

Richard Mansfield's avatar
Richard Mansfield committed
123
    if (!empty($element['browsehelp'])) {
124
125
126
127
        $config['plugintype'] = $form->get_property('plugintype');
        $config['pluginname'] = $form->get_property('pluginname');
        $config['browsehelp'] = $element['browsehelp'];
    }
128

129
130
131
    $config['showtags'] = !empty($config['tag']) ? (int) $userid : 0;
    $config['editmeta'] = (int) ($userid && !$config['edit'] && !empty($config['tag']));

132
133
    $smarty->assign('config', $config);

134
135
    $filters = isset($element['filters']) ? $element['filters'] : null;
    $filedata = ArtefactTypeFileBase::get_my_files_data($folder, $userid, $group, $institution, $filters);
136
137
138
139
140
    $smarty->assign('filelist', $filedata);

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

141
142
    $smarty->assign('prefix', $prefix);

143
    $initjs = "{$prefix} = new FileBrowser('{$prefix}', {$folder}, {$configstr}, config);
144
145
146
147
{$prefix}.filedata = {$fileliststr};";
    if ($config['select']) {
        $initjs .= "{$prefix}.selecteddata = {$selectedliststr};";
    }
148
149
150

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

151
    $initjs .= "addLoadEvent({$prefix}.init);";
152
153

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

156
157
158
    return $smarty->fetch('artefact:file:form/filebrowser.tpl');
}

159
160

function pieform_element_filebrowser_get_groupinfo($group) {
161
    require_once('group.php');
162
163
164
165
166
167
    $groupinfo = array(
        'roles' => group_get_role_info($group),
        'perms' => group_get_default_artefact_permissions($group),
        'perm'  => array(),
    );
    foreach (current($groupinfo['perms']) as $k => $v) {
168
        $groupinfo['perm'][$k] = get_string('filepermission.' . $k, 'artefact.file');
169
170
171
172
173
    }
    return $groupinfo;
}


174
175
176
177
178
179
180
181
182
183
184
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;
        }
    }

185
    $path[] = (object) array('title' => get_string('home', 'artefact.file'), 'id' => 0);
186
187
188
    return $path;
}

189

190
function pieform_element_filebrowser_build_path($form, $element, $folder, $owner=null, $ownerid=null) {
191
192
193
    if (!$form->submitted_by_js()) {
        return;
    }
194
    $querybase = $element['page'] . (strpos($element['page'], '?') === false ? '?' : '&');
195

196
197
198
199
200
    $path = pieform_element_filebrowser_get_path($folder);
    $foldername = $path[0]->title;

    $smarty = smarty_core();
    $smarty->assign('path', array_reverse($path));
201
202
    $smarty->assign('owner', $owner);
    $smarty->assign('ownerid', $ownerid);
203
    $smarty->assign('querybase', $querybase);
204
205
206
    return array('html' => $smarty->fetch('artefact:file:form/folderpath.tpl'), 'foldername' => $foldername);
}

207

208
function pieform_element_filebrowser_build_filelist($form, $element, $folder, $highlight=null, $user=null, $group=null, $institution=null) {
209
210
211
212
213
    if (!$form->submitted_by_js()) {
        // We're going to rebuild the page from scratch anyway.
        return;
    }

214
215
    global $USER;

216
    $smarty = smarty_core();
217
    $userid = null;
218
    if (is_null($group) && is_null($user)) {
219
220
        $group = $form->get_property('group');
    }
221
222
223
224
225
    else if ($user) {
        $userid = $USER->get('id');
        $smarty->assign('owner', 'user');
        $smarty->assign('ownerid', $userid);
    }
226
227
228
229
230
231
232
233
234
235
236
    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);
    }
237
238
239
240

    if (is_null($userid)) {
        $userid = ($group || $institution) ? null : $USER->get('id');
    }
241
242
    $editable = (int) $element['config']['edit'];
    $selectable = (int) $element['config']['select'];
243
    $selectfolders = (int) !empty($element['config']['selectfolders']);
244
    $publishing = (int) !empty($element['config']['publishing']);
245
246
    $showtags = !empty($element['config']['tag']) ? (int) $userid : 0;
    $editmeta = (int) ($userid && !$editable && !empty($element['config']['tag']));
247
248
249
    $querybase = $element['page'] . (strpos($element['page'], '?') === false ? '?' : '&');
    $prefix = $form->get_name() . '_' . $element['name'];

250
251
    $filters = isset($element['filters']) ? $element['filters'] : null;
    $filedata = ArtefactTypeFileBase::get_my_files_data($folder, $userid, $group, $institution, $filters);
252
253
254

    $smarty->assign('edit', -1);
    $smarty->assign('highlight', $highlight);
255
256
    $smarty->assign('editable', $editable);
    $smarty->assign('selectable', $selectable);
257
    $smarty->assign('selectfolders', $selectfolders);
258
    $smarty->assign('publishing', $publishing);
259
260
    $smarty->assign('showtags', $showtags);
    $smarty->assign('editmeta', $editmeta);
261
    $smarty->assign('filelist', $filedata);
262
263
    $smarty->assign('querybase', $querybase);
    $smarty->assign('prefix', $prefix);
264
265
266
267
268
269
270

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

271

272
273
274
275
276
277
278
279
280
281
282
283
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') {
284
        $selectedtab = param_variable('owner', 'institution');
285
286
287
288
        $upload = $selectedtab == 'institution';
        $tabs['institution'] = get_string('institutionfiles', 'admin');
    }
    else if ($viewowner['type'] == 'group') {
289
        $selectedtab = param_variable('owner', 'group');
290
        $upload = $selectedtab == 'group';
291
        $tabs['user'] = get_string('myfiles', 'artefact.file');
292
293
294
295
        $tabs['group'] = get_string('groupfiles', 'artefact.file');
    }
    else { // $viewowner['type'] == 'user'
        global $USER;
296
        $selectedtab = param_variable('owner', 'user');
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
323
324
325
326
327
328
329
        $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);
}
330

331

332
function pieform_element_filebrowser_get_value(Pieform $form, $element) {
333
334
335
336
337
338
339
340
    $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);
    }
341
342


343
344
345
    // 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);
346

347
348
349
350
351
352
353
354
355
    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;
356
            if (!empty($result['error'])) {
357
                $result['formelementerror'] = $prefix . '.callback';
Richard Mansfield's avatar
Richard Mansfield committed
358
            }
359
            else {
360
                $result['formelementsuccess'] = $prefix . '.callback';
361
            }
362
            $form->json_reply(empty($result['error']) ? PIEFORM_OK : PIEFORM_ERR, $result, $replacehtml);
363
        }
364

365
366
367
368
369
370
371
372
373
374
375
376
377
        // 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';
378
        }
379

380
381
382
383
384
385
386
387
388
389
390
        $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.
391
        if (!empty($result['select'])) {
392
393
            if ($element['config']['selectone']) {
                $selected = array($result['select']);
394
            }
395
396
            else {
                $selected = is_array($selected) ? $selected : array();
397
398
399
                if (!in_array($result['select'], $selected)) {
                    $selected[] = $result['select'];
                }
400
            }
401
        }
402
        else if (!empty($result['unselect'])) {
403
            $selected = is_array($selected) ? array_diff($selected, array($result['unselect'])) : array();
404
        }
405
    }
406

407
    if (is_array($selected) && !empty($selected)) {
408
        if (!empty($element['config']['selectone'])) {
409
410
411
            return $selected[0];
        }
        return $selected;
412
    }
413
    return null;
414
415
}

416

Richard Mansfield's avatar
Richard Mansfield committed
417
function pieform_element_filebrowser_doupdate(Pieform $form, $element) {
418
419
    $result = null;

420
421
422
    $prefix = $form->get_name() . '_' . $element['name'];

    $delete = param_variable($prefix . '_delete', null);
Richard Mansfield's avatar
Richard Mansfield committed
423
424
425
    if (is_array($delete)) {
        $keys = array_keys($delete);
        return pieform_element_filebrowser_delete($form, $element, (int) ($keys[0]));
426
    }
Richard Mansfield's avatar
Richard Mansfield committed
427

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

464
    $move = param_variable($prefix . '_move', null);
Richard Mansfield's avatar
Richard Mansfield committed
465
466
467
    if (!empty($move)) {
        return pieform_element_filebrowser_move($form, $element, array(
            'artefact'  => (int) $move,
468
            'newparent' => param_integer($prefix . '_moveto'),
Richard Mansfield's avatar
Richard Mansfield committed
469
            'folder'    => $element['folder'],
470
        ));
471
    }
Richard Mansfield's avatar
Richard Mansfield committed
472

473
    $createfolder = param_variable($prefix . '_createfolder', null);
Richard Mansfield's avatar
Richard Mansfield committed
474
    if (!empty($createfolder)) {
475
476
477
        $createfolder_name = param_variable($prefix . '_createfolder_name');
        $namelength = strlen($createfolder_name);
        if (!$namelength) {
478
479
480
481
            return array(
                'error'   => true,
                'message' => get_string('foldernamerequired', 'artefact.file'),
            );
482
        }
483
484
485
486
487
488
        else if ($namelength > 1024) {
            return array(
                'error'   => true,
                'message' => get_string('nametoolong', 'artefact.file'),
            );
        }
Richard Mansfield's avatar
Richard Mansfield committed
489
490
491
        return pieform_element_filebrowser_createfolder($form, $element, array(
            'title'  => $createfolder_name,
            'folder' => $element['folder'],
492
        ));
493
    }
Richard Mansfield's avatar
Richard Mansfield committed
494

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

    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']);
533
            }
534
535
            else {
                $result['select'] = $result['highlight'];
536
            }
537
        }
538
        return $result;
539
    }
Richard Mansfield's avatar
Richard Mansfield committed
540

541
542
543
544
545
546
547
    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'])) {
548
549
550
551
552
553
554
555
556
557
                try {
                    $element['selectcallback']($add);
                }
                catch (ArtefactNotFoundException $e) {
                    $result = array(
                        'error' => true,
                        'message' => get_string('selectingfailed', 'artefact.file'),
                    );
                    return $result;
                }
558
559
560
561
562
563
564
            }
            else {
                $result['select'] = $add;
            }
            $result['message'] = get_string('fileadded', 'artefact.file');
            $result['browse'] = 1;
            return $result;
565
566
        }

567
568
569
570
571
        $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'])) {
572
573
574
575
576
577
578
579
580
581
                try {
                    $element['unselectcallback']($del);
                }
                catch (ArtefactNotFoundException $e) {
                    $result = array(
                        'error' => true,
                        'message' => get_string('removingfailed', 'artefact.file'),
                    );
                    return $result;
                }
582
583
584
585
586
587
            }
            else {
                $result['unselect'] = $del;
            }
            $result['message'] = get_string('fileremoved', 'artefact.file');
            return $result;
588
        }
589
590
591
592
593
594

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

597
598
599
600
        if (param_variable('browse', 0) && !param_variable($prefix . '_cancelbrowse', 0)) {
            $result['browse'] = 1;
            return $result;
        }
601
602
603

    }

604
605
    $changeowner = param_variable($prefix . '_changeowner', null);
    if (!empty($changeowner)) {
606
        $result = pieform_element_filebrowser_changeowner($form, $element);
607
608
609
610
        $result['browse'] = 1;
        return $result;
    }

611
    $newfolder = param_variable($prefix . '_changefolder', null);
Richard Mansfield's avatar
Richard Mansfield committed
612
    if (!is_null($newfolder) && is_numeric($newfolder)) {
613
        $result = pieform_element_filebrowser_changefolder($form, $element, $newfolder);
614
        $result['browse'] = 1;
Richard Mansfield's avatar
Richard Mansfield committed
615
616
        $result['folder'] = $newfolder;
        return $result;
617
618
619
620
    }

}

621

622
function pieform_element_filebrowser_upload(Pieform $form, $element, $data) {
623
624
    global $USER;

625
626
627
    $parentfolder     = $data['uploadfolder'] ? (int) $data['uploadfolder'] : null;
    $institution      = $form->get_property('institution');
    $group            = $form->get_property('group');
628
629
630
631
632
633
634
    $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);
635

636
637
638
    if ($parentfolder == 0) {
        $parentfolder = null;
    }
639

640
641
642
    $data             = new StdClass;
    $data->parent     = $parentfolder;
    $data->owner      = null;
643

644
645
646
647
648
649
650
    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;
        }
651
652
653
654
655
        else if ($parentartefact->get('locked')) {
            $result['error'] = true;
            $result['message'] = get_string('cannoteditfoldersubmitted', 'artefact.file');
            return $result;
        }
656
657
658
659
        $parentfoldername = $parentartefact->get('title');
    }
    else {
        $parentfoldername = null;
660
661
    }
    if ($institution) {
662
663
664
665
666
        if (!$USER->can_edit_institution($institution)) {
            $result['error'] = true;
            $result['message'] = get_string('notadminforinstitution', 'admin');
            return $result;
        }
667
668
669
        $data->institution = $institution;
    } else if ($group) {
        if (!$parentfolder) {
670
671
            if (!pieform_element_filebrowser_edit_group_folder($group, 0)) {
                return array('error' => true, 'message' => get_string('cannoteditfolder', 'artefact.file'));
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
            }
        }
        $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);
690
691
692
693
        // update the file listing
        $result['quota'] = $USER->get('quota');
        $result['quotaused'] = $USER->get('quotaused');
        $result['newlist'] = pieform_element_filebrowser_build_filelist($form, $element, $parentfolder);
694
695
696
697
698
699
700
701
        return $result;
    }
    catch (UploadException $e) {
        prepare_upload_failed_message($result, $e, $parentfoldername, $originalname);
        return $result;
    }

    // Upload succeeded
702
703

    if (isset($element['filters'])) {
704
705
        $artefacttypes = isset($element['filters']['artefacttype']) ? $element['filters']['artefacttype'] : null;
        $filetypes = isset($element['filters']['filetype']) ? $element['filters']['filetype'] : null;
706
707
708
709
710
711
        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;
712
                $result['uploaded'] = true;
713
714
715
716
717
718
                $result['message'] = get_string('wrongfiletypeforblock', 'artefact.file');
                return $result;
            }
        }
    }

719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
    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;
737
738
    $result['uploaded'] = true;
    $result['newlist'] = pieform_element_filebrowser_build_filelist($form, $element, $parentfolder, $newid);
739
740
    $result['quota'] = $USER->get('quota');
    $result['quotaused'] = $USER->get('quotaused');
741
    $result['maxuploadsize'] = display_size(get_max_upload_size(!$institution && !$group));
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
    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();
}

761

762
function pieform_element_filebrowser_createfolder(Pieform $form, $element, $data) {
763
764
    global $USER;

765
766
767
    $parentfolder     = $data['folder'] ? (int) $data['folder'] : null;
    $institution      = $form->get_property('institution');
    $group            = $form->get_property('group');
768
769
770

    $result = array();

771
772
773
774
775
    $data = (object) array(
        'parent'      => $parentfolder,
        'owner'       => null,
        'title'       => $data['title'],
    );
776

777
778
779
780
781
782
783
784
    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'));
        }
785
786
787
788
789
    }
    if ($institution) {
        $data->institution = $institution;
    } else if ($group) {
        if (!$parentfolder) {
790
            if (!pieform_element_filebrowser_edit_group_folder($group, 0)) {
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
                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'),
811
        'newlist'   => pieform_element_filebrowser_build_filelist($form, $element, $parentfolder, $f->get('id')),
812
813
814
    );
}

815

816
function pieform_element_filebrowser_update(Pieform $form, $element, $data) {
817
    global $USER;
818
    $collide = !empty($data['collide']) ? $data['collide'] : 'fail';
819

820
821
822
823
824
825
826
827
828
829
830
831
832
    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;
    }

833
    if (!$USER->can_edit_artefact($artefact) || $artefact->get('locked')) {
834
835
836
        return array('error' => true, 'message' => get_string('noeditpermission', 'mahara'));
    }

837
    if ($existingid = ArtefactTypeFileBase::file_exists($data['title'], $artefact->get('owner'), $data['folder'],
838
                                                        $artefact->get('institution'), $artefact->get('group'))) {
839
840
        if ($existingid != $data['artefact']) {
            if ($collide == 'replace') {
841
842
843
844
845
846
847
848
849
850
                log_debug('deleting ' . $existingid);
                $copy = artefact_instance_from_id($existingid);
                $copy->delete();
            }
            else {
                return array('error' => true, 'message' => get_string('fileexists', 'artefact.file'));
            }
        }
    }

851
852
    $artefact->set('title', $data['title']);
    $artefact->set('description', $data['description']);
853
    $artefact->set('allowcomments', (int) $data['allowcomments']);
854
855
856
857
858
859
860
861

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

862
863
    if ($form->get_property('group') && $data['permissions']) {
        $artefact->set('rolepermissions', $data['permissions']);
864
865
866
    }
    $artefact->commit();

867
    $returndata = array(
868
869
        'error' => false,
        'message' => get_string('changessaved', 'artefact.file'),
870
        'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $artefact->get('parent')),
871
    );
872
873
874
875

    if ($updatetags && $form->submitted_by_js()) {
        $smarty = smarty_core();
        $tagdata = tags_sideblock();
876
        $smarty->assign('sbdata', $tagdata);
877
878
879
880
        $returndata['tagblockhtml'] = $smarty->fetch('sideblocks/tags.tpl');
    }

    return $returndata;
881
882
}

883

884
function pieform_element_filebrowser_delete(Pieform $form, $element, $artefact) {
885
    global $USER;
886
887
    $institution = $form->get_property('institution');
    $group       = $form->get_property('group');
888
889
890
891
892
893
894
895
896
897
898
899
900
901

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

902
    if (!$USER->can_edit_artefact($artefact) || $artefact->get('locked')) {
903
904
905
906
907
        return array('error' => true, get_string('nodeletepermission', 'mahara'));
    }
    $parentfolder = $artefact->get('parent');
    $artefact->delete();
    return array(
908
909
910
        'error' => false,
        'deleted' => true,
        'message' => get_string('filethingdeleted', 'artefact.file',
911
                                get_string($artefact->get('artefacttype'), 'artefact.file') . ' ' . $artefact->get('title')),
912
913
        'quotaused' => $USER->get('quotaused'),
        'quota' => $USER->get('quota'),
914
        'maxuploadsize' => display_size(get_max_upload_size(!$institution && !$group)),
915
        'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $parentfolder),
916
917
918
    );
}

919

920
function pieform_element_filebrowser_move(Pieform $form, $element, $data) {
921
    global $USER;
922
923
    $artefactid  = $data['artefact'];    // Artefact being moved
    $newparentid = $data['newparent'];   // Folder to move it to
924

925
926
927
928
929
930
931
932
933
934
935
    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;
    }
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950

    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'));
        }
951
952
953
954
955
956
957
958
959
960
961
962
        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;
        }
963
964
965
        if (!$USER->can_edit_artefact($newparent)) {
            return array('error' => true, 'message' => get_string('movefailednotowner', 'artefact.file'));
        }
966
967
968
        else if ($newparent->get('locked')) {
            return array('error' => true, 'message' => get_string('cannoteditfoldersubmitted', 'artefact.file'));
        }
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
        $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');
        if ($group) {
991
            if (!pieform_element_filebrowser_edit_group_folder($group, 0)) {
992
993
994
995
996
997
                return array('error' => true, 'message' => get_string('movefailednotowner', 'artefact.file'));
            }
        }
        $newparentid = null;
    }

998
999
1000
1001
1002
1003
1004
1005
    if ($oldparentid = $artefact->get('parent')) {
        $oldparent = artefact_instance_from_id($oldparentid);
        if ($oldparent->get('locked')) {
            return array('error' => true, 'message' => get_string('cannotremovefromsubmittedfolder', 'artefact.file'));
        }
    }


1006
1007
1008
    if ($artefact->move($newparentid)) {
        return array(
            'error' => false,
1009
            'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $data['folder']),
1010
1011
1012
1013
1014
        );
    }
    return array('error' => true, 'message' => get_string('movefailed', 'artefact.file'));
}

1015

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
function pieform_element_filebrowser_edit_group_folder($group, $folder) {
    global $USER;
    if ($folder) {
        if (!$folder instanceof ArtefactTypeFolder) {
            $folder = new ArtefactTypeFolder($folder);
        }
        return $USER->can_edit_artefact($folder);
    }
    require_once(get_config('libroot') . 'group.php');
    // Group root directory: use default grouptype artefact permissions
    if (!$role = group_user_access($group)) {
        return false;
    }
    $permissions = group_get_default_artefact_permissions($group);
    return $permissions[$role]->edit;
}


1034
function pieform_element_filebrowser_changeowner(Pieform $form, $element) {
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
    $newtabdata = pieform_element_filebrowser_configure_tabs($element['tabs']);
    $smarty = smarty_core();
    $smarty->assign('prefix', $form->get_name() . '_' . $element['name']);
    $smarty->assign('querybase', $element['page'] . (strpos($element['page'], '?') === false ? '?' : '&'));
    $smarty->assign('tabs', $newtabdata);
    $newtabhtml = $smarty->fetch('artefact:file:form/ownertabs.tpl');
    $newsubtabhtml = $smarty->fetch('artefact:file:form/ownersubtabs.tpl');

    $group = null;
    $institution = null;
1045
    $user = null;
1046
    $folder = 0;
1047
    if ($newtabdata['owner'] == 'site') {
1048
1049
1050
1051
        global $USER;
        if (!$USER->get('admin')) {
            $folder = ArtefactTypeFolder::admin_public_folder_id();
        }
1052
1053
1054
1055
1056
1057
1058
1059
        $institution = 'mahara';
    }
    else if ($newtabdata['owner'] == 'institution') {
        $institution = $newtabdata['ownerid'];
    }
    else if ($newtabdata['owner'] == 'group') {
        $group = $newtabdata['ownerid'];
    }
1060
1061
1062
    else if ($newtabdata['owner'] == 'user') {
        $user = true;
    }
1063
1064
1065
1066
1067
1068
1069

    return array(
        'error'         => false, 
        'changedowner'  => true,
        'changedfolder' => true,
        'tabupload'     => $newtabdata['upload'],
        'folder'        => $folder,
1070
        'disableedit'   => $group && !pieform_element_filebrowser_edit_group_folder($group, $folder),
1071
        'newlist'       => pieform_element_filebrowser_build_filelist($form, $element, $folder, null, $user, $group, $institution),
1072
1073
1074
1075
1076
1077
        'newpath'       => pieform_element_filebrowser_build_path($form, $element, $folder, $newtabdata['owner'], $newtabdata['ownerid']),
        'newtabs'       => $newtabhtml,
        'newsubtabs'    => $newsubtabhtml,
    );
}

1078

1079
function pieform_element_filebrowser_changefolder(Pieform $form, $element, $folder) {
1080
    $owner = $ownerid = $group = $institution = $user = null;
1081
1082
1083

    if (isset($element['tabs'])) {
        if ($owner = param_variable('owner', null)) {
1084
1085
1086
1087
            if ($owner == 'site') {
                $owner = 'institution';
                $institution = $ownerid = 'mahara';
            } else if ($ownerid = param_variable('ownerid', null)) {
1088
1089
                if ($owner == 'group') {
                    $group = (int) $ownerid;
1090
1091
                }
                else if ($owner == 'institution') {
1092
1093
                    $institution = $ownerid;
                }
1094
1095
1096
                else if ($owner == 'user') {
                    $user = true;
                }
1097
1098
1099
1100
            }
        }
    }
    
1101
1102
1103
1104
1105
    // If changing to a group folder, check whether the user can edit it
    if ($g = ($owner ? $group : $form->get_property('group'))) {
        $editgroupfolder = pieform_element_filebrowser_edit_group_folder($g, $folder);
    }

1106
    return array(
1107
1108
        'error'         => false, 
        'changedfolder' => true,
1109
        'folder'        => $folder,
1110
        'disableedit'   => isset($editgroupfolder) && $editgroupfolder == false,
1111
        'newlist'       => pieform_element_filebrowser_build_filelist($form, $element, $folder, null, $user, $group, $institution),
1112
        'newpath'       => pieform_element_filebrowser_build_path($form, $element, $folder, $owner, $ownerid),
1113
1114
1115
    );
}

1116

1117
1118
1119
1120
1121
1122
function pieform_element_filebrowser_views_js(Pieform $form, $element