view.php 238 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 42 43
    private $numcolumns; // now redundant
    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 $accessconf;
62
    private $locked;
63
    private $urlid;
64
    private $skin;
65
    private $anonymise = 0;
Penny Leach's avatar
Penny Leach committed
66

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

71 72 73 74 75 76 77 78 79 80 81 82
    /**
     * 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',
    );

83
    /**
84 85 86
     * 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.
87 88 89
     *
     * 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
90
     */
91
    public static $basic_column_layouts = array(
92 93 94 95 96 97 98 99 100 101 102
        1 => array(
            '100',
        ),
        2 => array(
            '50,50',
            '67,33',
            '33,67',
        ),
        3 => array(
            '33,33,33',
            '25,50,25',
103 104
            '25,25,50',
            '50,25,25',
105 106 107 108 109 110 111 112 113 114 115
            '15,70,15',
        ),
        4 => array(
            '25,25,25,25',
            '20,30,30,20',
        ),
        5 => array(
            '20,20,20,20,20',
        ),
    );

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

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

Penny Leach's avatar
Penny Leach committed
232
    public function __construct($id=0, $data=null) {
233
        global $USER;
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
        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 = ?',
                array($id['urlid'], $id['ownerurlid'])
            );
            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)) {
257 258 259 260 261 262
            $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)
            );
263
            if (empty($tempdata)) {
264 265
                throw new ViewNotFoundException(get_string('viewnotfound', 'error', $id));
            }
266 267
        }
        if (isset($tempdata)) {
268 269 270 271 272 273
            if (!empty($data)) {
                $data = array_merge((array)$tempdata, $data);
            }
            else {
                $data = $tempdata; // use what the database has
            }
274
            $this->id = $tempdata->id;
Penny Leach's avatar
Penny Leach committed
275 276 277
        }
        else {
            $this->ctime = time();
278
            $this->mtime = time();
Penny Leach's avatar
Penny Leach committed
279
            $this->dirty = true;
Penny Leach's avatar
Penny Leach committed
280 281
        }

282 283
        $data = empty($data) ? array() : (array)$data;
        foreach ($data as $field => $value) {
Penny Leach's avatar
Penny Leach committed
284 285 286 287
            if (property_exists($this, $field)) {
                $this->{$field} = $value;
            }
        }
288

289 290 291 292
        if (empty(self::$layoutcolumns)) {
            self::$layoutcolumns = get_records_assoc('view_layout_columns', '', '', 'columns,id');
        }

293 294 295 296 297 298 299 300 301 302 303
        // 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
304
        $this->atime = time();
305
        $this->rows = array();
306
        $this->columns = array();
307
        $this->dirtyrows = array();
308
        $this->dirtycolumns = array();
309 310 311 312 313

        // set only for existing views - _create provides default value
        if (empty($this->columnsperrow)) {
            $this->columnsperrow = get_records_assoc('view_rows_columns', 'view', $this->get('id'), 'row', 'row, columns');
        }
Penny Leach's avatar
Penny Leach committed
314 315
    }

316 317
    /**
     * Creates a new View for the given user/group/institution.
318 319
     *
     * You can specify who the view is being created _by_ with the second
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
     * 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;
    }

    /**
336
     * Creates a View for the given user, based off a given template and other
337 338
     * View information supplied.
     *
339
     * Will set a default title of 'Copy of $viewtitle' if title is not
340
     * specified in $viewdata and $titlefromtemplate == false.
341 342 343
     *
     * @param array $viewdata See View::_create
     * @param int $templateid The ID of the View to copy
344
     * @param int $userid     The user who has issued the command to create the
345
     *                        view. See View::_create
346
     * @param int $checkaccess Whether to check that the user can see the view before copying it
347 348
     * @return array A list consisting of the new view, the template view and
     *               information about the copy - i.e. how many blocks and
349
     *               artefacts were copied
350
     * @throws SystemException under various circumstances, see the source for
351 352
     *                         more information
     */
353
    public static function create_from_template($viewdata, $templateid, $userid=null, $checkaccess=true, $titlefromtemplate=false) {
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
        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");
        }

