view.php 151 KB
Newer Older
Penny Leach's avatar
Penny Leach committed
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * 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
Penny Leach's avatar
Penny Leach committed
6
 *
Francois Marier's avatar
Francois Marier committed
7
8
9
10
 * 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.
Penny Leach's avatar
Penny Leach committed
11
 *
Francois Marier's avatar
Francois Marier committed
12
13
14
15
 * 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.
Penny Leach's avatar
Penny Leach committed
16
 *
Francois Marier's avatar
Francois Marier committed
17
18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
Penny Leach's avatar
Penny Leach committed
19
20
21
 *
 * @package    mahara
 * @subpackage core
22
 * @author     Catalyst IT Ltd
Penny Leach's avatar
Penny Leach committed
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
Penny Leach's avatar
Penny Leach committed
25
26
27
28
29
30
31
 *
 */

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

class View {

32
33
34
35
36
    private $dirty;
    private $deleted;
    private $id;
    private $owner;
    private $ownerformat;
37
    private $group;
38
    private $institution;
39
40
41
    private $ctime;
    private $mtime;
    private $atime;
42
43
    private $startdate;
    private $stopdate;
44
45
    private $submittedgroup;
    private $submittedhost;
46
    private $submittedtime;
47
48
49
50
51
52
53
    private $title;
    private $description;
    private $loggedin;
    private $friendsonly;
    private $artefact_instances;
    private $artefact_metadata;
    private $ownerobj;
54
    private $groupobj;
55
    private $numcolumns;
56
    private $layout;
Nigel McNie's avatar
Nigel McNie committed
57
    private $theme;
58
    private $columns;
59
    private $dirtycolumns; // for when we change stuff
60
    private $tags;
61
    private $categorydata;
62
    private $editingroles;
63
    private $template;
64
    private $copynewuser = 0;
65
    private $copynewgroups;
66
    private $type;
67
    private $visits;
68
    private $allowcomments;
69
    private $approvecomments;
70
    private $collection;
71
    private $accessconf;
Penny Leach's avatar
Penny Leach committed
72

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    /**
     * Valid view layouts. These are read at install time and inserted into
     * view_layout, but not updated afterwards, so if you're changing one
     * you'll need to do that manually. Actually, you'd better talk to the
     * Mahara dev team about what else needs changing if you do touch this.
     *
     * A hash of columns => list of view widths
     */
    public static $layouts = array(
        1 => array(
            '100',
        ),
        2 => array(
            '50,50',
            '67,33',
            '33,67',
        ),
        3 => array(
            '33,33,33',
            '25,50,25',
            '15,70,15',
        ),
        4 => array(
            '25,25,25,25',
            '20,30,30,20',
        ),
        5 => array(
            '20,20,20,20,20',
        ),
    );

    /**
     * Which view layout is considered the "default" for views with the given
     * number of columns. Must be present in $layouts of course.
     */
    public static $defaultlayouts = array(
        1 => '100',
        2 => '50,50',
        3 => '33,33,33',
        4 => '25,25,25,25',
        5 => '20,20,20,20,20',
    );

Penny Leach's avatar
Penny Leach committed
116
117
    public function __construct($id=0, $data=null) {
        if (!empty($id)) {
118
119
            $tempdata = get_record('view','id',$id);
            if (empty($tempdata)) {
120
121
                throw new ViewNotFoundException(get_string('viewnotfound', 'error', $id));
            }
122
123
124
125
126
127
            if (!empty($data)) {
                $data = array_merge((array)$tempdata, $data);
            }
            else {
                $data = $tempdata; // use what the database has
            }
Penny Leach's avatar
Penny Leach committed
128
            $this->id = $id;
Penny Leach's avatar
Penny Leach committed
129
130
131
        }
        else {
            $this->ctime = time();
132
            $this->mtime = time();
Penny Leach's avatar
Penny Leach committed
133
            $this->dirty = true;
Penny Leach's avatar
Penny Leach committed
134
135
136
137
138
139
140
141
142
143
144
        }

        if (empty($data)) {
            $data = array();
        }
        foreach ((array)$data as $field => $value) {
            if (property_exists($this, $field)) {
                $this->{$field} = $value;
            }
        }
        $this->atime = time();
145
146
        $this->columns = array();
        $this->dirtycolumns = array();
147
148
        if ($this->group) {
            $group = get_record('group', 'id', $this->group);
149
150
151
            if ($group->deleted) {
                throw new ViewNotFoundException(get_string('viewnotfound', 'error', $id));
            }
152
            safe_require('grouptype', $group->grouptype);
153
            $this->editingroles = call_static_method('GroupType' . ucfirst($group->grouptype), 'get_view_editing_roles');
154
        }
Penny Leach's avatar
Penny Leach committed
155
156
    }

157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    /**
     * Creates a new View for the given user/group/institution.
     * 
     * You can specify who the view is being created _by_ with the second 
     * parameter. This defaults to the current logged in user's ID.
     *
     * @param array $viewdata See View::_create
     * @return View           The newly created View
     */
    public static function create($viewdata, $userid=null) {
        if (is_null($userid)) {
            global $USER;
            $userid = $USER->get('id');
        }

        $view = self::_create($viewdata, $userid);
        return $view;
    }

