lib.php 59.2 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
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
define('MIN_RATING', 1);
define('MAX_RATING', 5);

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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();
    }

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

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

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

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

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

130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    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',
                    'title' => get_string('placefeedback', 'artefact.comment'),
                    '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;
169
    }
Richard Mansfield's avatar
Richard Mansfield committed
170
171
172
173
174
175
176
177
}

class ArtefactTypeComment extends ArtefactType {

    protected $onview;
    protected $onartefact;
    protected $private;
    protected $deletedby;
178
    protected $requestpublic;
179
    protected $rating;
180
    protected $lastcontentupdate;
Richard Mansfield's avatar
Richard Mansfield committed
181
182
183
184
185
186
187
188
189
190
191
192
193

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

194
195
196
197
    public static function is_allowed_in_progressbar() {
        return false;
    }

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214

    /**
     * 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
215
216
217
218
219
220
221
222
223
224
225
226
    public function commit() {
        if (empty($this->dirty)) {
            return;
        }

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

        db_begin();

        parent::commit();

        $data = (object)array(
227
228
229
230
231
232
            'artefact'      => $this->get('id'),
            'onview'        => $this->get('onview'),
            'onartefact'    => $this->get('onartefact'),
            'private'       => $this->get('private'),
            'deletedby'     => $this->get('deletedby'),
            'requestpublic' => $this->get('requestpublic'),
233
            'rating'        => $this->get('rating'),
Richard Mansfield's avatar
Richard Mansfield committed
234
        );
235
236
237
        if ($this->get('lastcontentupdate')) {
            $data->lastcontentupdate = db_format_timestamp($this->get('lastcontentupdate'));
        }
Richard Mansfield's avatar
Richard Mansfield committed
238
239
240
241
242
243
244
245

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

246
247
248
249
250
251
252
253
        if (!$this->get('private')) {
            if ($this->get('onview')) {
                set_field('view', 'mtime', db_format_timestamp(time()), 'id', $this->get('onview'));
            }
            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
254
255
256
257
258
259
260
261
262
263
        db_commit();
        $this->dirty = false;
    }

    public static function is_singular() {
        return false;
    }

    public static function get_icon($options=null) {
        global $THEME;
264
        return false;
Richard Mansfield's avatar
Richard Mansfield committed
265
266
267
268
269
270
271
272
    }

    public function delete() {
        if (empty($this->id)) {
            return;
        }
        db_begin();
        $this->detach();
273
        delete_records('artefact_comment_comment', 'artefact', $this->id);
Richard Mansfield's avatar
Richard Mansfield committed
274
275
276
277
        parent::delete();
        db_commit();
    }

278
279
280
281
282
    public static function bulk_delete($artefactids) {
        if (empty($artefactids)) {
            return;
        }

283
        $idstr = join(',', array_map('intval', $artefactids));
284
285
286
287
288
289
290
291
292
293
294
295

        db_begin();
        delete_records_select('artefact_comment_comment', 'artefact IN (' . $idstr . ')');
        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);
    }

296
297
298
299
300
301
    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
302
303
    public static function get_links($id) {
        return array(
304
            '_default' => get_config('wwwroot') . 'artefact/comment/view.php?id=' . $id,
Richard Mansfield's avatar
Richard Mansfield committed
305
306
307
308
309
310
311
312
313
314
315
        );
    }

    public function can_have_attachments() {
        return true;
    }

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

316
    /**
317
318
319
     * 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.
320
     *
321
322
323
324
325
326
327
328
329
330
331
     * 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
332
     * string $sort            Optional - the sort order of the comments. Valid options are 'earliest' and 'latest'.
333
     * @return object $options Default comments data object
334
     */
335
336
337
338
339
340
341
342
    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;
343
        $options->onview = false;
344
345
        $sortorder = get_user_institution_comment_sort_order();
        $options->sort = (!empty($sortorder)) ? $sortorder : 'earliest';
346
347
348
349
350
351
352
353
354
355
356
        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) {
357
        global $USER;
358
359
360
361
        // set the object's key/val pairs as variables
        foreach ($options as $key => $option) {
            $$key = $option;
        }
362
363
364
365
        $userid = $USER->get('id');
        $viewid = $view->get('id');
        if (!empty($artefact)) {
            $canedit = $USER->can_edit_artefact($artefact);
366
367
            $owner = $artefact->get('owner');
            $isowner = $userid && $userid == $owner;
368
369
370
            $artefactid = $artefact->get('id');
        }
        else {
371
            $canedit = $USER->can_moderate_view($view);
372
373
            $owner = $view->get('owner');
            $isowner = $userid && $userid == $owner;
374
375
            $artefactid = null;
        }
376
377
378
379
380
381
382

        $result = (object) array(
            'limit'    => $limit,
            'offset'   => $offset,
            'view'     => $viewid,
            'artefact' => $artefactid,
            'canedit'  => $canedit,
383
            'owner'    => $owner,
384
            'isowner'  => $isowner,
385
            'export'   => $export,
386
            'sort'     => $sort,
387
388
389
            'data'     => array(),
        );

390
        if (!empty($artefactid)) {
391
            $where = 'c.onartefact = ' . (int)$artefactid;
392
393
        }
        else {
394
            $where = 'c.onview = ' . (int)$viewid;
395
396
397
398
399
400
401
402
403
404
        }
        if (!$canedit) {
            $where .= ' AND (c.private = 0 OR a.author = ' . (int) $userid . ')';
        }

        $result->count = count_records_sql('
            SELECT COUNT(*)
            FROM {artefact} a JOIN {artefact_comment_comment} c ON a.id = c.artefact
            WHERE ' . $where);

405
        if ($result->count > 0) {
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
            // If pagination is in use, see if we want to get a page with particular comment
            if ($limit) {
                if ($showcomment == 'last') {
                    // If we have limit (pagination is used) ignore $offset and just get the last page of feedback.
                    $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.
                    // Fetch everything up to $showcomment to get its rank
                    // This will get ugly if there are 1000s of comments
                    $ids = get_column_sql('
                    SELECT a.id
                    FROM {artefact} a JOIN {artefact_comment_comment} c ON a.id = c.artefact
                    WHERE ' . $where . ' AND a.id <= ?
                    ORDER BY a.ctime', array($showcomment));
                    $last = end($ids);
                    if ($last == $showcomment) {
424
425
                        // Add 1 because array index starts from 0 and therefore key value is offset by 1.
                        $rank = key($ids) + 1;
426
427
428
                        $result->forceoffset = $offset = ((ceil($rank / $limit) - 1) * $limit);
                        $result->showcomment = $showcomment;
                    }
429
                }
430
            }
431

432
            $sortorder = (!empty($sort) && $sort == 'latest') ? 'a.ctime DESC' : 'a.ctime ASC';
433
434
            $comments = get_records_sql_assoc('
                SELECT
435
                    a.id, a.author, a.authorname, a.ctime, a.mtime, a.description, a.group,
436
                    c.private, c.deletedby, c.requestpublic, c.rating, c.lastcontentupdate,
437
                    u.username, u.firstname, u.lastname, u.preferredname, u.email, u.staff, u.admin,
438
                    u.deleted, u.profileicon, u.urlid
439
440
441
                FROM {artefact} a
                    INNER JOIN {artefact_comment_comment} c ON a.id = c.artefact
                    LEFT JOIN {usr} u ON a.author = u.id
442
                WHERE ' . $where . '
443
                ORDER BY ' . $sortorder, array(), $offset, $limit);
444

445
            $files = ArtefactType::attachments_from_id_list(array_keys($comments));
446

447
448
449
450
451
            if ($files) {
                safe_require('artefact', 'file');
                foreach ($files as &$file) {
                    $comments[$file->artefact]->attachments[] = $file;
                }
452
453
            }

454
455
            $result->data = array_values($comments);
        }
456

457
458
459
460
461
462
463
464
465
466
467
468
469
        // check to see if the feedback is to be displayed in a block instance
        // or the base of the page
        $result->position = 'base';
        $blocks = get_records_array('block_instance', 'view', $viewid);
        if (!empty($blocks)) {
            foreach ($blocks as $block) {
                if ($block->blocktype == 'comment') {
                    $result->position = 'blockinstance';
                    break;
                }
            }
        }

470
        self::build_html($result, $onview);
471
472
473
        return $result;
    }

474
    public static function count_comments($viewids=null, $artefactids=null) {
475
476
477
478
        if (!empty($viewids)) {
            return get_records_sql_assoc('
                SELECT c.onview, COUNT(c.artefact) AS comments
                FROM {artefact_comment_comment} c
479
                WHERE c.onview IN (' . join(',', array_map('intval', $viewids)) . ') AND c.deletedby IS NULL
Richard Mansfield's avatar
Richard Mansfield committed
480
481
482
                GROUP BY c.onview',
                array()
            );
483
484
485
486
487
        }
        if (!empty($artefactids)) {
            return get_records_sql_assoc('
                SELECT c.onartefact, COUNT(c.artefact) AS comments
                FROM {artefact_comment_comment} c
488
                WHERE c.onartefact IN (' . join(',', array_map('intval', $artefactids)) . ') AND c.deletedby IS NULL
Richard Mansfield's avatar
Richard Mansfield committed
489
490
491
                GROUP BY c.onartefact',
                array()
            );
492
493
494
        }
    }

495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
    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
            WHERE c.private = 0 AND ' . $where . '
            ORDER BY a.ctime DESC', $values, 0, 1
        );
        return $newest[0];
    }

513
514
515
    /**
     * Fetching the comments for an artefact to display on a view
     *
516
     * @param   ArtefactType  $artfact  The artefact to display comments for
517
518
519
     * @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
520
     * @param   bool    $editing  Whether we are view edit mode or not
521
522
523
524
     *
     * @return  array   $commentcount, $comments   The count of comments and either the comments
     *                                             or the html to render them.
     */
525
    public function get_artefact_comments_for_view(ArtefactType $artefact, $view, $blockid, $html = true, $editing = false) {
526
527
        global $USER;

528
        if (!is_object($artefact) || !is_object($view)) {
529
530
531
532
533
534
535
536
537
538
539
            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;

540
541
542
543
544
        // If there are no comments, and comments are not allowed, don't display anything.
        if ($commentcount == 0 && !$artefact->get('allowcomments')) {
            return array(0, '');
        }

545
546
547
548
549
550
551
        $artefacturl = get_config('wwwroot') . 'artefact/artefact.php?view=' . $view->get('id') . '&artefact=' . $artefact->get('id');
        if ($html) {
            $smarty = smarty_core();
            $smarty->assign('artefacturl', $artefacturl);
            $smarty->assign('blockid', $blockid);
            $smarty->assign('commentcount', $commentcount);
            $smarty->assign('comments', $comments);
552
            $smarty->assign('editing', $editing);
553
            $smarty->assign('allowcomments', $artefact->get('allowcomments'));
554
            $smarty->assign('allowcommentsadd', ($artefact->get('allowcomments') && ( $USER->is_logged_in() || (!$USER->is_logged_in() && get_config('anonymouscomments')))));
555
556
557
558
559
560
561
562
            $render = $smarty->fetch('artefact/artefactcommentsview.tpl');
            return array($commentcount, $render);
        }
        else {
            return array($commentcount, $comments);
        }
    }

563
564
    public static function deleted_messages() {
        return array(
565
566
567
            'author' => 'commentremovedbyauthor',
            'owner'  => 'commentremovedbyowner',
            'admin'  => 'commentremovedbyadmin',
Richard Mansfield's avatar
Richard Mansfield committed
568
        );
569
570
    }

571
    public static function build_html(&$data, $onview) {
572
        global $USER, $THEME;
573
        $candelete = $data->canedit || $USER->get('admin');
574
575
576
577
        $deletedmessage = array();
        foreach (self::deleted_messages() as $k => $v) {
            $deletedmessage[$k] = get_string($v, 'artefact.comment');
        }
578
        $authors = array();
579
580
        $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
581
        foreach ($data->data as &$item) {
582
583
            $item->ts = strtotime($item->ctime);
            $item->date = format_date($item->ts, 'strftimedatetime');
584
585
            if ($item->ts < strtotime($item->lastcontentupdate)) {
                $item->updated = format_date(strtotime($item->lastcontentupdate), 'strftimedatetime');
586
            }
587
            $item->isauthor = $item->author && $item->author == $USER->get('id');
588
            if (!empty($item->attachments)) {
Richard Mansfield's avatar
Richard Mansfield committed
589
                if ($data->isowner) {
590
591
                    $item->attachmessage = get_string(
                        'feedbackattachmessage',
592
593
                        'artefact.comment',
                        get_string('feedbackattachdirname', 'artefact.comment')
594
595
596
597
598
599
                    );
                }
                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
600
601
                }
            }
602
            if ($item->private) {
603
                $item->pubmessage = get_string('thiscommentisprivate', 'artefact.comment');
604
            }
605

606
607
608
            if (isset($data->showcomment) && $data->showcomment == $item->id) {
                $item->highlight = 1;
            }
609
            $is_export_preview = param_integer('export',0);
Richard Mansfield's avatar
Richard Mansfield committed
610
611
612
            if ($item->deletedby) {
                $item->deletedmessage = $deletedmessage[$item->deletedby];
            }
613
            else if (($candelete || $item->isauthor) && !$is_export_preview) {
Richard Mansfield's avatar
Richard Mansfield committed
614
615
                $item->deleteform = pieform(self::delete_comment_form($item->id));
            }
616
617

            // Comment authors can edit recent comments if they're private or if no one has replied yet.
618
            if (!$item->deletedby && $item->isauthor && !$is_export_preview
619
620
621
622
623
624
625
626
                && ($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)) {
627
                if ((empty($item->requestpublic) && $data->isowner)
628
629
                    || $item->isauthor && $item->requestpublic == 'owner'
                    || $data->isowner && $item->requestpublic == 'author') {
630
631
632
                    if (!$is_export_preview) {
                        $item->makepublicform = pieform(self::make_public_form($item->id));
                    }
633
634
635
636
637
638
                }
                else if ($item->isauthor && $item->requestpublic == 'author'
                         || $data->isowner && $item->requestpublic == 'owner') {
                    $item->makepublicrequested = 1;
                }
            }
639
            else if (!$item->deletedby && $item->private && !$item->author
640
                && $data->owner && $data->isowner && $item->requestpublic == 'author' && !$is_export_preview) {
641
642
                $item->makepublicform = pieform(self::make_public_form($item->id));
            }
643
644
645
646
647
648
649
            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 {
650
                    if (($data->artefact && $data->canedit) || ($data->view && $data->canedit) && !$is_export_preview) {
651
652
653
654
655
656
657
                        $item->makepublicform = pieform(self::make_public_form($item->id));
                    }
                    else {
                        $item->makepublicrequested = 1;
                    }
                }
            }
658

659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
            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,
675
                        'profileurl'    => profile_url($item->author),
676
677
678
                    );
                }
            }
