lib.php 71.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
 * Helper interface to hold the PluginArtefact's abstract static functions
17
 */
18
interface IPluginArtefact {
Aaron Wells's avatar
Aaron Wells committed
19 20
    /**
     * This function returns a list of classnames
21
     * of artefact types this plugin provides.
Penny Leach's avatar
Penny Leach committed
22
     * @abstract
23 24
     * @return array
     */
25
    public static function get_artefact_types();
Aaron Wells's avatar
Aaron Wells committed
26

27 28 29 30 31 32 33
    /**
    * This function returns a list of classnames
    * of block types this plugin provides
    * they must match directories inside artefact/$name/blocktype
    * @abstract
    * @return array
    */
34
    public static function get_block_types();
35

36 37
    /**
     * This function returns the name of the plugin.
Penny Leach's avatar
Penny Leach committed
38
     * @abstract
39 40
     * @return string
     */
41 42
    public static function get_plugin_name();
}
43

44 45 46 47 48 49 50 51 52
/**
 * Base artefact plugin class
 * @abstract
 */
abstract class PluginArtefact extends Plugin implements IPluginArtefact {

    public static function get_plugintype_name() {
        return 'artefact';
    }
53

54 55 56
    /**
     * This function returns an array of menu items
     * to be displayed
57 58 59 60
     *
     * See the function find_menu_children() in lib/web.php
     * for a description of the expected array structure.
     *
61 62 63 64 65
     * @return array
     */
    public static function menu_items() {
        return array();
    }
66 67 68 69 70 71 72 73 74 75 76 77 78


    /**
     * 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();
    }
79 80 81 82 83 84 85 86 87 88 89


    /**
     * 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();
    }
90 91 92 93

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


    /**
104 105 106 107
     * 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
108
     */
109 110
    public static function has_progressbar_options() {
        return true;
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 138 139 140
    /**
     * 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;
    }

141 142 143 144 145 146 147
    /**
     * 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();
    }
148 149 150 151 152 153 154 155 156 157 158

    /**
     * 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;
    }
159 160 161 162 163 164 165 166 167 168 169 170 171

    /**
     * This function returns an array of menu items
     * to be displayed in the top right navigation menu
     *
     * See the function find_menu_children() in lib/web.php
     * for a description of the expected array structure.
     *
     * @return array
     */
    public static function right_nav_menu_items() {
        return array();
    }
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

    /**
     * This function returns an array of admin menu items
     * to be displayed
     *
     * See the function find_menu_children() in lib/web.php
     * for a description of the expected array structure.
     *
     * @return array
     */
    public static function admin_menu_items() {
        return array();
    }

    /**
     * This function returns an array of institution menu items
     * to be displayed
     *
     * See the function find_menu_children() in lib/web.php
     * for a description of the expected array structure.
     *
     * @return array
     */
    public static function institution_menu_items() {
        return array();
    }

    /**
     * This function returns an array of institution staff menu items
     * to be displayed
     *
     * See the function find_menu_children() in lib/web.php
     * for a description of the expected array structure.
     *
     * @return array
     */
    public static function institution_staff_menu_items() {
        return array();
    }
211 212
}

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
/**
 * Helper interface to hold the Artefact class's abstract static functions
 */
interface IArtefactType {
    /**
     * Returns a URL for an icon for the appropriate artefact
     *
     * @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
     *                       being displayed.
     * @abstract
     * @return string URL for the icon
     */
    public static function get_icon($options=null);

    /**
     * whether a user will have exactly 0 or 1 of this artefact type
     * @abstract
     */
    public static function is_singular();

    /**
     * Returns a list of key => value pairs where the key is either '_default'
     * or a language string, and value is a URL linking to that behaviour for
     * this artefact type
     *
     * @param integer This is the ID of the artefact being linked to
     */
    public static function get_links($id);