    /**
     * Creates a View for the given user, based off a given template and other 
     * View information supplied.
     *
180
     * Will set a default title of 'Copy of $viewtitle' if title is not 
181
182
183
184
185
186
     * specified in $viewdata.
     *
     * @param array $viewdata See View::_create
     * @param int $templateid The ID of the View to copy
     * @param int $userid     The user who has issued the command to create the 
     *                        view. See View::_create
187
     * @param int $checkaccess Whether to check that the user can see the view before copying it
188
189
190
191
192
193
     * @return array A list consisting of the new view, the template view and 
     *               information about the copy - i.e. how many blocks and 
     *               artefacts were copied
     * @throws SystemException under various circumstances, see the source for 
     *                         more information
     */
194
    public static function create_from_template($viewdata, $templateid, $userid=null, $checkaccess=true) {
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
        if (is_null($userid)) {
            global $USER;
            $userid = $USER->get('id');
        }

        $user = new User();
        $user->find_by_id($userid);

        db_begin();

        $template = new View($templateid);

        if ($template->get('deleted')) {
            throw new SystemException("View::create_from_template: This template has been deleted");
        }

        if (!$template->get('template') && !$user->can_edit_view($template)) {
            throw new SystemException("View::create_from_template: Attempting to create a View from another View that is not marked as a template");
        }
214
        else if ($checkaccess && !can_view_view($templateid, $userid)) {
215
216
217
218
219
220
221
222
223
224
            throw new SystemException("View::create_from_template: User $userid is not permitted to copy View $templateid");
        }

        $view = self::_create($viewdata, $userid);

        // Set a default title if one wasn't set
        if (!isset($viewdata['title'])) {
            $view->set('title', self::new_title(get_string('Copyof', 'mahara', $template->get('title')), (object)$viewdata));
            $view->set('dirty', true);
        }
225
226
227
228
229
230
231
232

        try {
            $copystatus = $view->copy_contents($template);
        }
        catch (QuotaExceededException $e) {
            db_rollback();
            return array(null, $template, array('quotaexceeded' => true));
        }
233
234

        $view->commit();
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

        $blocks = get_records_array('block_instance', 'view', $view->get('id'));
        if ($blocks) {
            foreach ($blocks as $b) {
                $configdata = unserialize($b->configdata);
                if (!isset($configdata['artefactid'])) {
                    continue;
                }
                if (!isset($configdata['copytype']) || $configdata['copytype'] !== 'reference') {
                    continue;
                }
                $va = new StdClass;
                $va->view = $b->view;
                $va->artefact = $configdata['artefactid'];
                $va->block = $b->id;
                insert_record('view_artefact', $va);
            }
        }
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
        db_commit();

        return array(
            $view,
            $template,
            $copystatus,
        );
    }

