lib.php 45.3 KB
Newer Older
Richard Mansfield's avatar
Richard Mansfield committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
/**
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    mahara
 * @subpackage artefact-comment
 * @author     Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
 *
 */

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

29
require_once('activity.php');
30
require_once('license.php');
31

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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();
    }

72
73
74
75
76
77
78
79
80
81
    public static function get_activity_types() {
        return array(
            (object)array(
                'name' => 'feedback',
                'admin' => 0,
                'delay' => 0,
            )
        );
    }

82
83
84
85
    public static function can_be_disabled() {
        return false;
    }

Richard Mansfield's avatar
Richard Mansfield committed
86
87
    public static function postinst($prevversion) {
        if ($prevversion == 0) {
88
            set_config_plugin('artefact', 'comment', 'commenteditabletime', 10);
Richard Mansfield's avatar
Richard Mansfield committed
89
90
91
92
93
            foreach(ArtefactTypeComment::deleted_types() as $type) {
                insert_record('artefact_comment_deletedby', (object)array('name' => $type));
            }
        }
    }
Richard Mansfield's avatar
Richard Mansfield committed
94
95
96
97
98
99

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

    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'));
    }
Richard Mansfield's avatar
Richard Mansfield committed
142
143
144
145
146
147
148
149
}

class ArtefactTypeComment extends ArtefactType {

    protected $onview;
    protected $onartefact;
    protected $private;
    protected $deletedby;
150
    protected $requestpublic;
151
    protected $rating;
Richard Mansfield's avatar
Richard Mansfield committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176

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

    public function commit() {
        if (empty($this->dirty)) {
            return;
        }

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

        db_begin();

        parent::commit();

        $data = (object)array(
177
178
179
180
181
182
            'artefact'      => $this->get('id'),
            'onview'        => $this->get('onview'),
            'onartefact'    => $this->get('onartefact'),
            'private'       => $this->get('private'),
            'deletedby'     => $this->get('deletedby'),
            'requestpublic' => $this->get('requestpublic'),
183
            'rating'        => $this->get('rating'),
Richard Mansfield's avatar
Richard Mansfield committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
        );

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

        db_commit();
        $this->dirty = false;
    }

    public static function is_singular() {
        return false;
    }

    public static function get_icon($options=null) {
        global $THEME;
203
        return $THEME->get_url('images/comment.png', false, 'artefact/comment');
Richard Mansfield's avatar
Richard Mansfield committed
204
205
206
207
208
209
210
211
    }

    public function delete() {
        if (empty($this->id)) {
            return;
        }
        db_begin();
        $this->detach();
212
        delete_records('artefact_comment_comment', 'artefact', $this->id);
Richard Mansfield's avatar
Richard Mansfield committed
213
214
215
216
        parent::delete();
        db_commit();
    }

217
218
219
220
221
    public static function bulk_delete($artefactids) {
        if (empty($artefactids)) {
            return;
        }

222
        $idstr = join(',', array_map('intval', $artefactids));
223
224
225
226
227
228
229
230
231
232
233
234

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

235
236
237
238
239
240
    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
241
242
    public static function get_links($id) {
        return array(
243
            '_default' => get_config('wwwroot') . 'artefact/comment/view.php?id=' . $id,
Richard Mansfield's avatar
Richard Mansfield committed
244
245
246
247
248
249
250
251
252
253
254
        );
    }

    public function can_have_attachments() {
        return true;
    }

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

255
256
257
258
259
260
261
262
263
264
265
266
    /**
     * Generates data object required for displaying comments on the page.
     *
     * @param  int $limit              The number of comments to display (set to
     *                                 0 for disabling pagination and showing all comments)
     * @param  int $offset             The offset of comments used for pagination
     * @param  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.
     * @param  object $view            The view object
     * @param  object $artefact        Optional artefact object
267
     * @param  bool   $export          Determines if comments are fetched for html export purposes
268
269
     * @return object $result          Comments data object
     */
270
    public static function get_comments($limit=10, $offset=0, $showcomment, &$view, &$artefact=null, $export=false) {
271
272
273
274
275
        global $USER;
        $userid = $USER->get('id');
        $viewid = $view->get('id');
        if (!empty($artefact)) {
            $canedit = $USER->can_edit_artefact($artefact);
276
277
            $owner = $artefact->get('owner');
            $isowner = $userid && $userid == $owner;
278
279
280
            $artefactid = $artefact->get('id');
        }
        else {
281
            $canedit = $USER->can_moderate_view($view);
282
283
            $owner = $view->get('owner');
            $isowner = $userid && $userid == $owner;
284
285
            $artefactid = null;
        }
286
287
288
289
290
291
292

        $result = (object) array(
            'limit'    => $limit,
            'offset'   => $offset,
            'view'     => $viewid,
            'artefact' => $artefactid,
            'canedit'  => $canedit,
293
            'owner'    => $owner,
294
            'isowner'  => $isowner,
295
            'export'   => $export,
296
297
298
            'data'     => array(),
        );

299
        if (!empty($artefactid)) {
300
            $where = 'c.onartefact = ' . (int)$artefactid;
301
302
        }
        else {
303
            $where = 'c.onview = ' . (int)$viewid;
304
305
306
307
308
309
310
311
312
313
        }
        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);

314
        if ($result->count > 0) {
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
            // 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) {
                        $rank = key($ids);
                        $result->forceoffset = $offset = ((ceil($rank / $limit) - 1) * $limit);
                        $result->showcomment = $showcomment;
                    }
337
                }
338
            }