370
        if ($checkaccess && !$template->get('template') && !$user->can_edit_view($template)) {
371 372
            throw new SystemException("View::create_from_template: Attempting to create a View from another View that is not marked as a template");
        }
373
        else if ($checkaccess && !can_view_view($templateid, $userid)) {
374 375 376 377 378 379
            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
380 381 382 383
        if ($titlefromtemplate) {
            $view->set('title', $template->get('title'));
        }
        else if (!isset($viewdata['title'])) {
384 385 386 387 388
            $desiredtitle = $template->get('title');
            if (get_config('renamecopies')) {
                $desiredtitle = get_string('Copyof', 'mahara', $desiredtitle);
            }
            $view->set('title', self::new_title($desiredtitle, (object)$viewdata));
389 390
            $view->set('dirty', true);
        }
391

392 393 394 395
        $view->urlid = generate_urlid($view->title, get_config('cleanurlviewdefault'), 3, 100);
        $viewdata['owner'] = $userid;
        $view->urlid = self::new_urlid($view->urlid, (object)$viewdata);

396 397 398 399 400 401 402
        try {
            $copystatus = $view->copy_contents($template);
        }
        catch (QuotaExceededException $e) {
            db_rollback();
            return array(null, $template, array('quotaexceeded' => true));
        }
403 404

        $view->commit();
405

406 407 408 409 410
        // 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) {
411
                // is the owner of the copy going to be a group or institution or not?
412
                $owner = $view->owner;
413 414 415
                $group = $view->group;
                $institution = $view->institution;
                $haslayout = false;
416

417
                if (!empty($group)) {
418 419 420
                    $owner = null;
                    $haslayout = get_record('usr_custom_layout', 'layout', $template->get('layout'), 'group', $group);
                }
421 422 423 424
                if (!empty($institution)) {
                    $owner = null;
                    $haslayout = get_record('usr_custom_layout', 'layout', $template->get('layout'), 'institution', $institution);
                }
425 426 427 428 429
                else if (isset($owner)) {
                    $haslayout = get_record('usr_custom_layout', 'layout', $template->get('layout'), 'usr', $owner);
                }

                if (!$haslayout) {
430
                    $newcustomlayout = insert_record('usr_custom_layout', (object) array('usr' => $owner, 'group' => $group, 'institution' => $institution, 'layout' => $template->get('layout')) );
431 432 433 434
                }
            }
        }

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
        $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);
            }
        }
452 453 454 455 456 457 458 459 460 461

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

462 463 464 465 466 467 468 469 470 471
        db_commit();

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

    /**
472
     * Creates a new View for the given user, based on the given information
473 474
     * about the view.
     *
475
     * Validation of the view data is performed, then the View is created. If
476 477
     * the View is to be owned by a group, that group is given access to it.
     *
478
     * @param array $viewdata Data about the view. You can pass in most fields
479 480
     *                        that appear in the view table.
     *
481 482
     *                        Note that you set who owns the View by setting
     *                        either the owner, group or institution field as
483 484
     *                        approriate.
     *
485 486
     *                        Currently, you cannot pass in access data. Use
     *                        $view->set_access() after retrieving the $view
487 488
     *                        object.
     *
489 490
     * @param int $userid The user who has issued the command to create the
     *                    View (note: this is different from the "owner" of the
491 492 493
     *                    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
494
     * @throws SystemException if the View data is invalid - mostly this is due
495 496 497
     *                         to owner information being specified incorrectly.
     */
    private static function _create(&$viewdata, $userid) {
498
        // If no owner information is provided, assume that the view is being
499 500 501 502 503 504 505 506 507 508 509 510 511 512
        // 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']}");
                }
            }

513
            // Users can only have one view of each non-portfolio type
514
            if (isset($viewdata['type']) && $viewdata['type'] != 'portfolio' && get_record('view', 'owner', $viewdata['owner'], 'type', $viewdata['type'])) {
515 516 517
                $viewdata['type'] = 'portfolio';
            }

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
            // 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']);
                }
535 536
                $ownerthemedata = $owner->get('institutiontheme');
                $ownertheme = isset($ownerthemedata->basename) ? $ownerthemedata->basename : null;
