MDL-22449 help string update
[moodle.git] / comment / lib.php
blob5cde7d36f0d2609ff52ee5a08190c5693b876397
1 <?php
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.
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/>.
18 /**
19 * Comment is helper class to add/delete comments anywhere in moodle
21 * @package comment
22 * @copyright 2010 Dongsheng Cai <dongsheng@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 class comment {
27 /**
28 * @var integer
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
36 private $cid;
37 private $contextid;
38 /**
39 * commentarea is used to specify different
40 * parts shared the same itemid
41 * @var string
43 private $commentarea;
44 /**
45 * itemid is used to associate with commenting content
46 * @var integer
48 private $itemid;
50 /**
51 * this html snippet will be used as a template
52 * to build comment content
53 * @var string
55 private $template;
56 private $context;
57 private $courseid;
58 /**
59 * course module object, only be used to help find pluginname automatically
60 * if pluginname is specified, it won't be used at all
61 * @var string
63 private $cm;
64 private $plugintype;
65 /**
66 * When used in module, it is recommended to use it
67 * @var string
69 private $pluginname;
70 private $viewcap;
71 private $postcap;
72 /**
73 * to tell comments api where it is used
74 * @var string
76 private $env;
77 /**
78 * to costomize link text
79 * @var string
81 private $linktext;
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;
89 /**
90 * Construct function of comment class, initialise
91 * class members
92 * @param object $options
94 public function __construct($options) {
95 global $CFG, $DB;
97 if (empty($CFG->commentsperpage)) {
98 $CFG->commentsperpage = 15;
101 $this->viewcap = false;
102 $this->postcap = false;
104 // setup client_id
105 if (!empty($options->client_id)) {
106 $this->cid = $options->client_id;
107 } else {
108 $this->cid = uniqid();
111 // setup context
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');
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 } else {
129 $this->courseid = SITEID;
132 if (!empty($options->pluginname)) {
133 $this->pluginname = $options->pluginname;
136 // setup coursemodule
137 if (!empty($options->cm)) {
138 $this->cm = $options->cm;
139 } else {
140 $this->cm = null;
143 // setup commentarea
144 if (!empty($options->area)) {
145 $this->commentarea = $options->area;
148 // setup itemid
149 if (!empty($options->itemid)) {
150 $this->itemid = $options->itemid;
151 } else {
152 $this->itemid = 0;
155 // setup env
156 if (!empty($options->env)) {
157 $this->env = $options->env;
158 } else {
159 $this->env = '';
162 // setup customized linktext
163 if (!empty($options->linktext)) {
164 $this->linktext = $options->linktext;
165 } else {
166 $this->linktext = get_string('comments');
168 // setting post and view permissions
169 $this->check_permissions();
171 if (!empty($options->showcount)) {
172 $count = $this->count();
173 if (empty($count)) {
174 $this->count = '';
175 } else {
176 $this->count = '('.$count.')';
178 } else {
179 $this->count = '';
182 $this->setup_plugin();
184 // setup options for callback functions
185 $this->args = new stdclass;
186 $this->args->context = $this->context;
187 $this->args->courseid = $this->courseid;
188 $this->args->cm = $this->cm;
189 $this->args->commentarea = $this->commentarea;
190 $this->args->itemid = $this->itemid;
192 // load template
193 $this->template = <<<EOD
194 <div class="comment-userpicture">___picture___</div>
195 <div class="comment-content">
196 ___name___ - <span>___time___</span>
197 <div>___content___</div>
198 </div>
199 EOD;
200 if (!empty($this->plugintype)) {
201 $this->template = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'template', $this->args, $this->template);
204 unset($options);
208 * Receive nonjs comment parameters
210 public static function init() {
211 global $PAGE, $CFG;
212 // setup variables for non-js interface
213 self::$nonjs = optional_param('nonjscomment', '', PARAM_ALPHA);
214 self::$comment_itemid = optional_param('comment_itemid', '', PARAM_INT);
215 self::$comment_context = optional_param('comment_context', '', PARAM_INT);
216 self::$comment_page = optional_param('comment_page', '', PARAM_INT);
217 self::$comment_area = optional_param('comment_area', '', PARAM_ALPHAEXT);
219 $PAGE->requires->string_for_js('addcomment', 'moodle');
220 $PAGE->requires->string_for_js('deletecomment', 'moodle');
221 $PAGE->requires->string_for_js('comments', 'moodle');
225 * Setup plugin type and plugin name
227 private function setup_plugin() {
228 global $DB;
229 // blog needs to set env as "blog"
230 if ($this->env == 'blog') {
231 $this->plugintype = 'moodle';
232 $this->pluginname = 'blog';
234 // tag page needs to set env as "tag"
235 if ($this->env == 'tag') {
236 $this->plugintype = 'moodle';
237 $this->pluginname = 'tag';
239 if ($this->context->contextlevel == CONTEXT_BLOCK) {
240 if ($block = $DB->get_record('block_instances', array('id'=>$this->context->instanceid))) {
241 $this->plugintype = 'block';
242 $this->pluginname = $block->blockname;
246 if ($this->context->contextlevel == CONTEXT_MODULE && $this->env != 'block_comments') {
247 $this->plugintype = 'mod';
248 // to improve performance, pluginname should be assigned before initilise comment object
249 // if it is empty, we will try to guess, it will rarely be used.
250 if (empty($this->pluginname)) {
251 if (empty($this->course)) {
252 $this->course = $DB->get_record('course', array('id'=>$this->courseid), '*', MUST_EXIST);
254 $this->modinfo = get_fast_modinfo($this->course);
255 $this->pluginname = $this->modinfo->cms[$this->cm->id]->modname;
261 * check posting comments permission
262 * It will check based on user roles and ask modules
263 * If you need to check permission by modules, a
264 * function named $pluginname_check_comment_post must be implemented
266 private function check_permissions() {
267 global $CFG;
268 $this->postcap = has_capability('moodle/comment:post', $this->context);
269 $this->viewcap = has_capability('moodle/comment:view', $this->context);
270 if (!empty($this->plugintype)) {
271 $permissions = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'permissions', $this->args, array('post'=>true, 'view'=>true));
272 $this->postcap = $this->postcap && $permissions['post'];
273 $this->viewcap = $this->viewcap && $permissions['view'];
278 * Prepare comment code in html
279 * @param boolean $return
280 * @return mixed
282 public function output($return = true) {
283 global $PAGE, $OUTPUT;
284 static $template_printed;
286 $this->link = $PAGE->url;
287 $murl = new moodle_url($this->link);
288 $murl->remove_params('nonjscomment');
289 $murl->param('nonjscomment', 'true');
290 $murl->param('comment_itemid', $this->itemid);
291 $murl->param('comment_context', $this->context->id);
292 $murl->param('comment_area', $this->commentarea);
293 $murl->remove_params('comment_page');
294 $this->link = $murl->out();
296 $options = new stdclass;
297 $options->client_id = $this->cid;
298 $options->commentarea = $this->commentarea;
299 $options->itemid = $this->itemid;
300 $options->page = 0;
301 $options->courseid = $this->courseid;
302 $options->contextid = $this->contextid;
303 $options->env = $this->env;
304 if ($this->env == 'block_comments') {
305 $options->autostart = true;
306 $options->notoggle = true;
309 $PAGE->requires->js_init_call('M.core_comment.init', array($options), true);
311 if (!empty(self::$nonjs)) {
312 // return non js comments interface
313 return $this->print_comments(self::$comment_page, $return, true);
316 $strsubmit = get_string('savecomment');
317 $strcancel = get_string('cancel');
318 $sesskey = sesskey();
319 $html = '';
320 // print html template
321 // Javascript will use the template to render new comments
322 if (empty($template_printed) && !empty($this->viewcap)) {
323 $html .= '<div style="display:none" id="cmt-tmpl">' . $this->template . '</div>';
324 $template_printed = true;
327 if (!empty($this->viewcap)) {
328 // print commenting icon and tooltip
329 $icon = $OUTPUT->pix_url('t/collapsed');
330 $html .= <<<EOD
331 <div class="mdl-left">
332 <a id="comment-link-{$this->cid}" href="{$this->link}">
333 <img id="comment-img-{$this->cid}" src="$icon" alt="{$this->linktext}" title="{$this->linktext}" />
334 <span id="comment-link-text-{$this->cid}">{$this->linktext} {$this->count}</span>
335 </a>
336 <div id="comment-ctrl-{$this->cid}" class="comment-ctrl">
337 <ul id="comment-list-{$this->cid}" class="comment-list">
338 EOD;
339 // in comments block, we print comments list right away
340 if ($this->env == 'block_comments') {
341 $html .= $this->print_comments(0, true, false);
342 $html .= '</ul>';
343 $html .= $this->get_pagination(0);
344 } else {
345 $html .= <<<EOD
346 </ul>
347 <div id="comment-pagination-{$this->cid}" class="comment-pagination"></div>
348 EOD;
351 // print posting textarea
352 if (!empty($this->postcap)) {
353 $html .= <<<EOD
354 <div class='comment-area'>
355 <div class="bd">
356 <textarea name="content" rows="2" id="dlg-content-{$this->cid}"></textarea>
357 </div>
358 <div class="fd" id="comment-action-{$this->cid}">
359 <a href="#" id="comment-action-post-{$this->cid}"> {$strsubmit} </a>
360 EOD;
361 if ($this->env != 'block_comments') {
362 $html .= <<<EOD
363 <span> | </span>
364 <a href="#" id="comment-action-cancel-{$this->cid}"> {$strcancel} </a>
365 EOD;
368 $html .= <<<EOD
369 </div>
370 </div>
371 <div class="clearer"></div>
372 EOD;
375 $html .= <<<EOD
376 </div><!-- end of comment-ctrl -->
377 </div>
378 EOD;
379 } else {
380 $html = '';
383 if ($return) {
384 return $html;
385 } else {
386 echo $html;
391 * Return matched comments
393 * @param int $page
394 * @return mixed
396 public function get_comments($page = '') {
397 global $DB, $CFG, $USER, $OUTPUT;
398 if (empty($this->viewcap)) {
399 return false;
401 if (!is_numeric($page)) {
402 $page = 0;
404 $this->page = $page;
405 $params = array();
406 $start = $page * $CFG->commentsperpage;
407 $ufields = user_picture::fields('u', array('username'));
408 $sql = "SELECT $ufields, c.id AS cid, c.content AS ccontent, c.format AS cformat, c.timecreated AS ctimecreated
409 FROM {comments} c
410 JOIN {user} u ON u.id = c.userid
411 WHERE c.contextid = :contextid AND c.commentarea = :commentarea AND c.itemid = :itemid
412 ORDER BY c.timecreated DESC";
413 $params['contextid'] = $this->contextid;
414 $params['commentarea'] = $this->commentarea;
415 $params['itemid'] = $this->itemid;
417 $comments = array();
418 $candelete = has_capability('moodle/comment:delete', $this->context);
419 $rs = $DB->get_recordset_sql($sql, $params, $start, $CFG->commentsperpage);
420 foreach ($rs as $u) {
421 $c = new object();
422 $c->id = $u->cid;
423 $c->content = $u->ccontent;
424 $c->format = $u->cformat;
425 $c->timecreated = $u->ctimecreated;
426 $url = new moodle_url('/user/view.php', array('id'=>$u->id, 'course'=>$this->courseid));
427 $c->username = $u->username;
428 $c->profileurl = $url;
429 $c->fullname = fullname($u);
430 $c->time = userdate($c->timecreated, get_string('strftimerecent', 'langconfig'));
431 $c->content = format_text($c->content, $c->format);
433 $c->avatar = $OUTPUT->user_picture($u, array('size'=>18));
434 if (($USER->id == $u->id) || !empty($candelete)) {
435 $c->delete = true;
437 $comments[] = $c;
439 $rs->close();
441 if (!empty($this->plugintype)) {
442 // moodle module will filter comments
443 $comments = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'display', array($comments, $this->args), $comments);
446 return $comments;
449 public function count() {
450 global $DB;
451 if ($count = $DB->count_records('comments', array('itemid'=>$this->itemid, 'commentarea'=>$this->commentarea, 'contextid'=>$this->context->id))) {
452 return $count;
453 } else {
454 return 0;
458 public function get_pagination($page = 0) {
459 global $DB, $CFG, $OUTPUT;
460 $count = $this->count();
461 $pages = (int)ceil($count/$CFG->commentsperpage);
462 if ($pages == 1 || $pages == 0) {
463 return '';
465 if (!empty(self::$nonjs)) {
466 // used in non-js interface
467 return $OUTPUT->paging_bar($count, $page, $CFG->commentsperpage, $this->link, 'comment_page');
468 } else {
469 // return ajax paging bar
470 $str = '';
471 $str .= '<div class="comment-paging" id="comment-pagination-'.$this->cid.'">';
472 for ($p=0; $p<$pages; $p++) {
473 if ($p == $page) {
474 $class = 'curpage';
475 } else {
476 $class = 'pageno';
478 $str .= '<a href="#" class="'.$class.'" id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
480 $str .= '</div>';
482 return $str;
486 * Add a new comment
487 * @param string $content
488 * @return mixed
490 public function add($content, $format = FORMAT_MOODLE) {
491 global $CFG, $DB, $USER, $OUTPUT;
492 if (empty($this->postcap)) {
493 throw new comment_exception('nopermissiontocomment');
495 $now = time();
496 $newcmt = new stdclass;
497 $newcmt->contextid = $this->contextid;
498 $newcmt->commentarea = $this->commentarea;
499 $newcmt->itemid = $this->itemid;
500 $newcmt->content = $content;
501 $newcmt->format = $format;
502 $newcmt->userid = $USER->id;
503 $newcmt->timecreated = $now;
505 if (!empty($this->plugintype)) {
506 // moodle module will check content
507 $ret = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'add', array(&$newcmt, $this->args), true);
508 if (!$ret) {
509 throw new comment_exception('modulererejectcomment');
513 $cmt_id = $DB->insert_record('comments', $newcmt);
514 if (!empty($cmt_id)) {
515 $newcmt->id = $cmt_id;
516 $newcmt->time = userdate($now, get_string('strftimerecent', 'langconfig'));
517 $newcmt->username = $USER->username;
518 $newcmt->fullname = fullname($USER);
519 $url = new moodle_url('/user/view.php', array('id'=>$USER->id, 'course'=>$this->courseid));
520 $newcmt->profileurl = $url->out();
521 $newcmt->content = format_text($newcmt->content);
522 $newcmt->avatar = $OUTPUT->user_picture($USER, array('size'=>16));
523 return $newcmt;
524 } else {
525 throw new comment_exception('dbupdatefailed');
530 * delete by context, commentarea and itemid
533 public function delete_comments() {
534 global $DB;
535 $DB->delete_records('comments', array(
536 'contextid'=>$this->context->id,
537 'commentarea'=>$this->commentarea,
538 'itemid'=>$this->itemid)
540 return true;
544 * Delete a comment
545 * @param int $commentid
546 * @return mixed
548 public function delete($commentid) {
549 global $DB, $USER;
550 $candelete = has_capability('moodle/comment:delete', $this->context);
551 if (!$comment = $DB->get_record('comments', array('id'=>$commentid))) {
552 throw new comment_exception('dbupdatefailed');
554 if (!($USER->id == $comment->userid || !empty($candelete))) {
555 throw new comment_exception('nopermissiontocomment');
557 $DB->delete_records('comments', array('id'=>$commentid));
558 return true;
562 * Print comments
563 * @param int $page
564 * @param boolean $return return comments list string or print it out
565 * @param boolean $nonjs print nonjs comments list or not?
566 * @return mixed
568 public function print_comments($page = 0, $return = true, $nonjs = true) {
569 global $DB, $CFG, $PAGE;
570 $html = '';
571 if (!(self::$comment_itemid == $this->itemid &&
572 self::$comment_context == $this->context->id &&
573 self::$comment_area == $this->commentarea)) {
574 $page = 0;
576 $comments = $this->get_comments($page);
578 $html = '';
579 if ($nonjs) {
580 $html .= '<h3>'.get_string('comments').'</h3>';
581 $html .= "<ul id='comment-list-$this->cid' class='comment-list'>";
583 $results = array();
584 $list = '';
586 foreach ($comments as $cmt) {
587 $list = '<li id="comment-'.$cmt->id.'-'.$this->cid.'">'.$this->print_comment($cmt, $nonjs).'</li>' . $list;
589 $html .= $list;
590 if ($nonjs) {
591 $html .= '</ul>';
592 $html .= $this->get_pagination($page);
594 $sesskey = sesskey();
595 $returnurl = $PAGE->url;
596 $strsubmit = get_string('submit');
597 if ($nonjs) {
598 $html .= <<<EOD
599 <form method="POST" action="{$CFG->wwwroot}/comment/comment_post.php">
600 <textarea name="content" rows="2"></textarea>
601 <input type="hidden" name="contextid" value="$this->contextid" />
602 <input type="hidden" name="action" value="add" />
603 <input type="hidden" name="area" value="$this->commentarea" />
604 <input type="hidden" name="itemid" value="$this->itemid" />
605 <input type="hidden" name="courseid" value="{$this->courseid}" />
606 <input type="hidden" name="sesskey" value="{$sesskey}" />
607 <input type="hidden" name="returnurl" value="{$returnurl}" />
608 <input type="submit" value="{$strsubmit}" />
609 </form>
610 EOD;
612 if ($return) {
613 return $html;
614 } else {
615 echo $html;
619 public function print_comment($cmt, $nonjs = true) {
620 global $OUTPUT;
621 $patterns = array();
622 $replacements = array();
624 if (!empty($cmt->delete) && empty($nonjs)) {
625 $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;
626 // add the button
628 $patterns[] = '___picture___';
629 $patterns[] = '___name___';
630 $patterns[] = '___content___';
631 $patterns[] = '___time___';
632 $replacements[] = $cmt->avatar;
633 $replacements[] = html_writer::link($cmt->profileurl, $cmt->fullname);
634 $replacements[] = $cmt->content;
635 $replacements[] = userdate($cmt->timecreated, get_string('strftimerecent', 'langconfig'));
637 // use html template to format a single comment.
638 return str_replace($patterns, $replacements, $this->template);
642 class comment_exception extends moodle_exception {
643 public $message;
644 function __construct($errorcode) {
645 $this->errorcode = $errorcode;
646 $this->message = get_string($errorcode, 'error');