339

340
341
            $comments = get_records_sql_assoc('
                SELECT
342
                    a.id, a.author, a.authorname, a.ctime, a.mtime, a.description, a.group,
343
                    c.private, c.deletedby, c.requestpublic, c.rating,
344
                    u.username, u.firstname, u.lastname, u.preferredname, u.email, u.staff, u.admin,
345
                    u.deleted, u.profileicon, u.urlid
346
347
348
                FROM {artefact} a
                    INNER JOIN {artefact_comment_comment} c ON a.id = c.artefact
                    LEFT JOIN {usr} u ON a.author = u.id
349
350
                WHERE ' . $where . '
                ORDER BY a.ctime', array(), $offset, $limit);
351

352
            $files = ArtefactType::attachments_from_id_list(array_keys($comments));
353

354
355
356
357
358
            if ($files) {
                safe_require('artefact', 'file');
                foreach ($files as &$file) {
                    $comments[$file->artefact]->attachments[] = $file;
                }
359
360
            }

361
362
            $result->data = array_values($comments);
        }
363

364
        self::build_html($result);
365
366
367
        return $result;
    }

368
    public static function count_comments($viewids=null, $artefactids=null) {
369
370
371
372
        if (!empty($viewids)) {
            return get_records_sql_assoc('
                SELECT c.onview, COUNT(c.artefact) AS comments
                FROM {artefact_comment_comment} c
373
                WHERE c.onview IN (' . join(',', array_map('intval', $viewids)) . ') AND c.deletedby IS NULL
Richard Mansfield's avatar
Richard Mansfield committed
374
375
376
                GROUP BY c.onview',
                array()
            );
377
378
379
380
381
        }
        if (!empty($artefactids)) {
            return get_records_sql_assoc('
                SELECT c.onartefact, COUNT(c.artefact) AS comments
                FROM {artefact_comment_comment} c
382
                WHERE c.onartefact IN (' . join(',', array_map('intval', $artefactids)) . ') AND c.deletedby IS NULL
Richard Mansfield's avatar
Richard Mansfield committed
383
384
385
                GROUP BY c.onartefact',
                array()
            );
386
387
388
        }
    }

389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
    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];
    }

