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

defined('INTERNAL') || die();
13
require_once(get_config('libroot') . 'group.php');
14
15
16
17
18

/**
 * Base artefact plugin class
 * @abstract
 */
19
abstract class PluginArtefact extends Plugin {
20

21
22
23
24
    public static function get_plugintype_name() {
        return 'artefact';
    }

Aaron Wells's avatar
Aaron Wells committed
25
26
    /**
     * This function returns a list of classnames
27
     * of artefact types this plugin provides.
Penny Leach's avatar
Penny Leach committed
28
     * @abstract
29
30
31
32
     * @return array
     */
    public static abstract function get_artefact_types();

Aaron Wells's avatar
Aaron Wells committed
33

34
35
36
37
38
39
40
41
42
43
    /**
    * This function returns a list of classnames
    * of block types this plugin provides
    * they must match directories inside artefact/$name/blocktype
    * @abstract
    * @return array
    */
    public static abstract function get_block_types();


44
45
    /**
     * This function returns the name of the plugin.
Penny Leach's avatar
Penny Leach committed
46
     * @abstract
47
48
49
50
51
     * @return string
     */
    public static abstract function get_plugin_name();


52
53
54
55
56
57
58
59
60
61
62
    /**
     * This function returns an array of menu items
     * to be displayed
     * Each item should be a StdClass object containing -
     * - name language pack key
     * - url relative to wwwroot
     * @return array
     */
    public static function menu_items() {
        return array();
    }
63
64
65
66
67
68
69
70
71
72
73
74
75


    /**
     * This function returns an array of menu items to be displayed
     * on a group page when viewed by group members.
     * Each item should be a StdClass object containing -
     * - title language pack key
     * - url relative to wwwroot
     * @return array
     */
    public static function group_tabs($groupid) {
        return array();
    }
76
77
78
79
80
81
82
83
84
85
86


    /**
     * Returns any artefacts that are not inside a view
     * but which need to be exported along with it.
     * @param array $viewids
     * @return array of artefact ids
     */
    public static function view_export_extra_artefacts($viewids) {
        return array();
    }
87
88
89
90

    /**
     * When filtering searches, some artefact types are classified the same way
     * even when they come from different artefact plugins.  This function allows
91
     * artefact plugins to declare which search filter content type each of their
92
93
94
95
96
97
     * artefact types belong to.
     * @return array of artefacttype => array of filter content types
     */
    public static function get_artefact_type_content_types() {
        return array();
    }
98
99
100


    /**
101
102
103
104
     * Indicates whether this particular plugin has any progress bar options. By default, any new plugin
     * will have progress bar options, for creating at least one of the artefact.
     *
     * @return boolean
105
     */
106
107
    public static function has_progressbar_options() {
        return true;
108
109
    }

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    /**
     * Returns the relative URL path to the place in mahara that relates
     * to the artefact.
     * E.g. For plan artefact the link will be 'artefact/plans/index.php'
     * @param int The name of the artefact type (in case different ones need different links)
     * @return string Url path to artefact.
     */
    public static function progressbar_link($artefacttype) {
        return '';
    }

    public static function progressbar_task_label($artefacttype, $target, $completed) {
        // By default we check to see if they provided a string called "progress_{$artefacttype}"
        // in the plugin lang file (which takes one param with the count remaining)
        $label = get_string('progress_' . $artefacttype, 'artefact.' . static::get_plugin_name(), ($target - $completed));

        // Kind of a hack: if get_string() gave us a result indicating the string could not be found,
        // try to construct one using the plugin and artefact name.
        if (substr($label, 0, 2) == '[[') {
            $artname = get_string($artefacttype, 'artefact.' . static::get_plugin_name());
            if (substr($artname, 0, 2) == '[[') {
                $artname = $artefacttype;
            }
            $label = get_string('progressbargenerictask', 'mahara', ($target - $completed), $artname);
        }
        return $label;
    }

138
139
140
141
142
143
144
    /**
     * Add any special progress items that may not exist as an artefact type.
     * @return array of objects each containing name, title, plugin, active, iscountable
     */
    public static function progressbar_additional_items() {
        return array();
    }
145
146
147
148
149
150
151
152
153
154
155

    /**
     * If this plugin provides some progress bar metaartefacts, then this method should
     * provide the logic to count them.
     * @param string $name The name of the meta-artefact to count
     * @return object A record containing the count data to be displayed in the sidebar.
     *                It should contain the fields "artefacttype" and "completion"
     */
    public static function progressbar_metaartefact_count($name) {
        return false;
    }
156
157
}

Aaron Wells's avatar
Aaron Wells committed
158
/**
159
160
161
162
 * Base artefact type class
 * @abstract
 */
