view.php 274 KB
Newer Older
Penny Leach's avatar
Penny Leach committed
1
2
3
4
5
<?php
/**
 *
 * @package    mahara
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
Penny Leach's avatar
Penny Leach committed
9
10
11
12
13
14
15
 *
 */

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

class View {

16
17
18
19
20
    private $dirty;
    private $deleted;
    private $id;
    private $owner;
    private $ownerformat;
21
    private $group;
22
    private $institution;
23
24
25
    private $ctime;
    private $mtime;
    private $atime;
26
27
    private $startdate;
    private $stopdate;
28
29
    private $submittedgroup;
    private $submittedhost;
30
    private $submittedtime;
31
    private $submittedstatus;
32
33
34
35
36
37
38
    private $title;
    private $description;
    private $loggedin;
    private $friendsonly;
    private $artefact_instances;
    private $artefact_metadata;
    private $ownerobj;
39
    private $groupobj;
40
    private $institutionobj;
41
    private $numcolumns; // Obsolete - need to leave for upgrade purposes. This can be deleted once we no longer need to support direct upgrades from 15.10 and earlier.
42
43
    private $columnsperrow; // assoc array of rows set and get using view_rows_columns db table
    private $numrows;
44
    private $layout;
Nigel McNie's avatar
Nigel McNie committed
45
    private $theme;
46
    private $rows;
47
    private $columns;
48
49
    private $dirtyrows; // for when we change stuff
    private $dirtycolumns; // now includes reference to row [row][column]
50
    private $tags;
51
    private $categorydata;
52
    private $template;
53
    private $retainview;
54
    private $copynewuser = 0;
55
    private $copynewgroups;
56
    private $type;
57
    private $visits;
58
    private $allowcomments;
59
    private $approvecomments;
60
    private $collection;
61
    private $locked;
62
    private $urlid;
63
    private $skin;
64
    private $anonymise = 0;
Penny Leach's avatar
Penny Leach committed
65

66
67
68
69
    const UNSUBMITTED = 0;
    const SUBMITTED = 1;
    const PENDING_RELEASE = 2;

70
71
72
73
    // constansts view templates
    const USER_TEMPLATE = 1;
    const SITE_TEMPLATE = 2;

74
75
76
77
78
79
80
81
82
83
84
85
    /**
     * Which view layout is considered the "default" for views with the given
     * number of columns. Must be present in $layouts of course.
     */
    public static $defaultcolumnlayouts = array(
            1 => '100',
            2 => '50,50',
            3 => '33,33,33',
            4 => '25,25,25,25',
            5 => '20,20,20,20,20',
    );

86
    /**
87
88
89
     * Valid view column layouts. These are read at install time and inserted into
     * view_layout_columns, but not updated afterwards, so if you're changing one
     * you'll need to do that manually.
90
91
92
     *
     * The key represents the number of columns, and the value is an array of all the
     * view_layout_columns records that have that number of columns
93
     */
94
    public static $basic_column_layouts = array(
95
96
97
98
99
100
101
102
103
104
105
        1 => array(
            '100',
        ),
        2 => array(
            '50,50',
            '67,33',
            '33,67',
        ),
        3 => array(
            '33,33,33',
            '25,50,25',
106
107
            '25,25,50',
            '50,25,25',
108
109
110
111
112
113
114
115
116
117
118
            '15,70,15',
        ),
        4 => array(
            '25,25,25,25',
            '20,30,30,20',
        ),
        5 => array(
            '20,20,20,20,20',
        ),
    );

119
120
121
122
123
124
    /**
     * The default layout options to be read at install time.
     * Each view_layout record is based on the array key and the count of its values.
     * Each view_layout_rows_columns record is based on the sub array.
     * For example:
     *  18 => array(
125
126
127
128
129
     *              1 => '100',
     *              2 => '50,50',
     *              3 => '100'
     *              'order' => 3
     *  ),
130
     * will insert a record in view_layout with id = 18 and rows = 3
131
132
133
134
     * and will insert 3 records in view_layout_rows_columns:
     *  - viewlayout = 18, rows = 1, columns = 1
     *  - viewlayout = 18, rows = 2, columns = 2
     *  - viewlayout = 18, rows = 3, columns = 1
135
     * And the "order" key indicates that this should be the 3rd option in the layout menu
136
137
138
     */
    public static $defaultlayoutoptions = array(
        1 => array(
139
140
                1 => '100',
                'order' => 1,
141
142
            ),
        2 => array(
143
144
                1 => '50,50',
                'order' => 2,
145
146
            ),
        3 => array(
147
148
                1 => '67,33',
                'order' => 3,
149
150
            ),
        4 => array(
151
152
                1 => '33,67',
                'order' => 4,
153
154
            ),
        5 => array(
155
156
                1 => '33,33,33',
                'order' => 5,
157
158
            ),
        6 => array(
159
160
                1 => '25,50,25',
                'order' => 6,
161
162
            ),
        7 => array(
163
                1 => '25,25,50'
164
165
            ),
        8 => array(
166
                1 => '50,25,25'
167
168
            ),
        9 => array(
169
                1 => '15,70,15'
170
171
            ),
        10 => array(
172
                1 => '25,25,25,25'
173
174
            ),
        11 => array(
175
                1 => '20,30,30,20'
176
177
            ),
        12 => array(
178
                1 => '20,20,20,20,20'
179
180
            ),
        13 => array(
181
182
                1 => '100',
                2 => '25,50,25'
183
184
            ),
        14 => array(
185
186
187
                1 => '100',
                2 => '33,67',
                'order' => 7
188
189
            ),
        15 => array(
190
191
                1 => '100',
                2 => '67,33'
192
193
            ),
        16 => array(
194
195
                1 => '100',
                2 => '50,50'
196
197
            ),
        17 => array(
198
199
200
                1 => '100',
                2 => '33,33,33',
                'order' => 8
201
202
            ),
        18 => array(
203
204
205
                1 => '100',
                2 => '50,50',
                3 => '100'
206
207
            ),
        19 => array(
208
209
210
211
                1 => '100',
                2 => '33,33,33',
                3 => '100',
                'order' => 9
212
213
            ),
        20 => array(
214
215
216
                1 => '100',
                2 => '25,50,25',
                3 => '100'
217
218
            ),
        21 => array(
219
220
221
222
                1 => '100',
                2 => '50,50',
                3 => '33,33,33',
                'order' => 10
223
224
225
226
227
228
229
230
231
232
233
            ),
    );

