lib.php 42 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
30
require_once('activity.php');

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

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

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

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

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

    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
141
142
143
144
145
146
147
148
}

class ArtefactTypeComment extends ArtefactType {

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

    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(
176
177
178
179
180
181
            'artefact'      => $this->get('id'),
            'onview'        => $this->get('onview'),
            'onartefact'    => $this->get('onartefact'),
            'private'       => $this->get('private'),
            'deletedby'     => $this->get('deletedby'),
            'requestpublic' => $this->get('requestpublic'),
182
            'rating'        => $this->get('rating'),
Richard Mansfield's avatar
Richard Mansfield committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
        );

        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;
        return $THEME->get_url('images/comment.gif', false, 'artefact/comment');
    }

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

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

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

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

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

    public function can_have_attachments() {
        return true;
    }

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

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

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

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

313
        if ($result->count > 0) {
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
            // 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;
                    }
336
                }
337
            }
338

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

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

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

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

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

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

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

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

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

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

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

            // 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)) {
                if (empty($item->requestpublic)
                    || $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
485
486
487
488
489
490
491
492
493
494
495
496
            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,
497
                        'profileurl'    => profile_url($item->author),
498
499
500
                    );
                }
            }
501

502
            if (get_config_plugin('artefact', 'comment', 'commentratings') and $item->rating) {
503
504
505
506
                $item->ratingdata = (object) array(
                    'value' => valid_rating($item->rating),
                    'min_rating' => MIN_RATING,
                    'max_rating' => MAX_RATING,
507
                    'export' => $data->export,
508
                );
509
            }
Richard Mansfield's avatar
Richard Mansfield committed
510
        }
511

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

Richard Mansfield's avatar
Richard Mansfield committed
515
516
517
518
519
520
521
        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;
        }
522

Richard Mansfield's avatar
Richard Mansfield committed
523
524
525
        $smarty = smarty_core();
        $smarty->assign_by_ref('data', $data->data);
        $smarty->assign('canedit', $data->canedit);
526
        $smarty->assign('viewid', $data->view);
Richard Mansfield's avatar
Richard Mansfield committed
527
        $smarty->assign('baseurl', $data->baseurl);
528
        $data->tablerows = $smarty->fetch('artefact:comment:commentlist.tpl');
Richard Mansfield's avatar
Richard Mansfield committed
529
530
531
532
533
534
535
536
537
        $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,
538
            'forceoffset' => isset($data->forceoffset) ? $data->forceoffset : null,
539
540
            'resultcounttextsingular' => get_string('comment', 'artefact.comment'),
            'resultcounttextplural' => get_string('comments', 'artefact.comment'),
Richard Mansfield's avatar
Richard Mansfield committed
541
542
543
544
545
546
            'extradata' => $extradata,
        ));
        $data->pagination = $pagination['html'];
        $data->pagination_js = $pagination['javascript'];
    }

Richard Mansfield's avatar
Richard Mansfield committed
547
548
549
550
    public function render_self() {
        return clean_html($this->get('description'));
    }

551
    public static function add_comment_form($defaultprivate=false, $moderate=false) {
552
553
554
555
556
557
558
559
560
561
562
563
564
        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()) {
565
566
            $form['spam'] = array(
                'secret'       => get_config('formsecret'),
567
                'mintime'      => 1,
568
569
                'hash'         => array('authorname', 'message', 'ispublic', 'message', 'submit'),
            );
570
571
572
573
574
575
576
577
578
579
580
581
582
            $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,
583
            'rules' => array('maxlength' => 8192),
584
        );
585
586
        if (get_config_plugin('artefact', 'comment', 'commentratings')) {
            $form['elements']['rating'] = array(
587
                'type'  => 'radio',
588
                'title' => get_string('rating', 'artefact.comment'),
589
590
                'options' => array('1' => '', '2' => '', '3' => '', '4' => '', '5' => ''),
                'class' => 'star',
591
592
            );
        }
