collection.php 51.5 KB
Newer Older
1
2
3
4
5
6
<?php
/**
 *
 * @package    mahara
 * @subpackage core
 * @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.
9
10
11
12
13
 *
 */

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

14
15
16
17
18
19
class Collection {

    private $id;
    private $name;
    private $description;
    private $owner;
20
21
    private $group;
    private $institution;
22
23
    private $mtime;
    private $ctime;
24
    private $navigation;
25
26
27
    private $submittedgroup;
    private $submittedhost;
    private $submittedtime;
28
    private $submittedstatus;
29
    private $views;
30
    private $tags;
31
    private $framework;
32

33
34
35
36
    const UNSUBMITTED = 0;
    const SUBMITTED = 1;
    const PENDING_RELEASE = 2;

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    public function __construct($id=0, $data=null) {

        if (!empty($id)) {
            $tempdata = get_record('collection','id',$id);
            if (empty($tempdata)) {
                throw new CollectionNotFoundException("Collection with id $id not found");
            }
            if (!empty($data)) {
                $data = array_merge((array)$tempdata, $data);
            }
            else {
                $data = $tempdata; // use what the database has
            }
            $this->id = $id;
        }
        else {
            $this->ctime = time();
            $this->mtime = time();
        }
56

57
58
59
60
61
62
63
        if (empty($data)) {
            $data = array();
        }
        foreach ((array)$data as $field => $value) {
            if (property_exists($this, $field)) {
                $this->{$field} = $value;
            }
64
        }
65
66
67
68
        if (empty($this->group) && empty($this->institution) && empty($this->owner)) {
            global $USER;
            $this->owner = $USER->get('id');
        }
69
70
    }

71
72
73
74
    public function get($field) {
        if (!property_exists($this, $field)) {
            throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
        }
75
76
77
        if ($field == 'tags') {
            return $this->get_tags();
        }
78
79
80
        if ($field == 'views') {
            return $this->views();
        }
81
82
        return $this->{$field};
    }
83

84
85
86
87
88
89
90
91
    public function set($field, $value) {
        if (property_exists($this, $field)) {
            $this->{$field} = $value;
            $this->mtime = time();
            return true;
        }
        throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
    }
92

93
    /**
94
     * Helper function to create or update a Collection from the supplied data.
95
96
     *
     * @param array $data
97
     * @return collection           The newly created/updated collection
98
99
     */
    public static function save($data) {
100
101
        if (array_key_exists('id', $data)) {
            $id = $data['id'];
102
            $state = 'updatecollection';
103
104
105
        }
        else {
            $id = 0;
106
            $state = 'createcollection';
107
108
        }
        $collection = new Collection($id, $data);
109
        $collection->set('mtime', time());
110
        $collection->commit();
111
112
        $views = $collection->get('views');
        $viewids = array();
113
114
115
116
        if (!empty($views)) {
            foreach ($views['views'] as $view) {
                $viewids[] = $view->view;
            }
117
118
119
        }
        $eventdata = array('id' => $collection->get('id'),
                           'name' => $collection->get('name'),
120
                           'eventfor' => 'collection',
121
122
                           'viewids' => $viewids);
        handle_event($state, $eventdata);
123
        return $collection; // return newly created Collections id
124
    }
125

126
127
128
129
130
    /**
     * Deletes a Collection
     *
     */
    public function delete() {
131
        $viewids = get_column('collection_view', 'view', 'collection', $this->id);
132
        db_begin();
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

        // Delete navigation blocks within the collection's views which point at this collection.
        if ($viewids) {
            $values = $viewids;
            $values[] = 'navigation';
            $navigationblocks = get_records_select_assoc(
                'block_instance', 'view IN (' . join(',', array_fill(0, count($viewids), '?')) . ') AND blocktype = ?',
                $values
            );
            if ($navigationblocks) {
                safe_require('blocktype', 'navigation');
                foreach ($navigationblocks as $b) {
                    $bi = new BlockInstance($b->id, $b);
                    $configdata = $bi->get('configdata');
                    if (isset($configdata['collection']) && $configdata['collection'] == $this->id) {
                        $bi->delete();
                    }
                }
            }
        }

Stacey Walker's avatar
Stacey Walker committed
154
        delete_records('collection_view','collection',$this->id);
155
        delete_records('tag', 'resourcetype', 'collection', 'resourceid', $this->id);
156
157
158
        if (is_plugin_active('lti', 'module')) {
            delete_records('lti_assessment_submission', 'collectionid', $this->id);
        }
159
        delete_records('collection','id',$this->id);
160
        delete_records('existingcopy', 'collection', $this->id);
161
162
163
164
165
166

        // Secret url records belong to the collection, so remove them from the view.
        // @todo: add user message to whatever calls this.
        if ($viewids) {
            delete_records_select('view_access', 'view IN (' . join(',', $viewids) . ') AND token IS NOT NULL');
        }
167
168
        $data = array('id' => $this->id,
                      'name' => $this->name,
169
                      'eventfor' => 'collection',
170
171
                      'viewids' => $viewids);
        handle_event('deletecollection', $data);
172
173
174
        db_commit();
    }

175
176
177
178
    /**
     * This method updates the contents of the collection table only.
     */
    public function commit() {
179
        global $USER;
180

181
        $fordb = new stdClass();
182
183
        foreach (get_object_vars($this) as $k => $v) {
            $fordb->{$k} = $v;
184
            if (in_array($k, array('mtime', 'ctime', 'submittedtime')) && !empty($v)) {
185
186
187
                $fordb->{$k} = db_format_timestamp($v);
            }
        }
188

189
        db_begin();
190

191
192
193
194
195
        // if id is not empty we are editing an existing collection
        if (!empty($this->id)) {
            update_record('collection', $fordb, 'id');
        }
        else {
196
197
            $id = insert_record('collection', $fordb, 'id', true);
            if ($id) {
198
                $this->set('id', $id);
199
            }
200
        }
201

202
        if (isset($this->tags)) {
203
204
205
206
207
208
209
210
211
212
213
214
215
216
            if ($this->group) {
                $ownertype = 'group';
                $ownerid = $this->group;
            }
            else if ($this->institution) {
                $ownertype = 'institution';
                $ownerid = $this->institution;
            }
            else {
                $ownertype = 'user';
                $ownerid = $this->owner;
            }
            delete_records('tag', 'resourcetype', 'collection', 'resourceid', $this->get('id'));
            $tags = check_case_sensitive($this->get_tags(), 'tag');
217
            foreach ($tags as $tag) {
218
219
                //truncate the tag before insert it into the database
                $tag = substr($tag, 0, 128);
220
                $tag = check_if_institution_tag($tag);
221
222
223
224
225
226
227
228
229
230
231
                insert_record('tag',
                    (object)array(
                        'resourcetype' => 'collection',
                        'resourceid' => $this->get('id'),
                        'ownertype' => $ownertype,
                        'ownerid' => $ownerid,
                        'tag' => $tag,
                        'ctime' => db_format_timestamp(time()),
                        'editedby' => $USER->get('id'),
                    )
                );
232
233
234
            }
        }

235
236
        db_commit();
    }
237

238
239
240
241
    /**
     * Generates a name for a newly created Collection
     */
    private static function new_name($name, $ownerdata) {
242
243
244
245
        $extText = get_string('version.', 'mahara');
        $tempname = preg_split('/ '. $extText . '[0-9]$/', $name);
        $name = $tempname[0];

246
247
248
249
250
        $taken = get_column_sql('
            SELECT name
            FROM {collection}
            WHERE ' . self::owner_sql($ownerdata) . "
                AND name LIKE ? || '%'", array($name));
251
252
253

        $ext = '';
        $i = 1;
254
255
        if ($taken) {
            while (in_array($name . $ext, $taken)) {
256
                $ext = ' ' . $extText . ++$i;
257
258
259
260
261
262
263
264
265
            }
        }
        return $name . $ext;
    }

    /**
     * Creates a Collection for the given user, based off a given template and other
     * Collection information supplied.
     *
266
267
     * Will set a default name of 'Copy of $collectiontitle' if name is not
     * specified in $collectiondata and $titlefromtemplate == false.
268
269
270
271
272
273
     *
     * @param array $collectiondata Contains information of the old collection, submitted in form
     * @param int $templateid The ID of the Collection to copy
     * @param int $userid     The user who has issued the command to create the
     *                        collection.
     * @param int $checkaccess Whether to check that the user can see the collection before copying it
274
275
     * @param boolean $titlefromtemplate  Title of new collection or view will be exactly copied from the template
     *
276
277
278
279
280
281
     * @return array A list consisting of the new collection, the template collection and
     *               information about the copy - i.e. how many blocks and
     *               artefacts were copied
     * @throws SystemException under various circumstances, see the source for
     *                         more information
     */
282
    public static function create_from_template($collectiondata, $templateid, $userid=null, $checkaccess=true, $titlefromtemplate=false) {
283
284
285
286
287
288
289
290
291
292
293
294
        require_once(get_config('libroot') . 'view.php');
        global $SESSION;

        if (is_null($userid)) {
            global $USER;
            $userid = $USER->get('id');
        }

        db_begin();

        $colltemplate = new Collection($templateid);

295
        $data = new stdClass();
296
297
298
299
300
301
302
303
304
305
306
307
308
        // Set a default name if one wasn't set in $collectiondata
        if ($titlefromtemplate) {
            $data->name = $colltemplate->get('name');
        }
        else if (!isset($collectiondata['name'])) {
            $desiredname = $colltemplate->get('name');
            if (get_config('renamecopies')) {
                $desiredname = get_string('Copyof', 'mahara', $desiredname);
            }
            $data->name = self::new_name($desiredname, (object)$collectiondata);
        }
        else {
            $data->name = $collectiondata['name'];
309
        }
310
        $data->description = $colltemplate->get('description');
311
        $data->tags = $colltemplate->get('tags');
312
        $data->navigation = $colltemplate->get('navigation');
313
314
315
316
317
318
319
320
321
322
323
324
        if (!empty($collectiondata['group'])) {
            $data->group = $collectiondata['group'];
        }
        else if (!empty($collectiondata['institution'])) {
            $data->institution = $collectiondata['institution'];
        }
        else if (!empty($collectiondata['owner'])) {
            $data->owner = $collectiondata['owner'];
        }
        else {
            $data->owner = $userid;
        }
Robert Lyon's avatar
Robert Lyon committed
325
        $data->framework = $colltemplate->get('framework');
326
        $data->submittedstatus = 0;
327
328
329
330
331
332
333

        $collection = self::save($data);

        $numcopied = array('pages' => 0, 'blocks' => 0, 'artefacts' => 0);

        $views = $colltemplate->get('views');
        $copyviews = array();
334
        $evidenceviews = array();
335
        $artefactcopies = array();
336
        foreach ($views['views'] as $v) {
337
338
339
340
341
342
343
            $values = array(
                'new' => true,
                'owner' => isset($data->owner) ? $data->owner : null,
                'group' => isset($data->group) ? $data->group : null,
                'institution' => isset($data->institution) ? $data->institution : null,
                'usetemplate' => $v->view
            );
344
            list($view, $template, $copystatus) = View::create_from_template($values, $v->view, $userid, $checkaccess, $titlefromtemplate, $artefactcopies);
345
346
347
348
            // Check to see if we need to re-map any framework evidence
            if (!empty($data->framework) && $userid == $data->owner && count_records('framework_evidence', 'view', $v->view)) {
                $evidenceviews[$v->view] = $view->get('id');
            }
349
350
351
352
353
354
355
356
357
358
359
360
            if (isset($copystatus['quotaexceeded'])) {
                $SESSION->clear('messages');
                return array(null, $colltemplate, array('quotaexceeded' => true));
            }
            $copyviews['view_' . $view->get('id')] = true;
            $numcopied['blocks'] += $copystatus['blocks'];
            $numcopied['artefacts'] += $copystatus['artefacts'];
        }
        $numcopied['pages'] = count($views['views']);

        $collection->add_views($copyviews);

361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
        // Update all the navigation blocks referring to this collection
        if ($viewids = get_column('collection_view', 'view', 'collection', $collection->get('id'))) {
            $navblocks = get_records_select_array(
                'block_instance',
                'view IN (' . join(',', array_fill(0, count($viewids), '?')) . ") AND blocktype = 'navigation'",
                $viewids
            );

            if ($navblocks) {
                safe_require('blocktype', 'navigation');
                foreach ($navblocks as $b) {
                    $bi = new BlockInstance($b->id, $b);
                    $configdata = $bi->get('configdata');
                    if (isset($configdata['collection']) && $configdata['collection'] == $templateid) {
                        $bi->set('configdata', array('collection' => $collection->get('id')));
                        $bi->commit();
                    }
                }
            }
        }
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
        // If there are views with framework evidence to re-map
        if (!empty($evidenceviews)) {
            // We need to get how the old views/artefacts/blocks/evidence fit together
            $evidences = get_records_sql_array('
                SELECT va.view, va.artefact, va.block, fe.*
                FROM {view} v
                JOIN {view_artefact} va ON va.view = v.id
                JOIN {artefact} a ON a.id = va.artefact
                JOIN {framework_evidence} fe ON fe.view = v.id
                WHERE v.id IN (' . join(',', array_keys($evidenceviews)) . ')
                AND a.id IN (' . join(',', array_keys($artefactcopies)) . ')
                AND fe.annotation = va.block', array());
            $newartefactcopies = array();
            foreach ($artefactcopies as $ac) {
                $newartefactcopies[$ac->newid] = 1;
            }
            // And get how the new views/artefacts/blocks fit together
            $newblocks = get_records_sql_assoc('
                SELECT va.artefact, va.view, va.block
                FROM {view} v
                JOIN {view_artefact} va ON va.view = v.id
                JOIN {artefact} a ON a.id = va.artefact
                WHERE v.id IN (' . join(',', array_values($evidenceviews)) . ')
                AND a.id IN (' . join(',', array_keys($newartefactcopies)) . ')
                AND artefacttype = ?', array('annotation'));

            foreach ($evidences as $evidence) {
                if (key_exists($evidence->artefact, $artefactcopies) && key_exists($artefactcopies[$evidence->artefact]->newid, $newartefactcopies)) {
                    $newartefact = $artefactcopies[$evidence->artefact]->newid;
                    $newevidence = new stdClass();
                    $newevidence->view = $newblocks[$newartefact]->view;
                    $newevidence->artefact = $newartefact;
                    $newevidence->annotation = $newblocks[$newartefact]->block;
                    $newevidence->framework = $evidence->framework;
                    $newevidence->element = $evidence->element;
                    $newevidence->state = 0;
                    $newevidence->reviewer = null;
                    $newevidence->ctime = $evidence->ctime;
                    $newevidence->mtime = $evidence->mtime;
                    insert_record('framework_evidence', $newevidence);
                }
            }
        }
424

425
426
427
428
429
430
431
432
433
        db_commit();

        return array(
            $collection,
            $colltemplate,
            $numcopied,
        );
    }

434
    /**
435
     * Returns a list of the current user, group, or institution collections
436
437
438
     *
     * @param offset current page to display
     * @param limit how many collections to display per page
439
440
     * @param groupid current group ID
     * @param institutionname current institution name
441
442
     * @return array (count: integer, data: array, offset: integer, limit: integer)
     */
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
    public static function get_mycollections_data($offset=0, $limit=10, $owner=null, $groupid=null, $institutionname=null) {
        if (!empty($groupid)) {
            $wherestm = '"group" = ?';
            $values = array($groupid);
            $count  = count_records('collection', 'group', $groupid);
        }
        else if (!empty($institutionname)) {
            $wherestm = 'institution = ?';
            $values = array($institutionname);
            $count  = count_records('collection', 'institution', $institutionname);
        }
        else if (!empty($owner)) {
            $wherestm = 'owner = ?';
            $values = array($owner);
            $count  = count_records('collection', 'owner', $owner);
        }
        else {
            $count = 0;
        }
        $data = array();
        if ($count > 0) {
            $data = get_records_sql_assoc("
465
466
467
468
469
470
471
                SELECT
                    c.id,
                    c.description,
                    c.name,
                    c.submittedgroup,
                    c.submittedhost,
                    c.submittedtime,
472
                    c.framework,
473
                    (SELECT COUNT(*) FROM {collection_view} cv WHERE cv.collection = c.id) AS numviews
474
                FROM {collection} c
475
476
477
478
                WHERE " . $wherestm .
                " ORDER BY c.name, c.ctime, c.id ASC
                ", $values, $offset, $limit);
        }
479

480
        self::add_submission_info($data);
481
        self::add_framework_urls($data);
482

483
        $result = (object) array(
484
485
            'count'  => $count,
            'data'   => $data,
486
487
488
489
490
            'offset' => $offset,
            'limit'  => $limit,
        );
        return $result;
    }
491

492
    private static function add_submission_info(&$data) {
493
494
495
        global $CFG;
        require_once($CFG->docroot . 'lib/group.php');

496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
        if (empty($data)) {
            return;
        }

        $records = get_records_sql_assoc('
            SELECT c.id, c.submittedgroup, c.submittedhost, ' . db_format_tsfield('submittedtime') . ',
                   sg.name AS groupname, sg.urlid, sh.name AS hostname
              FROM {collection} c
         LEFT JOIN {group} sg ON c.submittedgroup = sg.id
         LEFT JOIN {host} sh ON c.submittedhost = sh.wwwroot
             WHERE c.id IN (' . join(',', array_fill(0, count($data), '?')) . ')
               AND (c.submittedgroup IS NOT NULL OR c.submittedhost IS NOT NULL)',
            array_keys($data)
        );

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

        foreach ($records as $r) {
            if (!empty($r->submittedgroup)) {
                $groupdata = (object) array(
                    'id'    => $r->submittedgroup,
                    'name'  => $r->groupname,
                    'urlid' => $r->urlid,
                    'time'  => $r->submittedtime,
                );
                $groupdata->url = group_homepage_url($groupdata);
                $data[$r->id]->submitinfo = $groupdata;
            }
            else if (!empty($r->submittedhost)) {
                $data[$r->id]->submitinfo = (object) array(
                    'name' => $r->hostname,
                    'url'  => $r->submittedhost,
                    'time'  => $r->submittedtime,
                );
            }
        }
    }

536
537
538
539
    /**
    * Gets the fields for the new/edit collection form
    * - populates the fields with collection data if it is an edit
    *
540
    * @param array $collection
541
542
    * @return array $elements
    */
543
    public function get_collectionform_elements() {
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
        $elements = array(
            'name' => array(
                'type' => 'text',
                'defaultvalue' => null,
                'title' => get_string('name', 'collection'),
                'size' => 30,
                'rules' => array(
                    'required' => true,
                ),
            ),
            'description' => array(
                'type'  => 'textarea',
                'rows' => 10,
                'cols' => 50,
                'resizable' => false,
                'defaultvalue' => null,
                'title' => get_string('description', 'collection'),
            ),
562
563
564
565
566
567
            'tags'        => array(
                'type'         => 'tags',
                'title'        => get_string('tags'),
                'description'  => get_string('tagsdescprofile'),
                'defaultvalue' => null,
                'help'         => true,
568
                'institution'  =>  $this->institution,
569
            ),
570
            'navigation' => array(
571
                'type'  => 'switchbox',
572
573
574
575
                'title' => get_string('viewnavigation','collection'),
                'description' => get_string('viewnavigationdesc','collection'),
                'defaultvalue' => 1,
            ),
576
        );
577
        if ($frameworks = $this->get_available_frameworks()) {
578
579
580
581
582
583
584
585
586
587
588
589
590
            $options = array('' => get_string('noframeworkselected', 'module.framework'));
            foreach ($frameworks as $framework) {
                $options[$framework->id] = $framework->name;
            }
            $elements['framework'] = array(
                'type' => 'select',
                'title' => get_string('Framework', 'module.framework'),
                'options' => $options,
                'defaultvalue' => $this->framework,
                'width' => '280px',
                'description' => get_string('frameworkdesc', 'module.framework'),
            );
        }
591

592
        // populate the fields with the existing values if any
593
        if (!empty($this->id)) {
594
            foreach ($elements as $k => $element) {
595
596
597
598
599
600
                if ($k === 'tags') {
                    $elements[$k]['defaultvalue'] = $this->get_tags();
                }
                else {
                    $elements[$k]['defaultvalue'] = $this->$k;
                }
601
602
603
            }
            $elements['id'] = array(
                'type' => 'hidden',
604
                'value' => $this->id,
605
            );
606
607
608
609
610
611
612
613
614
615
616
617
618
619
        }
        if (!empty($this->group)) {
            $elements['group'] = array(
                'type' => 'hidden',
                'value' => $this->group,
            );
        }
        else if (!empty($this->institution)) {
            $elements['institution'] = array(
                'type' => 'hidden',
                'value' => $this->institution,
            );
        }
        else if (!empty($this->owner)) {
620
621
            $elements['owner'] = array(
                'type' => 'hidden',
622
                'value' => $this->owner,
623
            );
624
625
        }

626
627
        return $elements;
    }
628

629
    /**
630
     * Returns array of views in the current collection
631
     *
Aaron Wells's avatar
Aaron Wells committed
632
     * @return array views
633
     */
634
635
636
    public function views() {

        if (!isset($this->views)) {
637

638
            $sql = "SELECT v.id, cv.*, v.title, v.owner, v.group, v.institution, v.ownerformat, v.urlid
639
640
                FROM {collection_view} cv JOIN {view} v ON cv.view = v.id
                WHERE cv.collection = ?
641
                ORDER BY cv.displayorder, v.title, v.ctime ASC";
642

643
            $result = get_records_sql_assoc($sql, array($this->get('id')));
644

645
            if (!empty($result)) {
646
647
648
649
650
651
652
653
654
                require_once('view.php');
                View::get_extra_view_info($result, false, false);
                $result = array_values($result);
                $max = $min = $result[0]['displayorder'];
                foreach ($result as &$r) {
                    $max = max($max, $r['displayorder']);
                    $min = min($min, $r['displayorder']);
                    $r = (object) $r;
                }
655
                $this->views = array(
656
                    'views'     => array_values($result),
657
                    'count'     => count($result),
658
659
                    'max'       => $max,
                    'min'       => $min,
660
661
662
663
664
                );
            }
            else {
                $this->views = array();
            }
665

666
667
        }

668
        return $this->views;
669
    }
670

671
    /**
672
     * Check that a collection can have a framework
673
674
675
676
677
678
679
680
681
682
683
684
     *
     * @return bool
     */
    public function can_have_framework() {
        return ($this->get_framework_institution()) ? true : false;
    }

    /**
     * Check if any allowed institutions lets a collection have a framework
     * and return first valid one.
     *
     * Checks:
685
     * - The collection is not owned by a group
686
687
     * - The framework plugin is active
     * - The institution has 'SmartEvidence' turned on
688
     * - There are frameworks available for the institutions
689
     *
690
     * @return object $institution or false
691
     */
692
     public function get_framework_institution() {
693
694
695
696
        if (!empty($this->group)) {
            return false;
        }

697
        if (!is_plugin_active('framework', 'module')) {
698
699
            return false;
        }
700
        $allowsmartevidence = false;
701
702
        if ($this->institution) {
            $institution = $this->institution;
703
704
            $institution = new Institution($institution);
            $allowsmartevidence = ($institution->allowinstitutionsmartevidence) ? $institution : false;
705
706
707
708
        }
        else {
            $user = new User();
            $user->find_by_id($this->owner);
709
710
711
712
713
714
715
716
717
718
719
720
721
722
            $institutionids = array_keys($user->get('institutions'));
            if (!empty($institutionids)) {
                foreach ($institutionids as $institution) {
                    $institution = new Institution($institution);
                    if ($institution->allowinstitutionsmartevidence == true) {
                        $allowsmartevidence = $institution;
                        break;
                    }
                }
            }
            else {
                $institution = new Institution('mahara');
                $allowsmartevidence = ($institution->allowinstitutionsmartevidence) ? $institution : false;
            }
723
        }
724
        return $allowsmartevidence;
725
726
727
728
729
730
731
732
    }

    /**
     * Get available frameworks
     *
     * @return array Available frameworks
     */
    public function get_available_frameworks() {
733
734
        $institution = $this->get_framework_institution();
        if (!$institution) {
735
736
737
738
739
740
741
742
743
744
            return array();
        }

        if ($frameworks = Framework::get_frameworks($institution->name, true)) {
            // Inactive frameworks are only allowed if they were added to
            // collection when they were active.
            foreach ($frameworks as $key => $framework) {
                if (empty($framework->active) && $framework->id != $this->framework) {
                    unset ($frameworks[$key]);
                }
745
            }
746
            return $frameworks;
747
        }
748
        return array();
749
750
751
752
753
    }

    /**
     * Check that a collection has a framework
     * - The collection can have a framework
754
755
756
757
758
759
     * - It has a framework id
     * - It has views in the collection
     *
     * @return boolean
     */
    public function has_framework() {
760
        if (!$this->can_have_framework()) {
761
762
763
764
765
766
767
768
            return false;
        }
        if (empty($this->framework)) {
            return false;
        }
        if (!$this->views()) {
            return false;
        }
769
        if (!is_plugin_active('framework', 'module')) {
770
771
            return false;
        }
772
773
774
        return true;
    }

775
776
777
778
779
780
    /**
     * Get collection framework option for collection navigation
     *
     * @return object $option;
     */
    public function collection_nav_framework_option() {
781
        $option = new stdClass();
782
783
        $option->framework = $this->framework;
        $option->id = $this->id;
784
        $option->title = get_field('framework', 'name', 'id', $this->framework);
785
786
        $option->framework = true;

787
        $option->fullurl = self::get_framework_url($option);
788
789
790
791
792

        return $option;
    }

    /**
793
     * Adding the framework frameworkurl / fullurl to collections
794
     *
795
     * @param array  $data    Array of objects
796
     *
797
     * @return $data
798
     */
799
    public static function add_framework_urls(&$data) {
800
801
        if (is_array($data)) {
            foreach ($data as $k => $r) {
802
803
                $r->frameworkurl = self::get_framework_url($r, false);
                $r->fullurl = self::get_framework_url($r, true);
804
805
            }
        }
806
807
808
809
810
811
812
813
814
815
816
817
818
819
    }

    /**
     * Making the framework url
     *
     * @param object $data    Either a collection or standard object
     * @param bool   $fullurl Return full url rather than relative one
     *
     * @return $url
     */
    public static function get_framework_url($data, $fullurl = true) {
        $url = 'module/framework/matrix.php?id=' . $data->id;
        if ($fullurl) {
            return get_config('wwwroot') . $url;
820
        }
821
        return $url;
822
823
    }

824
    /**
825
826
     * Get the available views the current user can choose to add to their collections.
     * Restrictions on this list include:
827
     * - currently dashboard, group and profile views are ignored to solve access issues
828
     * - default pages (with template == 2) are ignored
829
     * - each view can only belong to one collection
830
     * - locked/submitted views can't be added to collections
831
832
833
     *
     * @return array $views
     */
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
    public static function available_views($owner=null, $groupid=null, $institutionname=null) {
        if (!empty($groupid)) {
            $wherestm = '"group" = ?';
            $values = array($groupid);
        }
        else if (!empty($institutionname)) {
            $wherestm = 'institution = ?';
            $values = array($institutionname);
        }
        else if (!empty($owner)) {
            $wherestm = 'owner = ?';
            $values = array($owner);
        }
        else {
            return array();
        }
850
        ($views = get_records_sql_array("SELECT v.id, v.title
851
852
853
854
            FROM {view} v
            LEFT JOIN {collection_view} cv ON cv.view = v.id
            WHERE " . $wherestm .
            "   AND cv.view IS NULL
855
                AND v.type NOT IN ('dashboard','grouphomepage','profile')
856
                AND v.template != 2
857
858
                AND v.submittedgroup IS NULL
                AND v.submittedhost IS NULL
859
860
861
862
            GROUP BY v.id, v.title
            ORDER BY v.title ASC
            ", $values))
            || ($views = array());
863
        return $views;
864
865
    }

866
    /**
867
     * Submits the selected views to the collection
868
869
870
871
872
     *
     * @param array values selected views
     * @return integer count so we know what SESSION message to display
     */
    public function add_views($values) {
873
        require_once(get_config('libroot') . 'view.php');
874

875
        $count = 0; // how many views we are adding
876
877
        db_begin();

878
        // each view was marked with a key of view_<id> in order to identify the correct items
879
        // from the form values
880
881
882
883
884
        foreach ($values as $key => $value) {
            if (substr($key,0,5) === 'view_' AND $value == true) {
                $cv = array();
                $cv['view'] = substr($key,5);
                $cv['collection'] = $this->get('id');
885
886
887
888
889

                // set displayorder value
                $max = get_field('collection_view', 'MAX(displayorder)', 'collection', $this->get('id'));
                $cv['displayorder'] = is_numeric($max) ? $max + 1 : 0;

890
891
892
893
                insert_record('collection_view', (object)$cv);
                $count++;
            }
        }
894

895
        $viewids = get_column('collection_view', 'view', 'collection', $this->id);
896
897

        // Set the most permissive access records on all views
898
        View::combine_access($viewids, true);
899

900
901
902
903
904
905
906
        // Copy the whole view config from the first view to all the others
        if (count($viewids)) {
            $firstview = new View($viewids[0]);
            $viewconfig = array(
                'startdate'       => $firstview->get('startdate'),
                'stopdate'        => $firstview->get('stopdate'),
                'template'        => $firstview->get('template'),
907
                'retainview'      => $firstview->get('retainview'),
908
909
910
                'allowcomments'   => $firstview->get('allowcomments'),
                'approvecomments' => (int) ($firstview->get('allowcomments') && $firstview->get('approvecomments')),
                'accesslist'      => $firstview->get_access(),
911
                'lockblocks'      => $firstview->get('lockblocks'),
912
913
914
915
            );
            View::update_view_access($viewconfig, $viewids);
        }

916
917
918
        // Now that we have added views to the collection we need to update the collection modified date
        $this->mtime = db_format_timestamp(time());
        $this->commit();
919
920
        db_commit();

921
922
        return $count;
    }
923

924
    /**
925
     * Removes the selected views from the collection
926
927
928
929
930
     *
     * @param integer $view the view to remove
     */
    public function remove_view($view) {
        db_begin();
931
932
933
934
935
936
937
938

        $position = get_field_sql('
            SELECT displayorder FROM {collection_view}
                WHERE collection = ?
                AND view = ?',
                array($this->get('id'),$view)
        );

939
        delete_records('collection_view','view',$view,'collection',$this->get('id'));
940

941
        $this->update_display_order($position);
942
943
944
945
        // Secret url records belong to the collection, so remove them from the view.
        // @todo: add user message to whatever calls this.
        delete_records_select('view_access', 'view = ? AND token IS NOT NULL', array($view));

946
947
948
949
        // Now that we have removed views from the collection we need to update the collection modified date
        $this->mtime = db_format_timestamp(time());
        $this->commit();

950
951
952
        db_commit();
    }

953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
    /**
     * Updates the position number of the views in a collection
     *
     * @param integer $start position from where to start updating
     */
    public function update_display_order($start = 0) {
        $start = intval($start);
        $ids = get_column_sql('
                SELECT view FROM {collection_view}
                WHERE collection = ?
                ORDER BY displayorder', array($this->get('id')));
        foreach ($ids as $k => $v) {
            if ($start <= $k) {
                set_field('collection_view', 'displayorder', $k, 'view', $v, 'collection',$this->get('id'));
            }
        }
    }

971
972
973
    /**
     * Sets the displayorder for a view
     *
974
975
976
977
     * @param integer   $id   view id
     * @param mixed  direction - either string consisting 'up' or 'down' to
     *               indicate which way to move $id item, or an array containing
     *               the ids in order you want them saved
978
979
     */
    public function set_viewdisplayorder($id, $direction) {
980
981
982
        if (is_array($direction)) {
            // we already have new sort order
            $neworder = $direction;
983
        }
984
985
986
987
988
989
990
991
992
993
994
995
        else {
            $ids = get_column_sql('
                SELECT view FROM {collection_view}
                WHERE collection = ?
                ORDER BY displayorder', array($this->get('id')));

            foreach ($ids as $k => $v) {
                if ($v == $id) {
                    $oldorder = $k;
                    break;
                }
            }
996

997
998
999
1000
1001
1002
1003
1004
1005
1006
            if ($direction == 'up' && $oldorder > 0) {
                $neworder = array_merge(array_slice($ids, 0, $oldorder - 1),
                                        array($id, $ids[$oldorder-1]),
                                        array_slice($ids, $oldorder+1));
            }
            else if ($direction == 'down' && ($oldorder + 1 < count($ids))) {
                $neworder = array_merge(array_slice($ids, 0, $oldorder),
                                        array($ids[$oldorder+1], $id),
                                        array_slice($ids, $oldorder+2));
            }
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
        }
        if (isset($neworder)) {
            foreach ($neworder as $k => $v) {
                set_field('collection_view', 'displayorder', $k, 'view', $v, 'collection',$this->get('id'));
            }
            $this->set('mtime', time());
            $this->commit();
        }
    }

1017
1018
1019
    /**
     * after editing the collection, redirect back to the appropriate place
     */
1020
1021
1022
1023
    public function post_edit_redirect($new=false, $copy=false, $urlparams=null) {
        if ($new || $copy) {
            $urlparams['id'] = $this->get('id');
            $redirecturl = '/collection/views.php';
1024
1025
        }
        else {
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
            if ($this->get('group')) {
                // Group owned collection
                $redirecturl = '/view/groupviews.php';
            }
            else if ($this->get('institution')) {
                if ($this->get('institution') == 'mahara') {
                    // Site owned collection
                    $redirecturl = '/admin/site/views.php';
                }
                else {
                    // Institution owned collection
                    $redirecturl = '/view/institutionviews.php';
                }
            }
            else {
                // User owned collection
                $redirecturl = '/view/index.php';
            }
1044
        }
1045
1046
1047
        if ($urlparams) {
            $redirecturl .= '?' . http_build_query($urlparams);
        }
1048
1049
1050
        redirect($redirecturl);
    }

1051
    public static function search_by_view_id($viewid) {
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
        $record = get_record_sql('
            SELECT c.*
            FROM {collection} c JOIN {collection_view} cv ON c.id = cv.collection
            WHERE cv.view = ?',
            array($viewid)
        );
        if ($record) {
            return new Collection(0, $record);
        }
        return false;
    }

1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
    /**
     * Returns an SQL snippet that can be used in a where clause to get views
     * with the given owner.
     *
     * @param object $ownerobj An object that has view ownership information -
     *                         either the institution, group or owner fields set
     * @return string
     */
    private static function owner_sql($ownerobj) {
        if (isset($ownerobj->institution)) {
            return 'institution = ' . db_quote($ownerobj->institution);
        }
        if (isset($ownerobj->group) && is_numeric($ownerobj->group)) {
            return '"group" = ' . (int)$ownerobj->group;
        }
        if (isset($ownerobj->owner) && is_numeric($ownerobj->owner)) {
            return 'owner = ' . (int)$ownerobj->owner;
        }
        throw new SystemException("View::owner_sql: Passed object did not have an institution, group or owner field");
    }
1084
1085
1086
1087
1088
1089
1090
1091
1092

    /**
     * Makes a URL for a collection
     *
     * @param bool $full return a full url
     * @param bool $useid ignore clean url settings and always return a url with an id in it
     *
     * @return string
     */
1093
    public function get_url($full=true, $useid=false, &$firstview=null) {
1094
        global $USER;
1095
        $firstview = null;
1096
1097
1098

        $views = $this->views();
        if (!empty($views)) {
1099
            if ($this->framework) {
1100
1101
                if ($full) {
                    $this->fullurl = Collection::get_framework_url($this);
1102
                    return $this->fullurl;
1103
1104
1105
                }
                else {
                    $this->frameworkurl = Collection::get_framework_url($this, false);
1106
                    return $this->frameworkurl;
1107
                }
1108
1109
            }

1110
1111
            $v = new View(0, $views['views'][0]);
            $v->set('dirty', false);
1112
            $firstview = $v;
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
            return $v->get_url($full, $useid);
        }

        log_warn("Attempting to get url for an empty collection");

        if ($this->owner === $USER->get('id')) {
            $url = 'collection/views.php?id=' . $this->id;
        }
        else {
            $url = '';
        }

        if ($full) {
            $url = get_config('wwwroot') . $url;
        }

        return $url;
    }

1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
    /**
     * Sets released submissions to pending release status and adds
     * the submission item to the export queue ready for archiving.
     *
     * @param object $releaseuser The user releasing the collection
     */
    public function pendingrelease($releaseuser=null) {
        $submitinfo = $this->submitted_to();
        if (!$this->is_submitted()) {
            throw new ParameterException("Collection with id " . $this->id . " has not been submitted");
        }
        $viewids = $this->get_viewids();
        db_begin();
        execute_sql("UPDATE {collection}
                     SET submittedstatus = " . self::PENDING_RELEASE . "
                     WHERE id = ?",
                     array($this->id)
        );
        View::_db_pendingrelease($viewids);
        db_commit();

        require_once(get_config('docroot') . 'export/lib.php');
        add_submission_to_export_queue($this, $releaseuser);
    }

1157
1158
1159
1160
1161
1162
    /**
     * Release a submitted collection
     *
     * @param object $releaseuser The user releasing the collection
     */
    public function release($releaseuser=null) {
1163
1164

        if (!$this->is_submitted()) {
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
            throw new ParameterException("Collection with id " . $this->id . " has not been submitted");
        }

        // One day there might be group and institution collections, so be safe
        if (empty($this->owner)) {
            throw new ParameterException("Collection with id " . $this->id . " has no owner");
        }

        $viewids = $this->get_viewids();

        db_begin();
        execute_sql('
            UPDATE {collection}
1178
1179
1180
1181
            SET submittedgroup = NULL,
                submittedhost = NULL,
                submittedtime = NULL,
                submittedstatus = ' . self::UNSUBMITTED . '
1182
1183
1184
1185
1186
1187
            WHERE id = ?',
            array($this->id)
        );
        View::_db_release($viewids, $this->owner, $this->submittedgroup);
        db_commit();

1188
1189
1190
1191
1192
        handle_event('releasesubmission', array('releaseuser' => $releaseuser,
                                                'id' => $this->get('id'),
                                                'groupname' => $this->submittedgroup,
                                                'eventfor' => 'collection'));

1193
1194
        // We don't send out notifications about the release of remote-submitted Views & Collections
        // (though I'm not sure why)
1195
1196
        // if the method is called in an upgrade and we dont have a release user
        if (!defined('INSTALLER') && $this->submittedgroup) {
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
            $releaseuser = optional_userobj($releaseuser);
            $releaseuserdisplay = display_name($releaseuser, $this->owner);
            $submitinfo = $this->submitted_to();

            require_once('activity.php');
            activity_occurred(
                'maharamessage',
                array(
                    'users' => array($this->get('owner')),
                    'strings' => (object) array(
                        'subject' => (object) array(
1208
                            'key'     => 'collectionreleasedsubject1',
1209
1210
1211
1212
                            'section' => 'group',
                            'args'    => array($this->name, $submitinfo->name, $releaseuserdisplay),
                        ),
                        'message' => (object) array(
1213
                            'key'     => 'collectionreleasedmessage1',
1214
1215
1216
                            'section' => 'group',
                            'args'    => array($this->name, $submitinfo->name, $releaseuserdisplay),
                        ),
1217
                    ),
1218
1219
1220
1221
1222
                    'url' => $this->get_url(false),
                    'urltext' => $this->name,
                )
            );
        }
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
    }

    public function get_viewids() {
        $ids = array();
        $viewdata = $this->views();

        if (!empty($viewdata['views'])) {
            foreach ($viewdata['views'] as $v) {
                $ids[] = $v->id;
            }
        }

        return $ids;
    }
1237
1238
1239
1240
1241

    public function is_submitted() {
        return $this->submittedgroup || $this->submittedhost;
    }

1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
    public function submitted_to() {
        if ($this->submittedgroup) {
            $record = get_record('group', 'id', $this->submittedgroup, null, null, null, null, 'id, name, urlid');
            $record->url = group_homepage_url($record);
        }
        else if ($this->submittedhost) {
            $record = get_record('host', 'wwwroot', $this->submittedhost, null, null, null, null, 'wwwroot, name');
            $record->url = $record->wwwroot;
        }
        else {
            throw new SystemException("Collection with id " . $this->id . " has not been submitted");
        }

        return $record;
    }

1258
1259
1260
1261
1262
1263
1264
    /**
     * Submit this collection to a group or a remote host (but only one or the other!)
     * @param object $group
     * @param string $submittedhost
     * @param int $owner The owner of the collection (if not just $USER)
     * @throws SystemException
     */