lib.php 80.6 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
class PluginArtefactComment extends PluginArtefact {

36 37 38 39
    public static function is_active() {
        return get_field('artefact_installed', 'active', 'name', 'comment');
    }

Richard Mansfield's avatar
Richard Mansfield committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    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();
    }

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

74 75 76 77
    public static function can_be_disabled() {
        return false;
    }

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

            set_config_plugin('artefact', 'comment', 'maxindent', '5');
Richard Mansfield's avatar
Richard Mansfield committed
86 87
        }
    }
Richard Mansfield's avatar
Richard Mansfield committed
88 89 90 91 92 93

    public static function view_export_extra_artefacts($viewids) {
        $artefacts = array();
        if (!$artefacts = get_column_sql("
            SELECT artefact
            FROM {artefact_comment_comment}
94
            WHERE deletedby IS NULL AND hidden=0 AND onview IN (" . join(',', array_map('intval', $viewids)) . ')', array())) {
Richard Mansfield's avatar
Richard Mansfield committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
            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}
110
            WHERE deletedby IS NULL AND hidden=0 AND onartefact IN (" . join(',', $artefactids) . ')', array())) {
Richard Mansfield's avatar
Richard Mansfield committed
111 112 113 114 115 116 117 118 119 120
            return array();
        }
        if ($attachments = get_column_sql('
            SELECT attachment
            FROM {artefact_attachment}
            WHERE artefact IN (' . join(',', $artefacts). ')')) {
            $artefacts = array_merge($artefacts, $attachments);
        }
        return $artefacts;
    }
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

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

137 138 139 140 141 142 143 144 145 146 147 148
    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',
149
                    'title' => get_string('addcomment', 'artefact.comment'),
150
                    'plugin' => 'comment',
151
                    'active' => get_field('blocktype_installed', 'active', 'name', 'comment', 'artefactplugin', 'comment'),
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
                    '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;
176
    }
Richard Mansfield's avatar
Richard Mansfield committed
177 178 179 180 181 182 183 184
}

class ArtefactTypeComment extends ArtefactType {

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

    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;
                }
            }
        }
    }

203 204 205 206
    public static function is_allowed_in_progressbar() {
        return false;
    }

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

    /**
     * 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
224 225 226 227 228 229 230 231 232 233 234 235
    public function commit() {
        if (empty($this->dirty)) {
            return;
        }

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

        db_begin();

        parent::commit();

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

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

257 258
        if ($this->get('onview')) {
            set_field('view', 'mtime', db_format_timestamp(time()), 'id', $this->get('onview'));
259
        }
260 261 262 263
        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
264 265 266 267 268 269 270 271 272
        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
273 274
        // global $THEME;
        // return false;
Richard Mansfield's avatar
Richard Mansfield committed
275 276 277 278 279 280 281 282
    }

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

288
    public static function bulk_delete($artefactids, $log=false) {
289 290 291 292
        if (empty($artefactids)) {
            return;
        }

293
        $idstr = join(',', array_map('intval', $artefactids));
294 295 296

        db_begin();
        delete_records_select('artefact_comment_comment', 'artefact IN (' . $idstr . ')');
297
        delete_records_select('artefact_file_embedded', 'resourcetype = ? AND resourceid IN (' . $idstr . ')', array('comment'));
298 299 300 301 302 303 304 305 306
        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);
    }

307 308 309 310 311 312
    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
313 314
    public static function get_links($id) {
        return array(
315
            '_default' => get_config('wwwroot') . 'artefact/comment/view.php?id=' . $id,
Richard Mansfield's avatar
Richard Mansfield committed
316 317 318 319 320 321 322 323 324 325 326
        );
    }

    public function can_have_attachments() {
        return true;
    }

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

327
    /**
328 329 330
     * 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.
331
     *
332 333 334 335 336 337 338 339 340 341 342
     * 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
343
     * string $sort            Optional - the sort order of the comments. Valid options are 'earliest' and 'latest'.
344
     * @return object $options Default comments data object
345
     */
346 347 348 349 350 351 352 353
    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;
354
        $options->onview = false;
355 356
        $sortorder = get_user_institution_comment_sort_order();
        $options->sort = (!empty($sortorder)) ? $sortorder : 'earliest';
Aaron Wells's avatar
Aaron Wells committed
357
        $options->threaded = null;