679

680
            if (get_config_plugin('artefact', 'comment', 'commentratings') and $item->rating) {
681
682
683
684
                $item->ratingdata = (object) array(
                    'value' => valid_rating($item->rating),
                    'min_rating' => MIN_RATING,
                    'max_rating' => MAX_RATING,
685
                    'export' => $data->export,
686
                );
687
            }
Richard Mansfield's avatar
Richard Mansfield committed
688
        }
689

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

Richard Mansfield's avatar
Richard Mansfield committed
693
        if (!empty($data->artefact)) {
694
            $data->baseurl = get_config('wwwroot') . 'artefact/artefact.php?view=' . $data->view . '&artefact=' . $data->artefact;
Richard Mansfield's avatar
Richard Mansfield committed
695
696
697
698
699
            $extradata['artefact'] = $data->artefact;
        }
        else {
            $data->baseurl = get_config('wwwroot') . 'view/view.php?id=' . $data->view;
        }
700

Richard Mansfield's avatar
Richard Mansfield committed
701
702
703
        $smarty = smarty_core();
        $smarty->assign_by_ref('data', $data->data);
        $smarty->assign('canedit', $data->canedit);
704
        $smarty->assign('viewid', $data->view);
705
        $smarty->assign('position', $data->position);
Richard Mansfield's avatar
Richard Mansfield committed
706
        $smarty->assign('baseurl', $data->baseurl);