    /**
     * Creates a new View for the given user, based on the given information 
     * about the view.
     *
     * Validation of the view data is performed, then the View is created. If 
     * the View is to be owned by a group, that group is given access to it.
     *
     * @param array $viewdata Data about the view. You can pass in most fields 
     *                        that appear in the view table.
     *
     *                        Note that you set who owns the View by setting 
     *                        either the owner, group or institution field as 
     *                        approriate.
     *
     *                        Currently, you cannot pass in access data. Use 
     *                        $view->set_access() after retrieving the $view 
     *                        object.
     *
     * @param int $userid The user who has issued the command to create the 
     *                    View (note: this is different from the "owner" of the 
     *                    View - a group or institution could be the "owner",
     *                    but it's a _user_ who requests a View is created for it)
     * @return View The created View
     * @throws SystemException if the View data is invalid - mostly this is due 
     *                         to owner information being specified incorrectly.
     */
    private static function _create(&$viewdata, $userid) {
        // If no owner information is provided, assume that the view is being 
        // created by the user for themself
        if (!isset($viewdata['owner']) && !isset($viewdata['group']) && !isset($viewdata['institution'])) {
            $viewdata['owner'] = $userid;
        }

        if (isset($viewdata['owner'])) {
            if ($viewdata['owner'] != $userid) {
                $userobj = new User();
                $userobj->find_by_id($userid);
                if (!$userobj->is_admin_for_user($viewdata['owner'])) {
                    throw new SystemException("View::_create: User $userid is not allowed to create a view for owner {$viewdata['owner']}");
                }
            }

304
            // Users can only have one view of each non-portfolio type
305
            if (isset($viewdata['type']) && $viewdata['type'] != 'portfolio' && get_record('view', 'owner', $viewdata['owner'], 'type', $viewdata['type'])) {
306
307
308
                $viewdata['type'] = 'portfolio';
            }

309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
            // Try to create the view with the owner's default theme if that theme is set by an
            // institution (i.e. if it's different from the site theme)
            //
            // This needs to be modified if users are ever allowed to change their own theme
            // preference.  Currently it's okay because users' themes are forced on them by
            // the site or institution default, but if some users are allowed to change their
            // own theme pref, we should create those users' views without a theme.
            if (!get_config('userscanchooseviewthemes') && !isset($viewdata['theme'])
                && (!isset($viewdata['type']) || $viewdata['type'] != 'dashboard')) {
                global $USER;
                if ($viewdata['owner'] == $USER->get('id')) {
                    $owner = $USER;
                }
                else {
                    $owner = new User();
                    $owner->find_by_id($viewdata['owner']);
                }
                $ownertheme = $owner->get('theme');
                if ($ownertheme && $ownertheme != get_config('theme')) {
                    $viewdata['theme'] = $ownertheme;
                }
            }
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
        }

        if (isset($viewdata['group'])) {
            require_once('group.php');
            if (!group_user_can_edit_views($viewdata['group'], $userid)) {
                throw new SystemException("View::_create: User $userid is not permitted to create a view for group {$viewdata['group']}");
            }
        }

        if (isset($viewdata['institution'])) {
            $user = new User();
            $user->find_by_id($userid);
            if (!$user->can_edit_institution($viewdata['institution'])) {
                throw new SystemException("View::_create: User $userid is not permitted to create a view for institution {$viewdata['institution']}");
            }
        }

        // Create the view
        $defaultdata = array(
            'numcolumns'  => 3,
            'template'    => 0,
            'type'        => 'portfolio',
            'title'       => self::new_title(get_string('Untitled', 'view'), (object)$viewdata),
        );

        $data = (object)array_merge($defaultdata, $viewdata);

        $view = new View(0, $data);
        $view->commit();

        if (isset($viewdata['group'])) {
            // By default, group views should be visible to the group
363
364
365
366
            insert_record('view_access', (object) array(
                'view'  => $view->get('id'),
                'group' => $viewdata['group'],
            ));
367
368
        }

369
        return new View($view->get('id')); // Reread to ensure defaults are set
370
371
    }

Penny Leach's avatar
Penny Leach committed
372
373
374
375
    public function get($field) {
        if (!property_exists($this, $field)) {
            throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
        }
376
377
378
        if ($field == 'tags') { // special case
            return $this->get_tags();
        }
379
380
381
        if ($field == 'categorydata') {
            return $this->get_category_data();
        }
382
383
384
        if ($field == 'collection') {
            return $this->get_collection();
        }
Penny Leach's avatar
Penny Leach committed
385
386
387
        return $this->{$field};
    }

388
389
390
391
392
393
394
395
396
397
398
399
400
    public function set($field, $value) {
        if (property_exists($this, $field)) {
            if ($this->{$field} != $value) {
                // only set it to dirty if it's changed
                $this->dirty = true;
            }
            $this->{$field} = $value;
            $this->mtime = time();
            return true;
        }
        throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
    }

401
402
403
404
405
406
407
    public function get_tags() {
        if (!isset($this->tags)) {
            $this->tags = get_column('view_tag', 'tag', 'view', $this->get('id'));
        }
        return $this->tags;
    }

408
409
410
    public function get_collection() {
        if (!isset($this->collection)) {
            require_once(get_config('libroot') . 'collection.php');
411
            $this->collection = Collection::search_by_view_id($this->id);
412
413
414
415
416
417
418
419
420
421
422
        }
        return $this->collection;
    }