    // @TODO maybe uncomment this later and implement it everywhere
    // when we know a bit more about what blocks we want.
    //public function render_self($options);
}

Aaron Wells's avatar
Aaron Wells committed
252
/**
253 254 255
 * Base artefact type class
 * @abstract
 */
256
abstract class ArtefactType implements IArtefactType {
257

258
    protected $dirty;
259
    protected $deleted = false;
260
    protected $id;
261 262
    protected $artefacttype;
    protected $owner;
263
    protected $container = 0;
264
    protected $parent;
265
    protected $oldparent;
266 267
    protected $ctime;
    protected $mtime;
268
    protected $atime;
269
    protected $locked = 0;
270 271 272
    protected $title;
    protected $description;
    protected $note;
273
    protected $tags = array();
274
    protected $institution;
275
    protected $group;
276 277
    protected $author;
    protected $authorname;
278 279
    protected $allowcomments = 0;
    protected $approvecomments = 0;
Richard Mansfield's avatar
Richard Mansfield committed
280
    protected $rolepermissions;
281
    protected $mtimemanuallyset;
282 283 284
    protected $license;
    protected $licensor;
    protected $licensorurl;
285
    protected $path;
286

Penny Leach's avatar
Penny Leach committed
287 288 289 290 291 292 293
    protected $viewsinstances;
    protected $viewsmetadata;
    protected $childreninstances;
    protected $childrenmetadata;
    protected $parentinstance;
    protected $parentmetadata;

294 295
    /**
     * Constructor.
296 297 298
     * 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
299 300 301 302 303 304 305
     * artefact, ready to be filled up.
     * If the $new parameter is true, we can skip the query
     * because we know the artefact is new.
     *
     * @param int   $id     artefact.id
     * @param mixed $data   optional data supplied for artefact
     * @param bool  $new
306
     */
307
    public function __construct($id=0, $data=null, $new = FALSE) {
308
        if (!empty($id)) {
Penny Leach's avatar
Penny Leach committed
309 310
            if (empty($data)) {
                if (!$data = get_record('artefact','id',$id)) {
311
                    throw new ArtefactNotFoundException(get_string('artefactnotfound', 'error', $id));
Penny Leach's avatar
Penny Leach committed
312
                }
313
            }
314
            $this->id = $id;
315 316
        }
        else {
317 318
            $this->ctime = $this->mtime = time();
            $this->dirty = true;
319
        }
320 321 322 323 324
        if (empty($data)) {
            $data = array();
        }
        foreach ((array)$data as $field => $value) {
            if (property_exists($this, $field)) {
325
                if (in_array($field, array('atime', 'ctime', 'mtime'))) {
326 327 328
                    if (!(!empty($value) && is_string($value) && $value = strtotime($value))) {
                        $value = time();
                    }
Aaron Wells's avatar
Aaron Wells committed
329
                }
Richard Mansfield's avatar
Richard Mansfield committed
330
                if ($field == 'tags' && !is_array($value)) {
331 332
                    $value = preg_split("/\s*,\s*/", trim($value));
                }
333 334 335 336
                $this->{$field} = $value;
            }
        }

337 338 339 340
        if (!empty($this->parent)) {
            $this->oldparent = $this->parent;
        }

341 342 343 344 345 346 347
        $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));
            }
        }

348 349
        // load tags
        if ($this->id) {
350
            $this->tags = ArtefactType::artefact_get_tags($this->id);
351 352
        }

Richard Mansfield's avatar
Richard Mansfield committed
353
        // load group permissions
354
        if ($this->group && !is_array($this->rolepermissions)) {
Richard Mansfield's avatar
Richard Mansfield committed
355 356 357
            $this->load_rolepermissions();
        }

358
        $this->atime = time();
359 360
    }

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    /**
     * 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']);
    }

402 403 404 405 406
    /**
     * Returns the instances of all views where this artefact is used.
     *
     * @return array Array of view instances.
     */
407
    public function get_views_instances() {
408 409 410 411 412
        // @todo test this
        if (!isset($this->viewsinstances)) {
            $this->viewsinstances = false;
            if ($views = $this->get_views_metadata()) {
                $this->viewsinstances = array();
413 414 415
                if (!class_exists('View')) {
                    require_once(get_config('libroot') . 'view.php');
                }
416
                foreach ($views as $view) {
417
                    $this->viewsinstances[] = new View($view->view);
418 419 420 421
                }
            }
        }
        return $this->viewsinstances;
422
    }