707
        $smarty->assign('onview', $onview);
708
        $data->tablerows = $smarty->fetch('artefact:comment:commentlist.tpl');
Richard Mansfield's avatar
Richard Mansfield committed
709
710
711
712
713
714
715
716
717
        $pagination = build_pagination(array(
            'id' => 'feedback_pagination',
            'class' => 'center',
            'url' => $data->baseurl,
            'jsonscript' => $data->jsonscript,
            'datatable' => 'feedbacktable',
            'count' => $data->count,
            'limit' => $data->limit,
            'offset' => $data->offset,
718
            'forceoffset' => isset($data->forceoffset) ? $data->forceoffset : null,
719
720
            'resultcounttextsingular' => get_string('comment', 'artefact.comment'),
            'resultcounttextplural' => get_string('comments', 'artefact.comment'),
Richard Mansfield's avatar
Richard Mansfield committed
721
722
723
724
725
726
            'extradata' => $extradata,
        ));
        $data->pagination = $pagination['html'];
        $data->pagination_js = $pagination['javascript'];
    }

Richard Mansfield's avatar
Richard Mansfield committed
727
728
729
730
    public function render_self() {
        return clean_html($this->get('description'));
    }

731
    public static function add_comment_form($defaultprivate=false, $moderate=false) {
732
733
734
735
        global $USER;
        $form = array(
            'name'            => 'add_feedback_form',
            'method'          => 'post',
736
            //'class'           => 'js-hidden',
737
738
739
740
741
742
            'plugintype'      => 'artefact',
            'pluginname'      => 'comment',
            'jsform'          => true,
            'autofocus'       => false,
            'elements'        => array(),
            'jssuccesscallback' => 'addFeedbackSuccess',
743
            'jserrorcallback'   => 'addFeedbackError',
744
745
        );
        if (!$USER->is_logged_in()) {
746
747
            $form['spam'] = array(
                'secret'       => get_config('formsecret'),
748
                'mintime'      => 1,
749
750
                'hash'         => array('authorname', 'message', 'ispublic', 'message', 'submit'),
            );
751
752
753
754
755
756
757
758
759
760
761
762
763
            $form['elements']['authorname'] = array(
                'type'  => 'text',
                'title' => get_string('name'),
                'rules' => array(
                    'required' => true,
                ),
            );
        }
        $form['elements']['message'] = array(
            'type'  => 'wysiwyg',
            'title' => get_string('message'),
            'rows'  => 5,
            'cols'  => 80,
764
            'rules' => array('maxlength' => 8192),
765
        );
766
767
        if (get_config_plugin('artefact', 'comment', 'commentratings')) {
            $form['elements']['rating'] = array(
768
                'type'  => 'radio',
769
                'title' => get_string('rating', 'artefact.comment'),
770
771
                'options' => array('1' => '', '2' => '', '3' => '', '4' => '', '5' => ''),
                'class' => 'star',
772
773
            );
        }
774
        $form['elements']['ispublic'] = array(
775
            'type'  => 'switchbox',
776
            'title' => get_string('makepublic', 'artefact.comment'),
777
            'defaultvalue' => !$defaultprivate,
778
        );
779
780
781
782
        if (get_config('licensemetadata')) {
            $form['elements']['license'] = license_form_el_basic(null);
            $form['elements']['licensing_advanced'] = license_form_el_advanced(null);
        }
783
        if ($moderate) {
784
785
786
787
788
789
            $form['elements']['ispublic']['description'] = get_string('approvalrequired', 'artefact.comment');
            $form['elements']['moderate'] = array(
                'type'  => 'hidden',
                'value' => true,
            );
        }
790
        if ($USER->is_logged_in()) {
791
792
793
794
            $form['elements']['attachments'] = array(
                'type'         => 'files',
                'title'        => get_string('attachfile', 'artefact.comment'),
                'defaultvalue' => array(),
795
                'maxfilesize'  => get_max_upload_size(false),
796
797
798
799
            );
        }
        $form['elements']['submit'] = array(
            'type'  => 'submitcancel',
800
801
            'class' => 'btn btn-default',
            'value' => array(get_string('Comment', 'artefact.comment'), get_string('cancel')),
802
803
804
        );
        return $form;
    }