    public function collection_id() {
        if ($collection = $this->get_collection()) {
            return $collection->get('id');
        }
        return false;
    }

423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
    /**
     * View destructor. Calls commit if necessary.
     *
     * A special case is when the object has just been deleted.  In this case,
     * we do nothing.
     */
    public function __destruct() {
        if ($this->deleted) {
            return;
        }
      
        if (!empty($this->dirty)) {
            return $this->commit();
        }
    }

    /** 
     * This method updates the contents of the view table only.
     */
    public function commit() {
        if (empty($this->dirty)) {
            return;
        }
        $fordb = new StdClass;
        foreach (get_object_vars($this) as $k => $v) {
            $fordb->{$k} = $v;
449
            if (in_array($k, array('mtime', 'ctime', 'atime', 'startdate', 'stopdate', 'submittedtime')) && !empty($v)) {
450
451
452
                $fordb->{$k} = db_format_timestamp($v);
            }
        }
453
454
455

        db_begin();

456
        if (empty($this->id)) {
457
458
            // users are only allowed one profile view
            if ($this->type == 'profile' && record_exists('view', 'owner', $this->owner, 'type', 'profile')) {
459
                throw new SystemException(get_string('onlonlyyoneprofileviewallowed', 'error'));
460
            }
461
462
463
464
465
            $this->id = insert_record('view', $fordb, 'id', true);
        }
        else {
            update_record('view', $fordb, 'id');
        }
466

467
468
469
470
471
        if (isset($this->tags)) {
            delete_records('view_tag', 'view', $this->get('id'));
            foreach ($this->get_tags() as $tag) {
                insert_record('view_tag', (object)array( 'view' => $this->get('id'), 'tag' => $tag));
            }
472
473
        }

474
475
476
477
478
479
480
        if (isset($this->copynewgroups)) {
            delete_records('view_autocreate_grouptype', 'view', $this->get('id'));
            foreach ($this->copynewgroups as $grouptype) {
                insert_record('view_autocreate_grouptype', (object)array( 'view' => $this->get('id'), 'grouptype' => $grouptype));
            }
        }

481
482
        db_commit();

483
484
485
486
        $this->dirty = false;
        $this->deleted = false;
    }

Penny Leach's avatar
Penny Leach committed
487
488
489
490
491
492
493
494
    public function get_artefact_instances() {
        if (!isset($this->artefact_instances)) {
            $this->artefact_instances = false;
            if ($instances = $this->get_artefact_metadata()) {
                foreach ($instances as $instance) {
                    safe_require('artefact', $instance->plugin);
                    $classname = generate_artefact_class_name($instance->artefacttype);
                    $i = new $classname($instance->id, $instance);
Penny Leach's avatar
Penny Leach committed
495
                    $this->childreninstances[] = $i;
Penny Leach's avatar
Penny Leach committed
496
497
498
499
500
501
502
                }
            }
        }
        return $this->artefact_instances;
    }