    public static $maxlayoutrows = 6; // see number of colours avail in layoutpreview.php

    /**
     * For retrieving and checking numbers of columnns in any given row
     * Initialised in constructor
     * An array of objects which represent each row in view_layout_columns
     */
    public static $layoutcolumns;
234

Penny Leach's avatar
Penny Leach committed
235
    public function __construct($id=0, $data=null) {
236
        global $USER;
237
238
239
240
241
        if (is_array($id) && isset($id['urlid']) && isset($id['ownerurlid'])) {
            $tempdata = get_record_sql('
                SELECT v.*
                FROM {view} v JOIN {usr} u ON v.owner = u.id
                WHERE v.urlid = ? AND u.urlid = ?',
242
243
                array($id['urlid'], $id['ownerurlid']),
                ERROR_MULTIPLE
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
            );
            if (empty($tempdata)) {
                throw new ViewNotFoundException(get_string('viewnotfoundbyname', 'error', $id['urlid'], $id['ownerurlid']));
            }
        }
        else if (is_array($id) && isset($id['urlid']) && isset($id['groupurlid'])) {
            $tempdata = get_record_sql('
                SELECT v.*
                FROM {view} v JOIN {group} g ON v.group = g.id
                WHERE v.urlid = ? AND g.urlid = ? AND g.deleted = 0',
                array($id['urlid'], $id['groupurlid'])
            );
            if (empty($tempdata)) {
                throw new ViewNotFoundException(get_string('viewnotfoundbyname', 'error', $id['urlid'], $id['groupurlid']));
            }
        }
        else if (!empty($id) && is_numeric($id)) {
261
262
263
264
265
266
            $tempdata = get_record_sql('
                SELECT v.*
                FROM {view} v LEFT JOIN {group} g ON v.group = g.id
                WHERE v.id = ? AND (v.group IS NULL OR g.deleted = 0)',
                array($id)
            );
267
            if (empty($tempdata)) {
268
269
                throw new ViewNotFoundException(get_string('viewnotfound', 'error', $id));
            }
270
271
        }
        if (isset($tempdata)) {
272
273
274
275
276
277
            if (!empty($data)) {
                $data = array_merge((array)$tempdata, $data);
            }
            else {
                $data = $tempdata; // use what the database has
            }
278
            $this->id = $tempdata->id;
Penny Leach's avatar
Penny Leach committed
279
280
281
        }
        else {
            $this->ctime = time();
282
            $this->mtime = time();
Penny Leach's avatar
Penny Leach committed
283
            $this->dirty = true;
Penny Leach's avatar
Penny Leach committed
284
285
        }

286
287
        $data = empty($data) ? array() : (array)$data;
        foreach ($data as $field => $value) {
Penny Leach's avatar
Penny Leach committed
288
289
290
291
            if (property_exists($this, $field)) {
                $this->{$field} = $value;
            }
        }
292

293
294
295
296
        if (empty(self::$layoutcolumns)) {
            self::$layoutcolumns = get_records_assoc('view_layout_columns', '', '', 'columns,id');
        }

297
298
299
300
301
302
303
304
305
306
307
        // Add in owner and group objects if we already happen to have them from view_search(), etc.
        if (isset($data['user']) && isset($data['user']->id) && $data['user']->id == $this->owner) {
            $this->ownerobj = $data['user'];
        }
        else if (isset($data['groupdata']->id) && $data['groupdata']->id == $this->group) {
            $this->groupobj = $data['groupdata'];
        }
        else if (!isset($data['user']) && !empty($this->owner) && $this->owner == $USER->get('id')) {
            $this->ownerobj = $USER;
        }

Penny Leach's avatar
Penny Leach committed
308
        $this->atime = time();
309
        $this->rows = array();
310
        $this->columns = array();
311
        $this->dirtyrows = array();
312
        $this->dirtycolumns = array();
313
314

        // set only for existing views - _create provides default value
315
316
        // Ignore if the constructor is called with deleted set to true
        if (empty($this->columnsperrow) && empty($this->deleted)) {
317
            $this->columnsperrow = get_records_assoc('view_rows_columns', 'view', $this->get('id'), 'row', 'row, columns');
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
            if (empty($this->columnsperrow)) {
                // if we are missing the info for some reason we will give the page it's layout back
                // this can happen in MySQL when many users are copying the same page
                if ($this->layout) {
                    if ($rowscols = get_records_sql_array("
                        SELECT vlrc.row, vlc.columns
                        FROM {view_layout_rows_columns} vlrc
                        JOIN {view_layout_columns} vlc ON vlc.id = vlrc.columns
                        WHERE viewlayout = ?", array($this->layout))) {
                            $default = array();
                            foreach ($rowscols as $row) {
                                insert_record('view_rows_columns', (object) array(
                                    'view' => $this->get('id'),
                                    'row' => $row->row, 'columns' => $row->columns));
                                $default[$row->row] = $row;
                            }
                    }
                }
                else if ($rowscols = get_records_sql_array("
                    SELECT vrc.row, vrc.columns
                    FROM {view} v
                    JOIN {view_rows_columns} vrc ON vrc.view = v.id
                    WHERE v.template = ?
                    AND v.type = ?", array(self::SITE_TEMPLATE, $this->type))) {
                        // Layout not specified so use the view type default layout
                        $default = array();
                        foreach ($rowscols as $row) {
                            insert_record('view_rows_columns', (object) array(
                                'view' => $this->get('id'),
                                'row' => $row->row, 'columns' => $row->columns));
                            $default[$row->row] = $row;
                        }
                }
                else {
                    // Layout not known so make it 1 row / 3 cols
                    insert_record('view_rows_columns', (object) array(
                        'view' => $this->get('id'),
                        'row' => 1, 'columns' => 3));
                    $default = self::default_columnsperrow();
                }
                $this->columnsperrow = $default;
            }
360
        }
Penny Leach's avatar
Penny Leach committed
361
362
    }

363
364
    /**
     * Creates a new View for the given user/group/institution.
365
366
     *
     * You can specify who the view is being created _by_ with the second
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
     * 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;
    }

    /**
383
     * Creates a View for the given user, based off a given template and other
384
385
     * View information supplied.
     *
386
     * Will set a default title of 'Copy of $viewtitle' if title is not
387
     * specified in $viewdata and $titlefromtemplate == false.
388
389
390
     *
     * @param array $viewdata See View::_create
     * @param int $templateid The ID of the View to copy
391
     * @param int $userid     The user who has issued the command to create the
392
     *                        view. See View::_create
393
     * @param int $checkaccess Whether to check that the user can see the view before copying it
394
395
     * @param bool $titlefromtemplate Use the default title supplied by template
     * @param array $artefactcopies The mapping between old artefact ids and new ones (created in blockinstance copy)
396
397
     * @return array A list consisting of the new view, the template view and
     *               information about the copy - i.e. how many blocks and
398
     *               artefacts were copied
399
     * @throws SystemException under various circumstances, see the source for
400
401
     *                         more information
     */
402
    public static function create_from_template($viewdata, $templateid, $userid=null, $checkaccess=true, $titlefromtemplate=false, &$artefactcopies) {
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
        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");
        }

419
        if ($checkaccess && !$template->get('template') && !$user->can_edit_view($template)) {
420
421
            throw new SystemException("View::create_from_template: Attempting to create a View from another View that is not marked as a template");
        }
422
        else if ($checkaccess && !can_view_view($templateid, $userid)) {
423
424
425
426
427
428
            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
429
430
431
        if ($titlefromtemplate) {
            $view->set('title', $template->get('title'));
        }
432
        else if (!isset($viewdata['title'])
433
                && !($template->get('owner') === 0
434
                    && $template->get('type') == 'portfolio')) {
435
436
437
438
439
            $desiredtitle = $template->get('title');
            if (get_config('renamecopies')) {
                $desiredtitle = get_string('Copyof', 'mahara', $desiredtitle);
            }
            $view->set('title', self::new_title($desiredtitle, (object)$viewdata));
440
441
            $view->set('dirty', true);
        }
442

443
444
445
446
        $view->urlid = generate_urlid($view->title, get_config('cleanurlviewdefault'), 3, 100);
        $viewdata['owner'] = $userid;
        $view->urlid = self::new_urlid($view->urlid, (object)$viewdata);

447
        try {
448
            $copystatus = $view->copy_contents($template, $artefactcopies);
449
450
451
452
453
        }
        catch (QuotaExceededException $e) {
            db_rollback();
            return array(null, $template, array('quotaexceeded' => true));
        }
454
455

        $view->commit();
456

457
458
459
460
461
        // if layout is set, and it's not a default layout
        // add an entry to usr_custom_layout if one does not already exist
        if ($template->get('layout') !== null) {
            $customlayout = get_record('view_layout', 'id', $template->get('layout'), 'iscustom', 1);
            if ($customlayout !== false) {
462
463
464
                // is the owner of the copy going to be a group or institution or not?
                $group = $view->group;
                $institution = $view->institution;
465
466
467
468
469
470
471
472
473
                $owner = (!empty($institution) || !empty($group)) ? null : $view->owner;
                $data = (object) array(
                    'usr' => $owner,
                    'group' => $group,
                    'institution' => $institution,
                    'layout' =>  $template->get('layout'),
                );
                $where = clone $data;
                ensure_record_exists('usr_custom_layout', $where, $data);
474
475
476
            }
        }

477
478
479
        $blocks = get_records_array('block_instance', 'view', $view->get('id'));
        if ($blocks) {
            foreach ($blocks as $b) {
480
481
482
483
                // As some artefact references have been changed, e.g embedded images
                // we need to rebuild the artefact list for each block
                $bi = new BlockInstance($b->id);
                $bi->rebuild_artefact_list();
484
485
486
487
488
489
490
491
492
493
494
495
496
497
                $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);
            }
        }
498
499
500
501
502
503
504
505
506
507

        if ($template->get('retainview') && !$template->get('institution')) {
            $obj = new StdClass;
            $obj->view  = $view->get('id');
            $obj->ctime = db_format_timestamp(time());
            $obj->usr   = $template->get('owner');
            $obj->group = $template->get('group');
            insert_record('view_access', $obj);
        }

508
509
510
511
512
513
514
515
516
517
        db_commit();

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

    /**
518
     * Creates a new View for the given user, based on the given information
519
520
     * about the view.
     *
521
     * Validation of the view data is performed, then the View is created. If
522
523
     * the View is to be owned by a group, that group is given access to it.
     *
524
     * @param array $viewdata Data about the view. You can pass in most fields
525
526
     *                        that appear in the view table.
     *
527
528
     *                        Note that you set who owns the View by setting
     *                        either the owner, group or institution field as
529
530
     *                        approriate.
     *
531
532
     *                        Currently, you cannot pass in access data. Use
     *                        $view->set_access() after retrieving the $view
533
534
     *                        object.
     *
535
536
     * @param int $userid The user who has issued the command to create the
     *                    View (note: this is different from the "owner" of the
537
538
539
     *                    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
540
     * @throws SystemException if the View data is invalid - mostly this is due
541
542
543
     *                         to owner information being specified incorrectly.
     */
    private static function _create(&$viewdata, $userid) {
544
        // If no owner information is provided, assume that the view is being
545
546
547
548
549
550
551
552
553
554
555
556
557
558
        // 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']}");
                }
            }

559
            // Users can only have one view of each non-portfolio type
560
            if (isset($viewdata['type']) && $viewdata['type'] != 'portfolio' && get_record('view', 'owner', $viewdata['owner'], 'type', $viewdata['type'])) {
561
562
                $viewdata['type'] = 'portfolio';
            }
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
        }

        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(
582
            'numcolumns'    => 2, // Obsolete - need to leave for upgrade purposes. This can be deleted once we no longer need to support direct upgrades from 15.10 and earlier.
583
            'numrows'       => 1,
584
            'columnsperrow' => self::default_columnsperrow(),
585
586
587
            'template'      => 0,
            'type'          => 'portfolio',
            'title'         => (array_key_exists('title', $viewdata)) ? $viewdata['title'] : self::new_title(get_string('Untitled', 'view'), (object)$viewdata),
588
            'anonymise'     => 0,
589
590
591
592
        );

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

593
594
595
596
597
        if ($data->type == 'portfolio' && (!isset($data->url) || is_null($data->url) || !strlen($data->url))) {
            $data->urlid = generate_urlid($data->title, get_config('cleanurlviewdefault'), 3, 100);
            $data->urlid = self::new_urlid($data->urlid, $data);
        }

598
599
        $view = new View(0, $data);
        $view->commit();
600
601
602
        if (isset($viewdata['group']) &&
            (empty($viewdata['type']) || (!empty($viewdata['type']) && $viewdata['type'] != 'grouphomepage'))
           ) {
603
604
605
            require_once('activity.php');

            // Although group views are owned by the group, the view creator is treated as owner here.
606
607
            // So we need to ignore them from the activity_occured email.
            $beforeusers[$userid] = get_record('usr', 'id', $userid);
608

609
            // By default, group views should be visible to the group
610
611
612
            insert_record('view_access', (object) array(
                'view'  => $view->get('id'),
                'group' => $viewdata['group'],
613
                'ctime' => db_format_timestamp(time()),
614
            ));
615
616
617

            // Notify group members
            $accessdata = new StdClass;
618
            $accessdata->view = $view->get('id');
619
620
            $accessdata->oldusers = $beforeusers;
            activity_occurred('viewaccess', $accessdata);
621
622
        }

623
624
625
626
627
628
629
630
631
632
633
        if (isset($viewdata['layout'])) {
            // e.g. importing via LEAP2A
            $layoutsrowscols = get_records_select_array('view_layout_rows_columns', 'viewlayout = ?', array($viewdata['layout']));
            if ($layoutsrowscols) {
                delete_records('view_rows_columns', 'view', $view->get('id'));
                foreach ($layoutsrowscols as $layoutrow) {
                    insert_record('view_rows_columns', (object)array( 'view' => $view->get('id'), 'row' => $layoutrow->row, 'columns' =>  self::$layoutcolumns[$layoutrow->columns]->columns));
                }
            }
        }

634
        return new View($view->get('id')); // Reread to ensure defaults are set
635
636
    }