407
408
    public static function deleted_messages() {
        return array(
409
410
411
            'author' => 'commentremovedbyauthor',
            'owner'  => 'commentremovedbyowner',
            'admin'  => 'commentremovedbyadmin',
Richard Mansfield's avatar
Richard Mansfield committed
412
        );
413
414
415
    }

    public static function build_html(&$data) {
416
        global $USER, $THEME;
417
        $candelete = $data->canedit || $USER->get('admin');
418
419
420
421
        $deletedmessage = array();
        foreach (self::deleted_messages() as $k => $v) {
            $deletedmessage[$k] = get_string($v, 'artefact.comment');
        }
422
        $authors = array();
423
424
        $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
425
        foreach ($data->data as &$item) {
426
427
            $item->ts = strtotime($item->ctime);
            $item->date = format_date($item->ts, 'strftimedatetime');
428
429
430
            if ($item->ts < strtotime($item->mtime)) {
                $item->updated = format_date(strtotime($item->mtime), 'strftimedatetime');
            }
431
            $item->isauthor = $item->author && $item->author == $USER->get('id');
432
            if (!empty($item->attachments)) {
Richard Mansfield's avatar
Richard Mansfield committed
433
                if ($data->isowner) {
434
435
                    $item->attachmessage = get_string(
                        'feedbackattachmessage',
436
437
                        'artefact.comment',
                        get_string('feedbackattachdirname', 'artefact.comment')
438
439
440
441
442
443
                    );
                }
                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
444
445
                }
            }
446
            if ($item->private) {
447
                $item->pubmessage = get_string('thiscommentisprivate', 'artefact.comment');
448
            }
449

450
451
452
453
            if (isset($data->showcomment) && $data->showcomment == $item->id) {
                $item->highlight = 1;
            }

Richard Mansfield's avatar
Richard Mansfield committed
454
455
456
            if ($item->deletedby) {
                $item->deletedmessage = $deletedmessage[$item->deletedby];
            }
457
            else if ($candelete || $item->isauthor) {
Richard Mansfield's avatar
Richard Mansfield committed
458
459
                $item->deleteform = pieform(self::delete_comment_form($item->id));
            }
460
461
462
463
464
465
466
467
468
469
470

            // Comment authors can edit recent comments if they're private or if no one has replied yet.
            if (!$item->deletedby && $item->isauthor
                && ($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)) {
471
                if ((empty($item->requestpublic) && $data->isowner)
472
473
474
475
476
477
478
479
480
                    || $item->isauthor && $item->requestpublic == 'owner'
                    || $data->isowner && $item->requestpublic == 'author') {
                    $item->makepublicform = pieform(self::make_public_form($item->id));
                }
                else if ($item->isauthor && $item->requestpublic == 'author'
                         || $data->isowner && $item->requestpublic == 'owner') {
                    $item->makepublicrequested = 1;
                }
            }
481
482
483
484
            else if (!$item->deletedby && $item->private && !$item->author
                && $data->owner && $data->isowner && $item->requestpublic == 'author') {
                $item->makepublicform = pieform(self::make_public_form($item->id));
            }
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
            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 {
                    if (($data->artefact && $data->canedit) || ($data->view && $data->canedit)) {
                        $item->makepublicform = pieform(self::make_public_form($item->id));
                    }
                    else {
                        $item->makepublicrequested = 1;
                    }
                }
            }
500

501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
            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,
517
                        'profileurl'    => profile_url($item->author),
518
519
520
                    );
                }
            }
521

522
            if (get_config_plugin('artefact', 'comment', 'commentratings') and $item->rating) {
523
524
525
526
                $item->ratingdata = (object) array(
                    'value' => valid_rating($item->rating),
                    'min_rating' => MIN_RATING,
                    'max_rating' => MAX_RATING,
527
                    'export' => $data->export,
528
                );
529
            }
Richard Mansfield's avatar
Richard Mansfield committed
530
        }
531

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

Richard Mansfield's avatar
Richard Mansfield committed
535
536
537
538
539
540
541
        if (!empty($data->artefact)) {
            $data->baseurl = get_config('wwwroot') . 'view/artefact.php?view=' . $data->view . '&artefact=' . $data->artefact;
            $extradata['artefact'] = $data->artefact;
        }
        else {
            $data->baseurl = get_config('wwwroot') . 'view/view.php?id=' . $data->view;
        }
542