abstract class ArtefactType {
163

164
    protected $dirty;
165
    protected $deleted = false;
166
    protected $id;
167
168
    protected $artefacttype;
    protected $owner;
169
    protected $container;
170
    protected $parent;
171
    protected $oldparent;
172
173
    protected $ctime;
    protected $mtime;
174
    protected $atime;
175
176
177
178
    protected $locked;
    protected $title;
    protected $description;
    protected $note;
179
    protected $tags = array();
180
    protected $institution;
181
    protected $group;
182
183
    protected $author;
    protected $authorname;
184
    protected $allowcomments;
185
    protected $approvecomments;
Richard Mansfield's avatar
Richard Mansfield committed
186
    protected $rolepermissions;
187
    protected $mtimemanuallyset;
188
189
190
    protected $license;
    protected $licensor;
    protected $licensorurl;
191
    protected $path;
192

Penny Leach's avatar
Penny Leach committed
193
194
195
196
197
198
199
    protected $viewsinstances;
    protected $viewsmetadata;
    protected $childreninstances;
    protected $childrenmetadata;
    protected $parentinstance;
    protected $parentmetadata;

200
201
    /**
     * Constructor.
202
203
204
205
206
207
     * If an id is supplied, will query the database
     * to build up the basic information about the object.
     * If an id is not supplied, we just create an empty
     * artefact, ready to be filled up
     * @param int $id artefact.id
     */
Penny Leach's avatar
Penny Leach committed
208
    public function __construct($id=0, $data=null) {
209
        if (!empty($id)) {
Penny Leach's avatar
Penny Leach committed
210
211
            if (empty($data)) {
                if (!$data = get_record('artefact','id',$id)) {
212
                    throw new ArtefactNotFoundException(get_string('artefactnotfound', 'error', $id));
Penny Leach's avatar
Penny Leach committed
213
                }
214
            }
215
            $this->id = $id;
216
217
        }
        else {
218
219
            $this->ctime = $this->mtime = time();
            $this->dirty = true;
220
        }
221
222
223
224
225
        if (empty($data)) {
            $data = array();
        }
        foreach ((array)$data as $field => $value) {
            if (property_exists($this, $field)) {
226
227
                if (in_array($field, array('atime', 'ctime', 'mtime'))) {
                    $value = strtotime($value);
Aaron Wells's avatar
Aaron Wells committed
228
                }
Richard Mansfield's avatar
Richard Mansfield committed
229
                if ($field == 'tags' && !is_array($value)) {
230
231
                    $value = preg_split("/\s*,\s*/", trim($value));
                }
232
233
234
235
                $this->{$field} = $value;
            }
        }

236
237
238
239
240
241
242
        $this->artefacttype = $this->get_artefact_type();
        if (!empty($data->artefacttype)) {
            if ($this->artefacttype != $data->artefacttype) {
                throw new SystemException(get_string('artefacttypemismatch', 'error', $data->artefacttype, $this->artefacttype));
            }
        }

243
244
        // load tags
        if ($this->id) {
245
            $this->tags = ArtefactType::artefact_get_tags($this->id);
246
247
        }

Richard Mansfield's avatar
Richard Mansfield committed
248
        // load group permissions
249
        if ($this->group && !is_array($this->rolepermissions)) {
Richard Mansfield's avatar
Richard Mansfield committed
250
251
252
            $this->load_rolepermissions();
        }

253
        $this->atime = time();
254
255
    }

256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
    /**
     * returns duplicated artefacts which have the same value of the following fields:
     *  - owner
     *  - type
     *  - content
     *      - title
     *      - description
     *
     * @param array $values
     */
    public static function get_duplicated_artefacts(array $values) {
        if (!empty($values['content']['description'])) {
            return get_column_sql('
                SELECT id
                FROM {artefact}
                WHERE owner = ?
                    AND artefacttype = ?
                    AND title = ?
                    AND description = ?',
                array($values['owner'], $values['type'], $values['content']['title'], $values['content']['description'])
            );
        }
        else {
            return get_column('artefact', 'id',
                'owner', $values['owner'],
                'artefacttype', $values['type'],
                'title', $values['content']['title']);
        }
    }

    /**
     * returns existing artefacts which have the same artefacttype and owner
     *
     * @param array $values
     */
    public static function get_existing_artefacts(array $values) {
        return get_column('artefact', 'id',
                        'owner', $values['owner'],
                        'artefacttype', $values['type']);
    }

297
298
299
300
301
    /**
     * Returns the instances of all views where this artefact is used.
     *
     * @return array Array of view instances.
     */
302
    public function get_views_instances() {
303
304
305
306
307
        // @todo test this
        if (!isset($this->viewsinstances)) {
            $this->viewsinstances = false;
            if ($views = $this->get_views_metadata()) {
                $this->viewsinstances = array();
308
309
310
                if (!class_exists('View')) {
                    require_once(get_config('libroot') . 'view.php');
                }
311
                foreach ($views as $view) {
312
                    $this->viewsinstances[] = new View($view->view);
313
314
315
316
                }
            }
        }
        return $this->viewsinstances;
317
    }
318

319
    public function get_views_metadata() {
320
321
322
323
        if (!isset($this->viewsmetadata)) {
            $this->viewsmetadata = get_records_array('view_artefact', 'artefact', $this->id);
        }
        return $this->viewsmetadata;
324
325
    }

Richard Mansfield's avatar
Richard Mansfield committed
326
327
328
329
    public function count_children() {
        return count_records('artefact', 'parent', $this->get('id'));
    }

330
331
332
333
334
335
336
    public function has_children() {
        if ($this->get_children_metadata()) {
            return true;
        }
        return false;
    }

337
338
339
340
    public function get_plugin_name() {
        return get_field('artefact_installed_type', 'plugin', 'name', $this->get('artefacttype'));
    }

Aaron Wells's avatar
Aaron Wells committed
341
342
    /**
     * This function returns the instances
Penny Leach's avatar
Penny Leach committed
343
     * of all children of this artefact
Aaron Wells's avatar
Aaron Wells committed
344
     * If you just want the basic info,
Penny Leach's avatar
Penny Leach committed
345
     * use {@link get_children_metadata} instead.
Aaron Wells's avatar
Aaron Wells committed
346
     *
Penny Leach's avatar
Penny Leach committed
347
348
     * @return array of instances.
     */
349
    public function get_children_instances() {
Penny Leach's avatar
Penny Leach committed
350
351
352
353
354
        if (!isset($this->childreninstances)) {
            $this->childreninstances = false;
            if ($children = $this->get_children_metadata()) {
                $this->childreninstances = array();
                foreach ($children as $child) {
355
                    $classname = generate_artefact_class_name($child->artefacttype);
Penny Leach's avatar
Penny Leach committed
356
357
358
359
360
361
                    $instance = new $classname($child->id, $child);
                    $this->childreninstances[] = $instance;
                }
            }
        }
        return $this->childreninstances;
362
363
    }

364
    /**
Aaron Wells's avatar
Aaron Wells committed
365
366
     * This function returns the db rows
     * from the artefact table that have this
367
368
369
     * artefact as the parent.
     * If you want instances, use {@link get_children_instances}
     * but bear in mind this will have a performance impact.
Aaron Wells's avatar
Aaron Wells committed
370
     *
371
372
     * @return array
     */
373
    public function get_children_metadata() {
Penny Leach's avatar
Penny Leach committed
374
        if (!isset($this->childrenmetadata)) {
375
            $this->childrenmetadata = get_records_array('artefact', 'parent', $this->id);
Penny Leach's avatar
Penny Leach committed
376
377
        }
        return $this->childrenmetadata;
378
    }
Penny Leach's avatar
Penny Leach committed
379
380
381
382
383
384
385
386
387