358 359 360 361 362 363 364 365 366 367 368
        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) {
369
        global $USER;
Aaron Wells's avatar
Aaron Wells committed
370
        $allowedoptions = self::get_comment_options();
371 372
        // set the object's key/val pairs as variables
        foreach ($options as $key => $option) {
Aaron Wells's avatar
Aaron Wells committed
373
            if (array_key_exists($key, $allowedoptions));
374 375
            $$key = $option;
        }
376 377 378 379
        $userid = $USER->get('id');
        $viewid = $view->get('id');
        if (!empty($artefact)) {
            $canedit = $USER->can_edit_artefact($artefact);
380 381
            $owner = $artefact->get('owner');
            $isowner = $userid && $userid == $owner;
382 383 384
            $artefactid = $artefact->get('id');
        }
        else {
385 386 387 388 389 390 391 392 393 394 395
            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;
            }
396 397
            $artefactid = null;
        }
398

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

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

421
        $where = 'c.hidden = 0';
422
        if (!empty($artefactid)) {
423
            $where .= ' AND c.onartefact = ' . (int)$artefactid;
424 425
        }
        else {
426
            $where .= ' AND c.onview = ' . (int)$viewid;
427 428
        }
        if (!$canedit) {
Aaron Wells's avatar
Aaron Wells committed
429 430 431 432 433 434 435
            $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 .= ')';
436 437 438 439
        }

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

448
        if ($result->count > 0) {
Aaron Wells's avatar
Aaron Wells committed
449 450 451 452 453 454

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

458 459 460
            // If pagination is in use, see if we want to get a page with particular comment
            if ($limit) {
                if ($showcomment == 'last') {
461
                    // If we have limit (pagination is used) ignore $offset and just get the last page of comments.
462 463 464 465 466
                    $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
467
                    // Fetch everything and figure out which page $showcomment is in.
468 469
                    // This will get ugly if there are 1000s of comments
                    $ids = get_column_sql('
Aaron Wells's avatar
Aaron Wells committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
                            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) {
485
                        // Add 1 because array index starts from 0 and therefore key value is offset by 1.
Aaron Wells's avatar
Aaron Wells committed
486
                        $rank = $found + 1;
487 488 489
                        $result->forceoffset = $offset = ((ceil($rank / $limit) - 1) * $limit);
                        $result->showcomment = $showcomment;
                    }
490
                }
491
            }
492

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

507
            $files = ArtefactType::attachments_from_id_list(array_keys($comments));
508

509 510 511 512 513
            if ($files) {
                safe_require('artefact', 'file');
                foreach ($files as &$file) {
                    $comments[$file->artefact]->attachments[] = $file;
                }
514 515
            }

Aaron Wells's avatar
Aaron Wells committed
516 517 518 519 520 521 522
            // 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
523
                $c->canpublicreply = (int) self::can_public_reply_to_comment($c->private, $c->deletedby);
Aaron Wells's avatar
Aaron Wells committed
524 525
                $c->canprivatereply = (int) self::can_private_reply_to_comment(
                        $c->private,
526
                        $c->deletedby,
Aaron Wells's avatar
Aaron Wells committed
527 528 529 530 531 532 533 534 535 536 537
                        $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;
            }
538 539
            $result->data = array_values($comments);
        }
540

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

553
        self::build_html($result, $onview);
554 555 556
        return $result;
    }

Aaron Wells's avatar
Aaron Wells committed
557 558 559 560
    /**
     * 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?
561
     * @param int $deletedby The id of the user who deleted the comment (or null)
Aaron Wells's avatar
Aaron Wells committed
562 563
     * @return boolean
     */
564 565
    public static function can_public_reply_to_comment($isprivate, $deletedby) {
        return !($isprivate || $deletedby);
Aaron Wells's avatar
Aaron Wells committed
566 567 568 569 570 571
    }

    /**
     * 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?
572
     * @param int $deletedby The id of the user who deleted the comment (or null)
Aaron Wells's avatar
Aaron Wells committed
573 574 575 576 577 578 579
     * @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
     */
580 581 582 583 584 585 586
    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
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
        // 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();
621
        if (array_key_exists($userid, $usercache) && !defined('BEHAT_TEST')) {
Aaron Wells's avatar
Aaron Wells committed
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
            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;
    }