423

424
    public function get_views_metadata() {
425 426 427 428
        if (!isset($this->viewsmetadata)) {
            $this->viewsmetadata = get_records_array('view_artefact', 'artefact', $this->id);
        }
        return $this->viewsmetadata;
429 430
    }

Richard Mansfield's avatar
Richard Mansfield committed
431 432 433 434
    public function count_children() {
        return count_records('artefact', 'parent', $this->get('id'));
    }

435 436 437 438 439 440 441
    public function has_children() {
        if ($this->get_children_metadata()) {
            return true;
        }
        return false;
    }

442
    public function get_plugin_name() {
443 444 445 446 447 448 449 450
        static $cache = array();

        $type = $this->get('artefacttype');
        if (!isset($cache[$type])) {
            $cache[$type] = get_field('artefact_installed_type', 'plugin', 'name', $type);
        }

        return $cache[$type];
451 452
    }

Aaron Wells's avatar
Aaron Wells committed
453 454
    /**
     * This function returns the instances
Penny Leach's avatar
Penny Leach committed
455
     * of all children of this artefact
Aaron Wells's avatar
Aaron Wells committed
456
     * If you just want the basic info,
Penny Leach's avatar
Penny Leach committed
457
     * use {@link get_children_metadata} instead.
Aaron Wells's avatar
Aaron Wells committed
458
     *
459
     * @return array of instances or false if no children.
Penny Leach's avatar
Penny Leach committed
460
     */
461
    public function get_children_instances() {
Penny Leach's avatar
Penny Leach committed
462 463 464 465 466
        if (!isset($this->childreninstances)) {
            $this->childreninstances = false;
            if ($children = $this->get_children_metadata()) {
                $this->childreninstances = array();
                foreach ($children as $child) {
467
                    $classname = generate_artefact_class_name($child->artefacttype);
Penny Leach's avatar
Penny Leach committed
468 469 470 471 472 473
                    $instance = new $classname($child->id, $child);
                    $this->childreninstances[] = $instance;
                }
            }
        }
        return $this->childreninstances;
474 475
    }

476
    /**
Aaron Wells's avatar
Aaron Wells committed
477 478
     * This function returns the db rows
     * from the artefact table that have this
479 480 481
     * 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
482
     *
483
     * @return array of false if no children
484
     */
485
    public function get_children_metadata() {
Penny Leach's avatar
Penny Leach committed
486
        if (!isset($this->childrenmetadata)) {
487
            $this->childrenmetadata = get_records_array('artefact', 'parent', $this->id);
Penny Leach's avatar
Penny Leach committed
488 489
        }
        return $this->childrenmetadata;
490
    }
Penny Leach's avatar
Penny Leach committed
491 492 493 494 495 496 497 498 499

    /**
     * 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
     */
500
    public function get_parent_instance() {
Penny Leach's avatar
Penny Leach committed
501 502 503
        if (!isset($this->parentinstance)) {
            $this->parentinstance = false;
            if ($parent = $this->get_parent_metadata()) {
504
                $classname = generate_artefact_class_name($parent->artefacttype);
Penny Leach's avatar
Penny Leach committed
505 506 507 508
                $this->parentinstance = new $classname($parent->id, $parent);
            }
        }
        return $this->parentinstance;
509
    }
510

Aaron Wells's avatar
Aaron Wells committed
511 512
    /**
     * This function returns the db row
513 514
     * (if there is one) of the parent
     * artefact for this instance.
Aaron Wells's avatar
Aaron Wells committed
515
     * If you want the instance, use
516
     * {@link get_parent_instance} instead.
Aaron Wells's avatar
Aaron Wells committed
517
     *
518
     * @return object - db row
519
     */
520
    public function get_parent_metadata() {
521 522 523
        if (empty($this->parent)) {
            return false;
        }
524
        return get_record('artefact','id',$this->parent);
525 526
    }