Richard Mansfield's avatar
Richard Mansfield committed
543
544
545
        $smarty = smarty_core();
        $smarty->assign_by_ref('data', $data->data);
        $smarty->assign('canedit', $data->canedit);
546
        $smarty->assign('viewid', $data->view);
Richard Mansfield's avatar
Richard Mansfield committed
547
        $smarty->assign('baseurl', $data->baseurl);
548
        $data->tablerows = $smarty->fetch('artefact:comment:commentlist.tpl');
Richard Mansfield's avatar
Richard Mansfield committed
549
550
551
552
553
554
555
556
557
        $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,
558
            'forceoffset' => isset($data->forceoffset) ? $data->forceoffset : null,
559
560
            'resultcounttextsingular' => get_string('comment', 'artefact.comment'),
            'resultcounttextplural' => get_string('comments', 'artefact.comment'),
Richard Mansfield's avatar
Richard Mansfield committed
561
562
563
564
565
566
            'extradata' => $extradata,
        ));
        $data->pagination = $pagination['html'];
        $data->pagination_js = $pagination['javascript'];
    }

Richard Mansfield's avatar
Richard Mansfield committed
567
568
569
570
    public function render_self() {
        return clean_html($this->get('description'));
    }

571
    public static function add_comment_form($defaultprivate=false, $moderate=false) {
572
573
574
575
576
577
578
579
580
581
582
583
584
        global $USER;
        $form = array(
            'name'            => 'add_feedback_form',
            'method'          => 'post',
            'class'           => 'js-hidden',
            'plugintype'      => 'artefact',
            'pluginname'      => 'comment',
            'jsform'          => true,
            'autofocus'       => false,
            'elements'        => array(),
            'jssuccesscallback' => 'addFeedbackSuccess',
        );
        if (!$USER->is_logged_in()) {
585
586
            $form['spam'] = array(
                'secret'       => get_config('formsecret'),
587
                'mintime'      => 1,
588
589
                'hash'         => array('authorname', 'message', 'ispublic', 'message', 'submit'),
            );
590
591
592
593
594
595
596
597
598
599
600
601
602
            $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,
603
            'rules' => array('maxlength' => 8192),
604
        );
605
606
        if (get_config_plugin('artefact', 'comment', 'commentratings')) {
            $form['elements']['rating'] = array(
607
                'type'  => 'radio',
608
                'title' => get_string('rating', 'artefact.comment'),
609
610
                'options' => array('1' => '', '2' => '', '3' => '', '4' => '', '5' => ''),
                'class' => 'star',
611
612
            );
        }
613
614
615
        $form['elements']['ispublic'] = array(
            'type'  => 'checkbox',
            'title' => get_string('makepublic', 'artefact.comment'),
616
            'defaultvalue' => !$defaultprivate,
617
        );
618
619
620
621
        if (get_config('licensemetadata')) {
            $form['elements']['license'] = license_form_el_basic(null);
            $form['elements']['licensing_advanced'] = license_form_el_advanced(null);
        }
622
        if ($moderate) {
623
624
625
626
627
628
            $form['elements']['ispublic']['description'] = get_string('approvalrequired', 'artefact.comment');
            $form['elements']['moderate'] = array(
                'type'  => 'hidden',
                'value' => true,
            );
        }
629
        if ($USER->is_logged_in()) {
630
631
632
633
            $form['elements']['attachments'] = array(
                'type'         => 'files',
                'title'        => get_string('attachfile', 'artefact.comment'),
                'defaultvalue' => array(),
634
                'maxfilesize'  => get_max_upload_size(false),
635
636
637
638
            );
        }
        $form['elements']['submit'] = array(
            'type'  => 'submitcancel',
639
            'value' => array(get_string('placefeedback', 'artefact.comment'), get_string('cancel')),
640
641
642
        );
        return $form;
    }
Richard Mansfield's avatar
Richard Mansfield committed
643

644
645
646
647
648
649
650
    public static function make_public_form($id) {
        return array(
            'name'            => 'make_public',
            'renderer'        => 'oneline',
            'elements'        => array(
                'comment'  => array('type' => 'hidden', 'value' => $id),
                'submit'   => array(
651
652
653
                    'type'  => 'submit',
                    'class' => 'quiet',
                    'name'  => 'make_public_submit',
654
655
656
657
658
659
                    'value' => get_string('makepublic', 'artefact.comment'),
                ),
            ),
        );
    }