637
    public static function count_comments($viewids=null, $artefactids=null) {
638 639 640 641
        if (!empty($viewids)) {
            return get_records_sql_assoc('
                SELECT c.onview, COUNT(c.artefact) AS comments
                FROM {artefact_comment_comment} c
642
                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
643 644 645
                GROUP BY c.onview',
                array()
            );
646 647 648 649 650
        }
        if (!empty($artefactids)) {
            return get_records_sql_assoc('
                SELECT c.onartefact, COUNT(c.artefact) AS comments
                FROM {artefact_comment_comment} c
651
                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
652 653 654
                GROUP BY c.onartefact',
                array()
            );
655 656 657
        }
    }

658 659 660 661 662 663 664 665 666 667 668 669
    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
670
            WHERE c.private = 0 AND c.hidden = 0 AND ' . $where . '
671 672 673 674 675
            ORDER BY a.ctime DESC', $values, 0, 1
        );
        return $newest[0];
    }

676 677 678
    /**
     * Fetching the comments for an artefact to display on a view
     *
679
     * @param   ArtefactType  $artfact  The artefact to display comments for
680 681 682
     * @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
683
     * @param   bool    $editing  Whether we are view edit mode or not
684
     * @param   bool    $versioning  Whether we are view versioning mode or not
685 686 687 688
     *
     * @return  array   $commentcount, $comments   The count of comments and either the comments
     *                                             or the html to render them.
     */
689
    public function get_artefact_comments_for_view(ArtefactType $artefact, $view, $blockid, $html = true, $editing = false, $versioning = false) {
690 691
        global $USER;

692
        if (!is_object($artefact) || !is_object($view)) {
693 694 695 696 697 698 699 700 701 702 703
            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;

704 705 706 707 708
        // If there are no comments, and comments are not allowed, don't display anything.
        if ($commentcount == 0 && !$artefact->get('allowcomments')) {
            return array(0, '');
        }

709 710
        $artefacttitle = $artefact->title;

711 712 713 714
        $artefacturl = get_config('wwwroot') . 'artefact/artefact.php?view=' . $view->get('id') . '&artefact=' . $artefact->get('id');
        if ($html) {
            $smarty = smarty_core();
            $smarty->assign('artefacturl', $artefacturl);
715
            $smarty->assign('artefacttitle', $artefacttitle);
716 717 718
            $smarty->assign('blockid', $blockid);
            $smarty->assign('commentcount', $commentcount);
            $smarty->assign('comments', $comments);
719
            $smarty->assign('editing', $editing);
720
            $smarty->assign('versioning', $versioning); // Do not show comments in versioning
721
            $smarty->assign('allowcomments', $artefact->get('allowcomments'));
722
            $smarty->assign('allowcommentsadd', ($artefact->get('allowcomments') && ( $USER->is_logged_in() || (!$USER->is_logged_in() && get_config('anonymouscomments')))));
723 724 725 726 727 728 729 730
            $render = $smarty->fetch('artefact/artefactcommentsview.tpl');
            return array($commentcount, $render);
        }
        else {
            return array($commentcount, $comments);
        }
    }

731 732
    public static function deleted_messages() {
        return array(
733 734 735
            'author' => 'commentremovedbyauthor',
            'owner'  => 'commentremovedbyowner',
            'admin'  => 'commentremovedbyadmin',
Richard Mansfield's avatar
Richard Mansfield committed
736
        );
737 738
    }

739
    public static function build_html(&$data, $onview) {
740
        global $USER, $THEME;
741

742
        $candelete = $data->canedit || $USER->get('admin');
743 744 745 746
        $deletedmessage = array();
        foreach (self::deleted_messages() as $k => $v) {
            $deletedmessage[$k] = get_string($v, 'artefact.comment');
        }
747
        $authors = array();
748 749
        $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
750
        foreach ($data->data as &$item) {
751

752
            $item->ts = strtotime($item->ctime);
753 754
            $timelapse = format_timelapse($item->ts);
            $item->date = ($timelapse) ? $timelapse : format_date($item->ts, 'strftimedatetime');
755
            if ($item->ts < strtotime($item->lastcontentupdate)) {
756 757
                $timelapseupdated = format_timelapse(strtotime($item->lastcontentupdate));
                $item->updated = ($timelapseupdated) ? $timelapseupdated : format_date(strtotime($item->lastcontentupdate), 'strftimedatetime');
758
            }
759
            $item->isauthor = $item->author && $item->author == $USER->get('id');
760
            if (!empty($item->attachments)) {
Pat Kira's avatar
Pat Kira committed
761 762 763

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

Richard Mansfield's avatar
Richard Mansfield committed
764
                if ($data->isowner) {
765 766
                    $item->attachmessage = get_string(
                        'feedbackattachmessage',
767 768
                        'artefact.comment',
                        get_string('feedbackattachdirname', 'artefact.comment')
769 770 771 772 773 774
                    );
                }
                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
775 776
                }
            }
777
            if ($item->private) {
778
                $item->pubmessage = get_string('thiscommentisprivate', 'artefact.comment');
779
            }
780

781 782 783
            if (isset($data->showcomment) && $data->showcomment == $item->id) {
                $item->highlight = 1;
            }
784
            $is_export_preview = param_integer('export',0);
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
                && ($item->private || $item->id == $lastcomment->id) && $item->ts > $editableafter) {
                $item->canedit = 1;
            }
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
            else {
                $item->canedit = 0;
            }

            if ($item->deletedby) {
                $item->deletedmessage = $deletedmessage[$item->deletedby];
            }
            else if (($candelete || $item->isauthor) && !$is_export_preview) {
                $check = get_record_sql('SELECT v.* FROM {view} v WHERE v.id = ?', array($data->view), ERROR_MULTIPLE);
                if ($check->submittedstatus == View::UNSUBMITTED ||
                    ($item->canedit && $item->id == $lastcomment->id && $item->ts > $editableafter)
                   ) {
                    $item->deleteform = pieform(self::delete_comment_form($item->id));
                }
            }
806 807 808 809 810

            // 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)) {
811
                if ((empty($item->requestpublic) && $data->isowner)
812 813
                    || $item->isauthor && $item->requestpublic == 'owner'
                    || $data->isowner && $item->requestpublic == 'author') {
814 815 816
                    if (!$is_export_preview) {
                        $item->makepublicform = pieform(self::make_public_form($item->id));
                    }
817 818 819 820 821 822
                }
                else if ($item->isauthor && $item->requestpublic == 'author'
                         || $data->isowner && $item->requestpublic == 'owner') {
                    $item->makepublicrequested = 1;
                }
            }