Richard Mansfield's avatar
Richard Mansfield committed
805

806
807
808
    public static function make_public_form($id) {
        return array(
            'name'            => 'make_public',
809
810
            'renderer'        => 'div',
            'class'           => 'form-as-button',
811
812
813
            'elements'        => array(
                'comment'  => array('type' => 'hidden', 'value' => $id),
                'submit'   => array(
814
815
816
                    'type'  => 'button',
                    'usebuttontag' => true,
                    'class' => 'btn btn-link btn-xs',
817
                    'name'  => 'make_public_submit',
818
                    'value' => '<span class="fa fa-lock text-default prs"></span>' . get_string('makepublic', 'artefact.comment'),
819
820
821
822
823
                ),
            ),
        );
    }

Richard Mansfield's avatar
Richard Mansfield committed
824
    public static function delete_comment_form($id) {
825
        global $THEME;
Richard Mansfield's avatar
Richard Mansfield committed
826
827
        return array(
            'name'     => 'delete_comment',
828
829
            'renderer' => 'div',
            'class' => 'form-as-button',
Richard Mansfield's avatar
Richard Mansfield committed
830
831
832
            'elements' => array(
                'comment' => array('type' => 'hidden', 'value' => $id),
                'submit'  => array(
833
834
835
836
                    'type'  => 'button',
                    'usebuttontag' => true,
                    'class' => 'btn btn-link btn-sm',
                    'value' => '<span class="fa fa-trash fa-lg text-danger"></span> <span class="sr-only">' . get_string('delete') . '</span>',
837
                    'confirm' => get_string('reallydeletethiscomment', 'artefact.comment'),
838
                    'name'  => 'delete_comment_submit',
Richard Mansfield's avatar
Richard Mansfield committed
839
840
841
842
                ),
            ),
        );
    }