Son Nguyen's avatar
Son Nguyen committed
637
    public static function default_columnsperrow() {
638
639
        $default = array(1 => (object)array('row' => 1, 'columns' => 3, 'widths' => '33,33,33'));
        if (!$id = get_field('view_layout_columns', 'id', 'columns', $default[1]->columns, 'widths', $default[1]->widths)) {
640
            throw new SystemException("View::default_columnsperrow: Default columns = 3, widths = '33,33,33' not in view_layout_columns table");
641
642
643
644
        }
        return $default;
    }

Penny Leach's avatar
Penny Leach committed
645
646
647
648
    public function get($field) {
        if (!property_exists($this, $field)) {
            throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
        }
649
650
651
        if ($field == 'tags') { // special case
            return $this->get_tags();
        }
652
653
654
        if ($field == 'categorydata') {
            return $this->get_category_data();
        }
655
656
657
        if ($field == 'collection') {
            return $this->get_collection();
        }
658
659
660
        if ($field == 'columnsperrow') {
            return $this->get_columnsperrow();
        }
Penny Leach's avatar
Penny Leach committed
661
662
663
        return $this->{$field};
    }

664
665
666
667
668
669
670
    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;
671
672
673
674
675
            if ($field != 'atime') {
                // don't bother updating the modified time if we are
                // only wanting to update the accessed time
                $this->mtime = time();
            }