823
            else if (!$item->deletedby && $item->private && !$item->author
824
                && $data->owner && $data->isowner && $item->requestpublic == 'author' && !$is_export_preview) {
825 826
                $item->makepublicform = pieform(self::make_public_form($item->id));
            }
827 828 829 830 831 832 833
            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 {
834
                    if (($data->artefact && $data->canedit) || ($data->view && $data->canedit) && !$is_export_preview) {
835 836 837 838 839 840 841
                        $item->makepublicform = pieform(self::make_public_form($item->id));
                    }
                    else {
                        $item->makepublicrequested = 1;
                    }
                }
            }
842

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
            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,
859
                        'profileurl'    => profile_url($item->author),
860 861 862
                    );
                }
            }
863

864
            if (get_config_plugin('artefact', 'comment', 'commentratings') and $item->rating) {
865 866 867 868
                $item->ratingdata = (object) array(
                    'value' => valid_rating($item->rating),
                    'min_rating' => MIN_RATING,
                    'max_rating' => MAX_RATING,
869
                    'export' => $data->export,
870
                );
871
            }
Richard Mansfield's avatar
Richard Mansfield committed
872
        }
873

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

Richard Mansfield's avatar
Richard Mansfield committed
877
        if (!empty($data->artefact)) {
878
            $data->baseurl = get_config('wwwroot') . 'artefact/artefact.php?view=' . $data->view . '&artefact=' . $data->artefact;
Richard Mansfield's avatar
Richard Mansfield committed
879 880 881 882 883
            $extradata['artefact'] = $data->artefact;
        }
        else {
            $data->baseurl = get_config('wwwroot') . 'view/view.php?id=' . $data->view;
        }
884

Richard Mansfield's avatar
Richard Mansfield committed
885
        $smarty = smarty_core();
886
        $smarty->assign('data', $data->data);
Richard Mansfield's avatar
Richard Mansfield committed
887
        $smarty->assign('canedit', $data->canedit);
888
        $smarty->assign('position', $data->position);
889
        $smarty->assign('viewid', $data->view);
Richard Mansfield's avatar
Richard Mansfield committed
890
        $smarty->assign('baseurl', $data->baseurl);
891
        $smarty->assign('onview', $onview);
892 893 894 895
        $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');
896

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