537
                if ($ownertheme && $ownertheme != get_config('theme') && $ownertheme != 'custom') {
538 539 540
                    $viewdata['theme'] = $ownertheme;
                }
            }
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
        }

        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(
560 561
            'numcolumns'    => 2,
            'numrows'       => 1,
562
            'columnsperrow' => self::default_columnsperrow(),
563 564 565
            'template'      => 0,
            'type'          => 'portfolio',
            'title'         => (array_key_exists('title', $viewdata)) ? $viewdata['title'] : self::new_title(get_string('Untitled', 'view'), (object)$viewdata),
566
            'anonymise'     => 0,
567 568 569 570
        );

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

571 572 573 574 575
        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);
        }

576 577
        $view = new View(0, $data);
        $view->commit();
578 579 580
        if (isset($viewdata['group']) &&
            (empty($viewdata['type']) || (!empty($viewdata['type']) && $viewdata['type'] != 'grouphomepage'))
           ) {
581 582 583
            require_once('activity.php');

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

587
            // By default, group views should be visible to the group
588 589 590
            insert_record('view_access', (object) array(
                'view'  => $view->get('id'),
                'group' => $viewdata['group'],
591
                'ctime' => db_format_timestamp(time()),
592
            ));
593 594 595

            // Notify group members
            $accessdata = new StdClass;
596
            $accessdata->view = $view->get('id');
597 598
            $accessdata->oldusers = $beforeusers;
            activity_occurred('viewaccess', $accessdata);
599 600
        }

601 602 603 604 605 606 607 608 609 610 611
        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));
                }
            }
        }

612
        return new View($view->get('id')); // Reread to ensure defaults are set
613 614
    }

Son Nguyen's avatar
Son Nguyen committed
615
    public static function default_columnsperrow() {
616 617 618 619 620 621 622
        $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)) {
            throw new SystemException("View::default_columnsperrow: Default columns = 3, widths = '33,33,33' not in view_layout_columns table");
        }
        return $default;
    }

Penny Leach's avatar
Penny Leach committed
623 624 625 626
    public function get($field) {
        if (!property_exists($this, $field)) {
            throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
        }
627 628 629
        if ($field == 'tags') { // special case
            return $this->get_tags();
        }
630 631 632
        if ($field == 'categorydata') {
            return $this->get_category_data();
        }
633 634 635
        if ($field == 'collection') {
            return $this->get_collection();
        }
636 637 638
        if ($field == 'columnsperrow') {
            return $this->get_columnsperrow();
        }
Penny Leach's avatar
Penny Leach committed
639 640 641
        return $this->{$field};
    }

642 643 644 645 646 647 648
    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;
649 650 651 652 653
            if ($field != 'atime') {
                // don't bother updating the modified time if we are
                // only wanting to update the accessed time
                $this->mtime = time();
            }
654 655 656 657 658
            return true;
        }
        throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
    }

659 660 661 662 663 664 665
    public function get_tags() {
        if (!isset($this->tags)) {
            $this->tags = get_column('view_tag', 'tag', 'view', $this->get('id'));
        }
        return $this->tags;
    }

666 667 668
    public function get_collection() {
        if (!isset($this->collection)) {
            require_once(get_config('libroot') . 'collection.php');
669
            $this->collection = Collection::search_by_view_id($this->id);
670 671 672 673
        }
        return $this->collection;
    }

674 675 676 677 678 679 680
    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;
    }

681 682 683 684 685 686 687
    public function collection_id() {
        if ($collection = $this->get_collection()) {
            return $collection->get('id');
        }
        return false;
    }