843
844
845
846

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

848
    public function get_view_url($viewid, $showcomment=true, $full=true) {
849
        if ($artefact = $this->get('onartefact')) {
850
            $url = 'artefact/artefact.php?view=' . $viewid . '&artefact=' . $artefact;
851
852
        }
        else {
853
            $url = 'view/view.php?id=' . $viewid;
854
855
856
857
        }
        if ($showcomment) {
            $url .= '&showcomment=' . $this->get('id');
        }
858
859
860
        if ($full) {
            $url = get_config('wwwroot') . $url;
        }
861
862
        return $url;
    }
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895

    // Check whether the logged-in user can see a comment within the
    // context of a given view.  Does not check whether the user can
    // view the view.
    public function viewable_in($viewid) {
        global $USER;
        if ($this->get('deletedby')) {
            return false;
        }

        if ($USER->is_logged_in()) {
            if ($USER->can_view_artefact($this)) {
                return true;
            }
            if ($this->get('author') == $USER->get('id')) {
                return true;
            }
        }

        if ($this->get('private')) {
            return false;
        }

        if ($onview = $this->get('onview')) {
            return $onview == $viewid;
        }

        if ($onartefact = $this->get('onartefact')) {
            return artefact_in_view($onartefact, $viewid);
        }

        return false;
    }
