3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * Comment is helper class to add/delete comments anywhere in moodle
22 * @copyright 2010 Dongsheng Cai <dongsheng@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 * there may be several comment box in one page
33 * so we need a client_id to recognize them
39 * commentarea is used to specify different
40 * parts shared the same itemid
45 * itemid is used to associate with commenting content
51 * this html snippet will be used as a template
52 * to build comment content
59 * course module object, only be used to help find pluginname automatically
60 * if pluginname is specified, it won't be used at all
66 * When used in module, it is recommended to use it
73 * to tell comments api where it is used
78 * to costomize link text
83 // static variable will be used by non-js comments UI
84 private static $nonjs = false;
85 private static $comment_itemid = null;
86 private static $comment_context = null;
87 private static $comment_area = null;
88 private static $comment_page = null;
90 * Construct function of comment class, initialise
92 * @param object $options
94 public function __construct($options) {
97 if (empty($CFG->commentsperpage)) {
98 $CFG->commentsperpage = 15;
101 $this->viewcap = false;
102 $this->postcap = false;
105 if (!empty($options->client_id)) {
106 $this->cid = $options->client_id;
108 $this->cid = uniqid();
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);
119 print_error('invalidcontext');
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;
130 if (!empty($options->pluginname)) {
131 $this->pluginname = $options->pluginname;
134 // setup coursemodule
135 if (!empty($options->cm)) {
136 $this->cm = $options->cm;
142 if (!empty($options->area)) {
143 $this->commentarea = $options->area;
147 if (!empty($options->itemid)) {
148 $this->itemid = $options->itemid;
154 if (!empty($options->env)) {
155 $this->env = $options->env;
160 // setup customized linktext
161 if (!empty($options->linktext)) {
162 $this->linktext = $options->linktext;
164 $this->linktext = get_string('comments');
166 // setting post and view permissions
167 $this->check_permissions();
169 if (!empty($options->showcount)) {
170 $count = $this->count();
174 $this->count = '('.$count.')';
180 $this->setup_plugin();
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;
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>
198 if (!empty($this->plugintype)) {
199 $this->template = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'template', $this->args, $this->template);
206 * Receive nonjs comment parameters
208 public static function init() {
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);
214 self::$comment_page = optional_param('comment_page', '', PARAM_INT);
215 self::$comment_area = optional_param('comment_area', '', PARAM_ALPHAEXT);
217 $PAGE->requires->string_for_js('addcomment', 'moodle');
218 $PAGE->requires->string_for_js('deletecomment', 'moodle');
219 $PAGE->requires->string_for_js('comments', 'moodle');
223 * Setup plugin type and plugin name
225 private function setup_plugin() {
227 // blog needs to set env as "blog"
228 if ($this->env == 'blog') {
229 $this->plugintype = 'moodle';
230 $this->pluginname = 'blog';
232 // tag page needs to set env as "tag"
233 if ($this->env == 'tag') {
234 $this->plugintype = 'moodle';
235 $this->pluginname = 'tag';
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;
244 if ($this->context->contextlevel == CONTEXT_MODULE) {
245 $this->plugintype = 'mod';
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);
252 $this->modinfo = get_fast_modinfo($this->course);
253 $this->pluginname = $this->modinfo->cms[$this->cm->id]->modname;
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
264 private function check_permissions() {
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)) {
269 $permissions = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'permissions', $this->args, array('post'=>true, 'view'=>true));
270 $this->postcap = $this->postcap && $permissions['post'];
271 $this->viewcap = $this->viewcap && $permissions['view'];
276 * Prepare comment code in html
277 * @param boolean $return
280 public function output($return = true) {
281 global $PAGE, $OUTPUT;
282 static $template_printed;
284 $this->link = $PAGE->url;
285 $murl = new moodle_url($this->link);
286 $murl->remove_params('nonjscomment');
287 $murl->param('nonjscomment', 'true');
288 $murl->param('comment_itemid', $this->itemid);
289 $murl->param('comment_context', $this->context->id);
290 $murl->param('comment_area', $this->commentarea);
291 $murl->remove_params('comment_page');
292 $this->link = $murl->out();
294 $options = new stdclass;
295 $options->client_id = $this->cid;
296 $options->commentarea = $this->commentarea;
297 $options->itemid = $this->itemid;
299 $options->courseid = $this->courseid;
300 $options->contextid = $this->contextid;
301 $options->env = $this->env;
302 if ($this->env == 'block_comments') {
303 $options->autostart = true;
304 $options->notoggle = true;
307 $PAGE->requires->js_init_call('M.core_comment.init', array($options), true);
309 if (!empty(self::$nonjs)) {
310 // return non js comments interface
311 return $this->print_comments(self::$comment_page, $return, true);
314 $strsubmit = get_string('submit');
315 $strcancel = get_string('cancel');
316 $sesskey = sesskey();
318 // print html template
319 // Javascript will use the template to render new comments
320 if (empty($template_printed) && !empty($this->viewcap)) {
321 $html .= '<div style="display:none" id="cmt-tmpl">' . $this->template . '</div>';
322 $template_printed = true;
325 if (!empty($this->viewcap)) {
326 // print commenting icon and tooltip
327 $icon = $OUTPUT->pix_url('t/collapsed');
329 <div class="mdl-left">
330 <a id="comment-link-{$this->cid}" href="{$this->link}">
331 <img id="comment-img-{$this->cid}" src="$icon" alt="{$this->linktext}" title="{$this->linktext}" />
332 <span id="comment-link-text-{$this->cid}">{$this->linktext} {$this->count}</span>
334 <div id="comment-ctrl-{$this->cid}" class="comment-ctrl">
335 <ul id="comment-list-{$this->cid}" class="comment-list">
337 // in comments block, we print comments list right away
338 if ($this->env == 'block_comments') {
339 $html .= $this->print_comments(0, true, false);
341 $html .= $this->get_pagination(0);
345 <div id="comment-pagination-{$this->cid}" class="comment-pagination"></div>
349 // print posting textarea
350 if (!empty($this->postcap)) {
352 <div class='comment-area'>
354 <textarea name="content" rows="2" id="dlg-content-{$this->cid}"></textarea>
356 <div class="fd" id="comment-action-{$this->cid}">
357 <a href="#" id="comment-action-post-{$this->cid}"> {$strsubmit} </a>
359 if ($this->env != 'block_comments') {
362 <a href="#" id="comment-action-cancel-{$this->cid}"> {$strcancel} </a>
369 <div class="clearer"></div>
374 </div><!-- end of comment-ctrl -->
389 * Return matched comments
393 public function get_comments($page = '') {
394 global $DB, $CFG, $USER, $OUTPUT;
395 if (empty($this->viewcap)) {
398 if (!is_numeric($page)) {
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;
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) {
415 $url = $CFG->httpswwwroot.'/user/view.php?id='.$c->userid.'&course='.$this->courseid;
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)) {
432 if (!empty($this->plugintype)) {
433 // moodle module will filter comments
434 $comments = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'display', array($comments, $this->args), $comments);
440 public function count() {
442 if ($count = $DB->count_records('comments', array('itemid'=>$this->itemid, 'commentarea'=>$this->commentarea, 'contextid'=>$this->context->id))) {
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) {
456 if (!empty(self::$nonjs)) {
457 // used in non-js interface
458 return $OUTPUT->paging_bar($count, $page, $CFG->commentsperpage, $this->link, 'comment_page');
460 // return ajax paging bar
462 $str .= '<div class="comment-paging" id="comment-pagination-'.$this->cid.'">';
463 for ($p=0; $p<$pages; $p++) {
469 $str .= '<a href="#" class="'.$class.'" id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
478 * @param string $content
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');
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;
496 if (!empty($this->plugintype)) {
497 // moodle module will check content
498 $ret = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'add', array(&$newcmt, $this->args), true);
500 throw new comment_exception('modulererejectcomment');
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));
513 throw new comment_exception('dbupdatefailed');
518 * delete by context, commentarea and itemid
521 public function delete_comments() {
523 $DB->delete_records('comments', array(
524 'contextid'=>$this->context->id,
525 'commentarea'=>$this->commentarea,
526 'itemid'=>$this->itemid)
533 * @param int $commentid
536 public function delete($commentid) {
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');
542 if (!($USER->id == $comment->userid || !empty($candelete))) {
543 throw new comment_exception('nopermissiontocomment');
545 $DB->delete_records('comments', array('id'=>$commentid));
552 * @param boolean $return return comments list string or print it out
553 * @param boolean $nonjs print nonjs comments list or not?
556 public function print_comments($page = 0, $return = true, $nonjs = true) {
557 global $DB, $CFG, $PAGE;
559 if (!(self::$comment_itemid == $this->itemid &&
560 self::$comment_context == $this->context->id &&
561 self::$comment_area == $this->commentarea)) {
564 $comments = $this->get_comments($page);
568 $html .= '<h3>'.get_string('comments').'</h3>';
569 $html .= "<ul id='comment-list-$this->cid' class='comment-list'>";
574 foreach ($comments as $cmt) {
575 $list = '<li id="comment-'.$cmt->id.'-'.$this->cid.'">'.$this->print_comment($cmt, $nonjs).'</li>' . $list;
580 $html .= $this->get_pagination($page);
582 $sesskey = sesskey();
583 $returnurl = $PAGE->url;
584 $strsubmit = get_string('submit');
587 <form method="POST" action="{$CFG->wwwroot}/comment/comment_post.php">
588 <textarea name="content" rows="2"></textarea>
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" />
593 <input type="hidden" name="courseid" value="{$this->courseid}" />
594 <input type="hidden" name="sesskey" value="{$sesskey}" />
595 <input type="hidden" name="returnurl" value="{$returnurl}" />
596 <input type="submit" value="{$strsubmit}" />
607 public function print_comment($cmt, $nonjs = true) {
610 $replacements = array();
612 if (!empty($cmt->delete) && empty($nonjs)) {
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;
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'));
625 // use html template to format a single comment.
626 return str_replace($patterns, $replacements, $this->template);
630 class comment_exception extends moodle_exception {
632 function __construct($errorcode) {
633 $this->errorcode = $errorcode;
634 $this->message = get_string($errorcode, 'error');