MDL-19118, set $PAGE->context for comment_ajax.php
[moodle.git] / comment / lib.php
CommitLineData
1bcb7eb5 1<?php
2
36051c9e
DC
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
1bcb7eb5 18/**
36051c9e 19 * Comment is helper class to add/delete comments anywhere in moodle
1bcb7eb5 20 *
36051c9e
DC
21 * @package comment
22 * @copyright 2010 Dongsheng Cai <dongsheng@moodle.com>
1bcb7eb5 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
1bcb7eb5 25
36051c9e 26class comment {
1bcb7eb5 27 /**
36051c9e 28 * @var integer
1bcb7eb5 29 */
36051c9e
DC
30 private $page;
31 /**
32 * there may be several comment box in one page
33 * so we need a client_id to recognize them
34 * @var integer
35 */
36 private $cid;
37 private $contextid;
38 /**
39 * commentarea is used to specify different
40 * parts shared the same itemid
41 * @var string
42 */
43 private $commentarea;
44 /**
45 * itemid is used to associate with commenting content
46 * @var integer
47 */
48 private $itemid;
49
50 /**
51 * this html snippet will be used as a template
52 * to build comment content
53 * @var string
54 */
55 private $template;
56 private $context;
866354a9 57 private $courseid;
36051c9e 58 /**
866354a9
DC
59 * course module object, only be used to help find pluginname automatically
60 * if pluginname is specified, it won't be used at all
36051c9e
DC
61 * @var string
62 */
63 private $cm;
64 private $plugintype;
866354a9
DC
65 /**
66 * When used in module, it is recommended to use it
67 * @var string
68 */
36051c9e
DC
69 private $pluginname;
70 private $viewcap;
71 private $postcap;
72 /**
73 * to tell comments api where it is used
74 * @var string
75 */
76 private $env;
77 /**
78 * to costomize link text
79 * @var string
80 */
81 private $linktext;
866354a9
DC
82
83 // static variable will be used by non-js comments UI
36051c9e 84 private static $nonjs = false;
36051c9e
DC
85 private static $comment_itemid = null;
86 private static $comment_context = null;
87 private static $comment_area = null;
a5306210 88 private static $comment_page = null;
36051c9e 89 /**
866354a9 90 * Construct function of comment class, initialise
36051c9e
DC
91 * class members
92 * @param object $options
93 */
94 public function __construct($options) {
95 global $CFG, $DB;
76951100 96
c794595d
DC
97 if (empty($CFG->commentsperpage)) {
98 $CFG->commentsperpage = 15;
99 }
100
36051c9e
DC
101 $this->viewcap = false;
102 $this->postcap = false;
76951100 103
866354a9 104 // setup client_id
36051c9e
DC
105 if (!empty($options->client_id)) {
106 $this->cid = $options->client_id;
107 } else {
108 $this->cid = uniqid();
109 }
866354a9
DC
110
111 // setup context
36051c9e
DC
112 if (!empty($options->context)) {
113 $this->context = $options->context;
114 $this->contextid = $this->context->id;
115 } else if(!empty($options->contextid)) {
116 $this->contextid = $options->contextid;
117 $this->context = get_context_instance_by_id($this->contextid);
118 } else {
119 print_error('invalidcontext');
120 }
76951100 121
866354a9
DC
122 // setup course
123 // course will be used to generate user profile link
124 if (!empty($options->course)) {
125 $this->courseid = $options->course->id;
126 } else if (!empty($options->courseid)) {
127 $this->courseid = $options->courseid;
128 }
129
130 if (!empty($options->pluginname)) {
131 $this->pluginname = $options->pluginname;
132 }
133
134 // setup coursemodule
135 if (!empty($options->cm)) {
136 $this->cm = $options->cm;
137 } else {
138 $this->cm = null;
139 }
140
141 // setup commentarea
36051c9e
DC
142 if (!empty($options->area)) {
143 $this->commentarea = $options->area;
144 }
76951100 145
866354a9 146 // setup itemid
36051c9e
DC
147 if (!empty($options->itemid)) {
148 $this->itemid = $options->itemid;
467c85d7
DC
149 } else {
150 $this->itemid = 0;
36051c9e 151 }
76951100 152
866354a9 153 // setup env
36051c9e
DC
154 if (!empty($options->env)) {
155 $this->env = $options->env;
1bcb7eb5 156 } else {
08a22be6 157 $this->env = '';
1bcb7eb5 158 }
1bcb7eb5 159
866354a9 160 // setup customized linktext
36051c9e
DC
161 if (!empty($options->linktext)) {
162 $this->linktext = $options->linktext;
163 } else {
164 $this->linktext = get_string('comments');
165 }
866354a9
DC
166 // setting post and view permissions
167 $this->check_permissions();
168
169 if (!empty($options->showcount)) {
170 $count = $this->count();
171 if (empty($count)) {
172 $this->count = '';
173 } else {
174 $this->count = '('.$count.')';
175 }
176 } else {
177 $this->count = '';
178 }
36051c9e 179
05fe3ab5 180 $this->setup_plugin();
36051c9e 181
866354a9
DC
182 // setup options for callback functions
183 $this->args = new stdclass;
184 $this->args->context = $this->context;
185 $this->args->courseid = $this->courseid;
186 $this->args->cm = $this->cm;
187 $this->args->commentarea = $this->commentarea;
188 $this->args->itemid = $this->itemid;
36051c9e
DC
189
190 // load template
191 $this->template = <<<EOD
192<div class="comment-userpicture">___picture___</div>
193<div class="comment-content">
194 ___name___ - <span>___time___</span>
195 <div>___content___</div>
196</div>
197EOD;
198 if (!empty($this->plugintype)) {
866354a9 199 $this->template = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'template', $this->args, $this->template);
1bcb7eb5 200 }
201
36051c9e
DC
202 unset($options);
203 }
204
205 /**
206 * Receive nonjs comment parameters
207 */
208 public static function init() {
209 global $PAGE, $CFG;
210 // setup variables for non-js interface
211 self::$nonjs = optional_param('nonjscomment', '', PARAM_ALPHA);
212 self::$comment_itemid = optional_param('comment_itemid', '', PARAM_INT);
213 self::$comment_context = optional_param('comment_context', '', PARAM_INT);
a5306210 214 self::$comment_page = optional_param('comment_page', '', PARAM_INT);
36051c9e
DC
215 self::$comment_area = optional_param('comment_area', '', PARAM_ALPHAEXT);
216
217 $PAGE->requires->string_for_js('addcomment', 'moodle');
218 $PAGE->requires->string_for_js('deletecomment', 'moodle');
219 $PAGE->requires->string_for_js('comments', 'moodle');
1bcb7eb5 220 }
221
36051c9e 222 /**
866354a9 223 * Setup plugin type and plugin name
36051c9e 224 */
05fe3ab5 225 private function setup_plugin() {
1bcb7eb5 226 global $DB;
36051c9e
DC
227 // blog needs to set env as "blog"
228 if ($this->env == 'blog') {
229 $this->plugintype = 'moodle';
230 $this->pluginname = 'blog';
231 }
232 // tag page needs to set env as "tag"
233 if ($this->env == 'tag') {
234 $this->plugintype = 'moodle';
235 $this->pluginname = 'tag';
236 }
1bcb7eb5 237 if ($this->context->contextlevel == CONTEXT_BLOCK) {
238 if ($block = $DB->get_record('block_instances', array('id'=>$this->context->instanceid))) {
239 $this->plugintype = 'block';
240 $this->pluginname = $block->blockname;
241 }
242 }
866354a9 243
1bcb7eb5 244 if ($this->context->contextlevel == CONTEXT_MODULE) {
245 $this->plugintype = 'mod';
866354a9
DC
246 // to improve performance, pluginname should be assigned before initilise comment object
247 // if it is empty, we will try to guess, it will rarely be used.
248 if (empty($this->pluginname)) {
249 if (empty($this->course)) {
250 $this->course = $DB->get_record('course', array('id'=>$this->courseid), '*', MUST_EXIST);
251 }
252 $this->modinfo = get_fast_modinfo($this->course);
253 $this->pluginname = $this->modinfo->cms[$this->cm->id]->modname;
254 }
1bcb7eb5 255 }
256 }
257
258 /**
36051c9e
DC
259 * check posting comments permission
260 * It will check based on user roles and ask modules
261 * If you need to check permission by modules, a
262 * function named $pluginname_check_comment_post must be implemented
1bcb7eb5 263 */
05fe3ab5 264 private function check_permissions() {
36051c9e
DC
265 global $CFG;
266 $this->postcap = has_capability('moodle/comment:post', $this->context);
267 $this->viewcap = has_capability('moodle/comment:view', $this->context);
268 if (!empty($this->plugintype)) {
866354a9 269 $permissions = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'permissions', $this->args, array('post'=>true, 'view'=>true));
36051c9e
DC
270 $this->postcap = $this->postcap && $permissions['post'];
271 $this->viewcap = $this->viewcap && $permissions['view'];
6f5e0852 272 }
1bcb7eb5 273 }
274
275 /**
36051c9e
DC
276 * Prepare comment code in html
277 * @param boolean $return
278 * @return mixed
1bcb7eb5 279 */
36051c9e 280 public function output($return = true) {
4b201bc6
DC
281 global $PAGE, $OUTPUT;
282 static $template_printed;
36051c9e 283
5dce9d1b 284 $this->link = $PAGE->url;
36051c9e
DC
285 $murl = new moodle_url($this->link);
286 $murl->remove_params('nonjscomment');
287 $murl->param('nonjscomment', 'true');
866354a9
DC
288 $murl->param('comment_itemid', $this->itemid);
289 $murl->param('comment_context', $this->context->id);
290 $murl->param('comment_area', $this->commentarea);
a5306210 291 $murl->remove_params('comment_page');
36051c9e 292 $this->link = $murl->out();
76951100 293
36051c9e
DC
294 $options = new stdclass;
295 $options->client_id = $this->cid;
296 $options->commentarea = $this->commentarea;
297 $options->itemid = $this->itemid;
298 $options->page = 0;
866354a9 299 $options->courseid = $this->courseid;
36051c9e 300 $options->contextid = $this->contextid;
76951100 301 $options->env = $this->env;
36051c9e
DC
302 if ($this->env == 'block_comments') {
303 $options->autostart = true;
304 $options->notoggle = true;
305 }
306
307 $PAGE->requires->js_init_call('M.core_comment.init', array($options), true);
308
309 if (!empty(self::$nonjs)) {
76951100 310 // return non js comments interface
a5306210 311 return $this->print_comments(self::$comment_page, $return, true);
36051c9e 312 }
76951100 313
36051c9e
DC
314 $strsubmit = get_string('submit');
315 $strcancel = get_string('cancel');
316 $sesskey = sesskey();
4b201bc6 317 $html = '';
36051c9e 318 // print html template
76951100 319 // Javascript will use the template to render new comments
4b201bc6
DC
320 if (empty($template_printed) && !empty($this->viewcap)) {
321 $html .= '<div style="display:none" id="cmt-tmpl">' . $this->template . '</div>';
322 $template_printed = true;
36051c9e
DC
323 }
324
325 if (!empty($this->viewcap)) {
326 // print commenting icon and tooltip
07eebf20 327 $icon = $OUTPUT->pix_url('t/collapsed');
4b201bc6 328 $html .= <<<EOD
b1d124d1 329<div class="mdl-left">
36051c9e 330<a id="comment-link-{$this->cid}" href="{$this->link}">
07eebf20 331 <img id="comment-img-{$this->cid}" src="$icon" alt="{$this->linktext}" title="{$this->linktext}" />
76951100 332 <span id="comment-link-text-{$this->cid}">{$this->linktext} {$this->count}</span>
36051c9e
DC
333</a>
334<div id="comment-ctrl-{$this->cid}" class="comment-ctrl">
335 <ul id="comment-list-{$this->cid}" class="comment-list">
76951100
DC
336EOD;
337 // in comments block, we print comments list right away
338 if ($this->env == 'block_comments') {
339 $html .= $this->print_comments(0, true, false);
3e34183a
DC
340 $html .= '</ul>';
341 $html .= $this->get_pagination(0);
342 } else {
343 $html .= <<<EOD
36051c9e
DC
344 </ul>
345 <div id="comment-pagination-{$this->cid}" class="comment-pagination"></div>
346EOD;
3e34183a 347 }
36051c9e
DC
348
349 // print posting textarea
350 if (!empty($this->postcap)) {
351 $html .= <<<EOD
352<div class='comment-area'>
353 <div class="bd">
76951100 354 <textarea name="content" rows="2" id="dlg-content-{$this->cid}"></textarea>
36051c9e
DC
355 </div>
356 <div class="fd" id="comment-action-{$this->cid}">
1150c1bd 357 <a href="#" id="comment-action-post-{$this->cid}"> {$strsubmit} </a>
36051c9e
DC
358EOD;
359 if ($this->env != 'block_comments') {
360 $html .= <<<EOD
361 <span> | </span>
1150c1bd 362 <a href="#" id="comment-action-cancel-{$this->cid}"> {$strcancel} </a>
36051c9e
DC
363EOD;
364 }
365
366 $html .= <<<EOD
367 </div>
368</div>
b1d124d1 369<div class="clearer"></div>
36051c9e
DC
370EOD;
371 }
372
373 $html .= <<<EOD
76951100 374</div><!-- end of comment-ctrl -->
36051c9e
DC
375</div>
376EOD;
377 } else {
378 $html = '';
379 }
380
381 if ($return) {
382 return $html;
383 } else {
384 echo $html;
1bcb7eb5 385 }
1bcb7eb5 386 }
36051c9e 387
1bcb7eb5 388 /**
36051c9e
DC
389 * Return matched comments
390 * @param int $page
391 * @return mixed
1bcb7eb5 392 */
36051c9e
DC
393 public function get_comments($page = '') {
394 global $DB, $CFG, $USER, $OUTPUT;
395 if (empty($this->viewcap)) {
396 return false;
397 }
36051c9e
DC
398 if (!is_numeric($page)) {
399 $page = 0;
400 }
401 $this->page = $page;
402 $params = array();
403 $start = $page * $CFG->commentsperpage;
404 $sql = "SELECT c.id, c.userid, c.content, c.format, c.timecreated, u.picture, u.imagealt, u.username, u.firstname, u.lastname
405 FROM {comments} c, {user} u WHERE u.id=c.userid AND c.contextid=? AND c.commentarea=? AND c.itemid=?
406 ORDER BY c.timecreated DESC";
407 $params[] = $this->contextid;
408 $params[] = $this->commentarea;
409 $params[] = $this->itemid;
410
411 $comments = array();
412 $candelete = has_capability('moodle/comment:delete', $this->context);
413 if ($records = $DB->get_records_sql($sql, $params, $start, $CFG->commentsperpage)) {
414 foreach ($records as &$c) {
866354a9 415 $url = $CFG->httpswwwroot.'/user/view.php?id='.$c->userid.'&amp;course='.$this->courseid;
36051c9e
DC
416 $c->username = '<a href="'.$url.'">'.fullname($c).'</a>';
417 $c->time = userdate($c->timecreated, get_string('strftimerecent', 'langconfig'));
418 $user = new stdclass;
419 $user->id = $c->userid;
420 $user->picture = $c->picture;
421 $user->firstname = $c->firstname;
422 $user->lastname = $c->lastname;
423 $user->imagealt = $c->imagealt;
424 $c->content = format_text($c->content, $c->format);
425 $c->avatar = $OUTPUT->user_picture($user, array('size'=>18));
426 if (($USER->id == $c->userid) || !empty($candelete)) {
427 $c->delete = true;
428 }
429 $comments[] = $c;
430 }
431 }
36051c9e
DC
432 if (!empty($this->plugintype)) {
433 // moodle module will filter comments
866354a9 434 $comments = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'display', array($comments, $this->args), $comments);
36051c9e
DC
435 }
436
437 return $comments;
438 }
439
440 public function count() {
1bcb7eb5 441 global $DB;
36051c9e
DC
442 if ($count = $DB->count_records('comments', array('itemid'=>$this->itemid, 'commentarea'=>$this->commentarea, 'contextid'=>$this->context->id))) {
443 return $count;
444 } else {
445 return 0;
446 }
447 }
448
449 public function get_pagination($page = 0) {
450 global $DB, $CFG, $OUTPUT;
451 $count = $this->count();
452 $pages = (int)ceil($count/$CFG->commentsperpage);
453 if ($pages == 1 || $pages == 0) {
454 return '';
455 }
456 if (!empty(self::$nonjs)) {
457 // used in non-js interface
a5306210 458 return $OUTPUT->paging_bar($count, $page, $CFG->commentsperpage, $this->link, 'comment_page');
36051c9e
DC
459 } else {
460 // return ajax paging bar
461 $str = '';
3e34183a 462 $str .= '<div class="comment-paging" id="comment-pagination-'.$this->cid.'">';
36051c9e 463 for ($p=0; $p<$pages; $p++) {
36051c9e 464 if ($p == $page) {
c794595d
DC
465 $class = 'curpage';
466 } else {
467 $class = 'pageno';
1bcb7eb5 468 }
1150c1bd 469 $str .= '<a href="#" class="'.$class.'" id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
36051c9e
DC
470 }
471 $str .= '</div>';
472 }
473 return $str;
474 }
475
476 /**
477 * Add a new comment
478 * @param string $content
479 * @return mixed
480 */
481 public function add($content, $format = FORMAT_MOODLE) {
482 global $CFG, $DB, $USER, $OUTPUT;
483 if (empty($this->postcap)) {
484 throw new comment_exception('nopermissiontocomment');
485 }
486 $now = time();
487 $newcmt = new stdclass;
488 $newcmt->contextid = $this->contextid;
489 $newcmt->commentarea = $this->commentarea;
490 $newcmt->itemid = $this->itemid;
491 $newcmt->content = $content;
492 $newcmt->format = $format;
493 $newcmt->userid = $USER->id;
494 $newcmt->timecreated = $now;
495
496 if (!empty($this->plugintype)) {
497 // moodle module will check content
866354a9 498 $ret = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'add', array(&$newcmt, $this->args), true);
36051c9e
DC
499 if (!$ret) {
500 throw new comment_exception('modulererejectcomment');
1bcb7eb5 501 }
502 }
36051c9e
DC
503
504 $cmt_id = $DB->insert_record('comments', $newcmt);
505 if (!empty($cmt_id)) {
506 $newcmt->id = $cmt_id;
507 $newcmt->time = userdate($now, get_string('strftimerecent', 'langconfig'));
508 $newcmt->username = fullname($USER);
509 $newcmt->content = format_text($newcmt->content);
510 $newcmt->avatar = $OUTPUT->user_picture($USER, array('size'=>16));
511 return $newcmt;
512 } else {
513 throw new comment_exception('dbupdatefailed');
514 }
515 }
516
517 /**
518 * delete by context, commentarea and itemid
519 *
520 */
521 public function delete_comments() {
522 global $DB;
b9a689e8 523 $DB->delete_records('comments', array(
36051c9e
DC
524 'contextid'=>$this->context->id,
525 'commentarea'=>$this->commentarea,
526 'itemid'=>$this->itemid)
527 );
b9a689e8 528 return true;
36051c9e
DC
529 }
530
531 /**
532 * Delete a comment
533 * @param int $commentid
534 * @return mixed
535 */
536 public function delete($commentid) {
537 global $DB, $USER;
538 $candelete = has_capability('moodle/comment:delete', $this->context);
539 if (!$comment = $DB->get_record('comments', array('id'=>$commentid))) {
540 throw new comment_exception('dbupdatefailed');
541 }
542 if (!($USER->id == $comment->userid || !empty($candelete))) {
543 throw new comment_exception('nopermissiontocomment');
544 }
b9a689e8
DC
545 $DB->delete_records('comments', array('id'=>$commentid));
546 return true;
36051c9e
DC
547 }
548
76951100
DC
549 /**
550 * Print comments
551 * @param int $page
552 * @param boolean $return return comments list string or print it out
553 * @param boolean $nonjs print nonjs comments list or not?
554 * @return mixed
555 */
556 public function print_comments($page = 0, $return = true, $nonjs = true) {
5dce9d1b 557 global $DB, $CFG, $PAGE;
36051c9e 558 $html = '';
866354a9
DC
559 if (!(self::$comment_itemid == $this->itemid &&
560 self::$comment_context == $this->context->id &&
561 self::$comment_area == $this->commentarea)) {
36051c9e
DC
562 $page = 0;
563 }
564 $comments = $this->get_comments($page);
565
76951100
DC
566 $html = '';
567 if ($nonjs) {
568 $html .= '<h3>'.get_string('comments').'</h3>';
569 $html .= "<ul id='comment-list-$this->cid' class='comment-list'>";
570 }
36051c9e
DC
571 $results = array();
572 $list = '';
76951100 573
36051c9e 574 foreach ($comments as $cmt) {
76951100 575 $list = '<li id="comment-'.$cmt->id.'-'.$this->cid.'">'.$this->print_comment($cmt, $nonjs).'</li>' . $list;
36051c9e
DC
576 }
577 $html .= $list;
76951100
DC
578 if ($nonjs) {
579 $html .= '</ul>';
3e34183a 580 $html .= $this->get_pagination($page);
76951100 581 }
36051c9e 582 $sesskey = sesskey();
5dce9d1b 583 $returnurl = $PAGE->url;
36051c9e 584 $strsubmit = get_string('submit');
76951100 585 if ($nonjs) {
36051c9e
DC
586 $html .= <<<EOD
587<form method="POST" action="{$CFG->wwwroot}/comment/comment_post.php">
76951100 588<textarea name="content" rows="2"></textarea>
36051c9e
DC
589<input type="hidden" name="contextid" value="$this->contextid" />
590<input type="hidden" name="action" value="add" />
591<input type="hidden" name="area" value="$this->commentarea" />
592<input type="hidden" name="itemid" value="$this->itemid" />
866354a9 593<input type="hidden" name="courseid" value="{$this->courseid}" />
36051c9e
DC
594<input type="hidden" name="sesskey" value="{$sesskey}" />
595<input type="hidden" name="returnurl" value="{$returnurl}" />
596<input type="submit" value="{$strsubmit}" />
597</form>
598EOD;
76951100 599 }
36051c9e
DC
600 if ($return) {
601 return $html;
602 } else {
603 echo $html;
604 }
605 }
606
76951100
DC
607 public function print_comment($cmt, $nonjs = true) {
608 global $OUTPUT;
36051c9e
DC
609 $patterns = array();
610 $replacements = array();
611
76951100 612 if (!empty($cmt->delete) && empty($nonjs)) {
1150c1bd 613 $cmt->content = '<div class="comment-delete"><a href="#" id ="comment-delete-'.$this->cid.'-'.$cmt->id.'"><img src="'.$OUTPUT->pix_url('t/delete').'" /></a></div>' . $cmt->content;
76951100
DC
614 // add the button
615 }
36051c9e
DC
616 $patterns[] = '___picture___';
617 $patterns[] = '___name___';
618 $patterns[] = '___content___';
619 $patterns[] = '___time___';
620 $replacements[] = $cmt->avatar;
621 $replacements[] = fullname($cmt);
622 $replacements[] = $cmt->content;
623 $replacements[] = userdate($cmt->timecreated, get_string('strftimerecent', 'langconfig'));
624
625 // use html template to format a single comment.
626 return str_replace($patterns, $replacements, $this->template);
627 }
628}
629
630class comment_exception extends moodle_exception {
631 public $message;
632 function __construct($errorcode) {
633 $this->errorcode = $errorcode;
634 $this->message = get_string($errorcode, 'error');
1bcb7eb5 635 }
636}