    public function get_artefact_metadata() {
Penny Leach's avatar
Penny Leach committed
503
        if (!isset($this->artefact_metadata)) {
504
            $sql = 'SELECT a.*, i.name, va.block
505
506
507
                    FROM {view_artefact} va
                    JOIN {artefact} a ON va.artefact = a.id
                    JOIN {artefact_installed_type} i ON a.artefacttype = i.name
Penny Leach's avatar
Penny Leach committed
508
                    WHERE va.view = ?';
509
            $this->artefact_metadata = get_records_sql_array($sql, array($this->id));
Penny Leach's avatar
Penny Leach committed
510
511
512
        }
        return $this->artefact_metadata;
    }
Penny Leach's avatar
Penny Leach committed
513

514
    public function find_artefact_children($artefact, $allchildren, &$refs) {
515
516

        $children = array();        
517
518
519
520
521
522
523
524
525
526
        if ($allchildren) {
            foreach ($allchildren as $child) {
                if ($child->parent != $artefact->id) {
                    continue;
                }
                $children[$child->id] = array();
                $children[$child->id]['artefact'] = $child;
                $refs[$child->id] = $child;
                $children[$child->id]['children'] = $this->find_artefact_children($child, 
                                                            $allchildren, $refs);
527
528
529
530
531
532
            }
        }

        return $children;
    }

Penny Leach's avatar
Penny Leach committed
533

Penny Leach's avatar
Penny Leach committed
534
535
536
537
538
539
    public function has_artefacts() {
        if ($this->get_artefact_metadata()) {
            return true;
        }
        return false;
    }
Penny Leach's avatar
Penny Leach committed
540
541
542
543
544
545
546
547

    public function get_owner_object() {
        if (!isset($this->ownerobj)) {
            $this->ownerobj = get_record('usr', 'id', $this->get('owner'));
        }
        return $this->ownerobj;
    }

548
549
550
551
552
553
554
    public function get_group_object() {
        if (!isset($this->groupobj)) {
            $this->groupobj = get_record('group', 'id', $this->get('group'));
        }
        return $this->groupobj;
    }

Penny Leach's avatar
Penny Leach committed
555
    
556
    public function delete() {
557
        safe_require('artefact', 'comment');
558
        db_begin();
559
        ArtefactTypeComment::delete_view_comments($this->id);
560
        delete_records('view_access','view',$this->id);
561
        delete_records('view_autocreate_grouptype', 'view', $this->id);
562
        delete_records('view_tag','view',$this->id);
563
        delete_records('view_visit','view',$this->id);
564
        delete_records('collection_view','view',$this->id);
565
        delete_records('usr_watchlist_view','view',$this->id);
566
        if ($blockinstanceids = get_column('block_instance', 'id', 'view', $this->id)) {
567
            require_once(get_config('docroot') . 'blocktype/lib.php');
568
569
570
571
572
            foreach ($blockinstanceids as $id) {
                $bi = new BlockInstance($id);
                $bi->delete();
            }
        }
573
        handle_event('deleteview', $this->id);
574
        delete_records('view','id',$this->id);
575
576
577
578
579
        if (!empty($this->owner) && $this->is_submitted()) {
            // There should be no way to delete a submitted view,
            // but unlock its artefacts just in case.
            ArtefactType::update_locked($this->owner);
        }
580
        $this->deleted = true;
581
        db_commit();
582
583
    }

584
585
586
587
588
589
    /* Only retrieve access records that the owner can edit on the
     * view access page.  Some records are not visible there, such as
     * tutor access records for submitted views and objectionable
     * content access records (visible = 0) and token/secret url
     * records which are managed per-view, on another page.
     */
590
    public function get_access($timeformat=null) {
591
592
593
594
595
        if ($data = $this->get_access_records()) {
            return self::process_access_records($data, $timeformat);
        }
        return array();
    }
596

597
    public function get_access_records() {
598
        $data = get_records_sql_array("
599
            SELECT accesstype, va.group, role, usr, startdate, stopdate, allowcomments, approvecomments
600
            FROM {view_access} va
601
            WHERE view = ? AND visible = 1 AND token IS NULL
602
603
604
605
606
607
            ORDER BY
                accesstype IS NULL, accesstype DESC,
                va.group, role IS NOT NULL, role,
                usr,
                startdate IS NOT NULL, startdate, stopdate IS NOT NULL, stopdate,
                allowcomments, approvecomments",
608
609
            array($this->id)
        );
610
611
        return $data ? $data : array();
    }
612

613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
    public static function process_access_records($data=array(), $timeformat=null) {
        $rolegroups = array();
        foreach ($data as &$item) {
            if ($item->role && !isset($roledata[$item->group])) {
                $rolegroups[$item->group] = 1;
            }
        }
        if ($rolegroups) {
            $grouptypes = get_records_sql_assoc('
                SELECT id, grouptype
                FROM {group}
                WHERE id IN (' . join(',', array_map('intval', array_keys($rolegroups))) . ')
                AND deleted = 0',
                array()
            );
        }
629

630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
        foreach ($data as &$item) {
            $item = (array)$item;
            if ($item['usr']) {
                $item['type'] = 'user';
                $item['id'] = $item['usr'];
            }
            else if ($item['group']) {
                $item['type'] = 'group';
                $item['id'] = $item['group'];
            }
            else {
                $item['type'] = $item['accesstype'];
                $item['id'] = null;
            }

            if ($item['role']) {
                $item['roledisplay'] = get_string($item['role'], 'grouptype.'.$grouptypes[$item['group']]->grouptype);
            }
            if ($timeformat) {
                if ($item['startdate']) {
                    $item['startdate'] = strftime($timeformat, strtotime($item['startdate']));
651
                }
652
653
                if ($item['stopdate']) {
                    $item['stopdate'] = strftime($timeformat, strtotime($item['stopdate']));
654
                }
655
            }
656
        }
657
658
659
        return $data;
    }

660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
    /* Attempt to sort two access records in the same order as the
       query in get_access_records */
    public static function cmp_accesslist($a, $b) {
        if (($c = empty($a->accesstype) - empty($b->accesstype))
            || ($c = strcmp($b->accesstype, $a->accesstype))
            || ($c = $a->group - $b->group)
            || ($c = !empty($a->role) - !empty($b->role))
            || ($c = strcmp($a->role, $b->role))
            || ($c = $a->usr - $b->usr)
            || ($c = !empty($a->startdate) - !empty($b->startdate))
            || ($c = strcmp($a->startdate, $b->startdate))
            || ($c = !empty($a->stopdate) - !empty($b->stopdate))
            || ($c = strcmp($a->stopdate, $b->stopdate))
            || ($c = $a->allowcomments - $b->allowcomments)) {
            return $c;
        }
        return $a->approvecomments - $b->approvecomments;
    }

679
680
681
682
683
684