    /**
     * This function returns the instance relating to the parent
     * of this object, or false if there isn't one.
     * If you just want basic information about it,
     * use {@link get_parent_metadata} instead.
     *
     * @return ArtefactType
     */
388
    public function get_parent_instance() {
Penny Leach's avatar
Penny Leach committed
389
390
391
        if (!isset($this->parentinstance)) {
            $this->parentinstance = false;
            if ($parent = $this->get_parent_metadata()) {
392
                $classname = generate_artefact_class_name($parent->artefacttype);
Penny Leach's avatar
Penny Leach committed
393
394
395
396
                $this->parentinstance = new $classname($parent->id, $parent);
            }
        }
        return $this->parentinstance;
397
    }
398

Aaron Wells's avatar
Aaron Wells committed
399
400
    /**
     * This function returns the db row
401
402
     * (if there is one) of the parent
     * artefact for this instance.
Aaron Wells's avatar
Aaron Wells committed
403
     * If you want the instance, use
404
     * {@link get_parent_instance} instead.
Aaron Wells's avatar
Aaron Wells committed
405
     *
406
     * @return object - db row
407
     */
408
    public function get_parent_metadata() {
409
410
411
        if (empty($this->parent)) {
            return false;
        }
412
        return get_record('artefact','id',$this->parent);
413
414
    }

415
416
417
    /**
     * Returns how much quota this artefact has used.
     *
Aaron Wells's avatar
Aaron Wells committed
418
     * It should try to not instantiate the artefact, because it is normally
419
420
421
422
423
424
425
426
     * called as part of an expensive cron job
     *
     * @return int Size in bytes that the artefact is taking up in quota
     */
    public static function get_quota_usage($artefact) {
        return 0;
    }

427
    public function get($field) {
428
        if (!property_exists($this, $field)) {
429
            throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
430
431
432
433
434
        }
        return $this->{$field};
    }

    public function set($field, $value) {
435
        if (property_exists($this, $field)) {
436
            if ($this->{$field} != $value) {
437
                // Only set it to dirty if it's changed.
438
                $this->dirty = true;
439
440
441
442
                // Set oldparent only if it has changed.
                if ($field == 'parent') {
                    $this->oldparent = $this->parent;
                }
443
            }
444
            $this->{$field} = $value;
445
446
447
448
449
450
            if ($field == 'mtime') {
                $this->mtimemanuallyset = true;
            }
            else if (!$this->mtimemanuallyset) {
                $this->mtime = time();
            }
451
452
            return true;
        }
453
        throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
454
    }
Aaron Wells's avatar
Aaron Wells committed
455

456
457
458
    /**
     * Artefact destructor. Calls commit and marks the
     * artefact cache as dirty if necessary.
459
460
461
     *
     * A special case is when the object has just been deleted.  In this case,
     * we do nothing.
462
     */
463
    public function __destruct() {
464
465
466
        if ($this->deleted) {
            return;
        }
Aaron Wells's avatar
Aaron Wells committed
467

468
        if (!empty($this->dirty) && !defined('MAHARA_CRASHING')) {
469
470
            $this->commit();
        }
471
    }
Aaron Wells's avatar
Aaron Wells committed
472
473

