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 $this->component = $component;
225 list($this->plugintype, $this->pluginname) = normalize_component($component);
229 public function set_view_permission($value) {
230 $this->viewcap = $value;
233 public function set_post_permission($value) {
234 $this->postcap = $value;
238 * check posting comments permission
239 * It will check based on user roles and ask modules
240 * If you need to check permission by modules, a
241 * function named $pluginname_check_comment_post must be implemented
243 private function check_permissions() {
245 $this->postcap = has_capability('moodle/comment:post', $this->context);
246 $this->viewcap = has_capability('moodle/comment:view', $this->context);
247 if (!empty($this->plugintype)) {
248 $permissions = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'permissions', array($this->args), array('post'=>true, 'view'=>true));
249 $this->postcap = $this->postcap && $permissions['post'];
250 $this->viewcap = $this->viewcap && $permissions['view'];
255 * Prepare comment code in html
256 * @param boolean $return
259 public function output($return = true) {
260 global $PAGE, $OUTPUT;
261 static $template_printed;
263 $this->link = $PAGE->url;
264 $murl = new moodle_url($this->link);
265 $murl->remove_params('nonjscomment');
266 $murl->param('nonjscomment', 'true');
267 $murl->param('comment_itemid', $this->itemid);
268 $murl->param('comment_context', $this->context->id);
269 $murl->param('comment_area', $this->commentarea);
270 $murl->remove_params('comment_page');
271 $this->link = $murl->out();
273 $options = new stdclass;
274 $options->client_id = $this->cid;
275 $options->commentarea = $this->commentarea;
276 $options->itemid = $this->itemid;
278 $options->courseid = $this->courseid;
279 $options->contextid = $this->contextid;
280 $options->env = $this->env;
281 $options->component = $this->component;
282 if ($this->env == 'block_comments') {
283 $options->notoggle = true;
284 $options->autostart = true;
287 $PAGE->requires->js_init_call('M.core_comment.init', array($options), true);
289 if (!empty(self::$nonjs)) {
290 // return non js comments interface
291 return $this->print_comments(self::$comment_page, $return, true);
294 $strsubmit = get_string('savecomment');
295 $strcancel = get_string('cancel');
296 $strshowcomments = get_string('showcommentsnonjs');
297 $sesskey = sesskey();
299 // print html template
300 // Javascript will use the template to render new comments
301 if (empty($template_printed) && !empty($this->viewcap)) {
302 $html .= '<div style="display:none" id="cmt-tmpl">' . $this->template . '</div>';
303 $template_printed = true;
306 if (!empty($this->viewcap)) {
307 // print commenting icon and tooltip
308 $icon = $OUTPUT->pix_url('t/collapsed');
310 <div class="mdl-left">
312 <a href="{$this->link}">{$strshowcomments}</a>
314 <a id="comment-link-{$this->cid}" class="comment-link" href="#">
315 <img id="comment-img-{$this->cid}" src="$icon" alt="{$this->linktext}" title="{$this->linktext}" />
316 <span id="comment-link-text-{$this->cid}">{$this->linktext} {$this->count}</span>
318 <div id="comment-ctrl-{$this->cid}" class="comment-ctrl">
319 <ul id="comment-list-{$this->cid}" class="comment-list">
321 // in comments block, we print comments list right away
322 if ($this->env == 'block_comments') {
323 $html .= $this->print_comments(0, true, false);
325 $html .= $this->get_pagination(0);
329 <div id="comment-pagination-{$this->cid}" class="comment-pagination"></div>
333 // print posting textarea
334 if (!empty($this->postcap)) {
336 <div class='comment-area'>
338 <textarea name="content" rows="2" id="dlg-content-{$this->cid}"></textarea>
340 <div class="fd" id="comment-action-{$this->cid}">
341 <a href="#" id="comment-action-post-{$this->cid}"> {$strsubmit} </a>
343 if ($this->env != 'block_comments') {
346 <a href="#" id="comment-action-cancel-{$this->cid}"> {$strcancel} </a>
353 <div class="clearer"></div>
358 </div><!-- end of comment-ctrl -->
373 * Return matched comments
378 public function get_comments($page = '') {
379 global $DB, $CFG, $USER, $OUTPUT;
380 if (empty($this->viewcap)) {
383 if (!is_numeric($page)) {
388 $start = $page * $CFG->commentsperpage;
389 $ufields = user_picture::fields('u', array('username'));
390 $sql = "SELECT $ufields, c.id AS cid, c.content AS ccontent, c.format AS cformat, c.timecreated AS ctimecreated
392 JOIN {user} u ON u.id = c.userid
393 WHERE c.contextid = :contextid AND c.commentarea = :commentarea AND c.itemid = :itemid
394 ORDER BY c.timecreated DESC";
395 $params['contextid'] = $this->contextid;
396 $params['commentarea'] = $this->commentarea;
397 $params['itemid'] = $this->itemid;
400 $candelete = has_capability('moodle/comment:delete', $this->context);
401 $rs = $DB->get_recordset_sql($sql, $params, $start, $CFG->commentsperpage);
402 foreach ($rs as $u) {
405 $c->content = $u->ccontent;
406 $c->format = $u->cformat;
407 $c->timecreated = $u->ctimecreated;
408 $url = new moodle_url('/user/view.php', array('id'=>$u->id, 'course'=>$this->courseid));
409 $c->username = $u->username;
410 $c->profileurl = $url;
411 $c->fullname = fullname($u);
412 $c->time = userdate($c->timecreated, get_string('strftimerecent', 'langconfig'));
413 $c->content = format_text($c->content, $c->format);
415 $c->avatar = $OUTPUT->user_picture($u, array('size'=>18));
416 if (($USER->id == $u->id) || !empty($candelete)) {
423 if (!empty($this->plugintype)) {
424 // moodle module will filter comments
425 $comments = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'display', array($comments, $this->args), $comments);
431 public function count() {
433 if ($count = $DB->count_records('comments', array('itemid'=>$this->itemid, 'commentarea'=>$this->commentarea, 'contextid'=>$this->context->id))) {
440 public function get_pagination($page = 0) {
441 global $DB, $CFG, $OUTPUT;
442 $count = $this->count();
443 $pages = (int)ceil($count/$CFG->commentsperpage);
444 if ($pages == 1 || $pages == 0) {
447 if (!empty(self::$nonjs)) {
448 // used in non-js interface
449 return $OUTPUT->paging_bar($count, $page, $CFG->commentsperpage, $this->link, 'comment_page');
451 // return ajax paging bar
453 $str .= '<div class="comment-paging" id="comment-pagination-'.$this->cid.'">';
454 for ($p=0; $p<$pages; $p++) {
460 $str .= '<a href="#" class="'.$class.'" id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
469 * @param string $content
472 public function add($content, $format = FORMAT_MOODLE) {
473 global $CFG, $DB, $USER, $OUTPUT;
474 if (empty($this->postcap)) {
475 throw new comment_exception('nopermissiontocomment');
478 $newcmt = new stdclass;
479 $newcmt->contextid = $this->contextid;
480 $newcmt->commentarea = $this->commentarea;
481 $newcmt->itemid = $this->itemid;
482 $newcmt->content = $content;
483 $newcmt->format = $format;
484 $newcmt->userid = $USER->id;
485 $newcmt->timecreated = $now;
487 if (!empty($this->plugintype)) {
488 // moodle module will check content
489 $ret = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'add', array(&$newcmt, $this->args), true);
491 throw new comment_exception('modulererejectcomment');
495 $cmt_id = $DB->insert_record('comments', $newcmt);
496 if (!empty($cmt_id)) {
497 $newcmt->id = $cmt_id;
498 $newcmt->time = userdate($now, get_string('strftimerecent', 'langconfig'));
499 $newcmt->username = $USER->username;
500 $newcmt->fullname = fullname($USER);
501 $url = new moodle_url('/user/view.php', array('id'=>$USER->id, 'course'=>$this->courseid));
502 $newcmt->profileurl = $url->out();
503 $newcmt->content = format_text($newcmt->content, $format);
504 $newcmt->avatar = $OUTPUT->user_picture($USER, array('size'=>16));
507 throw new comment_exception('dbupdatefailed');
512 * delete by context, commentarea and itemid
513 * @param object $param {
514 * contextid => int the context in which the comments exist [required]
515 * commentarea => string the comment area [optional]
516 * itemid => int comment itemid [optional]
520 public function delete_comments($param) {
522 $param = (array)$param;
523 if (empty($param['contextid'])) {
526 $DB->delete_records('comments', $param);
532 * @param int $commentid
535 public function delete($commentid) {
537 $candelete = has_capability('moodle/comment:delete', $this->context);
538 if (!$comment = $DB->get_record('comments', array('id'=>$commentid))) {
539 throw new comment_exception('dbupdatefailed');
541 if (!($USER->id == $comment->userid || !empty($candelete))) {
542 throw new comment_exception('nopermissiontocomment');
544 $DB->delete_records('comments', array('id'=>$commentid));
551 * @param boolean $return return comments list string or print it out
552 * @param boolean $nonjs print nonjs comments list or not?
555 public function print_comments($page = 0, $return = true, $nonjs = true) {
556 global $DB, $CFG, $PAGE;
558 if (!(self::$comment_itemid == $this->itemid &&
559 self::$comment_context == $this->context->id &&
560 self::$comment_area == $this->commentarea)) {
563 $comments = $this->get_comments($page);
567 $html .= '<h3>'.get_string('comments').'</h3>';
568 $html .= "<ul id='comment-list-$this->cid' class='comment-list'>";
573 foreach ($comments as $cmt) {
574 $list = '<li id="comment-'.$cmt->id.'-'.$this->cid.'">'.$this->print_comment($cmt, $nonjs).'</li>' . $list;
579 $html .= $this->get_pagination($page);
581 $sesskey = sesskey();
582 $returnurl = $PAGE->url;
583 $strsubmit = get_string('submit');
586 <form method="POST" action="{$CFG->wwwroot}/comment/comment_post.php">
587 <textarea name="content" rows="2"></textarea>
588 <input type="hidden" name="contextid" value="$this->contextid" />
589 <input type="hidden" name="action" value="add" />
590 <input type="hidden" name="area" value="$this->commentarea" />
591 <input type="hidden" name="itemid" value="$this->itemid" />
592 <input type="hidden" name="courseid" value="{$this->courseid}" />
593 <input type="hidden" name="sesskey" value="{$sesskey}" />
594 <input type="hidden" name="returnurl" value="{$returnurl}" />
595 <input type="submit" value="{$strsubmit}" />
606 public function print_comment($cmt, $nonjs = true) {
609 $replacements = array();
611 if (!empty($cmt->delete) && empty($nonjs)) {
612 $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;
615 $patterns[] = '___picture___';
616 $patterns[] = '___name___';
617 $patterns[] = '___content___';
618 $patterns[] = '___time___';
619 $replacements[] = $cmt->avatar;
620 $replacements[] = html_writer::link($cmt->profileurl, $cmt->fullname);
621 $replacements[] = $cmt->content;
622 $replacements[] = userdate($cmt->timecreated, get_string('strftimerecent', 'langconfig'));
624 // use html template to format a single comment.
625 return str_replace($patterns, $replacements, $this->template);
629 class comment_exception extends moodle_exception {
631 function __construct($errorcode) {
632 $this->errorcode = $errorcode;
633 $this->message = get_string($errorcode, 'error');