676
677
678
679
680
            return true;
        }
        throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
    }

681
682
683
684
685
686
687
    public function get_tags() {
        if (!isset($this->tags)) {
            $this->tags = get_column('view_tag', 'tag', 'view', $this->get('id'));
        }
        return $this->tags;
    }

688
689
690
    public function get_collection() {
        if (!isset($this->collection)) {
            require_once(get_config('libroot') . 'collection.php');
691
            $this->collection = Collection::search_by_view_id($this->id);
692
693
694
695
        }
        return $this->collection;
    }

696
697
698
699
700
701
702
    public function get_columnsperrow() {
        if (!isset($this->columnsperrow)) {
            $this->columnsperrow = get_records_assoc('view_rows_columns', 'view', $this->get('id'), 'row', 'row, columns');
        }
        return $this->columnsperrow;
    }

703
704
705
706
707
708
709
    public function collection_id() {
        if ($collection = $this->get_collection()) {
            return $collection->get('id');
        }
        return false;
    }

710
711
712
713
714
715
716
717
718
719
    /**
     * 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;
        }
720

721
722
723
724
725
        if (!empty($this->dirty)) {
            return $this->commit();
        }
    }

726
    /**
727
728
729
730
731
732
733
734
735
     * 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;
736
            if (in_array($k, array('mtime', 'ctime', 'atime', 'startdate', 'stopdate', 'submittedtime')) && !empty($v)) {
737
738
739
                $fordb->{$k} = db_format_timestamp($v);
            }
        }
740
741
742

        db_begin();

743
        if (empty($this->id)) {
744
            // users are only allowed one profile view
745
            if (!$this->template && $this->type == 'profile' && record_exists('view', 'owner', $this->owner, 'type', 'profile')) {
746
                throw new SystemException(get_string('onlonlyyoneprofileviewallowed', 'error'));
747
            }
748
749
750
751
752
            $this->id = insert_record('view', $fordb, 'id', true);
        }
        else {
            update_record('view', $fordb, 'id');
        }
753

754
        if (isset($this->tags)) {
755
            $this->tags = check_case_sensitive($this->tags, 'view_tag');
756
757
            delete_records('view_tag', 'view', $this->get('id'));
            foreach ($this->get_tags() as $tag) {
758
759
                //truncate the tag before insert it into the database
                $tag = substr($tag, 0, 128);
760
761
                insert_record('view_tag', (object)array( 'view' => $this->get('id'), 'tag' => $tag));
            }
762
763
        }

764
765
766
767
768
769
770
        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));
            }
        }

771
772
773
774
775
776
777
        if (isset($this->columnsperrow)) {
            delete_records('view_rows_columns', 'view', $this->get('id'));
            foreach ($this->get_columnsperrow() as $viewrow) {
                insert_record('view_rows_columns', (object)array( 'view' => $this->get('id'), 'row' => $viewrow->row, 'columns' => $viewrow->columns));
            }
        }

778
779
        db_commit();

780
781
782
783
        $this->dirty = false;
        $this->deleted = false;
    }

784
785
786
787
788
    /**
     * Returns an array of all the artefacts on this page.
     *
     * @return array
     */