527 528 529
    /**
     * Returns how much quota this artefact has used.
     *
Aaron Wells's avatar
Aaron Wells committed
530
     * It should try to not instantiate the artefact, because it is normally
531 532 533 534 535 536 537 538
     * 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;
    }

539
    public function get($field) {
540
        if (!property_exists($this, $field)) {
541
            throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
542 543 544 545 546
        }
        return $this->{$field};
    }

    public function set($field, $value) {
547
        if (property_exists($this, $field)) {
548
            if ($this->{$field} != $value) {
549
                // Only set it to dirty if it's changed.
550
                $this->dirty = true;
551 552 553 554
                // Set oldparent only if it has changed.
                if ($field == 'parent') {
                    $this->oldparent = $this->parent;
                }
555
            }
556
            $this->{$field} = $value;
557 558 559 560 561 562
            if ($field == 'mtime') {
                $this->mtimemanuallyset = true;
            }
            else if (!$this->mtimemanuallyset) {
                $this->mtime = time();
            }
563 564
            return true;
        }
565
        throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
566
    }
Aaron Wells's avatar
Aaron Wells committed
567

568 569 570
    /**
     * Artefact destructor. Calls commit and marks the
     * artefact cache as dirty if necessary.
571 572 573
     *
     * A special case is when the object has just been deleted.  In this case,
     * we do nothing.
574
     */
575
    public function __destruct() {
576 577 578
        if ($this->deleted) {
            return;
        }
Aaron Wells's avatar
Aaron Wells committed
579

580
        if (!empty($this->dirty) && !defined('MAHARA_CRASHING')) {
581 582
            $this->commit();
        }
583
    }
Aaron Wells's avatar
Aaron Wells committed
584 585

    /**
586 587 588
     * 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.
589
     */
590
    public function commit() {
591 592
        static $last_source, $last_output;

593 594
        $is_new = false;

595 596 597
        if (empty($this->dirty)) {
            return;
        }
598

599 600 601 602
        if (empty($this->author) && empty($this->authorname)) {
            $this->set_author();
        }

603 604
        db_begin();

605
        $fordb = new StdClass();
606 607 608
        foreach (get_object_vars($this) as $k => $v) {
            $fordb->{$k} = $v;
            if (in_array($k, array('mtime', 'ctime', 'atime')) && !empty($v)) {
609 610 611 612 613
                if ($v !== $last_source) {
                  $last_output = db_format_timestamp($v);
                  $last_source = $v;
                }
                $fordb->{$k} = $last_output;
614 615 616
            }
        }
        if (empty($this->id)) {
617
            $is_new = true;
618
            $this->id = insert_record('artefact', $fordb, 'id', true);
Richard Mansfield's avatar
Richard Mansfield committed
619 620 621
            if ($this->can_be_logged()) {
                $this->log('created');
            }
622
            $this->add_hierarchy_path($this->parent);
623 624
        }
        else {
Richard Mansfield's avatar
Richard Mansfield committed
625 626 627
            if ($this->can_be_logged()) {
                $this->log('edited');
            }
628
            update_record('artefact', $fordb, 'id');
629
            $this->update_hierarchy_path($this->parent);
630
        }
631

Richard Mansfield's avatar
Richard Mansfield committed
632 633 634 635
        if (!empty($this->group)) {
            $this->save_rolepermissions();
        }

636 637 638 639
        if (!$is_new) {
          $deleted = delete_records('artefact_tag', 'artefact', $this->id);
        }

640
        if (is_array($this->tags)) {
641
            $this->tags = check_case_sensitive($this->tags, 'artefact_tag');
Martyn Smith's avatar
Martyn Smith committed
642
            foreach (array_unique($this->tags) as $tag) {
643 644 645
                if (empty($tag)) {
                    continue;
                }
646 647 648 649 650 651 652 653 654 655
                insert_record(
                    'artefact_tag',
                    (object) array(
                        'artefact' => $this->id,
                        'tag'      => $tag,
                    )
                );
            }
        }

656
        $this->postcommit_hook($is_new);
657

658 659
        handle_event('saveartefact', $this);

660
        $this->dirty = false;
661
        $this->deleted = false;
662 663

        db_commit();
664 665
    }