896
897
898
899
900
901
902
903

    public static function has_config() {
        return true;
    }

    public static function get_config_options() {
        $elements =  array(
            'commentratings' => array(
904
                'type'  => 'switchbox',
905
906
907
908
909
910
911
912
                'title' => get_string('commentratings', 'artefact.comment'),
                'defaultvalue' => get_config_plugin('artefact', 'comment', 'commentratings'),
                'help'  => true,
            ),
        );
        return array(
            'name'     => 'commentconfig',
            'elements' => $elements,
913
            'renderer' => 'div'
914
915
916
        );
    }

917
    public static function save_config_options($form, $values) {
918
919
920
921
        foreach (array('commentratings') as $settingname) {
            set_config_plugin('artefact', 'comment', $settingname, $values[$settingname]);
        }
    }
922
923
924
925
926
927
928

    /**
     * Fetch all users that are currently watching the view the comment is being added to,
     * in case of comment on artefact it will be the view the artefact sits on,
     * so we can use this array to email affected parties.
     *
     * @param   int    $posterid   If set, the poster's id is ignored from resulting array
929
     * @return  array  $users      An array of user objects of the users that are watching this page or a page this artefact is on
930
     */
931
    public function get_watchlist_users($posterid = null) {
932
933
        $ontype = ($onview = $this->get('onview')) ? 'onview' : 'onartefact';
        $values = array();
934
        $sql = "SELECT DISTINCT u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email FROM {usr} u";
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
        if ($ontype == 'onview') {
            $sql .= " JOIN {usr_watchlist_view} uwv ON uwv.view = ? AND uwv.usr = u.id";
            $values[] = $this->get($ontype);
        }
        else if ($ontype == 'onartefact') {
            $sql .= " JOIN {view_artefact} va ON va.artefact = ?
                      JOIN {usr_watchlist_view} uwv ON uwv.view = va.view AND uwv.usr = u.id";
            $values[] = $this->get($ontype);
        }
        if ($posterid) {
            $sql .= " WHERE u.id != ?";
            $values[] = $posterid;
        }

        $users = get_records_sql_assoc($sql, $values);
950
951
952
953
954
955
        if ($users) {
            return $users;
        }
        else {
            return array();
        }
956
    }
957
958
}

959
960
961
962
963
964
965
966
/* To make private comments public, both the author and the owner must agree. */
function make_public_validate(Pieform $form, $values) {
    global $USER;
    $comment = new ArtefactTypeComment((int) $values['comment']);

    $author    = $comment->get('author');
    $owner     = $comment->get('owner');
    $requester = $USER->get('id');
967
    $group     = $comment->get('group');
968

969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    if (!$owner && !$group) {
        $form->set_error('comment', get_string('makepublicnotallowed', 'artefact.comment'));
    }
    else if (!$owner && $group) {
        if ($requester) {
            $allowed = false;
            // check to see if the requester is a group admin
            $group_admins = group_get_admin_ids($group);
            if (array_search($requester,$group_admins) === false) {
                $form->set_error('comment', get_string('makepublicnotallowed', 'artefact.comment'));
            }
        }
        else {
            $form->set_error('comment', get_string('makepublicnotallowed', 'artefact.comment'));
        }
    }
    else if (!$owner || !$requester || ($requester != $owner && $requester != $author)) {
986
987
988
989
990
991
992
993
994
        $form->set_error('comment', get_string('makepublicnotallowed', 'artefact.comment'));
    }
}

