collection.php 46 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
102
103
104
105
106
        if (array_key_exists('id', $data)) {
            $id = $data['id'];
        }
        else {
            $id = 0;
        }
        $collection = new Collection($id, $data);
107
        $collection->set('mtime', time());
108
109
        $collection->commit();

110
        return $collection; // return newly created Collections id
111
    }
112

113
114
115
116
117
    /**
     * Deletes a Collection
     *
     */
    public function delete() {
118
        $viewids = get_column('collection_view', 'view', 'collection', $this->id);
119
        db_begin();
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

        // 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
141
        delete_records('collection_view','collection',$this->id);
142
        delete_records('collection_tag','collection',$this->id);
143
        delete_records('collection','id',$this->id);
144
145
146
147
148
149
150

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

151
152
153
        db_commit();
    }

154
155
156
157
158
159
160
161
    /**
     * This method updates the contents of the collection table only.
     */
    public function commit() {

        $fordb = new StdClass;
        foreach (get_object_vars($this) as $k => $v) {
            $fordb->{$k} = $v;
162
            if (in_array($k, array('mtime', 'ctime', 'submittedtime')) && !empty($v)) {
163
164
165
                $fordb->{$k} = db_format_timestamp($v);
            }
        }
166

167
        db_begin();
168

169
170
171
172
173
        // if id is not empty we are editing an existing collection
        if (!empty($this->id)) {
            update_record('collection', $fordb, 'id');
        }
        else {
174
175
            $id = insert_record('collection', $fordb, 'id', true);
            if ($id) {
176
                $this->set('id', $id);
177
            }
178
        }
179

180
181
        if (isset($this->tags)) {
            delete_records('collection_tag', 'collection', $this->get('id'));
182
183
            $tags = check_case_sensitive($this->get_tags(), 'collection_tag');
            foreach ($tags as $tag) {
184
185
186
187
188
189
                //truncate the tag before insert it into the database
                $tag = substr($tag, 0, 128);
                insert_record('collection_tag', (object)array( 'collection' => $this->get('id'), 'tag' => $tag));
            }
        }

190
191
        db_commit();
    }
192

193
194
195
196
    /**
     * Generates a name for a newly created Collection
     */
    private static function new_name($name, $ownerdata) {
197
198
199
200
        $extText = get_string('version.', 'mahara');
        $tempname = preg_split('/ '. $extText . '[0-9]$/', $name);
        $name = $tempname[0];

201
202
203
204
205
        $taken = get_column_sql('
            SELECT name
            FROM {collection}
            WHERE ' . self::owner_sql($ownerdata) . "
                AND name LIKE ? || '%'", array($name));
206
207
208

        $ext = '';
        $i = 1;
209
210
        if ($taken) {
            while (in_array($name . $ext, $taken)) {
211
                $ext = ' ' . $extText . ++$i;
212
213
214
215
216
217
218
219
220
            }
        }
        return $name . $ext;
    }

    /**
     * Creates a Collection for the given user, based off a given template and other
     * Collection information supplied.
     *
221
222
     * Will set a default name of 'Copy of $collectiontitle' if name is not
     * specified in $collectiondata and $titlefromtemplate == false.
223
224
225
226
227
228
229
230
231
232
233
234
     *
     * @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
     * @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
     */
235
    public static function create_from_template($collectiondata, $templateid, $userid=null, $checkaccess=true, $titlefromtemplate=false) {
236
237
238
239
240
241
242
243
244
245
246
247
248
        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);

        $data = new StdClass;
249
250
251
252
253
254
255
256
257
258
259
260
261
        // 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'];
262
        }
263
        $data->description = $colltemplate->get('description');
264
        $data->tags = $colltemplate->get('tags');
265
        $data->navigation = $colltemplate->get('navigation');
266
267
268
269
270
271
272
273
274
275
276
277
        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
278
        $data->framework = $colltemplate->get('framework');
279
280
281
282
283
284
285

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

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

        $views = $colltemplate->get('views');
        $copyviews = array();
286
        $evidenceviews = array();
287
        $artefactcopies = array();
288
        foreach ($views['views'] as $v) {
289
290
291
292
293
294
295
            $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
            );
296
            list($view, $template, $copystatus) = View::create_from_template($values, $v->view, $userid, $checkaccess, $titlefromtemplate, $artefactcopies);
297
298
299
300
            // 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');
            }
301
302
303
304
305
306
307
308
309
310
311
312
            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);

313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
        // 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();
                    }
                }
            }
        }
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
        // 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);
                }
            }
        }
376

377
378
379
380
381
382
383
384
385
        db_commit();

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