    public static function update_view_access($config, $viewids) {

        db_begin();

        // Use set_access() on the first view to get a hopefully consistent
685
        // and complete representation of the access list
686
687
        $firstview = new View($viewids[0]);
        $fullaccesslist = $firstview->set_access($config['accesslist']);
688
689

        // Copy the first view's access records to all the other views
690
691
        $firstview->copy_access($viewids);

692
693
694
695
696
        // Sort the full access list in the same order as the list
        // returned by get_access, so that views with the same set of
        // access records get grouped together
        usort($fullaccesslist, array('self', 'cmp_accesslist'));

697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
        // Hash the config object so later on we can easily find
        // all the views with the same config/access rights
        $config['accesslist'] = $fullaccesslist;
        $accessconf = substr(md5(serialize($config)), 0, 10);

        foreach ($viewids as $viewid) {
            $v = new View((int) $viewid);
            $v->set('startdate', $config['startdate']);
            $v->set('stopdate', $config['stopdate']);
            $v->set('template', $config['template']);
            $v->set('allowcomments', $config['allowcomments']);
            $v->set('approvecomments', $config['approvecomments']);
            if (isset($config['copynewuser'])) {
                $v->set('copynewuser', $config['copynewuser']);
            }
            if (isset($config['copynewgroups'])) {
                $v->set('copynewgroups', $config['copynewgroups']);
            }
            $v->set('accessconf', $accessconf);
            $v->commit();
        }

        db_commit();
    }

722
    public function is_public() {
723
        $accessrecords = self::user_access_records($this->id, 0);
724
725
726
727
        if (!$accessrecords) {
            return false;
        }

728
729
730
        foreach($accessrecords as &$a) {
            if ($a->accesstype == 'public') {
                return true;
731
732
733
734
735
            }
        }
        return false;
    }

736
737
    public function set_access($accessdata) {
        global $USER;
738
        require_once('activity.php');
739
        require_once('group.php');
740
741
742

        $beforeusers = activity_get_viewaccess_users($this->get('id'), $USER->get('id'), 'viewaccess');

743
744
        $select = 'view = ? AND visible = 1 AND token IS NULL';

745
        db_begin();
746
        delete_records_select('view_access', $select, array($this->id));
747
748

        // View access
749
        $accessdata_added = array();
750
        if ($accessdata) {
751
752
753
754
            /*
             * There should be a cleaner way to do this
             * $accessdata_added ensures that the same access is not granted twice because the profile page
             * gets very grumpy if there are duplicate access rules
755
756
757
758
759
760
             *
             * Additional rules:
             * - Don't insert records with stopdate in the past
             * - Remove startdates that are in the past
             * - If view allows comments, access record comment permissions, don't apply, so reset them.
             * @todo: merge overlapping date ranges.
761
             */
762
            $time = time();
763
            foreach ($accessdata as $item) {
764
765
766
767
768
769
770
771
772
773
774
775

                if (!empty($item['stopdate']) && $item['stopdate'] < $time) {
                    continue;
                }
                if (!empty($item['startdate']) && $item['startdate'] < $time) {
                    unset($item['startdate']);
                }
                if ($this->get('allowcomments')) {
                    unset($item['allowcomments']);
                    unset($item['approvecomments']);
                }

776
777
778
779
780
781
782
783
784
785
786
                $accessrecord = (object)array(
                    'accesstype' => null,
                    'group' => null,
                    'role' => null,
                    'usr' => null,
                    'token' => null,
                    'startdate' => null,
                    'stopdate' => null,
                    'allowcomments' => 0,
                    'approvecomments' => 1,
                );
787
788
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

                switch ($item['type']) {
                case 'user':
                    $accessrecord->usr = $item['id'];
                    break;
                case 'group':
                    $accessrecord->group = $item['id'];
                    if (isset($item['role']) && strlen($item['role'])) {
                        // Don't insert a record for a role the group doesn't have
                        $roleinfo = group_get_role_info($item['id']);
                        if (!isset($roleinfo[$item['role']])) {
                            break;
                        }
                        $accessrecord->role = $item['role'];
                    }
                    break;
                case 'friends':
                    if (!$this->owner) {
                        continue; // Don't add friend access to group, institution or system views
                    }
                case 'public':
                case 'loggedin':
                    $accessrecord->accesstype = $item['type'];
                }

                if (isset($item['allowcomments'])) {
                    $accessrecord->allowcomments = (int) !empty($item['allowcomments']);
                    if ($accessrecord->allowcomments) {
                        $accessrecord->approvecomments = (int) !empty($item['approvecomments']);
                    }
                }
818
819
820
821
822
823
                if (isset($item['startdate'])) {
                    $accessrecord->startdate = db_format_timestamp($item['startdate']);
                }
                if (isset($item['stopdate'])) {
                    $accessrecord->stopdate  = db_format_timestamp($item['stopdate']);
                }
824

825
                if (array_search($accessrecord, $accessdata_added) === false) {
826
                    $accessrecord->view = $this->get('id');
827
                    insert_record('view_access', $accessrecord);
828
                    unset($accessrecord->view);
829
                    $accessdata_added[] = $accessrecord;
830
831
832
833
834
835
836
837
838
839
840
841
                }
            }
        }

        $data = new StdClass;
        $data->view = $this->get('id');
        $data->owner = $USER->get('id');
        $data->oldusers = $beforeusers;
        activity_occurred('viewaccess', $data);
        handle_event('saveview', $this->get('id'));

        db_commit();
842
        return $accessdata_added;
843
844
    }

845
    /**
846
847
     * Apply all the access rules among a set of views to every view in
     * the set.
848
     */
849
    public static function combine_access($viewids) {
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
        if (empty($viewids)) {
            return;
        }

        $select = 'view IN (' . join(',', array_map('intval', $viewids)) . ') AND visible = 1';

        if (!$access = get_records_select_array('view_access', $select)) {
            return;
        }

        $unique = array();
        foreach ($access as &$a) {
            unset($a->view);
            $k = serialize($a);
            if (!isset($unique[$k])) {
                $unique[$k] = $a;
            }
        }

        db_begin();

        delete_records_select('view_access', $select);

        foreach ($unique as &$a) {
            foreach ($viewids as $id) {
                $a->view = $id;
                insert_record('view_access', $a);
            }
        }

        db_commit();
    }