Penny Leach's avatar
Penny Leach committed
789
    public function get_artefact_instances() {
790
        $this->artefact_instances = array();
Penny Leach's avatar
Penny Leach committed
791

792
793
794
795
796
797
        $sql = 'SELECT a.*, i.name, i.plugin, va.block
                FROM {view_artefact} va
                JOIN {artefact} a ON va.artefact = a.id
                JOIN {artefact_installed_type} i ON a.artefacttype = i.name
                WHERE va.view = ?';
        $this->artefact_metadata = get_records_sql_array($sql, array($this->id));
Penny Leach's avatar
Penny Leach committed
798

799
800
801
802
803
804
        if ($instances = $this->artefact_metadata) {
            foreach ($instances as $instance) {
                safe_require('artefact', $instance->plugin);
                $classname = generate_artefact_class_name($instance->artefacttype);
                $i = new $classname($instance->id, $instance);
                $this->artefact_instances[] = $i;
805
806
            }
        }
807
        return $this->artefact_instances;
Penny Leach's avatar
Penny Leach committed
808
    }
Penny Leach's avatar
Penny Leach committed
809
810

    public function get_owner_object() {
811
        if (empty($this->owner)) {
812
813
            return false;
        }
Penny Leach's avatar
Penny Leach committed
814
        if (!isset($this->ownerobj)) {
815
816
817
818
            // $this->ownerobj = get_user_for_display($this->get('owner'));
            $user = new User();
            $user->find_by_id($this->get('owner'));
            $this->ownerobj = $user;
Penny Leach's avatar
Penny Leach committed
819
820
821
822
        }
        return $this->ownerobj;
    }

