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');
122 if (!empty($options->component)) {
123 $this->set_component($options->component);
127 // course will be used to generate user profile link
128 if (!empty($options->course)) {
129 $this->courseid = $options->course->id;
130 } else if (!empty($options->courseid)) {
131 $this->courseid = $options->courseid;
133 $this->courseid = SITEID;
136 // setup coursemodule
137 if (!empty($options->cm)) {
138 $this->cm = $options->cm;
144 if (!empty($options->area)) {
145 $this->commentarea = $options->area;
149 if (!empty($options->itemid)) {
150 $this->itemid = $options->itemid;
156 if (!empty($options->env)) {
157 $this->env = $options->env;
162 // setup customized linktext
163 if (!empty($options->linktext)) {
164 $this->linktext = $options->linktext;
166 $this->linktext = get_string('comments');
169 if (!empty($options->showcount)) {
170 $count = $this->count();
174 $this->count = '('.$count.')';
180 // setup options for callback functions
181 $this->args = new stdclass;
182 $this->args->context = $this->context;
183 $this->args->courseid = $this->courseid;
184 $this->args->cm = $this->cm;
185 $this->args->commentarea = $this->commentarea;
186 $this->args->itemid = $this->itemid;
188 // setting post and view permissions
189 $this->check_permissions();
192 $this->template = <<<EOD
193 <div class="comment-userpicture">___picture___</div>
194 <div class="comment-content">
195 ___name___ - <span>___time___</span>
196 <div>___content___</div>
199 if (!empty($this->plugintype)) {
200 $this->template = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'template', $this->args, $this->template);
207 * Receive nonjs comment parameters
209 public static function init() {
211 // setup variables for non-js interface
212 self::$nonjs = optional_param('nonjscomment', '', PARAM_ALPHA);
213 self::$comment_itemid = optional_param('comment_itemid', '', PARAM_INT);
214 self::$comment_context = optional_param('comment_context', '', PARAM_INT);
215 self::$comment_page = optional_param('comment_page', '', PARAM_INT);
216 self::$comment_area = optional_param('comment_area', '', PARAM_ALPHAEXT);
218 $PAGE->requires->string_for_js('addcomment', 'moodle');
219 $PAGE->requires->string_for_js('deletecomment', 'moodle');
220 $PAGE->requires->string_for_js('comments', 'moodle');
223 public function set_component($component) {
224 list($this->plugintype, $this->pluginname) = normalize_component($component);
228 public function set_view_permission($value) {
229 $this->viewcap = $value;
232 public function set_post_permission($value) {
233 $this->postcap = $value;
237 * check posting comments permission
238 * It will check based on user roles and ask modules
239 * If you need to check permission by modules, a
240 * function named $pluginname_check_comment_post must be implemented
242 private function check_permissions() {
244 $this->postcap = has_capability('moodle/comment:post', $this->context);
245 $this->viewcap = has_capability('moodle/comment:view', $this->context);
246 if (!empty($this->plugintype)) {
247 $permissions = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'permissions', array($this->args), array('post'=>true, 'view'=>true));
248 $this->postcap = $this->postcap && $permissions['post'];
249 $this->viewcap = $this->viewcap && $permissions['view'];
254 * Prepare comment code in html
255 * @param boolean $return
258 public function output($return = true) {
259 global $PAGE, $OUTPUT;
260 static $template_printed;
262 $this->link = $PAGE->url;
263 $murl = new moodle_url($this->link);
264 $murl->remove_params('nonjscomment');
265 $murl->param('nonjscomment', 'true');
266 $murl->param('comment_itemid', $this->itemid);
267 $murl->param('comment_context', $this->context->id);
268 $murl->param('comment_area', $this->commentarea);
269 $murl->remove_params('comment_page');
270 $this->link = $murl->out();
272 $options = new stdclass;
273 $options->client_id = $this->cid;
274 $options->commentarea = $this->commentarea;
275 $options->itemid = $this->itemid;
277 $options->courseid = $this->courseid;
278 $options->contextid = $this->contextid;
279 $options->env = $this->env;
280 if ($this->env == 'block_comments') {
281 $options->notoggle = true;
284 $PAGE->requires->js_init_call('M.core_comment.init', array($options), true);
286 if (!empty(self::$nonjs)) {
287 // return non js comments interface
288 return $this->print_comments(self::$comment_page, $return, true);
291 $strsubmit = get_string('savecomment');
292 $strcancel = get_string('cancel');
293 $strshowcomments = get_string('showcommentsnonjs');
294 $sesskey = sesskey();
296 // print html template
297 // Javascript will use the template to render new comments
298 if (empty($template_printed) && !empty($this->viewcap)) {
299 $html .= '<div style="display:none" id="cmt-tmpl">' . $this->template . '</div>';
300 $template_printed = true;
303 if (!empty($this->viewcap)) {
304 // print commenting icon and tooltip
305 $icon = $OUTPUT->pix_url('t/collapsed');
307 <div class="mdl-left">
309 <a href="{$this->link}">{$strshowcomments}</a>
311 <a id="comment-link-{$this->cid}" class="comment-link" href="#">
312 <img id="comment-img-{$this->cid}" src="$icon" alt="{$this->linktext}" title="{$this->linktext}" />
313 <span id="comment-link-text-{$this->cid}">{$this->linktext} {$this->count}</span>
315 <div id="comment-ctrl-{$this->cid}" class="comment-ctrl">
316 <ul id="comment-list-{$this->cid}" class="comment-list">
318 // in comments block, we print comments list right away
319 if ($this->env == 'block_comments') {
320 $html .= $this->print_comments(0, true, false);
322 $html .= $this->get_pagination(0);
326 <div id="comment-pagination-{$this->cid}" class="comment-pagination"></div>
330 // print posting textarea
331 if (!empty($this->postcap)) {
333 <div class='comment-area'>
335 <textarea name="content" rows="2" id="dlg-content-{$this->cid}"></textarea>
337 <div class="fd" id="comment-action-{$this->cid}">
338 <a href="#" id="comment-action-post-{$this->cid}"> {$strsubmit} </a>
340 if ($this->env != 'block_comments') {
343 <a href="#" id="comment-action-cancel-{$this->cid}"> {$strcancel} </a>
350 <div class="clearer"></div>
355 </div><!-- end of comment-ctrl -->
370 * Return matched comments
375 public function get_comments($page = '') {
376 global $DB, $CFG, $USER, $OUTPUT;
377 if (empty($this->viewcap)) {
380 if (!is_numeric($page)) {
385 $start = $page * $CFG->commentsperpage;
386 $ufields = user_picture::fields('u', array('username'));
387 $sql = "SELECT $ufields, c.id AS cid, c.content AS ccontent, c.format AS cformat, c.timecreated AS ctimecreated
389 JOIN {user} u ON u.id = c.userid
390 WHERE c.contextid = :contextid AND c.commentarea = :commentarea AND c.itemid = :itemid
391 ORDER BY c.timecreated DESC";
392 $params['contextid'] = $this->contextid;
393 $params['commentarea'] = $this->commentarea;
394 $params['itemid'] = $this->itemid;
397 $candelete = has_capability('moodle/comment:delete', $this->context);
398 $rs = $DB->get_recordset_sql($sql, $params, $start, $CFG->commentsperpage);
399 foreach ($rs as $u) {
402 $c->content = $u->ccontent;
403 $c->format = $u->cformat;
404 $c->timecreated = $u->ctimecreated;
405 $url = new moodle_url('/user/view.php', array('id'=>$u->id, 'course'=>$this->courseid));
406 $c->username = $u->username;
407 $c->profileurl = $url;
408 $c->fullname = fullname($u);
409 $c->time = userdate($c->timecreated, get_string('strftimerecent', 'langconfig'));
410 $c->content = format_text($c->content, $c->format);
412 $c->avatar = $OUTPUT->user_picture($u, array('size'=>18));
413 if (($USER->id == $u->id) || !empty($candelete)) {
420 if (!empty($this->plugintype)) {
421 // moodle module will filter comments
422 $comments = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'display', array($comments, $this->args), $comments);
428 public function count() {
430 if ($count = $DB->count_records('comments', array('itemid'=>$this->itemid, 'commentarea'=>$this->commentarea, 'contextid'=>$this->context->id))) {
437 public function get_pagination($page = 0) {
438 global $DB, $CFG, $OUTPUT;
439 $count = $this->count();
440 $pages = (int)ceil($count/$CFG->commentsperpage);
441 if ($pages == 1 || $pages == 0) {
444 if (!empty(self::$nonjs)) {
445 // used in non-js interface
446 return $OUTPUT->paging_bar($count, $page, $CFG->commentsperpage, $this->link, 'comment_page');
448 // return ajax paging bar
450 $str .= '<div class="comment-paging" id="comment-pagination-'.$this->cid.'">';
451 for ($p=0; $p<$pages; $p++) {
457 $str .= '<a href="#" class="'.$class.'" id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
466 * @param string $content
469 public function add($content, $format = FORMAT_MOODLE) {
470 global $CFG, $DB, $USER, $OUTPUT;
471 if (empty($this->postcap)) {
472 throw new comment_exception('nopermissiontocomment');
475 $newcmt = new stdclass;
476 $newcmt->contextid = $this->contextid;
477 $newcmt->commentarea = $this->commentarea;
478 $newcmt->itemid = $this->itemid;
479 $newcmt->content = $content;
480 $newcmt->format = $format;
481 $newcmt->userid = $USER->id;
482 $newcmt->timecreated = $now;
484 if (!empty($this->plugintype)) {
485 // moodle module will check content
486 $ret = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'add', array(&$newcmt, $this->args), true);
488 throw new comment_exception('modulererejectcomment');
492 $cmt_id = $DB->insert_record('comments', $newcmt);
493 if (!empty($cmt_id)) {
494 $newcmt->id = $cmt_id;
495 $newcmt->time = userdate($now, get_string('strftimerecent', 'langconfig'));
496 $newcmt->username = $USER->username;
497 $newcmt->fullname = fullname($USER);
498 $url = new moodle_url('/user/view.php', array('id'=>$USER->id, 'course'=>$this->courseid));
499 $newcmt->profileurl = $url->out();
500 $newcmt->content = format_text($newcmt->content, $format);
501 $newcmt->avatar = $OUTPUT->user_picture($USER, array('size'=>16));
504 throw new comment_exception('dbupdatefailed');
509 * delete by context, commentarea and itemid
510 * @param object $param {
511 * contextid => int the context in which the comments exist [required]
512 * commentarea => string the comment area [optional]
513 * itemid => int comment itemid [optional]
517 public function delete_comments($param) {
519 $param = (array)$param;
520 if (empty($param['contextid'])) {
523 $DB->delete_records('comments', $param);
529 * @param int $commentid
532 public function delete($commentid) {
534 $candelete = has_capability('moodle/comment:delete', $this->context);
535 if (!$comment = $DB->get_record('comments', array('id'=>$commentid))) {
536 throw new comment_exception('dbupdatefailed');
538 if (!($USER->id == $comment->userid || !empty($candelete))) {
539 throw new comment_exception('nopermissiontocomment');
541 $DB->delete_records('comments', array('id'=>$commentid));
548 * @param boolean $return return comments list string or print it out
549 * @param boolean $nonjs print nonjs comments list or not?
552 public function print_comments($page = 0, $return = true, $nonjs = true) {
553 global $DB, $CFG, $PAGE;
555 if (!(self::$comment_itemid == $this->itemid &&
556 self::$comment_context == $this->context->id &&
557 self::$comment_area == $this->commentarea)) {
560 $comments = $this->get_comments($page);
564 $html .= '<h3>'.get_string('comments').'</h3>';
565 $html .= "<ul id='comment-list-$this->cid' class='comment-list'>";
570 foreach ($comments as $cmt) {
571 $list = '<li id="comment-'.$cmt->id.'-'.$this->cid.'">'.$this->print_comment($cmt, $nonjs).'</li>' . $list;
576 $html .= $this->get_pagination($page);
578 $sesskey = sesskey();
579 $returnurl = $PAGE->url;
580 $strsubmit = get_string('submit');
583 <form method="POST" action="{$CFG->wwwroot}/comment/comment_post.php">
584 <textarea name="content" rows="2"></textarea>
585 <input type="hidden" name="contextid" value="$this->contextid" />
586 <input type="hidden" name="action" value="add" />
587 <input type="hidden" name="area" value="$this->commentarea" />
588 <input type="hidden" name="itemid" value="$this->itemid" />
589 <input type="hidden" name="courseid" value="{$this->courseid}" />
590 <input type="hidden" name="sesskey" value="{$sesskey}" />
591 <input type="hidden" name="returnurl" value="{$returnurl}" />
592 <input type="submit" value="{$strsubmit}" />
603 public function print_comment($cmt, $nonjs = true) {
606 $replacements = array();
608 if (!empty($cmt->delete) && empty($nonjs)) {
609 $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;
612 $patterns[] = '___picture___';
613 $patterns[] = '___name___';
614 $patterns[] = '___content___';
615 $patterns[] = '___time___';
616 $replacements[] = $cmt->avatar;
617 $replacements[] = html_writer::link($cmt->profileurl, $cmt->fullname);
618 $replacements[] = $cmt->content;
619 $replacements[] = userdate($cmt->timecreated, get_string('strftimerecent', 'langconfig'));
621 // use html template to format a single comment.
622 return str_replace($patterns, $replacements, $this->template);
626 class comment_exception extends moodle_exception {
628 function __construct($errorcode) {
629 $this->errorcode = $errorcode;
630 $this->message = get_string($errorcode, 'error');