lib.php 77.8 KB
Newer Older
Richard Mansfield's avatar
Richard Mansfield committed
1 2 3 4 5 6
<?php
/**
 *
 * @package    mahara
 * @subpackage artefact-comment
 * @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.
Richard Mansfield's avatar
Richard Mansfield committed
9 10 11 12 13
 *
 */

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

14
require_once('activity.php');
15
require_once('license.php');
16

17
define('MIN_RATING', 1);
18 19
$maxrating = get_config_plugin('artefact', 'comment', 'ratinglength');
define('MAX_RATING', $maxrating ? $maxrating : 5);
20 21 22 23 24 25 26 27 28 29 30 31 32 33

function valid_rating($ratingstr) {
    if (empty($ratingstr)) {
        return null;
    }

    $rating = intval($ratingstr);
    if ($rating < MIN_RATING) {
        return null;
    }

    return max(MIN_RATING, min(MAX_RATING, $rating));
}

Richard Mansfield's avatar
Richard Mansfield committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
class PluginArtefactComment extends PluginArtefact {

    public static function get_artefact_types() {
        return array(
            'comment',
        );
    }

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

    public static function get_plugin_name() {
        return 'comment';
    }

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

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

58 59 60 61 62 63
    public static function get_activity_types() {
        return array(
            (object)array(
                'name' => 'feedback',
                'admin' => 0,
                'delay' => 0,
64 65
                'allownonemethod' => 1,
                'defaultmethod' => 'email',
66 67 68 69
            )
        );
    }

70 71 72 73
    public static function can_be_disabled() {
        return false;
    }

Richard Mansfield's avatar
Richard Mansfield committed
74 75
    public static function postinst($prevversion) {
        if ($prevversion == 0) {
76
            set_config_plugin('artefact', 'comment', 'commenteditabletime', 10);
Richard Mansfield's avatar
Richard Mansfield committed
77 78 79
            foreach(ArtefactTypeComment::deleted_types() as $type) {
                insert_record('artefact_comment_deletedby', (object)array('name' => $type));
            }
Aaron Wells's avatar
Aaron Wells committed
80 81

            set_config_plugin('artefact', 'comment', 'maxindent', '5');
Richard Mansfield's avatar
Richard Mansfield committed
82 83
        }
    }
Richard Mansfield's avatar
Richard Mansfield committed
84 85 86 87 88 89