Richard Mansfield's avatar
Richard Mansfield committed
660
    public static function delete_comment_form($id) {
661
    	global $THEME;
Richard Mansfield's avatar
Richard Mansfield committed
662
663
664
665
666
667
        return array(
            'name'     => 'delete_comment',
            'renderer' => 'oneline',
            'elements' => array(
                'comment' => array('type' => 'hidden', 'value' => $id),
                'submit'  => array(
668
                    'type'  => 'image',
669
                    'src' => $THEME->get_url('images/btn_deleteremove.png'),
Richard Mansfield's avatar
Richard Mansfield committed
670
                    'value' => get_string('delete'),
671
                    'elementtitle' => get_string('delete'),
672
                    'confirm' => get_string('reallydeletethiscomment', 'artefact.comment'),
673
                    'name'  => 'delete_comment_submit',
Richard Mansfield's avatar
Richard Mansfield committed
674
675
676
677
                ),
            ),
        );
    }
678
679
680
681

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

683
    public function get_view_url($viewid, $showcomment=true, $full=true) {
684
        if ($artefact = $this->get('onartefact')) {
685
            $url = 'view/artefact.php?view=' . $viewid . '&artefact=' . $artefact;
686
687
        }
        else {
688
            $url = 'view/view.php?id=' . $viewid;
689
690
691
692
        }
        if ($showcomment) {
            $url .= '&showcomment=' . $this->get('id');
        }
693
694
695
        if ($full) {
            $url = get_config('wwwroot') . $url;
        }
696
697
        return $url;
    }
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730

    // 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;
    }
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756

    public static function has_config() {
        return true;
    }

    public static function get_config_options() {
        $elements =  array(
            'commentratings' => array(
                'type'  => 'checkbox',
                'title' => get_string('commentratings', 'artefact.comment'),
                'defaultvalue' => get_config_plugin('artefact', 'comment', 'commentratings'),
                'help'  => true,
            ),
        );
        return array(
            'name'     => 'commentconfig',
            'elements' => $elements,
            'renderer' => 'table'
        );
    }

    public static function save_config_options($values) {
        foreach (array('commentratings') as $settingname) {
            set_config_plugin('artefact', 'comment', $settingname, $values[$settingname]);
        }
    }
757
758
}