593
594
595
        $form['elements']['ispublic'] = array(
            'type'  => 'checkbox',
            'title' => get_string('makepublic', 'artefact.comment'),
596
            'defaultvalue' => !$defaultprivate,
597
        );
598
        if ($moderate) {
599
600
601
602
603
604
            $form['elements']['ispublic']['description'] = get_string('approvalrequired', 'artefact.comment');
            $form['elements']['moderate'] = array(
                'type'  => 'hidden',
                'value' => true,
            );
        }
605
        if ($USER->is_logged_in()) {
606
607
608
609
            $form['elements']['attachments'] = array(
                'type'         => 'files',
                'title'        => get_string('attachfile', 'artefact.comment'),
                'defaultvalue' => array(),
610
                'maxfilesize'  => get_max_upload_size(false),
611
612
613
614
            );
        }
        $form['elements']['submit'] = array(
            'type'  => 'submitcancel',
615
            'value' => array(get_string('placefeedback', 'artefact.comment'), get_string('cancel')),
616
617
618
        );
        return $form;
    }
Richard Mansfield's avatar
Richard Mansfield committed
619

620
621
622
623
624
625
626
    public static function make_public_form($id) {
        return array(
            'name'            => 'make_public',
            'renderer'        => 'oneline',
            'elements'        => array(
                'comment'  => array('type' => 'hidden', 'value' => $id),
                'submit'   => array(
627
628
629
                    'type'  => 'submit',
                    'class' => 'quiet',
                    'name'  => 'make_public_submit',
630
631
632
633
634
635
                    'value' => get_string('makepublic', 'artefact.comment'),
                ),
            ),
        );
    }

Richard Mansfield's avatar
Richard Mansfield committed
636
    public static function delete_comment_form($id) {
637
    	global $THEME;
Richard Mansfield's avatar
Richard Mansfield committed
638
639
640
641
642
643
        return array(
            'name'     => 'delete_comment',
            'renderer' => 'oneline',
            'elements' => array(
                'comment' => array('type' => 'hidden', 'value' => $id),
                'submit'  => array(
644
                    'type'  => 'image',
645
                    'src' => $THEME->get_url('images/icon_close.gif'),
Richard Mansfield's avatar
Richard Mansfield committed
646
                    'value' => get_string('delete'),
647
                    'elementtitle' => get_string('delete'),
648
                    'confirm' => get_string('reallydeletethiscomment', 'artefact.comment'),
649
                    'name'  => 'delete_comment_submit',
Richard Mansfield's avatar
Richard Mansfield committed
650
651
652
653
                ),
            ),
        );
    }
654
655
656
657

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

659
    public function get_view_url($viewid, $showcomment=true, $full=true) {
660
        if ($artefact = $this->get('onartefact')) {
661
            $url = 'view/artefact.php?view=' . $viewid . '&artefact=' . $artefact;
662
663
        }
        else {
664
            $url = 'view/view.php?id=' . $viewid;
665
666
667
668
        }
        if ($showcomment) {
            $url .= '&showcomment=' . $this->get('id');
        }
669
670
671
        if ($full) {
            $url = get_config('wwwroot') . $url;
        }
672
673
        return $url;
    }
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706

    // 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;
    }
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732

    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]);
        }
    }
733
734
}