386
    /**
387
     * Returns a list of the current user, group, or institution collections
388
389
390
     *
     * @param offset current page to display
     * @param limit how many collections to display per page
391
392
     * @param groupid current group ID
     * @param institutionname current institution name
393
394
     * @return array (count: integer, data: array, offset: integer, limit: integer)
     */
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
    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("
417
418
419
420
421
422
423
                SELECT
                    c.id,
                    c.description,
                    c.name,
                    c.submittedgroup,
                    c.submittedhost,
                    c.submittedtime,
424
                    c.framework,
425
                    (SELECT COUNT(*) FROM {collection_view} cv WHERE cv.collection = c.id) AS numviews
426
                FROM {collection} c
427
428
429
430
                WHERE " . $wherestm .
                " ORDER BY c.name, c.ctime, c.id ASC
                ", $values, $offset, $limit);
        }
431

432
        self::add_submission_info($data);
433
        self::add_framework_urls($data);
434

435
        $result = (object) array(
436
437
            'count'  => $count,
            'data'   => $data,
438
439
440
441
442
            'offset' => $offset,
            'limit'  => $limit,
        );
        return $result;
    }
443

444
    private static function add_submission_info(&$data) {
445
446
447
        global $CFG;
        require_once($CFG->docroot . 'lib/group.php');

448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
        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,
                );
            }
        }
    }

488
489
490
491
    /**
    * Gets the fields for the new/edit collection form
    * - populates the fields with collection data if it is an edit
    *
492
    * @param array $collection
493
494
    * @return array $elements
    */
495
    public function get_collectionform_elements() {
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
        $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'),
            ),
514
515
516
517
518
519
520
            'tags'        => array(
                'type'         => 'tags',
                'title'        => get_string('tags'),
                'description'  => get_string('tagsdescprofile'),
                'defaultvalue' => null,
                'help'         => true,
            ),
521
            'navigation' => array(
522
                'type'  => 'switchbox',
523
524
525
526
                'title' => get_string('viewnavigation','collection'),
                'description' => get_string('viewnavigationdesc','collection'),
                'defaultvalue' => 1,
            ),
527
        );
528
        if ($frameworks = $this->get_available_frameworks()) {
529
530
531
532
533
534
535
536
537
538
539
540
541
            $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'),
            );
        }
542

543
        // populate the fields with the existing values if any
544
        if (!empty($this->id)) {
545
            foreach ($elements as $k => $element) {
546
547
548
549
550
551
                if ($k === 'tags') {
                    $elements[$k]['defaultvalue'] = $this->get_tags();
                }
                else {
                    $elements[$k]['defaultvalue'] = $this->$k;
                }
552
553
554
            }
            $elements['id'] = array(
                'type' => 'hidden',
555
                'value' => $this->id,
556
            );
557
558
559
560
561
562
563
564
565
566
567
568
569
570
        }
        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)) {
571
572
            $elements['owner'] = array(
                'type' => 'hidden',
573
                'value' => $this->owner,
574
            );
575
576
        }

577
578
        return $elements;
    }
579

580
    /**
581
     * Returns array of views in the current collection
582
     *
Aaron Wells's avatar
Aaron Wells committed
583
     * @return array views
584
     */
585
586
587
    public function views() {

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

589
            $sql = "SELECT v.id, cv.*, v.title, v.owner, v.group, v.institution, v.ownerformat, v.urlid
590
591
                FROM {collection_view} cv JOIN {view} v ON cv.view = v.id
                WHERE cv.collection = ?
592
                ORDER BY cv.displayorder, v.title, v.ctime ASC";
593

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

596
            if (!empty($result)) {
597
598
599
600
601
602
603
604
605
                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;
                }
606
                $this->views = array(
607
                    'views'     => array_values($result),
608
                    'count'     => count($result),
609
610
                    'max'       => $max,
                    'min'       => $min,
611
612
613
614
615
                );
            }
            else {
                $this->views = array();
            }
616

617
618
        }

619
        return $this->views;
620
    }
621

622
    /**
623
     * Check that a collection can have a framework
624
625
626
627
628
629
630
631
632
633
634
635
     *
     * @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:
636
     * - The collection is not owned by a group
637
638
     * - The framework plugin is active
     * - The institution has 'SmartEvidence' turned on
639
     * - There are frameworks available for the institutions
640
     *
641
     * @return object $institution or false
642
     */