    /**
474
475
476
     * This method updates the contents of the artefact table only.  If your
     * artefact has extra information in other tables, you need to override
     * this method, and call parent::commit() in your own function.
477
     */
478
    public function commit() {
479
480
481
        if (empty($this->dirty)) {
            return;
        }
482

483
484
485
486
        if (empty($this->author) && empty($this->authorname)) {
            $this->set_author();
        }

487
488
        db_begin();

489
        $fordb = new StdClass();
490
491
492
493
494
495
496
497
        foreach (get_object_vars($this) as $k => $v) {
            $fordb->{$k} = $v;
            if (in_array($k, array('mtime', 'ctime', 'atime')) && !empty($v)) {
                $fordb->{$k} = db_format_timestamp($v);
            }
        }
        if (empty($this->id)) {
            $this->id = insert_record('artefact', $fordb, 'id', true);
Richard Mansfield's avatar
Richard Mansfield committed
498
499
500
            if ($this->can_be_logged()) {
                $this->log('created');
            }
501
            $this->add_hierarchy_path($this->parent);
502
503
        }
        else {
Richard Mansfield's avatar
Richard Mansfield committed
504
505
506
            if ($this->can_be_logged()) {
                $this->log('edited');
            }
507
            update_record('artefact', $fordb, 'id');
508
            $this->update_hierarchy_path($this->parent);
509
        }
510

Richard Mansfield's avatar
Richard Mansfield committed
511
512
513
514
        if (!empty($this->group)) {
            $this->save_rolepermissions();
        }

515
516
        delete_records('artefact_tag', 'artefact', $this->id);
        if (is_array($this->tags)) {
517
            $this->tags = check_case_sensitive($this->tags, 'artefact_tag');
Martyn Smith's avatar
Martyn Smith committed
518
            foreach (array_unique($this->tags) as $tag) {
519
520
521
                if (empty($tag)) {
                    continue;
                }
522
523
524
525
526
527
528
529
530
531
                insert_record(
                    'artefact_tag',
                    (object) array(
                        'artefact' => $this->id,
                        'tag'      => $tag,
                    )
                );
            }
        }

532
        artefact_watchlist_notification(array($this->id));
533

534
535
        handle_event('saveartefact', $this);

536
        $this->dirty = false;
537
        $this->deleted = false;
538
539

        db_commit();
540
541
    }

Aaron Wells's avatar
Aaron Wells committed
542
    /**
543
544
545
546
547
548
549
     * This function provides basic delete functionality.  It gets rid of the
     * artefact's row in the artefact table, and the tables that reference the
     * artefact table.  It also recursively deletes child artefacts.
     *
     * If your artefact has additional data in another table, you should
     * override this function, but you MUST call parent::delete() after you
     * have done your own thing.
550
     */
551
552
    public function delete() {
        if (empty($this->id)) {
553
            $this->dirty = false;
554
555
            return;
        }
Aaron Wells's avatar
Aaron Wells committed
556

557
        db_begin();
558

559
560
561
562
        // Call delete() on comments (if there are any)
        safe_require('artefact', 'comment');
        ArtefactTypeComment::delete_comments_onartefacts(array($this->id));

563
564
565
566
567
568
        // Call delete() on children (if there are any)
        if ($children = $this->get_children_instances()) {
            foreach ($children as $child) {
                $child->delete();
            }
        }
569

570
        artefact_watchlist_notification(array($this->id));
571

572
        self::_delete_dbrecords(array($this->id));
Richard Mansfield's avatar
Richard Mansfield committed
573
574
575
576

        if ($this->can_be_logged()) {
            $this->log('deleted');
        }
Aaron Wells's avatar
Aaron Wells committed
577

578
579
        handle_event('deleteartefact', $this);

580
        // Set flags.
581
        $this->dirty = false;
582
        $this->deleted = true;
583

584
        db_commit();
585
586
    }

587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
    /**
     * Does a bulk_delete on a list of artefacts, grouping artefacts of
     * the same type.
     *
     * Currently only tested for folders and their contents.
     */
    public static function delete_by_artefacttype($artefactids) {
        if (empty($artefactids)) {
            return;
        }

        db_begin();

        artefact_watchlist_notification($artefactids);

602
603
604
605
        // Delete comments first
        safe_require('artefact', 'comment');
        ArtefactTypeComment::delete_comments_onartefacts($artefactids);

606
607
        $records = get_records_select_assoc(
            'artefact',
608
            'id IN (' . join(',', array_map('intval', $artefactids)) . ')',
609
610
611
612
613
614
615
            null, 'artefacttype', 'id,parent,artefacttype,container'
        );

        $containers = array();
        $leaves = array();
        foreach ($records as $r) {
            if ($r->container) {
616
                $containers[$r->artefacttype][] = (int)$r->id;
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
            }
            else {
                $leaves[$r->artefacttype][] = $r->id;
            }
        }

        // Delete non-containers grouped by artefacttype
        foreach ($leaves as $artefacttype => $ids) {
            $classname = generate_artefact_class_name($artefacttype);
            call_static_method($classname, 'bulk_delete', $ids);
        }

        // Delete containers grouped by artefacttype
        foreach ($containers as $artefacttype => $ids) {
            $classname = generate_artefact_class_name($artefacttype);
632
633
634
            if (is_mysql()) {
                set_field_select('artefact', 'parent', null, 'id IN (' . join(',', $ids) . ')', array());
            }
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
            call_static_method($classname, 'bulk_delete', $ids);
        }

        handle_event('deleteartefacts', $artefactids);

        db_commit();
    }

    /**
     * Faster delete for multiple artefacts.
     *
     * Should only be called on artefacts with no children, after
     * additional data in other tables has already been deleted.
     */
    public static function bulk_delete($artefactids, $log=false) {
        db_begin();

        self::_delete_dbrecords($artefactids);

        // Logging must be triggered by the caller because it's
        // slow to go through each artefact and ask it if it should
        // be logged.
        if ($log) {
            global $USER;
            $entry = (object) array(
                'usr'      => $USER->get('id'),
                'time'     => db_format_timestamp(time()),
                'deleted'  => 1,
            );
            foreach ($artefactids as $id) {
                $entry->artefact = $id;
                insert_record('artefact_log', $entry);
            }
        }

        db_commit();
    }