823
824
    public function get_group_object() {
        if (!isset($this->groupobj)) {
825
            $this->groupobj = get_group_by_id($this->get('group'), true);
826
827
828
829
        }
        return $this->groupobj;
    }

830
831
832
833
834
835
836
    public function get_institution_object() {
        if (!isset($this->institutionobj)) {
            $this->institutionobj = get_record('institution', 'name', $this->get('institution'));
        }
        return $this->institutionobj;
    }

837
    public function delete() {
838
        safe_require('artefact', 'comment');
839
        db_begin();
840
        ArtefactTypeComment::delete_view_comments($this->id);
841
        delete_records('view_access','view',$this->id);
842
        delete_records('view_autocreate_grouptype', 'view', $this->id);
843
        delete_records('view_tag','view',$this->id);
844
        delete_records('view_visit','view',$this->id);
845
846
847
        if ($collection = $this->get_collection()) {
            $collection->remove_view($this->id);
        }
848
        delete_records('usr_watchlist_view','view',$this->id);
849
        if ($blockinstanceids = get_column('block_instance', 'id', 'view', $this->id)) {
850
            require_once(get_config('docroot') . 'blocktype/lib.php');
851
852
853
854
855
            foreach ($blockinstanceids as $id) {
                $bi = new BlockInstance($id);
                $bi->delete();
            }
        }
856
        handle_event('deleteview', $this->id);
857
        delete_records('view_rows_columns', 'view', $this->id);
858
        delete_records('view','id',$this->id);
859
860
861
862
863
        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);
        }
864
865
        require_once('embeddedimage.php');
        EmbeddedImage::delete_embedded_images('description', $this->id);
866
        $this->deleted = true;
867
        db_commit();
868
869
    }

870
871
872
873
874
875
    /* 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.
     */
876
    public function get_access($timeformat=null) {
877
        if ($data = $this->get_access_records()) {
878
            return $this->process_access_records($data, $timeformat);
879
880
881
        }
        return array();
    }
882

883
    public function get_access_records() {
884
        $data = get_records_sql_array("
885
            SELECT accesstype, va.group, institution, role, usr, startdate, stopdate, allowcomments, approvecomments
886
            FROM {view_access} va
887
            WHERE view = ? AND visible = 1 AND token IS NULL
888
889
890
            ORDER BY
                accesstype IS NULL, accesstype DESC,
                va.group, role IS NOT NULL, role,
891
                institution, usr,
892
893
                startdate IS NOT NULL, startdate, stopdate IS NOT NULL, stopdate,
                allowcomments, approvecomments",
894
895
            array($this->id)
        );
896
897
        return $data ? $data : array();
    }
898

899
    public function process_access_records($data=array(), $timeformat=null) {
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
        $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()
            );
        }
915

916
917
        foreach ($data as &$item) {
            $item = (array)$item;
Eugene Venter's avatar
Eugene Venter committed
918
            $item['locked'] = false; // Indicate if item is editable
919
920
921
922
923
924
925
926
            if ($item['usr']) {
                $item['type'] = 'user';
                $item['id'] = $item['usr'];
            }
            else if ($item['group']) {
                $item['type'] = 'group';
                $item['id'] = $item['group'];
            }
927
928
929
            else if ($item['institution']) {
                $item['type'] = 'institution';
                $item['id'] = $item['institution'];
930
931
932
933
934
935
936

                if ($this->type == 'profile') {
                    $myinstitutions = array_keys(load_user_institutions($this->owner));
                    if (in_array($item['id'], $myinstitutions) && empty($item['startdate']) && empty($item['stopdate'])) {
                        $item['locked'] = true;
                    }
                }
937
            }
938
939
940
941
942
            else {
                $item['type'] = $item['accesstype'];
                $item['id'] = null;
            }

943
944
945
946
            if ($this->type == 'profile' && $item['type'] == 'loggedin' && get_config('loggedinprofileviewaccess')) {
                $item['locked'] = true;
            }

947
948
949
950
951
952
            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']));
953
                }
954
955
                if ($item['stopdate']) {
                    $item['stopdate'] = strftime($timeformat, strtotime($item['stopdate']));
956
                }
957
            }
958
        }
959
960
961
        return $data;
    }

962
963
964
965
966
    public static function update_view_access($config, $viewids) {

        db_begin();

        // Use set_access() on the first view to get a hopefully consistent
967
        // and complete representation of the access list
968
        $firstview = new View($viewids[0]);
969
        $fullaccesslist = $firstview->set_access($config['accesslist'], $viewids, $config['allowcomments']);
970
971

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

974
975
976
        // 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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
        usort(
            $fullaccesslist,
            static function ($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 = !empty($a->institution) - !empty($b->institution))
                    || ($c = strcmp($a->institution, $b->institution))
                    || ($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;
            }
        );
998

999
1000
1001
1002
1003
1004
1005
1006
1007
        // Hash the config object so later on we can easily find
        // all the views with the same config/access rights
        $config['accesslist'] = $fullaccesslist;

        foreach ($viewids as $viewid) {
            $v = new View((int) $viewid);
            $v->set('startdate', $config['startdate']);
            $v->set('stopdate', $config['stopdate']);
            $v->set('template', $config['template']);
1008
            $v->set('retainview', $config['retainview']);
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
            $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->commit();
        }

        db_commit();
    }