function make_public_submit(Pieform $form, $values) {
    global $SESSION, $USER, $view;

    $comment = new ArtefactTypeComment((int) $values['comment']);

995
996
    $relativeurl = $comment->get_view_url($view->get('id'), true, false);
    $url = get_config('wwwroot') . $relativeurl;
997
998
999

    $author    = $comment->get('author');
    $owner     = $comment->get('owner');
1000
1001
1002
1003
1004
    $groupid   = $comment->get('group');
    $group_admins = array();
    if ($groupid) {
        $group_admins = group_get_admin_ids($groupid);
    }
1005
1006
1007
1008
    $requester = $USER->get('id');

    if (($author == $owner && $requester == $owner)
        || ($requester == $owner  && $comment->get('requestpublic') == 'author')
1009
        || (array_search($requester,$group_admins) !== false && $comment->get('requestpublic') == 'author')
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
        || ($requester == $author && $comment->get('requestpublic') == 'owner')) {
        $comment->set('private', 0);
        $comment->set('requestpublic', null);
        $comment->commit();
        $SESSION->add_ok_msg(get_string('commentmadepublic', 'artefact.comment'));
        redirect($url);
    }

    $subject = 'makepublicrequestsubject';
    if ($requester == $owner) {
        $comment->set('requestpublic', 'owner');
        $message = 'makepublicrequestbyownermessage';
        $arg = display_name($owner, $author);
        $userid = $author;
        $sessionmessage = get_string('makepublicrequestsent', 'artefact.comment', display_name($author));
    }
    else if ($requester == $author) {
        $comment->set('requestpublic', 'author');
        $message = 'makepublicrequestbyauthormessage';
        $arg = display_name($author, $owner);
        $userid = $owner;
        $sessionmessage = get_string('makepublicrequestsent', 'artefact.comment', display_name($owner));
    }
1033
1034
1035
1036
1037
1038
1039
    else if (array_search($requester,$group_admins) !== false) {
        $comment->set('requestpublic', 'owner');
        $message = 'makepublicrequestbyownermessage';
        $arg = display_name($requester, $author);
        $userid = $author;
        $sessionmessage = get_string('makepublicrequestsent', 'artefact.comment', display_name($author));
    }
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
    else {
        redirect($url); // Freak out?
    }

    db_begin();
    $comment->commit();

    $data = (object) array(
        'subject'   => false,
        'message'   => false,
        'strings'   => (object) array(
            'subject' => (object) array(
                'key'     => $subject,
                'section' => 'artefact.comment',
                'args'    => array(),
            ),
            'message' => (object) array(
                'key'     => $message,
                'section' => 'artefact.comment',
                'args'    => array(hsc($arg)),
            ),
1061
1062
1063
1064
            'urltext' => (object) array(
                'key'     => 'Comment',
                'section' => 'artefact.comment',
            ),
1065
1066
        ),
        'users'     => array($userid),
1067
        'url'       => $relativeurl,
1068
1069
1070
1071
1072
1073
1074
1075
    );
    activity_occurred('maharamessage', $data);
    db_commit();

    $SESSION->add_ok_msg($sessionmessage);
    redirect($url);
}

Richard Mansfield's avatar
Richard Mansfield committed
1076
1077
function delete_comment_submit(Pieform $form, $values) {
    global $SESSION, $USER, $view;
1078
    require_once('embeddedimage.php');
Richard Mansfield's avatar
Richard Mansfield committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091

    $comment = new ArtefactTypeComment((int) $values['comment']);

    if ($USER->get('id') == $comment->get('author')) {
        $deletedby = 'author';
    }
    else if ($USER->can_edit_view($view)) {
        $deletedby = 'owner';
    }
    else if ($USER->get('admin')) {
        $deletedby = 'admin';
    }

1092
1093
    $viewid = $view->get('id');
    if ($artefact = $comment->get('onartefact')) {
1094
        $url = 'artefact/artefact.php?view=' . $viewid . '&artefact=' . $artefact;
1095
1096
    }
    else {
1097
        $url = $view->get_url(false);
1098
1099
    }

1100
1101
    db_begin();

Richard Mansfield's avatar
Richard Mansfield committed
1102
1103
1104
    $comment->set('deletedby', $deletedby);
    $comment->commit();

1105
1106
    if ($deletedby != 'author') {
        // Notify author
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
        if ($artefact) {
            $title = get_field('artefact', 'title', 'id', $artefact);
        }
        else {
            $title = get_field('view', 'title', 'id', $comment->get('onview'));
        }
        $title = hsc($title);
        $data = (object) array(
            'subject'   => false,
            'message'   => false,
            'strings'   => (object) array(
                'subject' => (object) array(
                    'key'     => 'commentdeletednotificationsubject',
                    'section' => 'artefact.comment',
                    'args'    => array($title),
                ),
                'message' => (object) array(
                    'key'     => 'commentdeletedauthornotification',
                    'section' => 'artefact.comment',
                    'args'    => array($title, html2text($comment->get('description'))),
                ),
1128
1129
1130
                'urltext' => (object) array(
                    'key'     => $artefact ? 'artefact' : 'view',
                ),
1131
1132
1133
1134
1135
            ),
            'users'     => array($comment->get('author')),
            'url'       => $url,
        );
        activity_occurred('maharamessage', $data);
1136
1137
1138
1139
    }
    if ($deletedby != 'owner' && $comment->get('owner') != $USER->get('id')) {
        // Notify owner
        $data = (object) array(
1140
1141
            'commentid' => $comment->get('id'),
            'viewid'    => $view->get('id'),
1142
1143
1144
1145
        );
        activity_occurred('feedback', $data, 'artefact', 'comment');
    }

1146
    EmbeddedImage::delete_embedded_images('comment', $comment->get('id'));
1147
1148
    db_commit();

Richard Mansfield's avatar
Richard Mansfield committed
1149
    $SESSION->add_ok_msg(get_string('commentremoved', 'artefact.comment'));
1150
    redirect(get_config('wwwroot') . $url);
Richard Mansfield's avatar
Richard Mansfield committed
1151
1152
}