    private static function _delete_dbrecords($artefactids) {
        if (empty($artefactids)) {
            return;
        }

679
        $idstr = '(' . join(',', array_map('intval', $artefactids)) . ')';
680
681
682

        db_begin();

683
        // Detach any files from this artefact
684
        delete_records_select('artefact_attachment', "artefact IN $idstr");
685

686
687
688
689
690
691
692
693
694
695
696
697
        // Make sure that the artefacts are removed from any view blockinstances
        if ($records = get_records_sql_array("
            SELECT va.block, va.artefact, bi.configdata
            FROM {view_artefact} va JOIN {block_instance} bi ON va.block = bi.id
            WHERE va.artefact IN $idstr", array())) {
            require_once(get_config('docroot') . 'blocktype/lib.php');
            BlockInstance::bulk_delete_artefacts($records);
        }
        delete_records_select('view_artefact', "artefact IN $idstr");
        delete_records_select('artefact_tag', "artefact IN $idstr");
        delete_records_select('artefact_access_role', "artefact IN $idstr");
        delete_records_select('artefact_access_usr', "artefact IN $idstr");
698
        execute_sql("UPDATE {usr} SET profileicon = NULL WHERE profileicon IN $idstr");
699
        execute_sql("UPDATE {institution} SET logo = NULL WHERE logo IN $idstr");
700
701
702
703
704
705

        delete_records_select('artefact', "id IN $idstr");

        db_commit();
    }

706
707
708
709
710
711
712
713
714
715
716
717
718
719
720

    /**
     * Initialise artefact author to either the artefact owner, the
     * logged-in user, or the system user.
     */
    private function set_author() {
        global $USER;
        if (isset($this->owner)) {
            $this->author = $this->owner;
        }
        else {
            $this->author = $USER->get('id');
        }
    }

721
722
723
724
725
726
727
728
729
730
    /**
     * By default users are notified of all feedback on artefacts
     * which they own.  Artefact types which want to allow this
     * notification to be turned off should redefine this function.
     */
    public function feedback_notify_owner() {
        return true;
    }


731
732
733
734
    /**
     * A dummy method, giving graceful output, if this method is not implemented in the relevant child class
     */
    public function render_self($options) {
735
736
        $smarty = smarty_core();
        $smarty->assign('title', $this->get('title'));
737
738
        $smarty->assign('owner', $this->get('owner'));
        $smarty->assign('tags', $this->get('tags'));
739
        $smarty->assign('description', $this->get('description'));
740
741
742
743
744
745
        if (!empty($options['details']) and get_config('licensemetadata')) {
            $smarty->assign('license', render_license($this));
        }
        else {
            $smarty->assign('license', false);
        }
746
747

        return array(
748
            'html' => $smarty->fetch('artefact.tpl'),
749
750
751
752
753
            'javascript'=>''
        );
    }


Penny Leach's avatar
Penny Leach committed
754
    /**
755
756
     * Returns a URL for an icon for the appropriate artefact
     *
Aaron Wells's avatar
Aaron Wells committed
757
758
759
760
761
762
     * @param array $options Options for the artefact. The array MUST have the
     *                       'id' key, representing the ID of the artefact for
     *                       which the icon is being generated. Other keys
     *                       include 'size' for a [width]x[height] version of
     *                       the icon, as opposed to the default 20x20, and
     *                       'view' for the id of the view in which the icon is
763
     *                       being displayed.
Aaron Wells's avatar
Aaron Wells committed
764
     * @abstract
765
     * @return string URL for the icon
Penny Leach's avatar
Penny Leach committed
766
     */
767
    public static abstract function get_icon($options=null);
Aaron Wells's avatar
Aaron Wells committed
768

769
770
771
772
773
774
775
776
777
778
779

    // ******************** STATIC FUNCTIONS ******************** //

    public static function get_instances_by_userid($userid, $order, $offset, $limit) {
        // @todo
    }

    public static function get_metadata_by_userid($userid, $order, $offset, $limit) {
        // @todo
    }

Penny Leach's avatar
Penny Leach committed
780
781
782
783
    /**
     * whether a user will have exactly 0 or 1 of this artefact type
     * @abstract
     */
784
    public static abstract function is_singular();
Penny Leach's avatar
Penny Leach committed
785

Martyn Smith's avatar
Martyn Smith committed
786
787
    /**
     * Returns a list of key => value pairs where the key is either '_default'
788
     * or a language string, and value is a URL linking to that behaviour for
Martyn Smith's avatar
Martyn Smith committed
789
     * this artefact type
Aaron Wells's avatar
Aaron Wells committed
790
     *
Martyn Smith's avatar
Martyn Smith committed
791
792
793
794
     * @param integer This is the ID of the artefact being linked to
     */
    public static abstract function get_links($id);

Penny Leach's avatar
Penny Leach committed
795
796
797
798
    // @TODO maybe uncomment this later and implement it everywhere
    // when we know a bit more about what blocks we want.
    //public abstract function render_self($options);

799
800
801
802
803
804
805
806
807

    /**
    * Returns the printable name of this artefact
    * (used in lists and such)
    */
    public function get_name() {
        return $this->get('title');
    }

808
809
810
811
812
813
814
815
    /**
    * Should the artefact be linked to from the listing on my views?
    */
    public function in_view_list() {
        return true;
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
816
    * Returns a short name for the artefact to be used in a list of artefacts in a view
817
818
819
    */
    public function display_title($maxlen=null) {
        if ($maxlen) {
820
            return str_shorten_text($this->get('title'), $maxlen, true);
821
822
823
824
        }
        return $this->get('title');
    }

825
826
827
828
829
830
831
    public function display_owner() {
        if ($owner = $this->get('owner')) {
            return display_name($owner);
        }
        if ($group = $this->get('group')) {
            return get_field('group', 'name', 'id', $group);
        }
832
833
834
835
836
837
        if ($institution = $this->get('institution')) {
            if ($institution == 'mahara') {
                return get_config('sitename');
            }
            return get_field('institution', 'displayname', 'name', $institution);
        }
838
839
840
841
        return null;
    }


842
843
844
845
    // ******************** HELPER FUNCTIONS ******************** //

    protected function get_artefact_type() {
        $classname = get_class($this);
Aaron Wells's avatar
Aaron Wells committed
846

847
848
        $type = strtolower(substr($classname, strlen('ArtefactType')));

849
        if (!artefact_type_installed($type)) {
850
851
852
853
854
            throw new InvalidArgumentException("Classname $classname not a valid artefact type");
        }

        return $type;
    }
855

856
    public function to_stdclass() {
Aaron Wells's avatar
Aaron Wells committed
857
       return (object)get_object_vars($this);
858
859
    }

860
861
862
863
864
865
866
867
868
869
870
    public static function has_config() {
        return false;
    }

    public static function get_config_options() {
        return array();
    }

    public static function collapse_config() {
        return false;
    }
Richard Mansfield's avatar
Richard Mansfield committed
871
872

    private function save_rolepermissions() {
873
        if (!$this->group) {
Richard Mansfield's avatar
Richard Mansfield committed
874
875
            return;
        }
876
        if (!isset($this->rolepermissions)) {
877
            $this->rolepermissions = group_get_default_artefact_permissions($this->group);
878
        }
Richard Mansfield's avatar
Richard Mansfield committed
879
880
881
        $id = $this->get('id');
        db_begin();
        delete_records('artefact_access_role', 'artefact', $id);
882
        foreach ($this->rolepermissions as $role => $permissions) {
Richard Mansfield's avatar
Richard Mansfield committed
883
884
885
            insert_record('artefact_access_role', (object) array(
                'artefact'      => $id,
                'role'          => $role,
886
887
888
                'can_view'      => (int) !empty($permissions->view),
                'can_edit'      => (int) !empty($permissions->edit),
                'can_republish' => (int) !empty($permissions->republish),
Richard Mansfield's avatar
Richard Mansfield committed
889
890
891
892
893
894
            ));
        }
        db_commit();
    }

    private function load_rolepermissions() {
895
896
897
        if (!$this->group) {
            return;
        }
Richard Mansfield's avatar
Richard Mansfield committed
898
899
        $records = get_records_array('artefact_access_role', 'artefact', $this->get('id'));
        if ($records) {
900
            $this->rolepermissions = array();
Richard Mansfield's avatar
Richard Mansfield committed
901
            foreach ($records as $r) {
902
                $this->rolepermissions[$r->role] = (object) array(
Richard Mansfield's avatar
Richard Mansfield committed
903
904
905
906
907
908
                    'view' => (bool) $r->can_view,
                    'edit' => (bool) $r->can_edit,
                    'republish' => (bool) $r->can_republish,
                );
            }
        }
909
        else {
910
            $this->rolepermissions = group_get_default_artefact_permissions($this->group);
911
        }
Richard Mansfield's avatar
Richard Mansfield committed
912
913
    }

914
915
916
917
    public function role_has_permission($role, $permission) {
        return $this->rolepermissions[$role]->{$permission};
    }

Richard Mansfield's avatar
Richard Mansfield committed
918
919
920
921
922
923
924
925
926
927
928
929
930
931
    public function copy_data() {
        $ignore = array(
            'dirty' => 1,
            'deleted' => 1,
            'id' => 1,
            'locked' => 1,
            'rolepermissions' => 1,
            'viewsinstances' => 1,
            'viewsmetadata' => 1,
            'childreninstances' => 1,
            'childrenmetadata' => 1,
            'parentinstance' => 1,
            'parentmetadata' => 1
        );
932
        $data = new StdClass;
Richard Mansfield's avatar
Richard Mansfield committed
933
        foreach (get_object_vars($this) as $k => $v) {
934
            if (in_array($k, array('atime', 'ctime', 'mtime'))) {
935
                $data->$k = db_format_timestamp($v);
936
937
            }
            else if (!isset($ignore[$k])) {
938
                $data->$k = $v;
Richard Mansfield's avatar
Richard Mansfield committed
939
940
941
942
943
944
945
946
947
948
            }
        }
        return $data;
    }

    public function copy_extra($new) {
    }

    public function copy_for_new_owner($user, $group, $institution) {
        $data = $this->copy_data();
949
950
951
952
953
954
955
        $data->owner = $user;
        $data->group = $group;
        $data->institution = $institution;
        $data->parent = null;
        $classname = generate_artefact_class_name($data->artefacttype);
        safe_require('artefact', get_field('artefact_installed_type', 'plugin', 'name', $data->artefacttype));
        $copy = new $classname(0, (object) $data);
Richard Mansfield's avatar
Richard Mansfield committed
956
        $this->copy_extra($copy);
957
        $copy->commit();
Richard Mansfield's avatar
Richard Mansfield committed
958
959
        return $copy->get('id');
    }
Richard Mansfield's avatar
Richard Mansfield committed
960

961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
    /**
     * Called after a view has been copied to rewrite all artefact
     * references in the new artefact (which still point to the
     * original artefacts) so that they also point to new artefacts
     * that were copied during the view copy.
     *
     * @param View $view The newly copied view
     * @param View $template The old view
     * @param array $artefactcopies The mapping between old artefact ids and new ones (created in blockinstance copy)
     * @param integer $oldid id of the artefact this artefact was copied from
     */
    public function update_artefact_references(&$view, &$template, &$artefactcopies, $oldid) {
        $copyinfo = $artefactcopies[$oldid];
        if (isset($artefactcopies[$copyinfo->oldparent])) {
            $this->set('parent', $artefactcopies[$copyinfo->oldparent]->newid);
        }
        else {
978
            $this->set('parent', $this->default_parent_for_copy($view, $template, array_map(create_function('$a', 'return $a->newid;'), $artefactcopies)));
979
980
981
        }
    }

982
    /**
Aaron Wells's avatar
Aaron Wells committed
983
     * Returns the ID of the artefact that should be the parent for copied
984
985
986
987
988
989
     * artefacts - e.g. the folder that files should be placed in.
     *
     * The $artefactstoignore is used to work around bug #3106
     *
     * @param View $view The new view being created by the copy
     * @param View $template The view being copied from
Aaron Wells's avatar
Aaron Wells committed
990
991
992
993
994
995
996
997
     * @param array $artefacttoignore A list of artefact IDs to ignore. In
     *                                particular, it's a list of artefact IDs
     *                                that have been created by a view being
     *                                copied. This is so we don't accidentally
     *                                try to use a new artefact as the parent
     *                                for all of the artefacts, else we can get
     *                                into a nasty infinite loop (e.g. when a
     *                                folder called 'viewfiles' is being
998
999
1000
     *                                copied).
     */
    public function default_parent_for_copy(&$view, &$template, $artefactstoignore) {
1001
1002
1003
        return null;
    }

Richard Mansfield's avatar
Richard Mansfield committed
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
    public function can_be_logged() {
        return false;
    }

    public function log($action) {
        global $USER;
        $entry = (object) array(
            'artefact' => $this->id,
            'usr'      => $USER->get('id'),
            'time'     => db_format_timestamp($this->mtime),
            $action    => 1,
        );
        if ($action == 'deleted') {
            insert_record('artefact_log', $entry);
            return;
        }
        $loggedfields = array('title', 'description', 'parent');
        if ($action == 'edited') {
            $old = get_record('artefact', 'id', $this->id);
            foreach ($loggedfields as $key) {
                if ($this->$key != $old->$key) {
                    $entry->$key = $this->$key;
                    $changed = true;
Aaron Wells's avatar
Aaron Wells committed
1027
                }
Richard Mansfield's avatar
Richard Mansfield committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
            }
            if (isset($changed)) {
                insert_record('artefact_log', $entry);
            }
        }
        if ($action == 'created') {
            foreach ($loggedfields as $key) {
                $entry->$key = $this->$key;
            }
            insert_record('artefact_log', $entry);
        }
    }
1040

1041
1042
1043
1044
1045
1046
1047
1048
    public function can_have_attachments() {
        return false;
    }

    public function count_attachments() {
        return count_records('artefact_attachment', 'artefact', $this->get('id'));
    }

1049
    public function attachment_id_list() {
1050
1051
1052
1053
1054
1055
1056
        // During view copying, attachment_id_list can get called on artefacts of any type; don't call
        // get_column here unless it might actually return something.
        if ($this->can_have_attachments()) {
            if ($list = get_column('artefact_attachment', 'attachment', 'artefact', $this->get('id'))) {
                return $list;
            }
        }
1057
1058
        return array();
    }
1059

1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
    public function attachment_id_list_with_item($itemid) {
        // If artefact attachment table has 'item' column utilised.
        if ($this->can_have_attachments()) {
            if ($list = get_column('artefact_attachment', 'attachment', 'artefact', $this->get('id'), 'item', $itemid)) {
                return $list;
            }
        }
        return array();
    }

1070
1071
1072
1073
    public function attachments_from_id_list($artefactids) {
        if (empty($artefactids)) {
            return array();
        }
1074
1075
1076
1077
1078
        // @todo: Join on artefact_file_files shouldn't happen below.
        // We could either assume all attachments are files and then
        // move all these attachment functions to the artefact file
        // plugin, or we could allow artefact plugins to add stuff
        // to this query.
1079
1080
        $attachments = get_records_sql_array('
            SELECT
1081
                aa.artefact, aa.attachment, a.artefacttype, a.title, a.description, f.size
1082
1083
            FROM {artefact_attachment} aa
                INNER JOIN {artefact} a ON aa.attachment = a.id
1084
                LEFT JOIN {artefact_file_files} f ON a.id = f.artefact
1085
            WHERE aa.artefact IN (' . join(', ', array_map('intval', $artefactids)) . ')', '');
1086
1087
1088
1089
1090
1091
        if (!$attachments) {
            return array();
        }
        return $attachments;
    }

1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
    public function tags_from_id_list($artefactids) {
        if (empty($artefactids)) {
            return array();
        }
        $artefactids = join(',', array_map('intval', $artefactids));
        $tags = get_records_select_array('artefact_tag', 'artefact IN (' . $artefactids . ')');
        if (!$tags) {
            return array();
        }
        return $tags;
    }

1104
    public function get_attachments($assoc=false) {
Aaron Wells's avatar
Aaron Wells committed
1105
        $list = get_records_sql_assoc('SELECT a.id, a.artefacttype, a.title, a.description
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
            FROM {artefact_attachment} aa
            INNER JOIN {artefact} a ON a.id = aa.attachment
            WHERE aa.artefact = ?
            ORDER BY a.title', array($this->id));

        // load tags
        if ($list) {
            $tags = get_records_select_array('artefact_tag', 'artefact IN (' . join(',', array_keys($list)) . ')');
            if ($tags) {
                foreach ($tags as $t) {
                    $list[$t->artefact]->tags[] = $t->tag;
                }
                foreach ($list as &$attachment) {
                    if (!empty($attachment->tags)) {
                        $attachment->tags = join(', ', $attachment->tags);
                    }
                }
            }
        }
1125
1126
1127
1128
1129
1130
1131
        else {
            return array();
        }

        if ($assoc) {          // Remove once tablerenderers are gone.
            return $list;
        }
1132
1133
1134
        return array_values($list);
    }

1135
    public function attach($attachmentid, $itemid=null) {
1136
1137
1138
        if (record_exists('artefact_attachment', 'artefact', $this->get('id'), 'attachment', $attachmentid)) {
            return;
        }
1139
1140
1141
        if (!record_exists('artefact', 'id', $attachmentid)) {
            throw new ArtefactNotFoundException(get_string('artefactnotfound', 'mahara', $attachmentid));
        }
1142
        $data = new StdClass();
1143
1144
        $data->artefact = $this->get('id');
        $data->attachment = $attachmentid;
1145
        $data->item = $itemid;
1146
1147
1148
1149
1150
1151
1152
1153
        insert_record('artefact_attachment', $data);
    }

    public function detach($attachmentid=null) {
        if (is_null($attachmentid)) {
            delete_records('artefact_attachment', 'artefact', $this->id);
            return;
        }
1154
1155
1156
        if (!record_exists('artefact', 'id', $attachmentid)) {
            throw new ArtefactNotFoundException(get_string('artefactnotfound', 'mahara', $attachmentid));
        }
1157
1158
1159
1160
1161
1162
1163
        delete_records('artefact_attachment', 'artefact', $this->get('id'), 'attachment', $attachmentid);
    }

    // Interface:
    public static function attached_id_list($attachmentid) {
        return get_column('artefact_attachment', 'artefact', 'attachment', $attachmentid);
    }
1164
1165
1166
1167

    public function exportable() {
        return true;
    }
1168
1169
1170
1171
1172
1173
1174

    // Update the locked field on a user's artefacts
    // Lock anything in a submitted view, and unlock anything that isn't
    public static function update_locked($userid) {
        if (empty($userid)) {
            return;
        }
1175
1176
1177
1178
1179
1180
1181
1182
        $submitted = get_column_sql('
            SELECT a.id
            FROM {artefact} a
                JOIN {view_artefact} va ON a.id = va.artefact
                JOIN {view} v ON va.view = v.id
            WHERE a.owner = ?
                AND v.owner = ?
                AND (v.submittedgroup IS NOT NULL OR v.submittedhost IS NOT NULL)',
1183
1184
            array($userid, $userid)
        );
1185
        if ($submitted) {
1186
1187
1188
1189
1190
1191
1192
            $submitted = artefact_get_descendants($submitted);
            if ($attachments = get_column_sql('
                SELECT attachment FROM {artefact_attachment}
                WHERE artefact IN (' . join(',', $submitted) . ')',
                array())) {
                $submitted = array_merge($submitted, $attachments);
            }
1193
1194
        }
        db_begin();
1195
1196
        if (!empty($submitted)) {
            $idstr = '(' . join(',', $submitted) . ')';
1197
1198
1199
1200
1201
1202
1203
1204
            set_field_select('artefact', 'locked', 1, "locked = 0 AND id IN $idstr", array());
        }
        // Unlock
        $select = 'locked = 1 AND "owner" = ?';
        if (isset($idstr)) {
            $select .= " AND NOT id IN $idstr";
        }
        set_field_select('artefact', 'locked', 0, $select, array($userid));
1205
1206
        db_commit();
    }
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224

    /**
     * Return an array of tags associated to an artefact
     *
     * @param int  ID of the artefact
     *
     * @return array of strings
     */
    public static function artefact_get_tags($id) {
        if (empty($id)) {
            return array();
        }
        $tags = get_column_sql('SELECT tag FROM {artefact_tag} WHERE artefact = ? ORDER BY tag', array($id));
        if (!$tags) {
            return array();
        }
        return $tags;
    }
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254

    /**
     * Checks to see if artefact type is allowed to be part of the progress bar.
     * By default all artefacts are included in progress bar. To remove an artefact
     * from being a progress bar option have your artefacttype return false for this.
     * @return boolean
     */
    public static function is_allowed_in_progressbar() {
        return true;
    }

    /**
     * Checks to see if artefact for the progress bar is countable.
     * By default all artefacts are counted as true/false (1 or 0). If you need to have
     * more then one instance counting towards progress, say image upload, you can specify
     * it to be countable. This will show a select box rather than a check box on the
     * progress admin screen.
     * @return boolean
     */
    public static function is_countable_progressbar() {
        return false;
    }

    /**
     * Check if artefacttype is meant to be handled as a meta artefact by progress bar
     * @return boolean
     */
    public static function is_metaartefact() {
        return false;
    }
1255
1256
1257
1258
1259
1260
1261
1262

    /**
     * The (optional) custom title of this artefact on the profile completion progress bar config page
     * @return mixed FALSE if it should just use the artefact type, a string otherwise
     */
    public static function get_title_progressbar() {
        return false;
    }
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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349