Merge branch 'MDL-51147' of git://github.com/timhunt/moodle
[moodle.git] / comment / lib.php
blobd17d5bac5d40e2d71c34f8a60a65b6ef33a3d753
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes for commenting
20 * @package core
21 * @copyright 2010 Dongsheng Cai {@link http://dongsheng.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 defined('MOODLE_INTERNAL') || die();
26 /**
27 * Comment is helper class to add/delete comments anywhere in moodle
29 * @package core
30 * @category comment
31 * @copyright 2010 Dongsheng Cai {@link http://dongsheng.org}
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 class comment {
35 /** @var int there may be several comment box in one page so we need a client_id to recognize them */
36 private $cid;
37 /** @var string commentarea is used to specify different parts shared the same itemid */
38 private $commentarea;
39 /** @var int itemid is used to associate with commenting content */
40 private $itemid;
41 /** @var string this html snippet will be used as a template to build comment content */
42 private $template;
43 /** @var int The context id for comments */
44 private $contextid;
45 /** @var stdClass The context itself */
46 private $context;
47 /** @var int The course id for comments */
48 private $courseid;
49 /** @var stdClass course module object, only be used to help find pluginname automatically */
50 private $cm;
51 /**
52 * The component that this comment is for.
54 * It is STRONGLY recommended to set this.
55 * Added as a database field in 2.9, old comments will have a null component.
57 * @var string
59 private $component;
60 /** @var string This is calculated by normalising the component */
61 private $pluginname;
62 /** @var string This is calculated by normalising the component */
63 private $plugintype;
64 /** @var bool Whether the user has the required capabilities/permissions to view comments. */
65 private $viewcap = false;
66 /** @var bool Whether the user has the required capabilities/permissions to post comments. */
67 private $postcap = false;
68 /** @var string to customize link text */
69 private $linktext;
70 /** @var bool If set to true then comment sections won't be able to be opened and closed instead they will always be visible. */
71 protected $notoggle = false;
72 /** @var bool If set to true comments are automatically loaded as soon as the page loads. */
73 protected $autostart = false;
74 /** @var bool If set to true the total count of comments is displayed when displaying comments. */
75 protected $displaytotalcount = false;
76 /** @var bool If set to true a cancel button will be shown on the form used to submit comments. */
77 protected $displaycancel = false;
78 /** @var int The number of comments associated with this comments params */
79 protected $totalcommentcount = null;
81 /**
82 * Set to true to remove the col attribute from the textarea making it full width.
83 * @var bool
85 protected $fullwidth = false;
87 /** @var bool Use non-javascript UI */
88 private static $nonjs = false;
89 /** @var int comment itemid used in non-javascript UI */
90 private static $comment_itemid = null;
91 /** @var int comment context used in non-javascript UI */
92 private static $comment_context = null;
93 /** @var string comment area used in non-javascript UI */
94 private static $comment_area = null;
95 /** @var string comment page used in non-javascript UI */
96 private static $comment_page = null;
97 /** @var string comment itemid component in non-javascript UI */
98 private static $comment_component = null;
101 * Construct function of comment class, initialise
102 * class members
104 * @param stdClass $options {
105 * context => context context to use for the comment [required]
106 * component => string which plugin will comment being added to [required]
107 * itemid => int the id of the associated item (forum post, glossary item etc) [required]
108 * area => string comment area
109 * cm => stdClass course module
110 * course => course course object
111 * client_id => string an unique id to identify comment area
112 * autostart => boolean automatically expend comments
113 * showcount => boolean display the number of comments
114 * displaycancel => boolean display cancel button
115 * notoggle => boolean don't show/hide button
116 * linktext => string title of show/hide button
119 public function __construct(stdClass $options) {
120 $this->viewcap = false;
121 $this->postcap = false;
123 // setup client_id
124 if (!empty($options->client_id)) {
125 $this->cid = $options->client_id;
126 } else {
127 $this->cid = uniqid();
130 // setup context
131 if (!empty($options->context)) {
132 $this->context = $options->context;
133 $this->contextid = $this->context->id;
134 } else if(!empty($options->contextid)) {
135 $this->contextid = $options->contextid;
136 $this->context = context::instance_by_id($this->contextid);
137 } else {
138 print_error('invalidcontext');
141 if (!empty($options->component)) {
142 // set and validate component
143 $this->set_component($options->component);
144 } else {
145 // component cannot be empty
146 throw new comment_exception('invalidcomponent');
149 // setup course
150 // course will be used to generate user profile link
151 if (!empty($options->course)) {
152 $this->courseid = $options->course->id;
153 } else if (!empty($options->courseid)) {
154 $this->courseid = $options->courseid;
155 } else {
156 $this->courseid = SITEID;
159 // setup coursemodule
160 if (!empty($options->cm)) {
161 $this->cm = $options->cm;
162 } else {
163 $this->cm = null;
166 // setup commentarea
167 if (!empty($options->area)) {
168 $this->commentarea = $options->area;
171 // setup itemid
172 if (!empty($options->itemid)) {
173 $this->itemid = $options->itemid;
174 } else {
175 $this->itemid = 0;
178 // setup customized linktext
179 if (!empty($options->linktext)) {
180 $this->linktext = $options->linktext;
181 } else {
182 $this->linktext = get_string('comments');
185 // setup options for callback functions
186 $this->comment_param = new stdClass();
187 $this->comment_param->context = $this->context;
188 $this->comment_param->courseid = $this->courseid;
189 $this->comment_param->cm = $this->cm;
190 $this->comment_param->commentarea = $this->commentarea;
191 $this->comment_param->itemid = $this->itemid;
193 // setup notoggle
194 if (!empty($options->notoggle)) {
195 $this->set_notoggle($options->notoggle);
198 // setup notoggle
199 if (!empty($options->autostart)) {
200 $this->set_autostart($options->autostart);
203 // setup displaycancel
204 if (!empty($options->displaycancel)) {
205 $this->set_displaycancel($options->displaycancel);
208 // setup displaytotalcount
209 if (!empty($options->showcount)) {
210 $this->set_displaytotalcount($options->showcount);
213 // setting post and view permissions
214 $this->check_permissions();
216 // load template
217 $this->template = html_writer::start_tag('div', array('class' => 'comment-message'));
219 $this->template .= html_writer::start_tag('div', array('class' => 'comment-message-meta'));
221 $this->template .= html_writer::tag('span', '___picture___', array('class' => 'picture'));
222 $this->template .= html_writer::tag('span', '___name___', array('class' => 'user')) . ' - ';
223 $this->template .= html_writer::tag('span', '___time___', array('class' => 'time'));
225 $this->template .= html_writer::end_tag('div'); // .comment-message-meta
226 $this->template .= html_writer::tag('div', '___content___', array('class' => 'text'));
228 $this->template .= html_writer::end_tag('div'); // .comment-message
230 if (!empty($this->plugintype)) {
231 $this->template = plugin_callback($this->plugintype, $this->pluginname, 'comment', 'template', array($this->comment_param), $this->template);
234 unset($options);
238 * Receive nonjs comment parameters
240 * @param moodle_page $page The page object to initialise comments within
241 * If not provided the global $PAGE is used
243 public static function init(moodle_page $page = null) {
244 global $PAGE;
246 if (empty($page)) {
247 $page = $PAGE;
249 // setup variables for non-js interface
250 self::$nonjs = optional_param('nonjscomment', '', PARAM_ALPHANUM);
251 self::$comment_itemid = optional_param('comment_itemid', '', PARAM_INT);
252 self::$comment_component = optional_param('comment_component', '', PARAM_COMPONENT);
253 self::$comment_context = optional_param('comment_context', '', PARAM_INT);
254 self::$comment_page = optional_param('comment_page', '', PARAM_INT);
255 self::$comment_area = optional_param('comment_area', '', PARAM_AREA);
257 $page->requires->strings_for_js(array(
258 'addcomment',
259 'comments',
260 'commentscount',
261 'commentsrequirelogin',
262 'deletecomment',
264 'moodle'
269 * Sets the component.
271 * This method shouldn't be public, changing the component once it has been set potentially
272 * invalidates permission checks.
273 * A coding_error is now thrown if code attempts to change the component.
275 * @throws coding_exception if you try to change the component after it has been set.
276 * @param string $component
278 public function set_component($component) {
279 if (!empty($this->component) && $this->component !== $component) {
280 throw new coding_exception('You cannot change the component of a comment once it has been set');
282 $this->component = $component;
283 list($this->plugintype, $this->pluginname) = core_component::normalize_component($component);
287 * Determines if the user can view the comment.
289 * @param bool $value
291 public function set_view_permission($value) {
292 $this->viewcap = (bool)$value;
296 * Determines if the user can post a comment
298 * @param bool $value
300 public function set_post_permission($value) {
301 $this->postcap = (bool)$value;
305 * check posting comments permission
306 * It will check based on user roles and ask modules
307 * If you need to check permission by modules, a
308 * function named $pluginname_check_comment_post must be implemented
310 private function check_permissions() {
311 $this->postcap = has_capability('moodle/comment:post', $this->context);
312 $this->viewcap = has_capability('moodle/comment:view', $this->context);
313 if (!empty($this->plugintype)) {
314 $permissions = plugin_callback($this->plugintype, $this->pluginname, 'comment', 'permissions', array($this->comment_param), array('post'=>false, 'view'=>false));
315 $this->postcap = $this->postcap && $permissions['post'];
316 $this->viewcap = $this->viewcap && $permissions['view'];
321 * Gets a link for this page that will work with JS disabled.
323 * @global moodle_page $PAGE
324 * @param moodle_page $page
325 * @return moodle_url
327 public function get_nojslink(moodle_page $page = null) {
328 if ($page === null) {
329 global $PAGE;
330 $page = $PAGE;
333 $link = new moodle_url($page->url, array(
334 'nonjscomment' => true,
335 'comment_itemid' => $this->itemid,
336 'comment_context' => $this->context->id,
337 'comment_component' => $this->get_component(),
338 'comment_area' => $this->commentarea,
340 $link->remove_params(array('comment_page'));
341 return $link;
345 * Sets the value of the notoggle option.
347 * If set to true then the user will not be able to expand and collase
348 * the comment section.
350 * @param bool $newvalue
352 public function set_notoggle($newvalue = true) {
353 $this->notoggle = (bool)$newvalue;
357 * Sets the value of the autostart option.
359 * If set to true then the comments will be loaded during page load.
360 * Normally this happens only once the user expands the comment section.
362 * @param bool $newvalue
364 public function set_autostart($newvalue = true) {
365 $this->autostart = (bool)$newvalue;
369 * Sets the displaycancel option
371 * If set to true then a cancel button will be shown when using the form
372 * to post comments.
374 * @param bool $newvalue
376 public function set_displaycancel($newvalue = true) {
377 $this->displaycancel = (bool)$newvalue;
381 * Sets the displaytotalcount option
383 * If set to true then the total number of comments will be displayed
384 * when printing comments.
386 * @param bool $newvalue
388 public function set_displaytotalcount($newvalue = true) {
389 $this->displaytotalcount = (bool)$newvalue;
393 * Initialises the JavaScript that enchances the comment API.
395 * @param moodle_page $page The moodle page object that the JavaScript should be
396 * initialised for.
398 public function initialise_javascript(moodle_page $page) {
400 $options = new stdClass;
401 $options->client_id = $this->cid;
402 $options->commentarea = $this->commentarea;
403 $options->itemid = $this->itemid;
404 $options->page = 0;
405 $options->courseid = $this->courseid;
406 $options->contextid = $this->contextid;
407 $options->component = $this->component;
408 $options->notoggle = $this->notoggle;
409 $options->autostart = $this->autostart;
411 $page->requires->js_init_call('M.core_comment.init', array($options), true);
413 return true;
417 * Prepare comment code in html
418 * @param boolean $return
419 * @return string|void
421 public function output($return = true) {
422 global $PAGE, $OUTPUT;
423 static $template_printed;
425 $this->initialise_javascript($PAGE);
427 if (!empty(self::$nonjs)) {
428 // return non js comments interface
429 return $this->print_comments(self::$comment_page, $return, true);
432 $html = '';
434 // print html template
435 // Javascript will use the template to render new comments
436 if (empty($template_printed) && $this->can_view()) {
437 $html .= html_writer::tag('div', $this->template, array('style' => 'display:none', 'id' => 'cmt-tmpl'));
438 $template_printed = true;
441 if ($this->can_view()) {
442 // print commenting icon and tooltip
443 $html .= html_writer::start_tag('div', array('class' => 'mdl-left'));
444 $html .= html_writer::link($this->get_nojslink($PAGE), get_string('showcommentsnonjs'), array('class' => 'showcommentsnonjs'));
446 if (!$this->notoggle) {
447 // If toggling is enabled (notoggle=false) then print the controls to toggle
448 // comments open and closed
449 $countstring = '';
450 if ($this->displaytotalcount) {
451 $countstring = '('.$this->count().')';
453 $collapsedimage= 't/collapsed';
454 if (right_to_left()) {
455 $collapsedimage= 't/collapsed_rtl';
456 } else {
457 $collapsedimage= 't/collapsed';
459 $html .= html_writer::start_tag('a', array('class' => 'comment-link', 'id' => 'comment-link-'.$this->cid, 'href' => '#'));
460 $html .= html_writer::empty_tag('img', array('id' => 'comment-img-'.$this->cid, 'src' => $OUTPUT->pix_url($collapsedimage), 'alt' => $this->linktext, 'title' => $this->linktext));
461 $html .= html_writer::tag('span', $this->linktext.' '.$countstring, array('id' => 'comment-link-text-'.$this->cid));
462 $html .= html_writer::end_tag('a');
465 $html .= html_writer::start_tag('div', array('id' => 'comment-ctrl-'.$this->cid, 'class' => 'comment-ctrl'));
467 if ($this->autostart) {
468 // If autostart has been enabled print the comments list immediatly
469 $html .= html_writer::start_tag('ul', array('id' => 'comment-list-'.$this->cid, 'class' => 'comment-list comments-loaded'));
470 $html .= html_writer::tag('li', '', array('class' => 'first'));
471 $html .= $this->print_comments(0, true, false);
472 $html .= html_writer::end_tag('ul'); // .comment-list
473 $html .= $this->get_pagination(0);
474 } else {
475 $html .= html_writer::start_tag('ul', array('id' => 'comment-list-'.$this->cid, 'class' => 'comment-list'));
476 $html .= html_writer::tag('li', '', array('class' => 'first'));
477 $html .= html_writer::end_tag('ul'); // .comment-list
478 $html .= html_writer::tag('div', '', array('id' => 'comment-pagination-'.$this->cid, 'class' => 'comment-pagination'));
481 if ($this->can_post()) {
482 // print posting textarea
483 $textareaattrs = array(
484 'name' => 'content',
485 'rows' => 2,
486 'id' => 'dlg-content-'.$this->cid
488 if (!$this->fullwidth) {
489 $textareaattrs['cols'] = '20';
490 } else {
491 $textareaattrs['class'] = 'fullwidth';
494 $html .= html_writer::start_tag('div', array('class' => 'comment-area'));
495 $html .= html_writer::start_tag('div', array('class' => 'db'));
496 $html .= html_writer::tag('textarea', '', $textareaattrs);
497 $html .= html_writer::end_tag('div'); // .db
499 $html .= html_writer::start_tag('div', array('class' => 'fd', 'id' => 'comment-action-'.$this->cid));
500 $html .= html_writer::link('#', get_string('savecomment'), array('id' => 'comment-action-post-'.$this->cid));
502 if ($this->displaycancel) {
503 $html .= html_writer::tag('span', ' | ');
504 $html .= html_writer::link('#', get_string('cancel'), array('id' => 'comment-action-cancel-'.$this->cid));
507 $html .= html_writer::end_tag('div'); // .fd
508 $html .= html_writer::end_tag('div'); // .comment-area
509 $html .= html_writer::tag('div', '', array('class' => 'clearer'));
512 $html .= html_writer::end_tag('div'); // .comment-ctrl
513 $html .= html_writer::end_tag('div'); // .mdl-left
514 } else {
515 $html = '';
518 if ($return) {
519 return $html;
520 } else {
521 echo $html;
526 * Return matched comments
528 * @param int $page
529 * @return array
531 public function get_comments($page = '') {
532 global $DB, $CFG, $USER, $OUTPUT;
533 if (!$this->can_view()) {
534 return false;
536 if (!is_numeric($page)) {
537 $page = 0;
539 $params = array();
540 $perpage = (!empty($CFG->commentsperpage))?$CFG->commentsperpage:15;
541 $start = $page * $perpage;
542 $ufields = user_picture::fields('u');
544 list($componentwhere, $component) = $this->get_component_select_sql('c');
545 if ($component) {
546 $params['component'] = $component;
549 $sql = "SELECT $ufields, c.id AS cid, c.content AS ccontent, c.format AS cformat, c.timecreated AS ctimecreated
550 FROM {comments} c
551 JOIN {user} u ON u.id = c.userid
552 WHERE c.contextid = :contextid AND
553 c.commentarea = :commentarea AND
554 c.itemid = :itemid AND
555 $componentwhere
556 ORDER BY c.timecreated DESC";
557 $params['contextid'] = $this->contextid;
558 $params['commentarea'] = $this->commentarea;
559 $params['itemid'] = $this->itemid;
561 $comments = array();
562 $formatoptions = array('overflowdiv' => true);
563 $rs = $DB->get_recordset_sql($sql, $params, $start, $perpage);
564 foreach ($rs as $u) {
565 $c = new stdClass();
566 $c->id = $u->cid;
567 $c->content = $u->ccontent;
568 $c->format = $u->cformat;
569 $c->timecreated = $u->ctimecreated;
570 $c->strftimeformat = get_string('strftimerecentfull', 'langconfig');
571 $url = new moodle_url('/user/view.php', array('id'=>$u->id, 'course'=>$this->courseid));
572 $c->profileurl = $url->out(false); // URL should not be escaped just yet.
573 $c->fullname = fullname($u);
574 $c->time = userdate($c->timecreated, $c->strftimeformat);
575 $c->content = format_text($c->content, $c->format, $formatoptions);
576 $c->avatar = $OUTPUT->user_picture($u, array('size'=>18));
577 $c->userid = $u->id;
579 $candelete = $this->can_delete($c->id);
580 if (($USER->id == $u->id) || !empty($candelete)) {
581 $c->delete = true;
583 $comments[] = $c;
585 $rs->close();
587 if (!empty($this->plugintype)) {
588 // moodle module will filter comments
589 $comments = plugin_callback($this->plugintype, $this->pluginname, 'comment', 'display', array($comments, $this->comment_param), $comments);
592 return $comments;
596 * Returns an SQL fragment and param for selecting on component.
597 * @param string $alias
598 * @return array
600 protected function get_component_select_sql($alias = '') {
601 $component = $this->get_component();
602 if ($alias) {
603 $alias = $alias.'.';
605 if (empty($component)) {
606 $componentwhere = "{$alias}component IS NULL";
607 $component = null;
608 } else {
609 $componentwhere = "({$alias}component IS NULL OR {$alias}component = :component)";
611 return array($componentwhere, $component);
615 * Returns the number of comments associated with the details of this object
617 * @global moodle_database $DB
618 * @return int
620 public function count() {
621 global $DB;
622 if ($this->totalcommentcount === null) {
623 list($where, $component) = $this->get_component_select_sql();
624 $where .= ' AND itemid = :itemid AND commentarea = :commentarea AND contextid = :contextid';
625 $params = array(
626 'itemid' => $this->itemid,
627 'commentarea' => $this->commentarea,
628 'contextid' => $this->context->id,
630 if ($component) {
631 $params['component'] = $component;
634 $this->totalcommentcount = $DB->count_records_select('comments', $where, $params);
636 return $this->totalcommentcount;
640 * Returns HTML to display a pagination bar
642 * @global stdClass $CFG
643 * @global core_renderer $OUTPUT
644 * @param int $page
645 * @return string
647 public function get_pagination($page = 0) {
648 global $CFG, $OUTPUT;
649 $count = $this->count();
650 $perpage = (!empty($CFG->commentsperpage))?$CFG->commentsperpage:15;
651 $pages = (int)ceil($count/$perpage);
652 if ($pages == 1 || $pages == 0) {
653 return html_writer::tag('div', '', array('id' => 'comment-pagination-'.$this->cid, 'class' => 'comment-pagination'));
655 if (!empty(self::$nonjs)) {
656 // used in non-js interface
657 return $OUTPUT->paging_bar($count, $page, $perpage, $this->get_nojslink(), 'comment_page');
658 } else {
659 // return ajax paging bar
660 $str = '';
661 $str .= '<div class="comment-paging" id="comment-pagination-'.$this->cid.'">';
662 for ($p=0; $p<$pages; $p++) {
663 if ($p == $page) {
664 $class = 'curpage';
665 } else {
666 $class = 'pageno';
668 $str .= '<a href="#" class="'.$class.'" id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
670 $str .= '</div>';
672 return $str;
676 * Add a new comment
678 * @global moodle_database $DB
679 * @param string $content
680 * @param int $format
681 * @return stdClass
683 public function add($content, $format = FORMAT_MOODLE) {
684 global $CFG, $DB, $USER, $OUTPUT;
685 if (!$this->can_post()) {
686 throw new comment_exception('nopermissiontocomment');
688 $now = time();
689 $newcmt = new stdClass;
690 $newcmt->contextid = $this->contextid;
691 $newcmt->commentarea = $this->commentarea;
692 $newcmt->itemid = $this->itemid;
693 $newcmt->component = !empty($this->component) ? $this->component : null;
694 $newcmt->content = $content;
695 $newcmt->format = $format;
696 $newcmt->userid = $USER->id;
697 $newcmt->timecreated = $now;
699 // This callback allow module to modify the content of comment, such as filter or replacement
700 plugin_callback($this->plugintype, $this->pluginname, 'comment', 'add', array(&$newcmt, $this->comment_param));
702 $cmt_id = $DB->insert_record('comments', $newcmt);
703 if (!empty($cmt_id)) {
704 $newcmt->id = $cmt_id;
705 $newcmt->strftimeformat = get_string('strftimerecent', 'langconfig');
706 $newcmt->fullname = fullname($USER);
707 $url = new moodle_url('/user/view.php', array('id' => $USER->id, 'course' => $this->courseid));
708 $newcmt->profileurl = $url->out();
709 $newcmt->content = format_text($newcmt->content, $newcmt->format, array('overflowdiv'=>true));
710 $newcmt->avatar = $OUTPUT->user_picture($USER, array('size'=>16));
712 $commentlist = array($newcmt);
714 if (!empty($this->plugintype)) {
715 // Call the display callback to allow the plugin to format the newly added comment.
716 $commentlist = plugin_callback($this->plugintype,
717 $this->pluginname,
718 'comment',
719 'display',
720 array($commentlist, $this->comment_param),
721 $commentlist);
722 $newcmt = $commentlist[0];
724 $newcmt->time = userdate($newcmt->timecreated, $newcmt->strftimeformat);
726 // Trigger comment created event.
727 if (core_component::is_core_subsystem($this->component)) {
728 $eventclassname = '\\core\\event\\' . $this->component . '_comment_created';
729 } else {
730 $eventclassname = '\\' . $this->component . '\\event\comment_created';
732 if (class_exists($eventclassname)) {
733 $event = $eventclassname::create(
734 array(
735 'context' => $this->context,
736 'objectid' => $newcmt->id,
737 'other' => array(
738 'itemid' => $this->itemid
741 $event->trigger();
744 return $newcmt;
745 } else {
746 throw new comment_exception('dbupdatefailed');
751 * delete by context, commentarea and itemid
752 * @param stdClass|array $param {
753 * contextid => int the context in which the comments exist [required]
754 * commentarea => string the comment area [optional]
755 * itemid => int comment itemid [optional]
757 * @return boolean
759 public static function delete_comments($param) {
760 global $DB;
761 $param = (array)$param;
762 if (empty($param['contextid'])) {
763 return false;
765 $DB->delete_records('comments', $param);
766 return true;
770 * Delete page_comments in whole course, used by course reset
772 * @param stdClass $context course context
774 public static function reset_course_page_comments($context) {
775 global $DB;
776 $contexts = array();
777 $contexts[] = $context->id;
778 $children = $context->get_child_contexts();
779 foreach ($children as $c) {
780 $contexts[] = $c->id;
782 list($ids, $params) = $DB->get_in_or_equal($contexts);
783 $DB->delete_records_select('comments', "commentarea='page_comments' AND contextid $ids", $params);
787 * Delete a comment
789 * @param int $commentid
790 * @return bool
792 public function delete($commentid) {
793 global $DB, $USER;
794 $candelete = has_capability('moodle/comment:delete', $this->context);
795 if (!$comment = $DB->get_record('comments', array('id'=>$commentid))) {
796 throw new comment_exception('dbupdatefailed');
798 if (!($USER->id == $comment->userid || !empty($candelete))) {
799 throw new comment_exception('nopermissiontocomment');
801 $DB->delete_records('comments', array('id'=>$commentid));
802 // Trigger comment delete event.
803 if (core_component::is_core_subsystem($this->component)) {
804 $eventclassname = '\\core\\event\\' . $this->component . '_comment_deleted';
805 } else {
806 $eventclassname = '\\' . $this->component . '\\event\comment_deleted';
808 if (class_exists($eventclassname)) {
809 $event = $eventclassname::create(
810 array(
811 'context' => $this->context,
812 'objectid' => $commentid,
813 'other' => array(
814 'itemid' => $this->itemid
817 $event->add_record_snapshot('comments', $comment);
818 $event->trigger();
820 return true;
824 * Print comments
826 * @param int $page
827 * @param bool $return return comments list string or print it out
828 * @param bool $nonjs print nonjs comments list or not?
829 * @return string|void
831 public function print_comments($page = 0, $return = true, $nonjs = true) {
832 global $DB, $CFG, $PAGE;
834 if (!$this->can_view()) {
835 return '';
838 if (!(self::$comment_itemid == $this->itemid &&
839 self::$comment_context == $this->context->id &&
840 self::$comment_area == $this->commentarea &&
841 self::$comment_component == $this->component
842 )) {
843 $page = 0;
845 $comments = $this->get_comments($page);
847 $html = '';
848 if ($nonjs) {
849 $html .= html_writer::tag('h3', get_string('comments'));
850 $html .= html_writer::start_tag('ul', array('id' => 'comment-list-'.$this->cid, 'class' => 'comment-list'));
852 // Reverse the comments array to display them in the correct direction
853 foreach (array_reverse($comments) as $cmt) {
854 $html .= html_writer::tag('li', $this->print_comment($cmt, $nonjs), array('id' => 'comment-'.$cmt->id.'-'.$this->cid));
856 if ($nonjs) {
857 $html .= html_writer::end_tag('ul');
858 $html .= $this->get_pagination($page);
860 if ($nonjs && $this->can_post()) {
861 // Form to add comments
862 $html .= html_writer::start_tag('form', array('method' => 'post', 'action' => new moodle_url('/comment/comment_post.php')));
863 // Comment parameters
864 $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'contextid', 'value' => $this->contextid));
865 $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'action', 'value' => 'add'));
866 $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'area', 'value' => $this->commentarea));
867 $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'component', 'value' => $this->component));
868 $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'itemid', 'value' => $this->itemid));
869 $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'courseid', 'value' => $this->courseid));
870 $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
871 $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'returnurl', 'value' => $PAGE->url));
872 // Textarea for the actual comment
873 $html .= html_writer::tag('textarea', '', array('name' => 'content', 'rows' => 2));
874 // Submit button to add the comment
875 $html .= html_writer::empty_tag('input', array('type' => 'submit', 'value' => get_string('submit')));
876 $html .= html_writer::end_tag('form');
878 if ($return) {
879 return $html;
880 } else {
881 echo $html;
886 * Returns an array containing comments in HTML format.
888 * @global core_renderer $OUTPUT
889 * @param stdClass $cmt {
890 * id => int comment id
891 * content => string comment content
892 * format => int comment text format
893 * timecreated => int comment's timecreated
894 * profileurl => string link to user profile
895 * fullname => comment author's full name
896 * avatar => string user's avatar
897 * delete => boolean does user have permission to delete comment?
899 * @param bool $nonjs
900 * @return array
902 public function print_comment($cmt, $nonjs = true) {
903 global $OUTPUT;
904 $patterns = array();
905 $replacements = array();
907 if (!empty($cmt->delete) && empty($nonjs)) {
908 $deletelink = html_writer::start_tag('div', array('class'=>'comment-delete'));
909 $deletelink .= html_writer::start_tag('a', array('href' => '#', 'id' => 'comment-delete-'.$this->cid.'-'.$cmt->id));
910 $deletelink .= $OUTPUT->pix_icon('t/delete', get_string('delete'));
911 $deletelink .= html_writer::end_tag('a');
912 $deletelink .= html_writer::end_tag('div');
913 $cmt->content = $deletelink . $cmt->content;
915 $patterns[] = '___picture___';
916 $patterns[] = '___name___';
917 $patterns[] = '___content___';
918 $patterns[] = '___time___';
919 $replacements[] = $cmt->avatar;
920 $replacements[] = html_writer::link($cmt->profileurl, $cmt->fullname);
921 $replacements[] = $cmt->content;
922 $replacements[] = $cmt->time;
924 // use html template to format a single comment.
925 return str_replace($patterns, $replacements, $this->template);
929 * Revoke validate callbacks
931 * @param stdClass $params addtionall parameters need to add to callbacks
933 protected function validate($params=array()) {
934 foreach ($params as $key=>$value) {
935 $this->comment_param->$key = $value;
937 $validation = plugin_callback($this->plugintype, $this->pluginname, 'comment', 'validate', array($this->comment_param), false);
938 if (!$validation) {
939 throw new comment_exception('invalidcommentparam');
944 * Returns true if the user is able to view comments
945 * @return bool
947 public function can_view() {
948 $this->validate();
949 return !empty($this->viewcap);
953 * Returns true if the user can add comments against this comment description
954 * @return bool
956 public function can_post() {
957 $this->validate();
958 return isloggedin() && !empty($this->postcap);
962 * Returns true if the user can delete this comment
963 * @param int $commentid
964 * @return bool
966 public function can_delete($commentid) {
967 $this->validate(array('commentid'=>$commentid));
968 return has_capability('moodle/comment:delete', $this->context);
972 * Returns the component associated with the comment.
974 * @return string
976 public function get_component() {
977 return $this->component;
981 * Do not call! I am a deprecated method because of the typo in my name.
982 * @deprecated since 2.9
983 * @see comment::get_component()
984 * @return string
986 public function get_compontent() {
987 return $this->get_component();
991 * Returns the context associated with the comment
992 * @return stdClass
994 public function get_context() {
995 return $this->context;
999 * Returns the course id associated with the comment
1000 * @return int
1002 public function get_courseid() {
1003 return $this->courseid;
1007 * Returns the course module associated with the comment
1009 * @return stdClass
1011 public function get_cm() {
1012 return $this->cm;
1016 * Returns the item id associated with the comment
1018 * @return int
1020 public function get_itemid() {
1021 return $this->itemid;
1025 * Returns the comment area associated with the commentarea
1027 * @return stdClass
1029 public function get_commentarea() {
1030 return $this->commentarea;
1034 * Make the comments textarea fullwidth.
1036 * @since 2.8.1 + 2.7.4
1037 * @param bool $fullwidth
1039 public function set_fullwidth($fullwidth = true) {
1040 $this->fullwidth = (bool)$fullwidth;
1045 * Comment exception class
1047 * @package core
1048 * @copyright 2010 Dongsheng Cai {@link http://dongsheng.org}
1049 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1051 class comment_exception extends moodle_exception {