735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
/* 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');

    if (!$author || !$owner || !$requester || ($requester != $owner && $requester != $author)) {
        $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']);

754
755
    $relativeurl = $comment->get_view_url($view->get('id'), true, false);
    $url = get_config('wwwroot') . $relativeurl;
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806

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

    if (($author == $owner && $requester == $owner)
        || ($requester == $owner  && $comment->get('requestpublic') == 'author')
        || ($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));
    }
    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)),
            ),
807
808
809
810
            'urltext' => (object) array(
                'key'     => 'Comment',
                'section' => 'artefact.comment',
            ),
811
812
        ),
        'users'     => array($userid),
813
        'url'       => $relativeurl,
814
815
816
817
818
819
820
821
    );
    activity_occurred('maharamessage', $data);
    db_commit();

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

Richard Mansfield's avatar
Richard Mansfield committed
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
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';
    }

837
838
    $viewid = $view->get('id');
    if ($artefact = $comment->get('onartefact')) {
839
        $url = 'view/artefact.php?view=' . $viewid . '&artefact=' . $artefact;
840
841
    }
    else {
842
        $url = $view->get_url(false);
843
844
    }

845
846
    db_begin();

Richard Mansfield's avatar
Richard Mansfield committed
847
848
849
    $comment->set('deletedby', $deletedby);
    $comment->commit();

850
851
    if ($deletedby != 'author') {
        // Notify author
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
        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'))),
                ),
873
874
875
                'urltext' => (object) array(
                    'key'     => $artefact ? 'artefact' : 'view',
                ),
876
877
878
879
880
            ),
            'users'     => array($comment->get('author')),
            'url'       => $url,
        );
        activity_occurred('maharamessage', $data);
881
882
883
884
885
886
887
888
889
890
891
892
    }
    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
893
    $SESSION->add_ok_msg(get_string('commentremoved', 'artefact.comment'));
894
    redirect(get_config('wwwroot') . $url);
Richard Mansfield's avatar
Richard Mansfield committed
895
896
}

897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
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);
        }
    }
916
917
918
    if (empty($values['attachments']) && empty($values['message'])) {
        $form->set_error('message', get_string('messageempty', 'artefact.comment'));
    }
919
920
}

921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
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')) {
        $data->author = $author;
    }
    else {
        $data->authorname = $values['authorname'];
    }

948
949
950
951
952
953
954
    if (isset($values['moderate']) && $values['ispublic'] && !$USER->can_edit_view($view)) {
        $data->private = 1;
        $data->requestpublic = 'author';
    }
    else {
        $data->private = (int) !$values['ispublic'];
    }
955

956
957
958
959
    if (isset($values['rating'])) {
        $data->rating = valid_rating($values['rating']);
    }

960
    $comment = new ArtefactTypeComment(0, $data);
961
962
963

    db_begin();

964
965
    $comment->commit();

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

969
    if (isset($data->requestpublic) && $data->requestpublic === 'author' && $data->owner) {
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
        $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),
991
            'url'       => $url,
992
993
994
        );
    }

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

997
998
999
        require_once(get_config('libroot') . 'uploadmanager.php');
        safe_require('artefact', 'file');

1000
1001
        $ownerlang = empty($data->owner) ? get_config('lang') : get_user_language($data->owner);
        $folderid = ArtefactTypeFolder::get_folder_id(
1002
1003
            get_string_from_language($ownerlang, 'feedbackattachdirname', 'artefact.comment'),
            get_string_from_language($ownerlang, 'feedbackattachdirdesc', 'artefact.comment'),
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
            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) {
1024

1025
            $originalname = $_FILES[$filesindex]['name'];
1026
            $attachment->title = ArtefactTypeFileBase::get_new_file_title(
1027
                $originalname,
1028
1029
1030
1031
                $folderid,
                $data->owner,
                $data->group,
                $data->institution
1032
1033
1034
            );

            try {
1035
                $fileid = ArtefactTypeFile::save_uploaded_file($filesindex, $attachment);
1036
            }
1037
1038
1039
1040
            catch (QuotaExceededException $e) {
                if ($data->owner == $USER->get('id')) {
                    $form->reply(PIEFORM_ERR, array('message' => $e->getMessage()));
                }
1041
                redirect($goto);
1042
            }
1043
1044
1045
1046
            catch (UploadException $e) {
                $form->reply(PIEFORM_ERR, array('message' => $e->getMessage()));
                redirect($goto);
            }
1047
1048

            $comment->attach($fileid);
1049
1050
1051
1052
        }
    }

    require_once('activity.php');
1053
1054
1055
1056
    $data = (object) array(
        'commentid' => $comment->get('id'),
        'viewid'    => $view->get('id')
    );
1057
    activity_occurred('feedback', $data, 'artefact', 'comment');
1058

1059
1060
1061
1062
    if (isset($moderatemsg)) {
        activity_occurred('maharamessage', $moderatemsg);
    }

1063
1064
    db_commit();

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

1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
    $form->reply(PIEFORM_OK, array(
        'message' => get_string('feedbacksubmitted', 'artefact.comment'),
        'goto' => $goto,
        'data' => $newlist,
    ));
}

function add_feedback_form_cancel_submit(Pieform $form) {
    global $view;
    $form->reply(PIEFORM_OK, array(
1077
        'goto' => '/' . $view->get_url(false),
1078
1079
1080
    ));
}

1081
1082
class ActivityTypeArtefactCommentFeedback extends ActivityTypePlugin {

1083
1084
    protected $viewid;
    protected $commentid;
1085
1086
1087

    /**
     * @param array $data Parameters:
1088
1089
     *                    - viewid (int)
     *                    - commentid (int)
1090
1091
1092
1093
     */
    public function __construct($data, $cron=false) {
        parent::__construct($data, $cron);

1094
1095
        $comment = new ArtefactTypeComment($this->commentid);

1096
1097
        $this->overridemessagecontents = true;

1098
        if ($onartefact = $comment->get('onartefact')) { // feedback on artefact
1099
1100
            $userid = null;
            require_once(get_config('docroot') . 'artefact/lib.php');
1101
1102
1103
            $artefactinstance = artefact_instance_from_id($onartefact);
            if ($artefactinstance->feedback_notify_owner()) {
                $userid = $artefactinstance->get('owner');
1104
1105
            }
            if (empty($this->url)) {
1106
                $this->url = 'view/artefact.php?artefact=' . $onartefact . '&view=' . $this->viewid;
1107
1108
1109
            }
        }
        else { // feedback on view.
1110
1111
1112
            $onview = $comment->get('onview');
            if (!$viewrecord = get_record('view', 'id', $onview)) {
                throw new ViewNotFoundException(get_string('viewnotfound', 'error', $onview));
1113
            }
1114
            $userid = $viewrecord->owner;
1115
            if (empty($this->url)) {
1116
                $this->url = 'view/view.php?id=' . $onview;
1117
1118
            }
        }
1119
1120
        if (empty($userid)) {
            return;
1121
1122
        }

1123
1124
        $this->users = activity_get_users($this->get_id(), array($userid));
        $title = $onartefact ? $artefactinstance->get('title') : $viewrecord->title;
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
        $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',
1150
                hsc($title), $removedbyline, clean_html($body), get_config('wwwroot') . $this->url, hsc($title)
1151
1152
1153
            );
            $this->users[0]->emailmessage = get_string_from_language(
                $lang, 'feedbackdeletedtext', 'artefact.comment',
1154
                $title, $removedbyline, trim(html2text($body)), $title, get_config('wwwroot') . $this->url
1155
1156
1157
            );
            return;
        }
1158
1159
1160

        $this->strings = (object) array(
            'subject' => (object) array(
1161
                'key'     => 'newfeedbacknotificationsubject',
1162
1163
1164
1165
1166
                'section' => 'artefact.comment',
                'args'    => array($title),
            ),
        );

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

1169
1170
1171
1172
1173
1174
        // 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',
1175
            hsc($authorname), hsc($title), $posttime, clean_html($body), get_config('wwwroot') . $this->url
1176
1177
        );
        $this->users[0]->emailmessage = get_string_from_language(
1178
            $lang, 'feedbacknotificationtext', 'artefact.comment',
1179
            $authorname, $title, $posttime, trim(html2text($body)), get_config('wwwroot') . $this->url
1180
        );
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
    }

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

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

    public function get_required_parameters() {
1192
        return array('commentid', 'viewid');
1193
1194
    }
}