    public static function view_export_extra_artefacts($viewids) {
        $artefacts = array();
        if (!$artefacts = get_column_sql("
            SELECT artefact
            FROM {artefact_comment_comment}
90
            WHERE deletedby IS NULL AND hidden=0 AND onview IN (" . join(',', array_map('intval', $viewids)) . ')', array())) {
Richard Mansfield's avatar
Richard Mansfield committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
            return array();
        }
        if ($attachments = get_column_sql('
            SELECT attachment
            FROM {artefact_attachment}
            WHERE artefact IN (' . join(',', $artefacts). ')')) {
            $artefacts = array_merge($artefacts, $attachments);
        }
        return $artefacts;
    }

    public static function artefact_export_extra_artefacts($artefactids) {
        if (!$artefacts = get_column_sql("
            SELECT artefact
            FROM {artefact_comment_comment}
106
            WHERE deletedby IS NULL AND hidden=0 AND onartefact IN (" . join(',', $artefactids) . ')', array())) {
Richard Mansfield's avatar
Richard Mansfield committed
107 108 109 110 111 112 113 114 115 116
            return array();
        }
        if ($attachments = get_column_sql('
            SELECT attachment
            FROM {artefact_attachment}
            WHERE artefact IN (' . join(',', $artefacts). ')')) {
            $artefacts = array_merge($artefacts, $attachments);
        }
        return $artefacts;
    }
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

    public static function get_cron() {
        return array(
            (object)array(
                'callfunction' => 'clean_feedback_notifications',
                'minute'       => '35',
                'hour'         => '22',
            ),
        );
    }

    public static function clean_feedback_notifications() {
        safe_require('notification', 'internal');
        PluginNotificationInternal::clean_notifications(array('feedback'));
    }
132

133 134 135 136 137 138 139 140 141 142 143 144
    public static function progressbar_link($artefacttype) {
        switch ($artefacttype) {
            case 'feedback':
                return 'view/sharedviews.php';
                break;
        }
    }

    public static function progressbar_additional_items() {
        return array(
            (object)array(
                    'name' => 'feedback',
145
                    'title' => get_string('addcomment', 'artefact.comment'),
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
                    'plugin' => 'comment',
                    'active' => true,
                    'iscountable' => true,
                    'is_metaartefact' => true,
            )
        );
    }

    public static function progressbar_metaartefact_count($name) {
        global $USER;
        $meta = new stdClass();
        $meta->artefacttype = $name;
        $meta->completed = 0;
        switch ($name) {
            case 'feedback':
                $sql = "SELECT COUNT(*) AS completed
                         FROM {artefact}
                       WHERE artefacttype='comment'
                         AND owner <> ? AND author = ?";
                $count = get_records_sql_array($sql, array($USER->get('id'), $USER->get('id')));
                $meta->completed = $count[0]->completed;
                break;
            default:
                return false;
        }
        return $meta;
172
    }
Richard Mansfield's avatar
Richard Mansfield committed
173 174 175 176 177 178 179 180
}

class ArtefactTypeComment extends ArtefactType {

    protected $onview;
    protected $onartefact;
    protected $private;
    protected $deletedby;
181
    protected $requestpublic;
182
    protected $rating;
183
    protected $lastcontentupdate;
184
    protected $threadedposition;
185
    protected $hidden;
Richard Mansfield's avatar
Richard Mansfield committed
186 187 188 189 190 191 192 193 194 195 196 197 198

    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);

        if ($this->id && ($extra = get_record('artefact_comment_comment', 'artefact', $this->id))) {
            foreach($extra as $name => $value) {
                if (property_exists($this, $name)) {
                    $this->{$name} = $value;
                }
            }
        }
    }

199 200 201 202
    public static function is_allowed_in_progressbar() {
        return false;
    }

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

    /**
     * For comments, the artefact.mtime property is displayed to users, as the "Update on" date,
     * if it is later than the artefact's creation time. The purpose of this is for transparency
     * in communication, so that people will know that a later comment may be in response to one
     * that no longer exists.
     *
     * So, we don't want the publishing
     * @see ArtefactType::set()
     */
    public function set($field, $value) {
        if (($field == 'title' || $field == 'description') && $this->{$field} != $value) {
            $this->lastcontentupdate = $this->mtime;
        }
        return parent::set($field, $value);
    }

Richard Mansfield's avatar
Richard Mansfield committed
220 221 222 223 224 225 226 227 228 229 230 231
    public function commit() {
        if (empty($this->dirty)) {
            return;
        }

        $new = empty($this->id);

        db_begin();

        parent::commit();

        $data = (object)array(
232 233 234 235 236 237
            'artefact'      => $this->get('id'),
            'onview'        => $this->get('onview'),
            'onartefact'    => $this->get('onartefact'),
            'private'       => $this->get('private'),
            'deletedby'     => $this->get('deletedby'),
            'requestpublic' => $this->get('requestpublic'),
238
            'rating'        => $this->get('rating'),
239
            'threadedposition'        => $this->get('threadedposition'),
240
            'hidden'        => $this->get('hidden'),
Richard Mansfield's avatar
Richard Mansfield committed
241
        );
242 243 244
        if ($this->get('lastcontentupdate')) {
            $data->lastcontentupdate = db_format_timestamp($this->get('lastcontentupdate'));
        }
Richard Mansfield's avatar
Richard Mansfield committed
245 246 247 248 249 250 251 252

        if ($new) {
            insert_record('artefact_comment_comment', $data);
        }
        else {
            update_record('artefact_comment_comment', $data, 'artefact');
        }

253 254
        if ($this->get('onview')) {
            set_field('view', 'mtime', db_format_timestamp(time()), 'id', $this->get('onview'));
255
        }
256 257 258 259
        else if ($this->get('onartefact')) {
            execute_sql("UPDATE {view} SET mtime = ? WHERE id IN (SELECT va.view FROM {view_artefact} va WHERE va.artefact = ?)", array(db_format_timestamp(time()), $this->get('onartefact')));
        }

Richard Mansfield's avatar
Richard Mansfield committed
260 261 262 263 264 265 266 267 268
        db_commit();
        $this->dirty = false;
    }

    public static function is_singular() {
        return false;
    }

    public static function get_icon($options=null) {
Pat Kira's avatar
Pat Kira committed
269 270
        // global $THEME;
        // return false;
Richard Mansfield's avatar
Richard Mansfield committed
271 272 273 274 275 276 277 278
    }

    public function delete() {
        if (empty($this->id)) {
            return;
        }
        db_begin();
        $this->detach();
279
        delete_records('artefact_comment_comment', 'artefact', $this->id);
Richard Mansfield's avatar
Richard Mansfield committed
280 281 282 283
        parent::delete();
        db_commit();
    }

284
    public static function bulk_delete($artefactids, $log=false) {
285 286 287 288
        if (empty($artefactids)) {
            return;
        }

289
        $idstr = join(',', array_map('intval', $artefactids));
290 291 292

        db_begin();
        delete_records_select('artefact_comment_comment', 'artefact IN (' . $idstr . ')');
293
        delete_records_select('artefact_file_embedded', 'resourcetype = ? AND resourceid IN (' . $idstr . ')', array('comment'));
294 295 296 297 298 299 300 301 302
        parent::bulk_delete($artefactids);
        db_commit();
    }

    public static function delete_view_comments($viewid) {
        $ids = get_column('artefact_comment_comment', 'artefact', 'onview', $viewid);
        self::bulk_delete($ids);
    }

303 304 305 306 307 308
    public static function delete_comments_onartefacts($artefactids) {
        $idstr = join(',', array_map('intval', $artefactids));
        $commentids = get_column_sql("SELECT artefact FROM {artefact_comment_comment} WHERE onartefact IN ($idstr)");
        self::bulk_delete($commentids);
    }

Richard Mansfield's avatar
Richard Mansfield committed
309 310
    public static function get_links($id) {
        return array(
311
            '_default' => get_config('wwwroot') . 'artefact/comment/view.php?id=' . $id,
Richard Mansfield's avatar
Richard Mansfield committed
312 313 314 315 316 317 318 319 320 321 322
        );
    }

    public function can_have_attachments() {
        return true;
    }

    public static function deleted_types() {
        return array('author', 'owner', 'admin');
    }

323
    /**
324 325 326
     * Generates default data object required for displaying comments on the page.
     * The is called before populating with specific data to send to get_comments() as
     * an easy way to add variables to get passed to get_comments.
327
     *
328 329 330 331 332 333 334 335 336 337 338
     * int $limit              The number of comments to display (set to
     *                         0 for disabling pagination and showing all comments)
     * int $offset             The offset of comments used for pagination
     * int|string $showcomment Optionally show page with particular comment
     *                         on it or the last page. $offset will be ignored.
     *                         Specify either comment_id or 'last' respectively.
     *                         Set to null to use $offset for pagination.
     * object $view            The view object
     * object $artefact        Optional artefact object
     * bool   $export          Determines if comments are fetched for html export purposes
     * bool   $onview          Optional - is viewing artefact comments on view page so don't show edit buttons
339
     * string $sort            Optional - the sort order of the comments. Valid options are 'earliest' and 'latest'.
340
     * @return object $options Default comments data object
341
     */
342 343 344 345 346 347 348 349
    public static function get_comment_options() {
        $options = new stdClass();
        $options->limit = 10;
        $options->offset = 0;
        $options->showcomment = null;
        $options->view = null;
        $options->artefact = null;
        $options->export = false;
350
        $options->onview = false;
351 352
        $sortorder = get_user_institution_comment_sort_order();
        $options->sort = (!empty($sortorder)) ? $sortorder : 'earliest';
Aaron Wells's avatar
Aaron Wells committed
353
        $options->threaded = null;
354 355 356 357 358 359 360 361 362 363 364
        return $options;
    }

    /**
     * Generates the data object required for displaying comments on the page.
     *
     * @param   object  $options  Object of comment options
     *                            - defaults can be retrieved from get_comment_options()
     * @return  object $result    Comment data object
     */
    public static function get_comments($options) {
365
        global $USER;
Aaron Wells's avatar
Aaron Wells committed
366
        $allowedoptions = self::get_comment_options();
367 368
        // set the object's key/val pairs as variables
        foreach ($options as $key => $option) {
Aaron Wells's avatar
Aaron Wells committed
369
            if (array_key_exists($key, $allowedoptions));
370 371
            $$key = $option;
        }
372 373 374 375
        $userid = $USER->get('id');
        $viewid = $view->get('id');
        if (!empty($artefact)) {
            $canedit = $USER->can_edit_artefact($artefact);
376 377
            $owner = $artefact->get('owner');
            $isowner = $userid && $userid == $owner;
378 379 380
            $artefactid = $artefact->get('id');
        }
        else {
381 382 383 384 385 386 387 388 389 390 391
            if ($group = $view->get('group')) {
                $group_admins = group_get_admin_ids($group);
                $canedit = (array_search($userid, $group_admins) !== false) ? true : false;
                $owner = null;
                $isowner = null;
            }
            else {
                $canedit = $USER->can_moderate_view($view);
                $owner = $view->get('owner');
                $isowner = $userid && $userid == $owner;
            }
392 393
            $artefactid = null;
        }
394

Aaron Wells's avatar
Aaron Wells committed
395 396 397 398 399 400 401 402
        // Find out whether the page's owner has threaded comments or not
        if ($owner) {
            $threaded = get_user_institution_comment_threads($owner);
        }
        else {
            $threaded = false;
        }

403 404 405 406 407 408
        $result = (object) array(
            'limit'    => $limit,
            'offset'   => $offset,
            'view'     => $viewid,
            'artefact' => $artefactid,
            'canedit'  => $canedit,
409
            'owner'    => $owner,
410
            'isowner'  => $isowner,
411
            'export'   => $export,
412
            'sort'     => $sort,
Aaron Wells's avatar
Aaron Wells committed
413
            'threaded' => $threaded,
414 415 416
            'data'     => array(),
        );

417
        $where = 'c.hidden = 0';
418
        if (!empty($artefactid)) {
419
            $where .= ' AND c.onartefact = ' . (int)$artefactid;
420 421
        }
        else {
422
            $where .= ' AND c.onview = ' . (int)$viewid;
423 424
        }
        if (!$canedit) {
Aaron Wells's avatar
Aaron Wells committed
425 426 427 428 429 430 431
            $where .= ' AND (';
            $where .= 'c.private = 0 '; // Comment is public
            $where .= 'OR a.author = ' . (int) $userid; // You are the comment author
            if ($threaded) {
                $where .= ' OR p.author = ' . (int) $userid; // you authored the parent
            }
            $where .= ')';
432 433 434 435
        }

        $result->count = count_records_sql('
            SELECT COUNT(*)
Aaron Wells's avatar
Aaron Wells committed
436 437 438 439 440 441
            FROM
                {artefact} a
                JOIN {artefact_comment_comment} c
                    ON a.id = c.artefact
                LEFT JOIN {artefact} p
                    ON a.parent = p.id
442 443
            WHERE ' . $where);

444
        if ($result->count > 0) {
Aaron Wells's avatar
Aaron Wells committed
445 446 447 448 449 450

            // Figure out sortorder
            if (!$threaded) {
                $orderby = 'a.ctime ' . ($sort == 'latest' ? 'DESC' : 'ASC');
            }
            else {
451
                $orderby = 'c.threadedposition ' . ($sort == 'latest' ? 'DESC' : 'ASC');
Aaron Wells's avatar
Aaron Wells committed
452 453
            }

454 455 456
            // If pagination is in use, see if we want to get a page with particular comment
            if ($limit) {
                if ($showcomment == 'last') {
457
                    // If we have limit (pagination is used) ignore $offset and just get the last page of comments.
458 459 460 461 462
                    $result->forceoffset = $offset = (ceil($result->count / $limit) - 1) * $limit;
                }
                else if (is_numeric($showcomment)) {
                    // Ignore $offset and get the page that has the comment
                    // with id $showcomment on it.
Aaron Wells's avatar
Aaron Wells committed
463
                    // Fetch everything and figure out which page $showcomment is in.
464 465
                    // This will get ugly if there are 1000s of comments
                    $ids = get_column_sql('
Aaron Wells's avatar
Aaron Wells committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
                            SELECT a.id
                            FROM {artefact} a JOIN {artefact_comment_comment} c ON a.id = c.artefact
                                LEFT JOIN {artefact} p ON a.parent = p.id
                            WHERE ' . $where . '
                            ORDER BY ' . $orderby,
                            array()
                    );
                    $found = false;
                    foreach ($ids as $k => $v) {
                        if ($v == $showcomment) {
                            $found = $k;
                            break;
                        }
                    }
                    if ($found !== false) {
481
                        // Add 1 because array index starts from 0 and therefore key value is offset by 1.
Aaron Wells's avatar
Aaron Wells committed
482
                        $rank = $found + 1;
483 484 485
                        $result->forceoffset = $offset = ((ceil($rank / $limit) - 1) * $limit);
                        $result->showcomment = $showcomment;
                    }
486
                }
487
            }
488

489 490
            $comments = get_records_sql_assoc('
                SELECT
491
                    a.id, a.author, a.authorname, a.ctime, a.mtime, a.description, a.group,
492
                    c.private, c.deletedby, c.requestpublic, c.rating, c.lastcontentupdate,
493
                    u.username, u.firstname, u.lastname, u.preferredname, u.email, u.staff, u.admin,
Aaron Wells's avatar
Aaron Wells committed
494
                    u.deleted, u.profileicon, u.urlid, a.path, p.id AS parent, p.author AS parentauthor
495 496
                FROM {artefact} a
                    INNER JOIN {artefact_comment_comment} c ON a.id = c.artefact
Aaron Wells's avatar
Aaron Wells committed
497 498
                    LEFT JOIN {artefact} p
                        ON a.parent = p.id
499
                    LEFT JOIN {usr} u ON a.author = u.id
500
                WHERE ' . $where . '
Aaron Wells's avatar
Aaron Wells committed
501
                ORDER BY ' . $orderby, array(), $offset, $limit);
502

503
            $files = ArtefactType::attachments_from_id_list(array_keys($comments));
504

505 506 507 508 509
            if ($files) {
                safe_require('artefact', 'file');
                foreach ($files as &$file) {
                    $comments[$file->artefact]->attachments[] = $file;
                }
510 511
            }

Aaron Wells's avatar
Aaron Wells committed
512 513 514 515 516 517 518
            // calculate the indent tabs for the comments
            $max_depth = ($threaded ? get_config_plugin('artefact', 'comment', 'maxindent') : 1);

            $usercache = array($userid => $canedit);

            foreach($comments as &$c) {
                // You can post a public reply to a comment if you can see it & the comment is not private
519
                $c->canpublicreply = (int) self::can_public_reply_to_comment($c->private, $c->deletedby);
Aaron Wells's avatar
Aaron Wells committed
520 521
                $c->canprivatereply = (int) self::can_private_reply_to_comment(
                        $c->private,
522
                        $c->deletedby,
Aaron Wells's avatar
Aaron Wells committed
523 524 525 526 527 528 529 530 531 532 533
                        $userid,
                        $c->author,
                        $c->parentauthor,
                        $artefact,
                        $view
                );
                $c->canreply = ($threaded && ($c->canpublicreply || $c->canprivatereply)) ? 1 : 0;
                $c->indent = ($max_depth == 1) ? 1 : min($max_depth, substr_count($c->path, '/'));
                // Count indent levels starting from 0 instead of 1.
                $c->indent -= 1;
            }
534 535
            $result->data = array_values($comments);
        }
536

537
        // check to see if the comments are to be displayed in a block instance
538
        // or the base of the page
Pat Kira's avatar
Pat Kira committed
539
        $result->position = 'base';
540
        $blocks = get_records_array('block_instance', 'view', $viewid);
Pat Kira's avatar
Pat Kira committed
541
        if (!empty($blocks)) {
542
            foreach ($blocks as $block) {
Pat Kira's avatar
Pat Kira committed
543
                if ($block->blocktype === 'comment') {
544
                    $result->position = 'blockinstance';
545
                }
546 547 548
            }
        }

549
        self::build_html($result, $onview);
550 551 552
        return $result;
    }

Aaron Wells's avatar
Aaron Wells committed
553 554 555 556
    /**
     * Can you post a public reply to this comment?
     * (Made into a separate function so we can re-use the logic)
     * @param boolean $isprivate Is the comment private?
557
     * @param int $deletedby The id of the user who deleted the comment (or null)
Aaron Wells's avatar
Aaron Wells committed
558 559
     * @return boolean
     */
560 561
    public static function can_public_reply_to_comment($isprivate, $deletedby) {
        return !($isprivate || $deletedby);
Aaron Wells's avatar
Aaron Wells committed
562 563 564 565 566 567
    }

    /**
     * Can you post a private reply to this comment?
     * (Made into a separate function so we can re-use the logic)
     * @param boolean $isprivate Is the replied-to comment private?
568
     * @param int $deletedby The id of the user who deleted the comment (or null)
Aaron Wells's avatar
Aaron Wells committed
569 570 571 572 573 574 575
     * @param int $commenter User replying to the comment
     * @param int $author Author of the replied-to comment
     * @param int $parentauthor Author of the replied-to comment's parent
     * @param ArtefactType $artefact The artefact being commented on (or null)
     * @param View $view The view being commented on (or null)
     * @return boolean
     */
576 577 578 579 580 581 582
    public static function can_private_reply_to_comment($isprivate, $deletedby, $commenter, $author, $parentauthor, $artefact=null, $view=null) {

        // Can't post a private reply to a deleted comment
        if ($deletedby) {
            return false;
        }

Aaron Wells's avatar
Aaron Wells committed
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
        // No private replies to anonymous comments
        // (It would be impossible for the commenter to see!)
        if (!$author) {
            return false;
        }

        // No private replies to your own private comments
        if ($isprivate && $author == $commenter) {
            return false;
        }

        // You can post a private reply to a comment that is a private reply to one of your comments
        if ($isprivate && $parentauthor == $commenter) {
            return true;
        }

        // The page owner can post private replies to others' comments
        if (self::can_moderate_comments($commenter, $artefact, $view)) {
            return true;
        }

        // Other users can post a private reply to a comment by the page owner.
        return self::can_moderate_comments($author, $artefact, $view);
    }

    /**
     * Whether a user can moderate comments on a particular (view or artefact) page
     * @param int $userid
     * @param ArtefactType $artefact
     * @param View $view
     * @return boolean
     */
    public static function can_moderate_comments($userid, $artefact=null, $view=null) {
        static $usercache = array();
        if (array_key_exists($userid, $usercache)) {
            return $usercache[$userid];
        }

        $user = new User();
        $user->find_by_id($userid);
        if ($artefact) {
            $canmod = $user->can_edit_artefact($artefact);
        }
        else {
            $canmod = $user->can_moderate_view($view);
        }
        $usercache[$userid] = $canmod;
        return $canmod;
    }

633
    public static function count_comments($viewids=null, $artefactids=null) {
634 635 636 637
        if (!empty($viewids)) {
            return get_records_sql_assoc('
                SELECT c.onview, COUNT(c.artefact) AS comments
                FROM {artefact_comment_comment} c
638
                WHERE c.onview IN (' . join(',', array_map('intval', $viewids)) . ') AND c.deletedby IS NULL AND c.hidden=0
Richard Mansfield's avatar
Richard Mansfield committed
639 640 641
                GROUP BY c.onview',
                array()
            );
642 643 644 645 646
        }
        if (!empty($artefactids)) {
            return get_records_sql_assoc('
                SELECT c.onartefact, COUNT(c.artefact) AS comments
                FROM {artefact_comment_comment} c
647
                WHERE c.onartefact IN (' . join(',', array_map('intval', $artefactids)) . ') AND c.deletedby IS NULL AND c.hidden=0
Richard Mansfield's avatar
Richard Mansfield committed
648 649 650
                GROUP BY c.onartefact',
                array()
            );
651 652 653
        }
    }

654 655 656 657 658 659 660 661 662 663 664 665
    public static function last_public_comment($view=null, $artefact=null) {
        if (!empty($artefact)) {
            $where = 'c.onartefact = ?';
            $values = array($artefact);
        }
        else {
            $where = 'c.onview = ?';
            $values = array($view);
        }
        $newest = get_records_sql_array('
            SELECT a.id, a.ctime
            FROM {artefact} a INNER JOIN {artefact_comment_comment} c ON a.id = c.artefact
666
            WHERE c.private = 0 AND c.hidden = 0 AND ' . $where . '
667 668 669 670 671
            ORDER BY a.ctime DESC', $values, 0, 1
        );
        return $newest[0];
    }

672 673 674
    /**
     * Fetching the comments for an artefact to display on a view
     *
675
     * @param   ArtefactType  $artfact  The artefact to display comments for
676 677 678
     * @param   object  $view     The view on which the artefact appears
     * @param   int     $blockid  The id of the block instance that connects the artefact to the view
     * @param   bool    $html     Whether to return the information rendered as html or not
679
     * @param   bool    $editing  Whether we are view edit mode or not
680 681 682 683
     *
     * @return  array   $commentcount, $comments   The count of comments and either the comments
     *                                             or the html to render them.
     */
684
    public function get_artefact_comments_for_view(ArtefactType $artefact, $view, $blockid, $html = true, $editing = false) {
685 686
        global $USER;

687
        if (!is_object($artefact) || !is_object($view)) {
688 689 690 691 692 693 694 695 696 697 698
            throw new MaharaException('we do not have the right information to display the comments');
        }

        $commentoptions = ArtefactTypeComment::get_comment_options();
        $commentoptions->limit = 0;
        $commentoptions->view = $view;
        $commentoptions->artefact = $artefact;
        $commentoptions->onview = true;
        $comments = ArtefactTypeComment::get_comments($commentoptions);
        $commentcount = isset($comments->count) ? $comments->count : 0;

699 700 701 702 703
        // If there are no comments, and comments are not allowed, don't display anything.
        if ($commentcount == 0 && !$artefact->get('allowcomments')) {
            return array(0, '');
        }

704 705
        $artefacttitle = $artefact->title;

706 707 708 709
        $artefacturl = get_config('wwwroot') . 'artefact/artefact.php?view=' . $view->get('id') . '&artefact=' . $artefact->get('id');
        if ($html) {
            $smarty = smarty_core();
            $smarty->assign('artefacturl', $artefacturl);
710
            $smarty->assign('artefacttitle', $artefacttitle);
711 712 713
            $smarty->assign('blockid', $blockid);
            $smarty->assign('commentcount', $commentcount);
            $smarty->assign('comments', $comments);
714
            $smarty->assign('editing', $editing);
715
            $smarty->assign('allowcomments', $artefact->get('allowcomments'));
716
            $smarty->assign('allowcommentsadd', ($artefact->get('allowcomments') && ( $USER->is_logged_in() || (!$USER->is_logged_in() && get_config('anonymouscomments')))));
717 718 719 720 721 722 723 724
            $render = $smarty->fetch('artefact/artefactcommentsview.tpl');
            return array($commentcount, $render);
        }
        else {
            return array($commentcount, $comments);
        }
    }

725 726
    public static function deleted_messages() {
        return array(
727 728 729
            'author' => 'commentremovedbyauthor',
            'owner'  => 'commentremovedbyowner',
            'admin'  => 'commentremovedbyadmin',
Richard Mansfield's avatar
Richard Mansfield committed
730
        );
731 732
    }

733
    public static function build_html(&$data, $onview) {
734
        global $USER, $THEME;
735

736
        $candelete = $data->canedit || $USER->get('admin');
737 738 739 740
        $deletedmessage = array();
        foreach (self::deleted_messages() as $k => $v) {
            $deletedmessage[$k] = get_string($v, 'artefact.comment');
        }
741
        $authors = array();
742 743
        $lastcomment = self::last_public_comment($data->view, $data->artefact);
        $editableafter = time() - 60 * get_config_plugin('artefact', 'comment', 'commenteditabletime');
Richard Mansfield's avatar
Richard Mansfield committed
744
        foreach ($data->data as &$item) {
745

746
            $item->ts = strtotime($item->ctime);
747 748
            $timelapse = format_timelapse($item->ts);
            $item->date = ($timelapse) ? $timelapse : format_date($item->ts, 'strftimedatetime');
749
            if ($item->ts < strtotime($item->lastcontentupdate)) {
750 751
                $timelapseupdated = format_timelapse(strtotime($item->lastcontentupdate));
                $item->updated = ($timelapseupdated) ? $timelapseupdated : format_date(strtotime($item->lastcontentupdate), 'strftimedatetime');
752
            }
753
            $item->isauthor = $item->author && $item->author == $USER->get('id');
754
            if (!empty($item->attachments)) {
Pat Kira's avatar
Pat Kira committed
755 756 757

                $item->filescount = count($item->attachments);

Richard Mansfield's avatar
Richard Mansfield committed
758
                if ($data->isowner) {
759 760
                    $item->attachmessage = get_string(
                        'feedbackattachmessage',
761 762
                        'artefact.comment',
                        get_string('feedbackattachdirname', 'artefact.comment')
763 764 765 766 767 768
                    );
                }
                foreach ($item->attachments as &$a) {
                    $a->attachid    = $a->attachment;
                    $a->attachtitle = $a->title;
                    $a->attachsize  = display_size($a->size);
Richard Mansfield's avatar
Richard Mansfield committed
769 770
                }
            }
771
            if ($item->private) {
772
                $item->pubmessage = get_string('thiscommentisprivate', 'artefact.comment');
773
            }
774

775 776 777
            if (isset($data->showcomment) && $data->showcomment == $item->id) {
                $item->highlight = 1;
            }
778
            $is_export_preview = param_integer('export',0);
Richard Mansfield's avatar
Richard Mansfield committed
779 780 781
            if ($item->deletedby) {
                $item->deletedmessage = $deletedmessage[$item->deletedby];
            }
782
            else if (($candelete || $item->isauthor) && !$is_export_preview) {
Richard Mansfield's avatar
Richard Mansfield committed
783 784
                $item->deleteform = pieform(self::delete_comment_form($item->id));
            }
785 786

            // Comment authors can edit recent comments if they're private or if no one has replied yet.
787
            if (!$item->deletedby && $item->isauthor && !$is_export_preview
788 789 790 791 792 793 794 795
                && ($item->private || $item->id == $lastcomment->id) && $item->ts > $editableafter) {
                $item->canedit = 1;
            }

            // Form to make private comment public, or request that a
            // private comment be made public
            if (!$item->deletedby && $item->private && $item->author && $data->owner
                && ($item->isauthor || $data->isowner)) {
796
                if ((empty($item->requestpublic) && $data->isowner)
797 798
                    || $item->isauthor && $item->requestpublic == 'owner'
                    || $data->isowner && $item->requestpublic == 'author') {
799 800 801
                    if (!$is_export_preview) {
                        $item->makepublicform = pieform(self::make_public_form($item->id));
                    }
802 803 804 805 806 807
                }
                else if ($item->isauthor && $item->requestpublic == 'author'
                         || $data->isowner && $item->requestpublic == 'owner') {
                    $item->makepublicrequested = 1;
                }
            }
808
            else if (!$item->deletedby && $item->private && !$item->author
809
                && $data->owner && $data->isowner && $item->requestpublic == 'author' && !$is_export_preview) {
810 811
                $item->makepublicform = pieform(self::make_public_form($item->id));
            }
812 813 814 815 816 817 818
            else if (!$item->deletedby && $item->private && !$data->owner
                && $item->group && $item->requestpublic == 'author') {
                // no owner as comment is on a group view / artefact
                if ($item->isauthor) {
                    $item->makepublicrequested = 1;
                }
                else {
819
                    if (($data->artefact && $data->canedit) || ($data->view && $data->canedit) && !$is_export_preview) {
820 821 822 823 824 825 826
                        $item->makepublicform = pieform(self::make_public_form($item->id));
                    }
                    else {
                        $item->makepublicrequested = 1;
                    }
                }
            }
827

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
            if ($item->author) {
                if (isset($authors[$item->author])) {
                    $item->author = $authors[$item->author];
                }
                else {
                    $item->author = $authors[$item->author] = (object) array(
                        'id'            => $item->author,
                        'username'      => $item->username,
                        'firstname'     => $item->firstname,
                        'lastname'      => $item->lastname,
                        'preferredname' => $item->preferredname,
                        'email'         => $item->email,
                        'staff'         => $item->staff,
                        'admin'         => $item->admin,
                        'deleted'       => $item->deleted,
                        'profileicon'   => $item->profileicon,
844
                        'profileurl'    => profile_url($item->author),
845 846 847
                    );
                }
            }
848

849
            if (get_config_plugin('artefact', 'comment', 'commentratings') and $item->rating) {
850 851 852 853
                $item->ratingdata = (object) array(
                    'value' => valid_rating($item->rating),
                    'min_rating' => MIN_RATING,
                    'max_rating' => MAX_RATING,
854
                    'export' => $data->export,
855
                );
856
            }
Richard Mansfield's avatar
Richard Mansfield committed
857
        }
858

Richard Mansfield's avatar
Richard Mansfield committed
859
        $extradata = array('view' => $data->view);
860 861
        $data->jsonscript = 'artefact/comment/comments.json.php';

Richard Mansfield's avatar
Richard Mansfield committed
862
        if (!empty($data->artefact)) {
863
            $data->baseurl = get_config('wwwroot') . 'artefact/artefact.php?view=' . $data->view . '&artefact=' . $data->artefact;
Richard Mansfield's avatar
Richard Mansfield committed
864 865 866 867 868
            $extradata['artefact'] = $data->artefact;
        }
        else {
            $data->baseurl = get_config('wwwroot') . 'view/view.php?id=' . $data->view;
        }
869

Richard Mansfield's avatar
Richard Mansfield committed
870
        $smarty = smarty_core();
871
        $smarty->assign('data', $data->data);
Richard Mansfield's avatar
Richard Mansfield committed
872
        $smarty->assign('canedit', $data->canedit);
873
        $smarty->assign('position', $data->position);
874
        $smarty->assign('viewid', $data->view);
Richard Mansfield's avatar
Richard Mansfield committed
875
        $smarty->assign('baseurl', $data->baseurl);
876
        $smarty->assign('onview', $onview);
877 878 879 880
        $icon = get_config_plugin('artefact', 'comment', 'ratingicon');
        $smarty->assign('star', $icon ? $icon : 'star');
        $colour = get_config_plugin('artefact', 'comment', 'ratingcolour');
        $smarty->assign('colour', $colour ? $colour : '#DBB80E');
881

882
        $data->tablerows = $smarty->fetch('artefact:comment:commentlist.tpl');
Pat Kira's avatar
Pat Kira committed
883

Richard Mansfield's avatar
Richard Mansfield committed
884 885 886 887 888
        $pagination = build_pagination(array(
            'id' => 'feedback_pagination',
            'class' => 'center',
            'url' => $data->baseurl,
            'jsonscript' => $data->jsonscript,
889
            'datatable' => 'feedbacktable',
Richard Mansfield's avatar
Richard Mansfield committed
890 891 892
            'count' => $data->count,
            'limit' => $data->limit,
            'offset' => $data->offset,
893
            'forceoffset' => isset($data->forceoffset) ? $data->forceoffset : null,
894 895
            'resultcounttextsingular' => get_string('comment', 'artefact.comment'),
            'resultcounttextplural' => get_string('comments', 'artefact.comment'),
Richard Mansfield's avatar
Richard Mansfield committed
896 897 898 899 900 901
            'extradata' => $extradata,
        ));
        $data->pagination = $pagination['html'];
        $data->pagination_js = $pagination['javascript'];
    }

902
    public function render_self($options) {
Richard Mansfield's avatar
Richard Mansfield committed
903 904 905
        return clean_html($this->get('description'));
    }

906
    public static function add_comment_form($defaultprivate=false, $moderate=false) {
907 908 909 910 911 912 913 914 915 916
        global $USER;
        $form = array(
            'name'            => 'add_feedback_form',
            'method'          => 'post',
            'plugintype'      => 'artefact',
            'pluginname'      => 'comment',
            'jsform'          => true,
            'autofocus'       => false,
            'elements'        => array(),
            'jssuccesscallback' => 'addFeedbackSuccess',
917
            'jserrorcallback'   => 'addFeedbackError',
918 919
        );
        if (!$USER->is_logged_in()) {
920 921
            $form['spam'] = array(
                'secret'       => get_config('formsecret'),
922
                'mintime'      => 1,
Aaron Wells's avatar
Aaron Wells committed
923 924 925
                // Not hashing the "ispublic" element, so that we can show/hide it with JS when
                // doing threaded comments.
                'hash'         => array('authorname', 'message', 'message', 'submit'),
926
            );
927 928 929 930 931 932 933 934 935 936
            $form['elements']['authorname'] = array(
                'type'  => 'text',
                'title' => get_string('name'),
                'rules' => array(
                    'required' => true,
                ),
            );
        }
        $form['elements']['message'] = array(
            'type'  => 'wysiwyg',
Pramith Dayananda's avatar
Pramith Dayananda committed
937
            'title' => get_string('Comment', 'artefact.comment'),
938
            'class' => ($USER->is_logged_in() ? 'hide-label' : ''),
939 940
            'rows'  => 5,
            'cols'  => 80,
941
            'rules' => array('maxlength' => 8192),
942
        );
943 944
        if (get_config_plugin('artefact', 'comment', 'commentratings')) {
            $form['elements']['rating'] = array(
945
                'type'  => 'ratings',
946 947 948
                'title' => get_string('rating', 'artefact.comment'),
            );
        }
949
        $form['elements']['ispublic'] = array(
950
            'type'  => 'switchbox',
951
            'title' => get_string('makecommentpublic', 'artefact.comment'),
952
            'defaultvalue' => !$defaultprivate,
953
        );
954 955 956 957
        if (get_config('licensemetadata')) {
            $form['elements']['license'] = license_form_el_basic(null);
            $form['elements']['licensing_advanced'] = license_form_el_advanced(null);
        }
958
        if ($moderate) {
959 960 961 962 963 964
            $form['elements']['ispublic']['description'] = get_string('approvalrequired', 'artefact.comment');
            $form['elements']['moderate'] = array(
                'type'  => 'hidden',
                'value' => true,
            );
        }
965
        if ($USER->is_logged_in()) {
966 967 968 969
            $form['elements']['attachments'] = array(
                'type'         => 'files',
                'title'        => get_string('attachfile', 'artefact.comment'),
                'defaultvalue' => array(),
970
                'maxfilesize'  => get_max_upload_size(false),
971 972 973 974
            );
        }
        $form['elements']['submit'] = array(
            'type'  => 'submitcancel',
975
            'class' => 'btn-default',
976
            'value' => array(get_string('Comment', 'artefact.comment'), get_string('cancel')),
977
        );
Aaron Wells's avatar
Aaron Wells committed
978 979 980 981 982 983 984 985 986 987 988 989 990
        // This is a placeholder where we can display the parent comment's text
        // And also the strings we display when we are forcing a reply to be public or private
        $snippet = smarty_core();
        $form['elements']['replytoview'] = array(
            'type' => 'html',
            'value' => $snippet->fetch('artefact:comment:replyplaceholder.tpl')
        );
        // This is a placeholder for the parent comment's ID. It'll be populated by Javascript if needed.
        $form['elements']['replyto'] = array(
            'type' => 'hidden',
            'dynamic' => 'true',
            'value' => null
        );
991 992
        return $form;
    }
Richard Mansfield's avatar
Richard Mansfield committed
993

994 995 996
    public static function make_public_form($id) {
        return array(
            'name'            => 'make_public',
997 998
            'renderer'        => 'div',
            'class'           => 'form-as-button',
999 1000 1001
            'elements'        => array(
                'comment'  => array('type' => 'hidden', 'value' => $id),
                'submit'   => array(
1002 1003
                    'type'  => 'button',
                    'usebuttontag' => true,
1004
                    'class' => 'btn-link btn-xs',
1005
                    'name'  => 'make_public_submit',
1006
                    'value' => '<span class="icon icon-lock text-default left" role="presentation" aria-hidden="true"></span>' . get_string('makecommentpublic', 'artefact.comment'),
1007 1008 1009 1010 1011
                ),
            ),
        );
    }

Richard Mansfield's avatar
Richard Mansfield committed
1012
    public static function delete_comment_form($id) {
1013
        global $THEME;
Richard Mansfield's avatar
Richard Mansfield committed
1014
        return array(
1015 1016
            'name'     => 'delete_comment' . $id,
            'successcallback' => 'delete_comment_submit',
1017
            'renderer' => 'div',
Pat Kira's avatar
Pat Kira committed
1018
            'class' => 'form-as-button pull-left delete-comment btn-group-item',
Richard Mansfield's avatar
Richard Mansfield committed
1019 1020 1021
            'elements' => array(
                'comment' => array('type' => 'hidden', 'value' => $id),
                'submit'  => array(
1022 1023
                    'type'  => 'button',
                    'usebuttontag' => true,
1024
                    'class' => 'btn-default btn-sm',
1025
                    'value' => '<span class="icon icon-trash icon-lg text-danger" role="presentation" aria-hidden="true"></span> <span class="sr-only">' . get_string('delete') . '</span>',
1026
                    'confirm' => get_string('reallydeletethiscomment', 'artefact.comment'),
1027
                    'name'  => 'delete_comment_submit',
Richard Mansfield's avatar
Richard Mansfield committed
1028 1029 1030 1031
                ),
            ),
        );
    }
1032 1033 1034 1035

    public function exportable() {
        return empty($this->deletedby);
    }
1036

1037
    public function get_view_url($viewid, $showcomment=true, $full=true) {
1038
        if ($artefact = $this->get('onartefact')) {
1039
            $url = 'artefact/artefact.php?view=' . $viewid . '&artefact=' . $artefact;
1040 1041
        }
        else {
1042
            $url = 'view/view.php?id=' . $viewid;
1043 1044 1045 1046
        }
        if ($showcomment) {
            $url .= '&showcomment=' . $this->get('id');
        }