    /**
     * Copy access records from one view to a set of other views
     */
    public function copy_access($to) {
        if (empty($this->id)) {
            return;
        }

        $toupdate = array();
        foreach ($to as $viewid) {
            if ($this->id != $viewid) {
                $toupdate[] = (int) $viewid;
            }
        }

        if (empty($toupdate)) {
            return;
        }

902
903
904
905
906
907
        $firstviewaccess = get_records_select_array(
            'view_access',
            'view = ? AND visible = 1 AND token IS NULL',
            array($this->id)
        );

908
        db_begin();
909
910
911
912
913
914
915
916
917
918
919
920
921
        delete_records_select(
            'view_access',
            'view IN (' . join(',', $toupdate) . ') AND visible = 1 AND token IS NULL'
        );

        if ($firstviewaccess) {
            foreach ($toupdate as $id) {
                foreach ($firstviewaccess as &$a) {
                    $a->view = $id;
                    insert_record('view_access', $a);
                }
            }
        }
922
923
924
925
        db_commit();
    }


926
927
928
929
930
931
    public function get_autocreate_grouptypes() {
        if (!isset($this->copynewgroups)) {
            $this->copynewgroups = get_column('view_autocreate_grouptype', 'grouptype', 'view', $this->id);
        }
        return $this->copynewgroups;
    }
932

933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
    public function is_submitted() {
        return $this->get('submittedgroup') || $this->get('submittedhost');
    }