688 689 690 691 692 693 694 695 696 697
    /**
     * 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;
        }
698

699 700 701 702 703
        if (!empty($this->dirty)) {
            return $this->commit();
        }
    }

704
    /**
705 706 707 708 709 710 711 712 713
     * 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;
714
            if (in_array($k, array('mtime', 'ctime', 'atime', 'startdate', 'stopdate', 'submittedtime')) && !empty($v)) {
715 716 717
                $fordb->{$k} = db_format_timestamp($v);
            }
        }
718 719 720

        db_begin();

721
        if (empty($this->id)) {
722 723
            // users are only allowed one profile view
            if ($this->type == 'profile' && record_exists('view', 'owner', $this->owner, 'type', 'profile')) {
724
                throw new SystemException(get_string('onlonlyyoneprofileviewallowed', 'error'));
725
            }
726 727 728 729 730
            $this->id = insert_record('view', $fordb, 'id', true);
        }
        else {
            update_record('view', $fordb, 'id');
        }
731

732
        if (isset($this->tags)) {
733
            $this->tags = check_case_sensitive($this->tags, 'view_tag');
734 735
            delete_records('view_tag', 'view', $this->get('id'));
            foreach ($this->get_tags() as $tag) {
736 737
                //truncate the tag before insert it into the database
                $tag = substr($tag, 0, 128);
738 739
                insert_record('view_tag', (object)array( 'view' => $this->get('id'), 'tag' => $tag));
            }
740 741
        }

742 743 744 745 746 747 748
        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));
            }
        }

749 750 751 752 753 754 755
        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));
            }
        }

756 757
        db_commit();

758 759 760 761
        $this->dirty = false;
        $this->deleted = false;
    }

Penny Leach's avatar
Penny Leach committed
762 763 764 765 766 767 768 769
    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
770
                    $this->childreninstances[] = $i;
Penny Leach's avatar
Penny Leach committed
771 772 773 774 775 776 777
                }
            }
        }
        return $this->artefact_instances;
    }

    public function get_artefact_metadata() {
Penny Leach's avatar
Penny Leach committed
778
        if (!isset($this->artefact_metadata)) {
779
            $sql = 'SELECT a.*, i.name, va.block
780 781 782
                    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
783
                    WHERE va.view = ?';
784
            $this->artefact_metadata = get_records_sql_array($sql, array($this->id));
Penny Leach's avatar
Penny Leach committed
785 786 787
        }
        return $this->artefact_metadata;
    }
Penny Leach's avatar
Penny Leach committed
788

789
    public function find_artefact_children($artefact, $allchildren, &$refs) {
790

791
        $children = array();
792 793 794 795 796 797 798 799
        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;
800
                $children[$child->id]['children'] = $this->find_artefact_children($child,
801
                                                            $allchildren, $refs);
802 803 804 805 806 807
            }
        }

        return $children;
    }

Penny Leach's avatar
Penny Leach committed
808

Penny Leach's avatar
Penny Leach committed
809 810 811 812 813 814
    public function has_artefacts() {
        if ($this->get_artefact_metadata()) {
            return true;
        }
        return false;
    }
Penny Leach's avatar
Penny Leach committed
815 816

    public function get_owner_object() {
817
        if (empty($this->owner)) {
818 819
            return false;
        }
Penny Leach's avatar
Penny Leach committed
820
        if (!isset($this->ownerobj)) {
821
            $this->ownerobj = get_user_for_display($this->get('owner'));
Penny Leach's avatar
Penny Leach committed
822 823 824 825
        }
        return $this->ownerobj;
    }

826 827 828 829 830 831 832
    public function get_group_object() {
        if (!isset($this->groupobj)) {
            $this->groupobj = get_record('group', 'id', $this->get('group'));
        }
        return $this->groupobj;
    }

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

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

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

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

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

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

                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;
                    }
                }
936
            }
937 938 939 940 941
            else {
                $item['type'] = $item['accesstype'];
                $item['id'] = null;
            }

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

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

961 962 963 964 965 966 967 968
    /* 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))
969 970
            || ($c = !empty($a->institution) - !empty($b->institution))
            || ($c = strcmp($a->institution, $b->institution))
971 972 973 974 975 976 977 978 979 980 981
            || ($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;
    }

982 983 984 985 986
    public static function update_view_access($config, $viewids) {

        db_begin();

        // Use set_access() on the first view to get a hopefully consistent
987
        // and complete representation of the access list
988
        $firstview = new View($viewids[0]);
989
        $fullaccesslist = $firstview->set_access($config['accesslist'], $viewids);
990 991

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

994 995 996 997 998
        // 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'));

999 1000 1001 1002 1003 1004 1005 1006 1007 1008
        // 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']);
1009
            $v->set('retainview', $config['retainview']);
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
            $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(</