666 667 668 669 670 671 672 673 674 675 676 677
    /**
     * A hook method called immediately after the basic data is save in the commit() method,
     * but before the DB transaction is closed and before the saveartefact event is triggered.
     *
     * Child classes may use this to alter data or add data into additional tables so that
     * it's present when the saveartefact event is called.
     *
     * @param boolean $new True if the artefact has just been created
     */
    protected function postcommit_hook($new) {
    }

Aaron Wells's avatar
Aaron Wells committed
678
    /**
679 680 681 682 683 684 685
     * 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.
686
     */
687 688
    public function delete() {
        if (empty($this->id)) {
689
            $this->dirty = false;
690 691
            return;
        }
Aaron Wells's avatar
Aaron Wells committed
692

693
        db_begin();
694

695 696 697 698
        // Call delete() on comments (if there are any)
        safe_require('artefact', 'comment');
        ArtefactTypeComment::delete_comments_onartefacts(array($this->id));

699 700 701 702 703 704
        // Call delete() on children (if there are any)
        if ($children = $this->get_children_instances()) {
            foreach ($children as $child) {
                $child->delete();
            }
        }
705

706
        artefact_watchlist_notification(array($this->id));
707

708
        self::_delete_dbrecords(array($this->id));
Richard Mansfield's avatar
Richard Mansfield committed
709 710 711 712

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

714 715
        handle_event('deleteartefact', $this);

716
        // Set flags.
717
        $this->dirty = false;
718
        $this->deleted = true;
719

720
        db_commit();
721 722
    }

723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    /**
     * 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);

738 739 740 741
        // Delete comments first
        safe_require('artefact', 'comment');
        ArtefactTypeComment::delete_comments_onartefacts($artefactids);

742 743
        $records = get_records_select_assoc(
            'artefact',
744
            'id IN (' . join(',', array_map('intval', $artefactids)) . ')',
745 746 747 748 749 750 751
            null, 'artefacttype', 'id,parent,artefacttype,container'
        );

        $containers = array();
        $leaves = array();
        foreach ($records as $r) {
            if ($r->container) {
752
                $containers[$r->artefacttype][] = (int)$r->id;
753 754 755 756 757 758
            }
            else {
                $leaves[$r->artefacttype][] = $r->id;
            }
        }

759
        safe_require('artefact', 'file');
760 761 762 763 764 765 766 767 768
        // 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);
769 770 771
            if (is_mysql()) {
                set_field_select('artefact', 'parent', null, 'id IN (' . join(',', $ids) . ')', array());
            }
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
            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;
        }

816
        $idstr = '(' . join(',', array_map('intval', $artefactids)) . ')';
817 818 819

        db_begin();

820
        // Detach any files from this artefact
821
        delete_records_select('artefact_attachment', "artefact IN $idstr");
822

823 824 825 826 827 828 829 830 831 832 833 834
        // 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");
835
        execute_sql("UPDATE {usr} SET profileicon = NULL WHERE profileicon IN $idstr");
836
        execute_sql("UPDATE {institution} SET logo = NULL WHERE logo IN $idstr");
837

838 839 840
        // Delete any references to files embedded in textboxes
        delete_records_select('artefact_file_embedded', "fileid IN $idstr");

841 842 843 844 845
        delete_records_select('artefact', "id IN $idstr");

        db_commit();
    }

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860

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

861
    /**
862
     * By default users are notified of all comments on artefacts
863 864 865 866 867 868 869 870
     * 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;
    }


871 872 873 874
    /**
     * A dummy method, giving graceful output, if this method is not implemented in the relevant child class
     */
    public function render_self($options) {
875 876
        $smarty = smarty_core();
        $smarty->assign('title', $this->get('title'));
877 878
        $smarty->assign('owner', $this->get('owner'));
        $smarty->assign('tags', $this->get('tags'));
879
        $smarty->assign('description', $this->get('description'));
880 881 882 883 884 885
        if (!empty($options['details']) and get_config('licensemetadata')) {
            $smarty->assign('license', render_license($this));
        }
        else {
            $smarty->assign('license', false);
        }
886 887

        return array(
888
            'html' => $smarty->fetch('artefact.tpl'),
889 890 891 892 893
            'javascript'=>''
        );
    }