643
     public function get_framework_institution() {
644
645
646
647
        if (!empty($this->group)) {
            return false;
        }

648
        if (!is_plugin_active('framework', 'module')) {
649
650
            return false;
        }
651
        $allowsmartevidence = false;
652
653
        if ($this->institution) {
            $institution = $this->institution;
654
655
            $institution = new Institution($institution);
            $allowsmartevidence = ($institution->allowinstitutionsmartevidence) ? $institution : false;
656
657
658
659
        }
        else {
            $user = new User();
            $user->find_by_id($this->owner);
660
661
662
663
664
665
666
667
668
669
670
671
672
673
            $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;
            }
674
        }
675
        return $allowsmartevidence;
676
677
678
679
680
681
682
683
    }

    /**
     * Get available frameworks
     *
     * @return array Available frameworks
     */
    public function get_available_frameworks() {
684
685
        $institution = $this->get_framework_institution();
        if (!$institution) {
686
687
688
689
690
691
692
693
694
695
            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]);
                }
696
            }
697
            return $frameworks;
698
        }
699
        return array();
700
701
702
703
704
    }

    /**
     * Check that a collection has a framework
     * - The collection can have a framework
705
706
707
708
709
710
     * - It has a framework id
     * - It has views in the collection
     *
     * @return boolean
     */
    public function has_framework() {
711
        if (!$this->can_have_framework()) {
712
713
714
715
716
717
718
719
            return false;
        }
        if (empty($this->framework)) {
            return false;
        }
        if (!$this->views()) {
            return false;
        }
720
        if (!is_plugin_active('framework', 'module')) {
721
722
            return false;
        }
723
724
725
        return true;
    }

726
727
728
729
730
731
732
733
734
    /**
     * Get collection framework option for collection navigation
     *
     * @return object $option;
     */
    public function collection_nav_framework_option() {
        $option = new StdClass;
        $option->framework = $this->framework;
        $option->id = $this->id;
735
        $option->title = get_field('framework', 'name', 'id', $this->framework);
736
737
        $option->framework = true;

738
        $option->fullurl = self::get_framework_url($option);
739
740
741
742
743

        return $option;
    }

    /**
744
     * Adding the framework frameworkurl / fullurl to collections
745
     *
746
     * @param array  $data    Array of objects
747
     *
748
     * @return $data
749
     */
750
    public static function add_framework_urls(&$data) {
751
752
        if (is_array($data)) {
            foreach ($data as $k => $r) {
753
754
                $r->frameworkurl = self::get_framework_url($r, false);
                $r->fullurl = self::get_framework_url($r, true);
755
756
            }
        }
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    }

    /**
     * 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;
771
        }
772
        return $url;
773
774
    }

775
    /**
776
777
     * Get the available views the current user can choose to add to their collections.
     * Restrictions on this list include:
778
     * - currently dashboard, group and profile views are ignored to solve access issues
779
     * - default pages (with template == 2) are ignored
780
     * - each view can only belong to one collection
781
     * - locked/submitted views can't be added to collections
782
783
784
     *
     * @return array $views
     */
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
    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();
        }
801
        ($views = get_records_sql_array("SELECT v.id, v.title
802
803
804
805
            FROM {view} v
            LEFT JOIN {collection_view} cv ON cv.view = v.id
            WHERE " . $wherestm .
            "   AND cv.view IS NULL
806
                AND v.type NOT IN ('dashboard','grouphomepage','profile')
807
                AND v.template != 2
808
809
                AND v.submittedgroup IS NULL
                AND v.submittedhost IS NULL
810
811
812
813
            GROUP BY v.id, v.title
            ORDER BY v.title ASC
            ", $values))
            || ($views = array());
814
        return $views;
815
816
    }

817
    /**
818
     * Submits the selected views to the collection
819
820
821
822
823
     *
     * @param array values selected views
     * @return integer count so we know what SESSION message to display
     */
    public function add_views($values) {
824
        require_once(get_config('libroot') . 'view.php');
825

826
        $count = 0; // how many views we are adding
827
828
        db_begin();

829
        // each view was marked with a key of view_<id> in order to identify the correct items
830
        // from the form values
831
832
833
834
835
        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');
836
837
838
839
840

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

841
842
843
844
                insert_record('collection_view', (object)$cv);
                $count++;
            }
        }
845

846
        $viewids = get_column('collection_view', 'view', 'collection', $this->id);
847
848

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

851
852
853
854
855
856
857
        // 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'),
858
                'retainview'      => $firstview->get('retainview'),
859
860
861
862
863
864
865
                'allowcomments'   => $firstview->get('allowcomments'),
                'approvecomments' => (int) ($firstview->get('allowcomments') && $firstview->get('approvecomments')),
                'accesslist'      => $firstview->get_access(),
            );
            View::update_view_access($viewconfig, $viewids);
        }

866
867
        db_commit();

868
869
        return $count;
    }
870