1153
function add_feedback_form_validate(Pieform $form, $values) {
1154
    require_once(get_config('libroot') . 'antispam.php');
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
    if ($form->get_property('spam')) {
        $spamtrap = new_spam_trap(array(
            array(
                'type' => 'body',
                'value' => $values['message'],
            ),
        ));

        if ($form->spam_error() || $spamtrap->is_spam()) {
            $msg = get_string('formerror');
            $emailcontact = get_config('emailcontact');
            if (!empty($emailcontact)) {
                $msg .= ' ' . get_string('formerroremail', 'mahara', $emailcontact, $emailcontact);
            }
            $form->set_error('message', $msg);
        }
    }
1172
1173
1174
    if (empty($values['attachments']) && empty($values['message'])) {
        $form->set_error('message', get_string('messageempty', 'artefact.comment'));
    }
1175
1176
1177
1178
    $result = probation_validate_content($values['message']);
    if ($result !== true) {
        $form->set_error('message', get_string('newuserscantpostlinksorimages'));
    }
1179
1180
}

1181
1182
function add_feedback_form_submit(Pieform $form, $values) {
    global $view, $artefact, $USER;
1183
    require_once('embeddedimage.php');
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
    $data = (object) array(
        'title'       => get_string('Comment', 'artefact.comment'),
        'description' => $values['message'],
    );

    if ($artefact) {
        $data->onartefact  = $artefact->get('id');
        $data->owner       = $artefact->get('owner');
        $data->group       = $artefact->get('group');
        $data->institution = $artefact->get('institution');
    }
    else {
        $data->onview      = $view->get('id');
        $data->owner       = $view->get('owner');
        $data->group       = $view->get('group');
        $data->institution = $view->get('institution');
    }

1202
1203
    $owner = $data->owner;
    $author = null;
1204
    if ($author = $USER->get('id')) {
1205
        $anonymous = false;
1206
1207
1208
        $data->author = $author;
    }
    else {
1209
        $anonymous = true;
1210
1211
1212
        $data->authorname = $values['authorname'];
    }

1213
1214
1215
    if (isset($values['moderate']) && $values['ispublic'] && !$USER->can_edit_view($view)) {
        $data->private = 1;
        $data->requestpublic = 'author';
1216
        $moderated = true;
1217
1218
1219
    }
    else {
        $data->private = (int) !$values['ispublic'];
1220
        $moderated = false;
1221
    }
1222
    $private = $data->private;
1223

1224
1225
1226
1227
1228
1229
    if (get_config('licensemetadata')) {
        $data->license       = $values['license'];
        $data->licensor      = $values['licensor'];
        $data->licensorurl   = $values['licensorurl'];
    }

1230
1231
1232
1233
    if (isset($values['rating'])) {
        $data->rating = valid_rating($values['rating']);
    }

1234
    $comment = new ArtefactTypeComment(0, $data);
1235
1236
1237

    db_begin();

1238
1239
    $comment->commit();

1240
1241
1242
1243
1244
1245
1246
1247
1248
    $newdescription = EmbeddedImage::prepare_embedded_images($values['message'], 'comment', $comment->get('id'), $data->group);

    if ($newdescription !== $values['message']) {
        $updatedcomment = new stdClass();
        $updatedcomment->id = $comment->get('id');
        $updatedcomment->description = $newdescription;
        update_record('artefact', $updatedcomment, 'id');
    }

1249
1250
    $url = $comment->get_view_url($view->get('id'), true, false);
    $goto = get_config('wwwroot') . $url;