759
760
761
762
763
764
765
766
/* 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');
767
    $group     = $comment->get('group');
768

769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
    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)) {
786
787
788
789
790
791
792
793
794
        $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']);

795
796
    $relativeurl = $comment->get_view_url($view->get('id'), true, false);
    $url = get_config('wwwroot') . $relativeurl;
797
798
799

    $author    = $comment->get('author');
    $owner     = $comment->get('owner');
800
801
802
803
804
    $groupid   = $comment->get('group');
    $group_admins = array();
    if ($groupid) {
        $group_admins = group_get_admin_ids($groupid);
    }
805
806
807
808
    $requester = $USER->get('id');

    if (($author == $owner && $requester == $owner)
        || ($requester == $owner  && $comment->get('requestpublic') == 'author')
809
        || (array_search($requester,$group_admins) !== false && $comment->get('requestpublic') == 'author')
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
        || ($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));
    }
833
834
835
836
837
838
839
    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));
    }
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
    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)),
            ),
861
862
863
864
            'urltext' => (object) array(
                'key'     => 'Comment',
                'section' => 'artefact.comment',
            ),
865
866
        ),
        'users'     => array($userid),
867
        'url'       => $relativeurl,
868
869
870
871
872
873
874
875
    );
    activity_occurred('maharamessage', $data);
    db_commit();

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

Richard Mansfield's avatar
Richard Mansfield committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
function delete_comment_submit(Pieform $form, $values) {
    global $SESSION, $USER, $view;

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

891
892
    $viewid = $view->get('id');
    if ($artefact = $comment->get('onartefact')) {
893
        $url = 'view/artefact.php?view=' . $viewid . '&artefact=' . $artefact;
894
895
    }
    else {
896
        $url = $view->get_url(false);
897
898
    }

899
900
    db_begin();

Richard Mansfield's avatar
Richard Mansfield committed
901
902
903
    $comment->set('deletedby', $deletedby);
    $comment->commit();

904
905
    if ($deletedby != 'author') {
        // Notify author
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
        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'))),
                ),
927
928
929
                'urltext' => (object) array(
                    'key'     => $artefact ? 'artefact' : 'view',
                ),
930
931
932
933
934
            ),
            'users'     => array($comment->get('author')),
            'url'       => $url,
        );
        activity_occurred('maharamessage', $data);
935
936
937
938
939
940
941
942
943
944
945
946
    }
    if ($deletedby != 'owner' && $comment->get('owner') != $USER->get('id')) {
        // Notify owner
        $data = (object) array(
            'commentid' => $comment->get('id'),
            'viewid'    => $view->get('id'),
        );
        activity_occurred('feedback', $data, 'artefact', 'comment');
    }

    db_commit();

Richard Mansfield's avatar
Richard Mansfield committed
947
    $SESSION->add_ok_msg(get_string('commentremoved', 'artefact.comment'));
948
    redirect(get_config('wwwroot') . $url);
Richard Mansfield's avatar
Richard Mansfield committed
949
950
}

951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
function add_feedback_form_validate(Pieform $form, $values) {
    if ($form->get_property('spam')) {
        require_once(get_config('libroot') . 'antispam.php');
        $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);
        }
    }
970
971
972
    if (empty($values['attachments']) && empty($values['message'])) {
        $form->set_error('message', get_string('messageempty', 'artefact.comment'));
    }
973
974
}

975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
function add_feedback_form_submit(Pieform $form, $values) {
    global $view, $artefact, $USER;
    $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');
    }

    if ($author = $USER->get('id')) {
996
        $anonymous = false;
997
998
999
        $data->author = $author;
    }
    else {
1000
        $anonymous = true;
1001
1002
1003
        $data->authorname = $values['authorname'];
    }

1004
1005
1006
    if (isset($values['moderate']) && $values['ispublic'] && !$USER->can_edit_view($view)) {
        $data->private = 1;
        $data->requestpublic = 'author';
1007
        $moderated = true;
1008
1009
1010
    }
    else {
        $data->private = (int) !$values['ispublic'];
1011
        $moderated = false;
1012
    }
1013
    $private = $data->private;
1014

1015
1016
1017
1018
1019
1020
    if (get_config('licensemetadata')) {
        $data->license       = $values['license'];
        $data->licensor      = $values['licensor'];
        $data->licensorurl   = $values['licensorurl'];
    }

1021
1022
1023
1024
    if (isset($values['rating'])) {
        $data->rating = valid_rating($values['rating']);
    }

1025
    $comment = new ArtefactTypeComment(0, $data);
1026
1027
1028

    db_begin();

1029
1030
    $comment->commit();

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

1034
    if (isset($data->requestpublic) && $data->requestpublic === 'author' && $data->owner) {
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
        $arg = $author ? display_name($USER, null, true) : $data->authorname;
        $moderatemsg = (object) array(
            'subject'   => false,
            'message'   => false,
            'strings'   => (object) array(
                'subject' => (object) array(
                    'key'     => 'makepublicrequestsubject',
                    'section' => 'artefact.comment',
                    'args'    => array(),
                ),
                'message' => (object) array(
                    'key'     => 'makepublicrequestbyauthormessage',
                    'section' => 'artefact.comment',
                    'args'    => array(hsc($arg)),
                ),
                'urltext' => (object) array(
                    'key'     => 'Comment',
                    'section' => 'artefact.comment',
                ),
            ),
            'users'     => array($data->owner),
1056
            'url'       => $url,
1057
1058
1059
        );
    }

1060
1061
    if (!empty($values['attachments']) && is_array($values['attachments']) && !empty($data->author)) {

1062
1063
1064
        require_once(get_config('libroot') . 'uploadmanager.php');
        safe_require('artefact', 'file');

1065
1066
        $ownerlang = empty($data->owner) ? get_config('lang') : get_user_language($data->owner);
        $folderid = ArtefactTypeFolder::get_folder_id(
1067
1068
            get_string_from_language($ownerlang, 'feedbackattachdirname', 'artefact.comment'),
            get_string_from_language($ownerlang, 'feedbackattachdirdesc', 'artefact.comment'),
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
            null, true, $data->owner, $data->group, $data->institution
        );

        $attachment = (object) array(
            'owner'         => $data->owner,
            'group'         => $data->group,
            'institution'   => $data->institution,
            'author'        => $data->author,
            'allowcomments' => 0,
            'parent'        => $folderid,
            'description'   => get_string_from_language(
                $ownerlang,
                'feedbackonviewbyuser',
                'artefact.comment',
                $view->get('title'),
                display_name($USER)
            ),
        );

        foreach ($values['attachments'] as $filesindex) {
1089

1090
            $originalname = $_FILES[$filesindex]['name'];
1091
            $attachment->title = ArtefactTypeFileBase::get_new_file_title(
1092
                $originalname,
1093
1094
1095
1096
                $folderid,
                $data->owner,
                $data->group,
                $data->institution
1097
1098
1099
            );

            try {
1100
                $fileid = ArtefactTypeFile::save_uploaded_file($filesindex, $attachment);
1101
            }
1102
1103
1104
1105
            catch (QuotaExceededException $e) {
                if ($data->owner == $USER->get('id')) {
                    $form->reply(PIEFORM_ERR, array('message' => $e->getMessage()));
                }
1106
                redirect($goto);
1107
            }
1108
1109
1110
1111
            catch (UploadException $e) {
                $form->reply(PIEFORM_ERR, array('message' => $e->getMessage()));
                redirect($goto);
            }
1112
1113

            $comment->attach($fileid);
1114
1115
1116
1117
        }
    }

    require_once('activity.php');
1118
1119
1120
1121
    $data = (object) array(
        'commentid' => $comment->get('id'),
        'viewid'    => $view->get('id')
    );
1122
    activity_occurred('feedback', $data, 'artefact', 'comment');
1123

1124
1125
1126
1127
    if (isset($moderatemsg)) {
        activity_occurred('maharamessage', $moderatemsg);
    }

1128
1129
    db_commit();

1130
1131
    $newlist = ArtefactTypeComment::get_comments(10, 0, 'last', $view, $artefact);

1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
    // If you're anonymous and your message is moderated or private, then you won't
    // be able to tell what happened to it. So we'll provide some more explanation in
    // the feedback message.
    if ($anonymous && $moderated) {
        $message = get_string('feedbacksubmittedmoderatedanon', 'artefact.comment');
    }
    else if ($anonymous && $private) {
        $message = get_string('feedbacksubmittedprivateanon', 'artefact.comment');
    }
    else {
        $message = get_string('feedbacksubmitted', 'artefact.comment');
    }

1145
    $form->reply(PIEFORM_OK, array(
1146
        'message' => $message,
1147
1148
1149
1150
1151
1152
1153
1154
        'goto' => $goto,
        'data' => $newlist,
    ));
}

function add_feedback_form_cancel_submit(Pieform $form) {
    global $view;
    $form->reply(PIEFORM_OK, array(
1155
        'goto' => '/' . $view->get_url(false),
1156
1157
1158
    ));
}

1159
1160
class ActivityTypeArtefactCommentFeedback extends ActivityTypePlugin {

1161
1162
    protected $viewid;
    protected $commentid;
1163
1164
1165

    /**
     * @param array $data Parameters:
1166
1167
     *                    - viewid (int)
     *                    - commentid (int)
1168
1169
1170
1171
     */
    public function __construct($data, $cron=false) {
        parent::__construct($data, $cron);

1172
1173
        $comment = new ArtefactTypeComment($this->commentid);

1174
1175
        $this->overridemessagecontents = true;

1176
        if ($onartefact = $comment->get('onartefact')) { // feedback on artefact
1177
1178
            $userid = null;
            require_once(get_config('docroot') . 'artefact/lib.php');
1179
1180
1181
            $artefactinstance = artefact_instance_from_id($onartefact);
            if ($artefactinstance->feedback_notify_owner()) {
                $userid = $artefactinstance->get('owner');
1182
1183
            }
            if (empty($this->url)) {
1184
                $this->url = 'view/artefact.php?artefact=' . $onartefact . '&view=' . $this->viewid;
1185
1186
1187
            }
        }
        else { // feedback on view.
1188
1189
1190
            $onview = $comment->get('onview');
            if (!$viewrecord = get_record('view', 'id', $onview)) {
                throw new ViewNotFoundException(get_string('viewnotfound', 'error', $onview));
1191
            }
1192
            $userid = $viewrecord->owner;
1193
            if (empty($this->url)) {
1194
                $this->url = 'view/view.php?id=' . $onview;
1195
1196
            }
        }
1197
1198
        if (empty($userid)) {
            return;
1199
1200
        }

1201
1202
        $this->users = activity_get_users($this->get_id(), array($userid));
        $title = $onartefact ? $artefactinstance->get('title') : $viewrecord->title;
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
        $this->urltext = $title;
        $body = $comment->get('description');
        $posttime = strftime(get_string('strftimedaydatetime'), $comment->get('ctime'));
        $user = $this->users[0];
        $lang = (empty($user->lang) || $user->lang == 'default') ? get_config('lang') : $user->lang;

        // Internal
        $this->message = strip_tags(str_shorten_html($body, 200, true));

        // Comment deleted notification
        if ($deletedby = $comment->get('deletedby')) {
            $this->strings = (object) array(
                'subject' => (object) array(
                    'key'     => 'commentdeletednotificationsubject',
                    'section' => 'artefact.comment',
                    'args'    => array($title),
                ),
            );
            $deletedmessage = ArtefactTypeComment::deleted_messages();
            $removedbyline = get_string_from_language($lang, $deletedmessage[$deletedby], 'artefact.comment');
            $this->message = $removedbyline . ":\n" . $this->message;

            // Email
            $this->users[0]->htmlmessage = get_string_from_language(
                $lang, 'feedbackdeletedhtml', 'artefact.comment',
1228
                hsc($title), $removedbyline, clean_html($body), get_config('wwwroot') . $this->url, hsc($title)
1229
1230
1231
            );
            $this->users[0]->emailmessage = get_string_from_language(
                $lang, 'feedbackdeletedtext', 'artefact.comment',
1232
                $title, $removedbyline, trim(html2text($body)), $title, get_config('wwwroot') . $this->url
1233
1234
1235
            );
            return;
        }
1236
1237
1238

        $this->strings = (object) array(
            'subject' => (object) array(
1239
                'key'     => 'newfeedbacknotificationsubject',
1240
1241
1242
1243
1244
                'section' => 'artefact.comment',
                'args'    => array($title),
            ),
        );

1245
        $this->url .= '&showcomment=' . $comment->get('id');
1246

1247
1248
1249
1250
1251
1252
        // Email
        $author = $comment->get('author');
        $authorname = empty($author) ? $comment->get('authorname') : display_name($author, $user);

        $this->users[0]->htmlmessage = get_string_from_language(
            $lang, 'feedbacknotificationhtml', 'artefact.comment',
1253
            hsc($authorname), hsc($title), $posttime, clean_html($body), get_config('wwwroot') . $this->url
1254
1255
        );
        $this->users[0]->emailmessage = get_string_from_language(
1256
            $lang, 'feedbacknotificationtext', 'artefact.comment',
1257
            $authorname, $title, $posttime, trim(html2text($body)), get_config('wwwroot') . $this->url
1258
        );
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
    }

    public function get_plugintype(){
        return 'artefact';
    }

    public function get_pluginname(){
        return 'comment';
    }

    public function get_required_parameters() {
1270
        return array('commentid', 'viewid');
1271
1272
    }
}