    public function submitted_to() {
        if ($group = $this->get('submittedgroup')) {
            return array('type' => 'group', 'id' => $group, 'name' => get_field('group', 'name', 'id', $group));
        }
        if ($host = $this->get('submittedhost')) {
            return array('type' => 'host', 'wwwroot' => $host, 'name' => get_field('host', 'name', 'wwwroot', $host));
        }
        return null;
    }

    public function release($releaseuser=null) {
948
        require_once(get_config('docroot') . 'artefact/lib.php');
949
950
951
        $submitinfo = $this->submitted_to();
        if (is_null($submitinfo)) {
            throw new ParameterException("View with id " . $this->get('id') . " has not been submitted");
952
953
        }
        $releaseuser = optional_userobj($releaseuser);
954
        db_begin();
955
        if ($submitinfo['type'] == 'group') {
956
            $group = $this->get('submittedgroup');
957
            $this->set('submittedgroup', null);
958
959
960
961
            if ($group) {
                // Remove hidden tutor view access records
                delete_records('view_access', 'view', $this->id, 'group', $group, 'visible', 0);
            }
962
963
964
965
        }
        else if ($submitinfo['type'] == 'host') {
            $this->set('submittedhost', null);
        }
966
        $this->set('submittedtime', null);
967
        $this->commit();
968
        ArtefactType::update_locked($this->owner);
969
        db_commit();
970
        $ownerlang = get_user_language($this->get('owner'));
971
        $url = get_config('wwwroot') . 'view/view.php?id=' . $this->get('id');
972
973
        require_once('activity.php');
        activity_occurred('maharamessage', 
974
975
976
977
978
979
980
            array(
                'users' => array($this->get('owner')),
                'subject' => get_string_from_language($ownerlang, 'viewreleasedsubject', 'group', $this->get('title'),
                    $submitinfo['name'], display_name($releaseuser, $this->get_owner_object())),
                'message' => get_string_from_language($ownerlang, 'viewreleasedmessage', 'group', $this->get('title'),
                    $submitinfo['name'], display_name($releaseuser, $this->get_owner_object())),
                'url' => $url,
981
                'urltext' => $this->get('title'),
982
983
            )
        );
984
985
    }

986
987
988
    /**
     * Returns HTML for the category list
     *
989
     * @param string $category The currently selected category
990
    */
991
992
    public function build_category_list($category, $new=0) {
        $categories = $this->get_category_data();
993
994
995
996
997
998
999
        $flag = false;
        foreach ($categories as &$cat) {
            $classes = '';
            if (!$flag) {
                $flag = true;
                $classes[] = 'first';
            }
1000
            if ($category == $cat['name']) {