Richard Mansfield's avatar
Richard Mansfield committed
899 900 901 902 903
        $pagination = build_pagination(array(
            'id' => 'feedback_pagination',
            'class' => 'center',
            'url' => $data->baseurl,
            'jsonscript' => $data->jsonscript,
904
            'datatable' => 'feedbacktable',
Richard Mansfield's avatar
Richard Mansfield committed
905 906 907
            'count' => $data->count,
            'limit' => $data->limit,
            'offset' => $data->offset,
908
            'forceoffset' => isset($data->forceoffset) ? $data->forceoffset : null,
909 910
            'resultcounttextsingular' => get_string('comment', 'artefact.comment'),
            'resultcounttextplural' => get_string('comments', 'artefact.comment'),
Richard Mansfield's avatar
Richard Mansfield committed
911 912 913 914 915 916
            'extradata' => $extradata,
        ));
        $data->pagination = $pagination['html'];
        $data->pagination_js = $pagination['javascript'];
    }

917
    public function render_self($options) {
Richard Mansfield's avatar
Richard Mansfield committed
918 919 920
        return clean_html($this->get('description'));
    }

921
    public static function add_comment_form($defaultprivate=false, $moderate=false) {
922 923 924 925 926 927 928 929 930 931
        global $USER;
        $form = array(
            'name'            => 'add_feedback_form',
            'method'          => 'post',
            'plugintype'      => 'artefact',
            'pluginname'      => 'comment',
            'jsform'          => true,
            'autofocus'       => false,
            'elements'        => array(),
            'jssuccesscallback' => 'addFeedbackSuccess',
932
            'jserrorcallback'   => 'addFeedbackError',
933 934
        );
        if (!$USER->is_logged_in()) {
935 936
            $form['spam'] = array(
                'secret'       => get_config('formsecret'),
937
                'mintime'      => 1,
Aaron Wells's avatar
Aaron Wells committed
938 939 940
                // Not hashing the "ispublic" element, so that we can show/hide it with JS when
                // doing threaded comments.
                'hash'         => array('authorname', 'message', 'message', 'submit'),
941
            );
942 943 944 945 946 947 948 949 950 951
            $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
952
            'title' => get_string('Comment', 'artefact.comment'),
953
            'class' => ($USER->is_logged_in() ? 'hide-label' : ''),
954 955
            'rows'  => 5,
            'cols'  => 80,
956
            'rules' => array('maxlength' => 1000000),
957
        );
958 959
        if (get_config_plugin('artefact', 'comment', 'commentratings')) {
            $form['elements']['rating'] = array(
960
                'type'  => 'ratings',
961 962 963
                'title' => get_string('rating', 'artefact.comment'),
            );
        }
964
        $form['elements']['ispublic'] = array(
965
            'type'  => 'switchbox',
966
            'title' => get_string('makecommentpublic', 'artefact.comment'),
967
            'defaultvalue' => !$defaultprivate,
968
        );
969 970 971 972
        if (get_config('licensemetadata')) {
            $form['elements']['license'] = license_form_el_basic(null);
            $form['elements']['licensing_advanced'] = license_form_el_advanced(null);
        }
973
        if ($moderate) {
974 975 976 977 978 979
            $form['elements']['ispublic']['description'] = get_string('approvalrequired', 'artefact.comment');
            $form['elements']['moderate'] = array(
                'type'  => 'hidden',
                'value' => true,
            );
        }
980
        if ($USER->is_logged_in()) {
981 982 983 984
            $form['elements']['attachments'] = array(
                'type'         => 'files',
                'title'        => get_string('attachfile', 'artefact.comment'),
                'defaultvalue' => array(),
985
                'maxfilesize'  => get_max_upload_size(false),
986 987 988 989
            );
        }
        $form['elements']['submit'] = array(
            'type'  => 'submitcancel',
990
            'class' => 'btn-secondary',
991
            'value' => array(get_string('Comment', 'artefact.comment'), get_string('cancel')),
992
        );
Aaron Wells's avatar
Aaron Wells committed
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        // 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
        );
1006 1007
        return $form;
    }
Richard Mansfield's avatar
Richard Mansfield committed
1008

1009 1010 1011
    public static function make_public_form($id) {
        return array(
            'name'            => 'make_public',
1012 1013
            'renderer'        => 'div',
            'class'           => 'form-as-button',
1014 1015 1016
            'elements'        => array(
                'comment'  => array('type' => 'hidden', 'value' => $id),
                'submit'   => array(