1023
1024
1025
1026
    /* Returns preview image for creation of custom layout
     *
     * @param array
     * @return string SVG preview image
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
     */
    public function updatecustomlayoutpreview($values) {
        require_once(get_config('libroot') . 'layoutpreviewimage.php');

        $require = array('numrows');
        foreach ($require as $require) {
            if (!array_key_exists($require, $values) || empty($values[$require])) {
                throw new ParamOutOfRangeException(get_string('missingparam' . $require, 'error'));
            }
        }

        $numrows = $values['numrows'];
        $collayouts = array();
        for ($i=0; $i<$numrows; $i++) {
            if (array_key_exists('row'. ($i+1), $values)) {
                $collayouts['row' . ($i+1)] = $values['row' . ($i+1)];
            }
        }

        $alttext = '';
        $customlayout = array();
        for ($i=0; $i<$numrows; $i++) {
            $id = $collayouts['row' . ($i+1)];
            $widths = get_field('view_layout_columns', 'widths', 'id', $id);
1051
            $customlayout[$i+1] = $widths;
1052
1053
            $hyphenatedwidths = str_replace(',', '-', $widths);
            $alttext .= $hyphenatedwidths;
1054
            if ($i != $numrows - 1) {
1055
1056
1057
1058
                $alttext .= ' / ';
            }
        }

1059
1060
1061
1062
1063
1064
1065
1066
1067
        // Generate thumbnail images.
        $data = array();
        $data['layout'] = $customlayout;
        $data['text'] = $alttext;

        $previewlayoutimage = new LayoutPreviewImage($data);
        $previewimage = $previewlayoutimage->create_preview();

        return $previewimage;
1068
1069
    }

1070
1071
1072
1073
1074
1075
1076
    /*
     * Adds custom layout records to database and returns an array
    * with layout id and image preview.
    *
    * @param array
    * @return array
    */
1077
    public function addcustomlayout($values) {
1078
        require_once(get_config('libroot') . 'layoutpreviewimage.php');
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
        $require = array('numrows');
        foreach ($require as $require) {
            if (!array_key_exists($require, $values) || empty($values[$require])) {
                throw new ParamOutOfRangeException(get_string('missingparam' . $require, 'error'));
            }
        }

        $numrows = $values['numrows'];
        $alttext = '';
        $rowscolssql = '';
        $rowscols = array();

        for ($i=0; $i<$numrows; $i++) {
            if (array_key_exists('row'. ($i+1), $values)) {
                $rowscolssql .= '(row = ' . ($i+1) . ' AND columns = ' . $values['row' . ($i+1)] . ')';
                if ($i != $numrows-1) {
                    $rowscolssql .= ' OR ';
                }
                $widths = get_field('view_layout_columns', 'widths', 'id', $values['row' . ($i+1)]);
                $hyphenatedwidths = str_replace(',', '-', $widths);
                $alttext .= $hyphenatedwidths;
                if ($i != $numrows -1) {
                    $alttext .= ' / ';
                }
                $rowscols[$i+1] = $values['row' . ($i+1)];
            }
        }

1107
        $owner = $this->owner;
1108
1109
1110
        $group = $this->group;
        $institution = $this->institution;
        if (!empty($group)) {
1111
1112
            $owner = null;
            $andclause = 'AND ucl.group = ?';
1113
1114
1115
1116
1117
1118
            $andclausevalue = $group;
        }
        else if (!empty($institution)) {
            $owner = null;
            $andclause = 'AND ucl.institution = ?';
            $andclausevalue = $institution;
1119
1120
1121
        }
        else if (isset($owner)) {
            $andclause = 'AND ucl.usr = ?';
1122
            $andclausevalue = $owner;
1123
1124
        }
        else {
1125
1126
1127
            // no group or owner or institution set
            // site pages should have institution set
            throw new SystemException("View::addcustomlayout: No owner, group or institution set for view.");
1128
1129
        }

1130
        // check for existing layout
1131
1132
1133
1134
        $sql = 'SELECT vlrc.viewlayout AS id
                FROM
                {view_layout} vl
                INNER JOIN {view_layout_rows_columns} vlrc
1135
                ON vl.id = vlrc.viewlayout
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
                INNER JOIN (
                    SELECT
                    viewlayout, COUNT(*)
                    FROM {view_layout_rows_columns}
                    GROUP BY viewlayout
                    HAVING COUNT(*) = ?
                    ) vlrc2
                ON vlrc.viewlayout = vlrc2.viewlayout
                INNER JOIN {usr_custom_layout} ucl
                ON ucl.layout = vl.id
                WHERE (' . $rowscolssql . ')
                AND (
                   vl.iscustom = 0
                   OR (
1150
                       vl.iscustom = 1 ' . $andclause . '
1151
1152
1153
1154
1155
                      )
                )
                GROUP BY vlrc.viewlayout
                HAVING count(*) = ?
                LIMIT 1';
1156
        $layoutids = get_records_sql_array($sql, array($numrows, $andclausevalue, $numrows));
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171

        if ($layoutids) {
            $data = array('layoutid' => $layoutids[0]->id, 'newlayout' => 0);
            return $data;
        }
        else {

            db_begin();
            // no existing layout of this kind, create it
            $newlayoutid = insert_record('view_layout', (object) array('rows' => $numrows, 'iscustom' => 1), 'id', true);
            if (!$newlayoutid) {
                db_rollback();
                throw new SystemException("View::addcustomlayout: Couldn't create new layout record.");
            }

1172
1173
1174
1175
1176
1177
1178
1179
1180
            $owner = (!empty($institution) || !empty($group)) ? null : $owner;
            $data = (object) array(
                'usr' => $owner,
                'group' => $group,
                'institution' => $institution,
                'layout' =>  $newlayoutid,
            );
            $where = clone $data;
            ensure_record_exists('usr_custom_layout', $where, $data);
1181
1182
1183

            for ($i=0; $i<$numrows; $i++) {
                if (array_key_exists(($i+1), $rowscols)) {
1184
                    $widths = get_field('view_layout_columns', 'widths', 'id', $rowscols[$i+1]);
1185
                    $structure['layout']['row' . ($i + 1)] = $widths;
1186
1187
1188
1189
1190
1191
1192
1193
1194
                    $newrec = insert_record('view_layout_rows_columns', (object) array('viewlayout' => $newlayoutid, 'row' => ($i+1), 'columns' => $rowscols[$i+1]));
                    if (!$newrec) {
                        db_rollback();
                        throw new SystemException("View::addcustomlayout: Couldn't create new vlrc record.");
                    }
                }
            }

            db_commit();
1195
1196
1197
1198
1199

            // Generate new custom layout preview.
            $structure['text'] = $alttext;
            $layoutpreview = new LayoutPreviewImage($structure);
            $preview = $layoutpreview->create_preview();
1200
1201
1202
1203
1204
1205
            $data = array(
                'layoutid' => $newlayoutid,
                'newlayout' => 1,
                'layoutpreview' => $preview,
                'text' => $structure['text']
            );
1206

1207
1208
1209
1210
            return $data;
        }
    }