871
    /**
872
     * Removes the selected views from the collection
873
874
875
876
877
878
     *
     * @param integer $view the view to remove
     */
    public function remove_view($view) {
        db_begin();
        delete_records('collection_view','view',$view,'collection',$this->get('id'));
879
880
881
882
883

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

884
885
886
        db_commit();
    }

887
888
889
    /**
     * Sets the displayorder for a view
     *
890
891
892
893
     * @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
894
895
     */
    public function set_viewdisplayorder($id, $direction) {
896
897
898
        if (is_array($direction)) {
            // we already have new sort order
            $neworder = $direction;
899
        }
900
901
902
903
904
905
906
907
908
909
910
911
        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;
                }
            }
912

913
914
915
916
917
918
919
920
921
922
            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));
            }
923
924
925
926
927
928
929
930
931
932
        }
        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();
        }
    }

933
934
935
    /**
     * after editing the collection, redirect back to the appropriate place
     */
936
937
938
939
    public function post_edit_redirect($new=false, $copy=false, $urlparams=null) {
        if ($new || $copy) {
            $urlparams['id'] = $this->get('id');
            $redirecturl = '/collection/views.php';
940
941
        }
        else {
942
            $redirecturl = '/collection/index.php';
943
        }
944
945
946
        if ($urlparams) {
            $redirecturl .= '?' . http_build_query($urlparams);
        }
947
948
949
        redirect($redirecturl);
    }

950
    public static function search_by_view_id($viewid) {
951
952
953
954
955
956
957
958
959
960
961
962
        $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;
    }

963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
    /**
     * 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");
    }
983
984
985
986
987
988
989
990
991

    /**
     * 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
     */
992
    public function get_url($full=true, $useid=false, &$firstview=null) {
993
        global $USER;
994
        $firstview = null;
995
996
997

        $views = $this->views();
        if (!empty($views)) {
998
            if ($this->framework) {
999
1000
                if ($full) {
                    $this->fullurl = Collection::get_framework_url($this);
1001
                    return $this->fullurl;
1002
1003
1004
                }
                else {
                    $this->frameworkurl = Collection::get_framework_url($this, false);
1005
                    return $this->frameworkurl;
1006
                }
1007
1008
            }

1009
1010
            $v = new View(0, $views['views'][0]);
            $v->set('dirty', false);
1011
            $firstview = $v;
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
            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;
    }

1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
    /**
     * 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);
    }

1056
1057
1058
1059
1060
1061
    /**
     * Release a submitted collection
     *
     * @param object $releaseuser The user releasing the collection
     */
    public function release($releaseuser=null) {
1062
1063

        if (!$this->is_submitted()) {
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
            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}
1077
1078
1079
1080
            SET submittedgroup = NULL,
                submittedhost = NULL,
                submittedtime = NULL,
                submittedstatus = ' . self::UNSUBMITTED . '
1081
1082
1083
1084
1085
1086
            WHERE id = ?',
            array($this->id)
        );
        View::_db_release($viewids, $this->owner, $this->submittedgroup);
        db_commit();

1087
1088
        // We don't send out notifications about the release of remote-submitted Views & Collections
        // (though I'm not sure why)
1089
1090
        // if the method is called in an upgrade and we dont have a release user
        if (!defined('INSTALLER') && $this->submittedgroup) {
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
            $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(
1102
                            'key'     => 'collectionreleasedsubject1',
1103
1104
1105
1106
                            'section' => 'group',
                            'args'    => array($this->name, $submitinfo->name, $releaseuserdisplay),
                        ),
                        'message' => (object) array(
1107
                            'key'     => 'collectionreleasedmessage1',
1108
1109
1110
                            'section' => 'group',
                            'args'    => array($this->name, $submitinfo->name, $releaseuserdisplay),
                        ),
1111
                    ),
1112
1113
1114
1115
1116
                    'url' => $this->get_url(false),
                    'urltext' => $this->name,
                )
            );
        }
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
    }

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

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

        return $ids;
    }
1131
1132
1133
1134
1135

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

1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
    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;
    }