894 895 896 897 898 899 900 901 902 903
    // ******************** 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
    }

904 905 906 907 908 909 910 911
    /**
    * Returns the printable name of this artefact
    * (used in lists and such)
    */
    public function get_name() {
        return $this->get('title');
    }

912 913 914 915 916 917 918 919
    /**
    * 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
920
    * Returns a short name for the artefact to be used in a list of artefacts in a view
921 922 923
    */
    public function display_title($maxlen=null) {
        if ($maxlen) {
924
            return str_shorten_text($this->get('title'), $maxlen, true);
925 926 927 928
        }
        return $this->get('title');
    }

929 930 931 932 933 934 935
    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);
        }
936 937 938 939 940 941
        if ($institution = $this->get('institution')) {
            if ($institution == 'mahara') {
                return get_config('sitename');
            }
            return get_field('institution', 'displayname', 'name', $institution);
        }
942 943 944 945
        return null;
    }


946 947 948 949
    // ******************** HELPER FUNCTIONS ******************** //

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

951 952
        $type = strtolower(substr($classname, strlen('ArtefactType')));

953
        if (!artefact_type_installed($type)) {
954 955 956 957 958
            throw new InvalidArgumentException("Classname $classname not a valid artefact type");
        }

        return $type;
    }
959

960
    public function to_stdclass() {
Aaron Wells's avatar
Aaron Wells committed
961
       return (object)get_object_vars($this);
962 963
    }

964 965 966 967 968 969 970 971 972 973 974
    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
975 976

    private function save_rolepermissions() {
977
        if (!$this->group) {
Richard Mansfield's avatar
Richard Mansfield committed
978 979
            return;
        }
980
        if (!isset($this->rolepermissions)) {
981
            $this->rolepermissions = group_get_default_artefact_permissions($this->group);
982
        }
Richard Mansfield's avatar
Richard Mansfield committed
983 984 985
        $id = $this->get('id');
        db_begin();
        delete_records('artefact_access_role', 'artefact', $id);
986
        foreach ($this->rolepermissions as $role => $permissions) {
Richard Mansfield's avatar
Richard Mansfield committed
987 988 989
            insert_record('artefact_access_role', (object) array(
                'artefact'      => $id,
                'role'          => $role,
990 991 992
                '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
993 994 995 996 997 998
            ));
        }
        db_commit();
    }

    private function load_rolepermissions() {
999 1000 1001
        if (!$this->group) {
            return;
        }
Richard Mansfield's avatar
Richard Mansfield committed
1002 1003
        $records = get_records_array('artefact_access_role', 'artefact', $this->get('id'));
        if ($records) {
1004
            $this->rolepermissions = array();
Richard Mansfield's avatar
Richard Mansfield committed
1005
            foreach ($records as $r) {
1006
                $this->rolepermissions[$r->role] = (object) array(
Richard Mansfield's avatar
Richard Mansfield committed
1007 1008 1009 1010 1011 1012
                    'view' => (bool) $r->can_view,
                    'edit' => (bool) $r->can_edit,
                    'republish' => (bool) $r->can_republish,
                );
            }
        }
1013
        else {
1014
            $this->rolepermissions = group_get_default_artefact_permissions($this->group);
1015
        }
Richard Mansfield's avatar
Richard Mansfield committed
1016 1017
    }

1018 1019 1020 1021
    public function role_has_permission($role, $permission) {
        return $this->rolepermissions[$role]->{$permission};
    }

Richard Mansfield's avatar
Richard Mansfield committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    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,
1034 1035
            'parentmetadata' => 1,
            'path' => 1    // the path value will be updated later
Richard Mansfield's avatar
Richard Mansfield committed
1036
        );
1037
        $data = new StdClass;
Richard Mansfield's avatar
Richard Mansfield committed
1038
        foreach (get_object_vars($this) as $k => $v) {
1039
            if (in_array($k, array('atime', 'ctime', 'mtime'))) {
1040
                $data->$k = db_format_timestamp($v);
1041 1042
            }
            else if (!isset($ignore[$k])) {
1043
                $data->$k = $v;
Richard Mansfield's avatar
Richard Mansfield committed