1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
    /**
     * Returns true if the view is currently marked as objectionable
     *
     * @return boolean True if view is objectionable
     */
    public function is_objectionable() {
        $params = array('view', $this->id);
        return record_exists_select('objectionable', 'objecttype = ? AND objectid = ? AND resolvedby IS NULL', $params);
    }

1221
    public function is_public() {
1222
        $accessrecords = self::user_access_records($this->id, 0);
1223
1224
1225
1226
        if (!$accessrecords) {
            return false;
        }

1227
1228
1229
        foreach($accessrecords as &$a) {
            if ($a->accesstype == 'public') {
                return true;
1230
1231
1232
1233
1234
            }
        }
        return false;
    }

1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
    /**
     * Set the view access rules
     * @param  $accessdata     array  For each view access row
                                      Can contain id, type, startdate, stopdate, allowcomments, approvecomments
     * @param  $viewids        array  Contains ids of the views getting the access rules
     * @param  $allowcomments  bool   Holding the view wide allowcomments option
                                      Needed when changing this and saving page at same time
                                      as the views are not saved at this point.
     *
     * @return  $accessdata_added  array  The added access rows
     */
    public function set_access($accessdata, $viewids = null, $allowcomments = true) {
1247
        global $USER;
1248
        require_once('activity.php');
1249
        require_once('group.php');
1250
        require_once('institution.php');
1251

1252
        $beforeusers = activity_get_viewaccess_users($this->get('id'));
1253

1254
1255
        $select = 'view = ? AND visible = 1 AND token IS NULL';

1256
        db_begin();
1257
        delete_records_select('view_access', $select, array($this->id));
1258
1259

        // View access
1260
        $accessdata_added = array();
1261
        if ($accessdata) {
1262
1263
1264
1265
            /*
             * 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
1266
1267
1268
1269
1270
1271
             *
             * 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.
1272
             */
1273
            $time = time();
1274
            foreach ($accessdata as $item) {
1275
1276
1277
1278
1279
1280
1281

                if (!empty($item['stopdate']) && $item['stopdate'] < $time) {
                    continue;
                }
                if (!empty($item['startdate']) && $item['startdate'] < $time) {
                    unset($item['startdate']);
                }
1282
1283

                if ($allowcomments) {
1284
1285
1286
1287
                    unset($item['allowcomments']);
                    unset($item['approvecomments']);
                }

1288
                $accessrecord = (object)array(
1289
1290
1291
                    'accesstype'      => null,
                    'group'           => null,
                    'role'            => null,
1292
                    'institution'     => null,
1293
1294
1295
1296
1297
                    'usr'             => null,
                    'token'           => null,
                    'startdate'       => null,
                    'stopdate'        => null,
                    'allowcomments'   => 0,
1298
                    'approvecomments' => 1,
1299
                    'ctime'           => db_format_timestamp(time()),
1300
                );
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316

                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;
1317
1318
1319
                case 'institution':
                    $accessrecord->institution = $item['id'];
                    break;
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
                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']);
                    }
                }
1335
1336
1337
1338
1339
1340
                if (isset($item['startdate'])) {
                    $accessrecord->startdate = db_format_timestamp($item['startdate']);
                }
                if (isset($item['stopdate'])) {
                    $accessrecord->stopdate  = db_format_timestamp($item['stopdate']);
                }
1341

1342
                if (array_search($accessrecord, $accessdata_added) === false) {
1343
                    $accessrecord->view = $this->get('id');
1344
                    insert_record('view_access', $accessrecord);
1345
                    unset($accessrecord->view);