1152
1153
1154
1155
1156
1157
1158
1159
    /**
     * 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
     */
    public function submit($group = null, $submittedhost = null, $owner = null) {
1160
1161
1162
        global $USER;

        if ($this->is_submitted()) {
1163
1164
1165
1166
1167
            throw new CollectionSubmissionException(get_string('collectionalreadysubmitted', 'view'));
        }
        // Gotta provide one or the other
        if (!$group && !$submittedhost) {
            return false;
1168
1169
1170
        }

        $viewids = $this->get_viewids();
1171
1172
1173
        if (!$viewids) {
            throw new CollectionSubmissionException(get_string('cantsubmitemptycollection', 'view'));
        }
1174
        $idstr = join(',', array_map('intval', $viewids));
1175
        $owner = ($owner == null) ? $USER->get('id') : $owner;
1176
1177
1178
1179

        // Check that none of the views is submitted to some other group.  This is bound to happen to someone,
        // because collection submission is being introduced at a time when it is still possible to submit
        // individual views in a collection.
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
        $sql = "SELECT title FROM {view} WHERE id IN ({$idstr}) AND (submittedhost IS NOT NULL OR (submittedgroup IS NOT NULL";
        $params = array();
        // To ease the transition, if you've submitted one page of the collection to this group already, you
        // can submit the rest as well
        if ($group) {
            $sql .= ' AND submittedgroup != ?';
            $params[] = $group->id;
        }
        $sql .= '))';
        $submittedtitles = get_column_sql($sql, $params );
1190
1191

        if (!empty($submittedtitles)) {
1192
            throw new CollectionSubmissionException(get_string('collectionviewsalreadysubmitted', 'view', implode('", "', $submittedtitles)));
1193
1194
        }

1195
1196
1197
        if ($group) {
            $group->roles = get_column('grouptype_roles', 'role', 'grouptype', $group->grouptype, 'see_submitted_views', 1);
        }
1198
1199

        db_begin();
1200
1201
1202
1203
1204
1205
1206
1207
1208
        View::_db_submit($viewids, $group, $submittedhost, $owner);
        if ($group) {
            $this->set('submittedgroup', $group->id);
            $this->set('submittedhost', null);
        }
        else {
            $this->set('submittedgroup', null);
            $this->set('submittedhost', $submittedhost);
        }
1209
        $this->set('submittedtime', time());
1210
        $this->set('submittedstatus', self::SUBMITTED);
1211
1212
1213
        $this->commit();
        db_commit();

1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
        if ($group) {
            activity_occurred(
                'groupmessage',
                array(
                    'group'         => $group->id,
                    'roles'         => $group->roles,
                    'url'           => $this->get_url(false),
                    'strings'       => (object) array(
                        'urltext' => (object) array(
                            'key'     => 'Collection',
                            'section' => 'collection',
                        ),
                        'subject' => (object) array(
                            'key'     => 'viewsubmittedsubject1',
                            'section' => 'activity',
                            'args'    => array($group->name),
                        ),
                        'message' => (object) array(
                            'key'     => 'viewsubmittedmessage1',
                            'section' => 'activity',
                            'args'    => array(
                                display_name($USER, null, false, true),
                                $this->name,
                                $group->name,
                            ),
1239
1240
                        ),
                    ),
1241
1242
1243
                )
            );
        }
1244
    }
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257

    /**
     * Returns the collection tags
     *
     * @return mixed
     */
    public function get_tags() {
        if (!isset($this->tags)) {
            $this->tags = get_column('collection_tag', 'tag', 'collection', $this->get('id'));
        }
        return $this->tags;
    }

1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
    /**
     * Creates a new secret url for this collection
     * @param int $collectionid
     * @param false $visible
     * @return object The view_access record for the first view's secret URL
     */
    public function new_token($visible=1) {
        $viewids = $this->get_viewids();
        // It's not possible to add a secret key to a collection with no pages
        if (!$viewids) {
            return false;
        }

        reset($viewids);
        $access = View::new_token(current($viewids), $visible);
        while (next($viewids)) {
            $todb = new stdClass();
            $todb->view = current($viewids);
            $todb->visible = $access->visible;
            $todb->token = $access->token;
            $todb->ctime = $access->ctime;
            insert_record('view_access', $todb);
        }

        return $access;
    }

    /**
     * Retrieves the collection's invisible access token, if it has one. (Each
     * collection can only have one, because invisible access tokens are used
     * for submission access, and each collection can only be submitted to
     * one place at a time.)
     *
     * @return mixed boolean FALSE if there is no token, a data object if there is
     */
    public function get_invisible_token() {
        $viewids = $this->get_viewids();
        if (!$viewids) {
            return false;
        }
        reset($viewids);
        return View::get_invisible_token(current($viewids));
    }
}

class CollectionSubmissionException extends UserException {

    // For a CollectionSubmissionException, the error message is mandatory
    public function __construct($message) {
        parent::__construct($message);
    }

    public function strings() {
        return array_merge(
            parent::strings(),
            array(
                'title' => get_string('collectionsubmissionexceptiontitle', 'view'),
                'message' => get_string('collectionsubmissionexceptionmessage', 'view'),
            )
        );
    }
1319
}