rating MDL-21657 put default scale in a constant
[moodle.git] / comment / lib.php
CommitLineData
1bcb7eb5 1<?php
2
36051c9e
DC
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.
14//
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/>.
17
1bcb7eb5 18/**
36051c9e 19 * Comment is helper class to add/delete comments anywhere in moodle
1bcb7eb5 20 *
36051c9e
DC
21 * @package comment
22 * @copyright 2010 Dongsheng Cai <dongsheng@moodle.com>
1bcb7eb5 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
1bcb7eb5 25
36051c9e 26class comment {
1bcb7eb5 27 /**
36051c9e 28 * @var integer
1bcb7eb5 29 */
36051c9e
DC
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
35 */
36 private $cid;
37 private $contextid;
38 /**
39 * commentarea is used to specify different
40 * parts shared the same itemid
41 * @var string
42 */
43 private $commentarea;
44 /**
45 * itemid is used to associate with commenting content
46 * @var integer
47 */
48 private $itemid;
49
50 /**
51 * this html snippet will be used as a template
52 * to build comment content
53 * @var string
54 */
55 private $template;
56 private $context;
57 private $course;
58 /**
59 * course module object
60 * @var string
61 */
62 private $cm;
63 private $plugintype;
64 private $pluginname;
65 private $viewcap;
66 private $postcap;
67 /**
68 * to tell comments api where it is used
69 * @var string
70 */
71 private $env;
72 /**
73 * to costomize link text
74 * @var string
75 */
76 private $linktext;
77 private static $nonjs = false;
78 // will be used by non-js comments UI
79 private static $comment_itemid = null;
80 private static $comment_context = null;
81 private static $comment_area = null;
82 /**
83 * Construct function of comment class, initilize
84 * class members
85 * @param object $options
86 */
87 public function __construct($options) {
88 global $CFG, $DB;
89 $this->viewcap = false;
90 $this->postcap = false;
91 if (!empty($options->client_id)) {
92 $this->cid = $options->client_id;
93 } else {
94 $this->cid = uniqid();
95 }
96 if (!empty($options->context)) {
97 $this->context = $options->context;
98 $this->contextid = $this->context->id;
99 } else if(!empty($options->contextid)) {
100 $this->contextid = $options->contextid;
101 $this->context = get_context_instance_by_id($this->contextid);
102 } else {
103 print_error('invalidcontext');
104 }
105 if (!empty($options->area)) {
106 $this->commentarea = $options->area;
107 }
108 if (!empty($options->itemid)) {
109 $this->itemid = $options->itemid;
110 }
111 if (!empty($options->env)) {
112 $this->env = $options->env;
1bcb7eb5 113 } else {
36051c9e 114 $this->env = '';
1bcb7eb5 115 }
1bcb7eb5 116
36051c9e
DC
117 if (!empty($options->linktext)) {
118 $this->linktext = $options->linktext;
119 } else {
120 $this->linktext = get_string('comments');
121 }
122
123 $this->_setup_plugin();
124
125 $this->options = new stdclass;
126 $this->options->context = $this->context;
127 $this->options->commentarea = $this->commentarea;
128 $this->options->itemid = $this->itemid;
129
130 // load template
131 $this->template = <<<EOD
132<div class="comment-userpicture">___picture___</div>
133<div class="comment-content">
134 ___name___ - <span>___time___</span>
135 <div>___content___</div>
136</div>
137EOD;
138 if (!empty($this->plugintype)) {
139 $this->template = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'template', $this->options, $this->template);
140 }
141
142 // setting post and view permissions
143 $this->_check_permissions();
144
145 // setup course
146 if (!empty($options->course)) {
147 $this->course = $options->course;
148 } else if (!empty($options->courseid)) {
149 $courseid = $options->courseid;
150 $this->_setup_course($courseid);
151 } else {
152 $courseid = SITEID;
153 $this->_setup_course($courseid);
154 }
155 if (!empty($options->showcount)) {
156 $count = $this->count();
157 if (empty($count)) {
158 $this->count = '';
159 } else {
160 $this->count = '('.$count.')';
1bcb7eb5 161 }
36051c9e
DC
162 } else {
163 $this->count = '';
1bcb7eb5 164 }
165
36051c9e
DC
166 unset($options);
167 }
168
169 /**
170 * Receive nonjs comment parameters
171 */
172 public static function init() {
173 global $PAGE, $CFG;
174 // setup variables for non-js interface
175 self::$nonjs = optional_param('nonjscomment', '', PARAM_ALPHA);
176 self::$comment_itemid = optional_param('comment_itemid', '', PARAM_INT);
177 self::$comment_context = optional_param('comment_context', '', PARAM_INT);
178 self::$comment_area = optional_param('comment_area', '', PARAM_ALPHAEXT);
179
180 $PAGE->requires->string_for_js('addcomment', 'moodle');
181 $PAGE->requires->string_for_js('deletecomment', 'moodle');
182 $PAGE->requires->string_for_js('comments', 'moodle');
1bcb7eb5 183 }
184
185 private function _setup_course($courseid) {
186 global $COURSE, $DB;
187 if (!empty($this->course)) {
188 // already set, stop
189 return;
190 }
191 if ($courseid == $COURSE->id) {
192 $this->course = $COURSE;
193 } else if (!$this->course = $DB->get_record('course', array('id'=>$courseid))) {
194 $this->course = null;
195 }
196 }
197
36051c9e
DC
198 /**
199 * Setting module info
200 *
201 */
202 private function _setup_plugin() {
1bcb7eb5 203 global $DB;
36051c9e
DC
204 // blog needs to set env as "blog"
205 if ($this->env == 'blog') {
206 $this->plugintype = 'moodle';
207 $this->pluginname = 'blog';
208 }
209 // tag page needs to set env as "tag"
210 if ($this->env == 'tag') {
211 $this->plugintype = 'moodle';
212 $this->pluginname = 'tag';
213 }
1bcb7eb5 214 if ($this->context->contextlevel == CONTEXT_BLOCK) {
215 if ($block = $DB->get_record('block_instances', array('id'=>$this->context->instanceid))) {
216 $this->plugintype = 'block';
217 $this->pluginname = $block->blockname;
218 }
219 }
220 if ($this->context->contextlevel == CONTEXT_MODULE) {
221 $this->plugintype = 'mod';
222 $this->cm = get_coursemodule_from_id('', $this->context->instanceid);
223 $this->_setup_course($this->cm->course);
224 $this->modinfo = get_fast_modinfo($this->course);
225 $this->pluginname = $this->modinfo->cms[$this->cm->id]->modname;
226 }
227 }
228
229 /**
36051c9e
DC
230 * check posting comments permission
231 * It will check based on user roles and ask modules
232 * If you need to check permission by modules, a
233 * function named $pluginname_check_comment_post must be implemented
1bcb7eb5 234 */
36051c9e
DC
235 private function _check_permissions() {
236 global $CFG;
237 $this->postcap = has_capability('moodle/comment:post', $this->context);
238 $this->viewcap = has_capability('moodle/comment:view', $this->context);
239 if (!empty($this->plugintype)) {
240 $permissions = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'permissions', $this->options, array('post'=>true, 'view'=>true));
241 $this->postcap = $this->postcap && $permissions['post'];
242 $this->viewcap = $this->viewcap && $permissions['view'];
6f5e0852 243 }
1bcb7eb5 244 }
245
246 /**
36051c9e
DC
247 * Prepare comment code in html
248 * @param boolean $return
249 * @return mixed
1bcb7eb5 250 */
36051c9e
DC
251 public function output($return = true) {
252 global $CFG, $COURSE, $PAGE;
253
254
255 $this->link = qualified_me();
256 $murl = new moodle_url($this->link);
257 $murl->remove_params('nonjscomment');
258 $murl->param('nonjscomment', 'true');
259 $murl->param('comment_itemid', $this->options->itemid);
260 $murl->param('comment_context', $this->options->context->id);
261 $murl->param('comment_area', $this->options->commentarea);
262 $murl->remove_params('page');
263 $this->link = $murl->out();
264 $options = new stdclass;
265 $options->client_id = $this->cid;
266 $options->commentarea = $this->commentarea;
267 $options->itemid = $this->itemid;
268 $options->page = 0;
269 $options->courseid = $this->course->id;
270 $options->contextid = $this->contextid;
271 if ($this->env == 'block_comments') {
272 $options->autostart = true;
273 $options->notoggle = true;
274 }
275
276 $PAGE->requires->js_init_call('M.core_comment.init', array($options), true);
277
278 if (!empty(self::$nonjs)) {
279 return $this->print_comments($this->page, $return);
280 }
281 $strsubmit = get_string('submit');
282 $strcancel = get_string('cancel');
283 $sesskey = sesskey();
284
285 // print html template
286 if (empty($CFG->commentcommentcode) && !empty($this->viewcap)) {
287 echo '<div style="display:none" id="cmt-tmpl">' . $this->template . '</div>';
288 $CFG->commentcommentcode = true;
289 }
290
291 if (!empty($this->viewcap)) {
292 // print commenting icon and tooltip
293 $html = <<<EOD
294<div style="text-align:left">
295<a id="comment-link-{$this->cid}" href="{$this->link}">
296<img id="comment-img-{$this->cid}" src="{$CFG->wwwroot}/pix/t/collapsed.png" alt="{$this->linktext}" title="{$this->linktext}" />
297<span id="comment-link-text-{$this->cid}">{$this->linktext} {$this->count}</span>
298</a>
299<div id="comment-ctrl-{$this->cid}" class="comment-ctrl">
300 <ul id="comment-list-{$this->cid}" class="comment-list">
301 </ul>
302 <div id="comment-pagination-{$this->cid}" class="comment-pagination"></div>
303EOD;
304
305 // print posting textarea
306 if (!empty($this->postcap)) {
307 $html .= <<<EOD
308<div class='comment-area'>
309 <div class="bd">
310 <textarea name="content" rows="1" id="dlg-content-{$this->cid}"></textarea>
311 </div>
312 <div class="fd" id="comment-action-{$this->cid}">
313 <a href="###" id="comment-action-post-{$this->cid}"> {$strsubmit} </a>
314EOD;
315 if ($this->env != 'block_comments') {
316 $html .= <<<EOD
317 <span> | </span>
318 <a href="###" id="comment-action-cancel-{$this->cid}"> {$strcancel} </a>
319EOD;
320 }
321
322 $html .= <<<EOD
323 </div>
324</div>
325<div style="clear:both"></div>
326EOD;
327 }
328
329 $html .= <<<EOD
330</div>
331</div>
332EOD;
333 } else {
334 $html = '';
335 }
336
337 if ($return) {
338 return $html;
339 } else {
340 echo $html;
1bcb7eb5 341 }
1bcb7eb5 342 }
36051c9e 343
1bcb7eb5 344 /**
36051c9e
DC
345 * Return matched comments
346 * @param int $page
347 * @return mixed
1bcb7eb5 348 */
36051c9e
DC
349 public function get_comments($page = '') {
350 global $DB, $CFG, $USER, $OUTPUT;
351 if (empty($this->viewcap)) {
352 return false;
353 }
354 $CFG->commentsperpage = 15;
355 if (!is_numeric($page)) {
356 $page = 0;
357 }
358 $this->page = $page;
359 $params = array();
360 $start = $page * $CFG->commentsperpage;
361 $sql = "SELECT c.id, c.userid, c.content, c.format, c.timecreated, u.picture, u.imagealt, u.username, u.firstname, u.lastname
362 FROM {comments} c, {user} u WHERE u.id=c.userid AND c.contextid=? AND c.commentarea=? AND c.itemid=?
363 ORDER BY c.timecreated DESC";
364 $params[] = $this->contextid;
365 $params[] = $this->commentarea;
366 $params[] = $this->itemid;
367
368 $comments = array();
369 $candelete = has_capability('moodle/comment:delete', $this->context);
370 if ($records = $DB->get_records_sql($sql, $params, $start, $CFG->commentsperpage)) {
371 foreach ($records as &$c) {
372 $url = $CFG->httpswwwroot.'/user/view.php?id='.$c->userid.'&amp;course='.$this->course->id;
373 $c->username = '<a href="'.$url.'">'.fullname($c).'</a>';
374 $c->time = userdate($c->timecreated, get_string('strftimerecent', 'langconfig'));
375 $user = new stdclass;
376 $user->id = $c->userid;
377 $user->picture = $c->picture;
378 $user->firstname = $c->firstname;
379 $user->lastname = $c->lastname;
380 $user->imagealt = $c->imagealt;
381 $c->content = format_text($c->content, $c->format);
382 $c->avatar = $OUTPUT->user_picture($user, array('size'=>18));
383 if (($USER->id == $c->userid) || !empty($candelete)) {
384 $c->delete = true;
385 }
386 $comments[] = $c;
387 }
388 }
389
390 if (!empty($this->plugintype)) {
391 // moodle module will filter comments
392 plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'display', array(&$comments, $this->options));
393 }
394
395 return $comments;
396 }
397
398 public function count() {
1bcb7eb5 399 global $DB;
36051c9e
DC
400 if ($count = $DB->count_records('comments', array('itemid'=>$this->itemid, 'commentarea'=>$this->commentarea, 'contextid'=>$this->context->id))) {
401 return $count;
402 } else {
403 return 0;
404 }
405 }
406
407 public function get_pagination($page = 0) {
408 global $DB, $CFG, $OUTPUT;
409 $count = $this->count();
410 $pages = (int)ceil($count/$CFG->commentsperpage);
411 if ($pages == 1 || $pages == 0) {
412 return '';
413 }
414 if (!empty(self::$nonjs)) {
415 // used in non-js interface
416 return $OUTPUT->paging_bar($count, $page, $CFG->commentsperpage, $this->link);
417 } else {
418 // return ajax paging bar
419 $str = '';
420 $str .= '<div class="comment-paging" id="comment-paging-'.$this->cid.'">';
421 for ($p=0; $p<$pages; $p++) {
422 $extra = '';
423 if ($p == $page) {
424 $extra = ' style="border:1px solid grey" ';
1bcb7eb5 425 }
36051c9e
DC
426 $str .= '<a class="pageno" href="###"'.$extra.' id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
427 }
428 $str .= '</div>';
429 }
430 return $str;
431 }
432
433 /**
434 * Add a new comment
435 * @param string $content
436 * @return mixed
437 */
438 public function add($content, $format = FORMAT_MOODLE) {
439 global $CFG, $DB, $USER, $OUTPUT;
440 if (empty($this->postcap)) {
441 throw new comment_exception('nopermissiontocomment');
442 }
443 $now = time();
444 $newcmt = new stdclass;
445 $newcmt->contextid = $this->contextid;
446 $newcmt->commentarea = $this->commentarea;
447 $newcmt->itemid = $this->itemid;
448 $newcmt->content = $content;
449 $newcmt->format = $format;
450 $newcmt->userid = $USER->id;
451 $newcmt->timecreated = $now;
452
453 if (!empty($this->plugintype)) {
454 // moodle module will check content
455 $ret = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'add', array(&$newcmt, $this->options), true);
456 if (!$ret) {
457 throw new comment_exception('modulererejectcomment');
1bcb7eb5 458 }
459 }
36051c9e
DC
460
461 $cmt_id = $DB->insert_record('comments', $newcmt);
462 if (!empty($cmt_id)) {
463 $newcmt->id = $cmt_id;
464 $newcmt->time = userdate($now, get_string('strftimerecent', 'langconfig'));
465 $newcmt->username = fullname($USER);
466 $newcmt->content = format_text($newcmt->content);
467 $newcmt->avatar = $OUTPUT->user_picture($USER, array('size'=>16));
468 return $newcmt;
469 } else {
470 throw new comment_exception('dbupdatefailed');
471 }
472 }
473
474 /**
475 * delete by context, commentarea and itemid
476 *
477 */
478 public function delete_comments() {
479 global $DB;
480 return $DB->delete_records('comments', array(
481 'contextid'=>$this->context->id,
482 'commentarea'=>$this->commentarea,
483 'itemid'=>$this->itemid)
484 );
485 }
486
487 /**
488 * Delete a comment
489 * @param int $commentid
490 * @return mixed
491 */
492 public function delete($commentid) {
493 global $DB, $USER;
494 $candelete = has_capability('moodle/comment:delete', $this->context);
495 if (!$comment = $DB->get_record('comments', array('id'=>$commentid))) {
496 throw new comment_exception('dbupdatefailed');
497 }
498 if (!($USER->id == $comment->userid || !empty($candelete))) {
499 throw new comment_exception('nopermissiontocomment');
500 }
501 return $DB->delete_records('comments', array('id'=>$commentid));
502 }
503
504 public function print_comments($page = 0, $return = true) {
505 global $DB, $CFG;
506 $html = '';
507 if (!(self::$comment_itemid == $this->options->itemid &&
508 self::$comment_context == $this->options->context->id &&
509 self::$comment_area == $this->options->commentarea)) {
510 $page = 0;
511 }
512 $comments = $this->get_comments($page);
513
514 $html .= '<h3>'.get_string('comments').'</h3>';
515 $html .= "<ul id='comment-list-$this->cid' class='comment-list'>";
516 $results = array();
517 $list = '';
518 foreach ($comments as $cmt) {
519 $list = $this->print_comment($cmt, $this->contextid, $this->commentarea, $this->itemid) . $list;
520 }
521 $html .= $list;
522 $html .= '</ul>';
523 $html .= $this->get_pagination($page);
524 $sesskey = sesskey();
525 $returnurl = qualified_me();
526 $strsubmit = get_string('submit');
527 $html .= <<<EOD
528<form method="POST" action="{$CFG->wwwroot}/comment/comment_post.php">
529<textarea name="content" rows="1"></textarea>
530<input type="hidden" name="contextid" value="$this->contextid" />
531<input type="hidden" name="action" value="add" />
532<input type="hidden" name="area" value="$this->commentarea" />
533<input type="hidden" name="itemid" value="$this->itemid" />
534<input type="hidden" name="courseid" value="{$this->course->id}" />
535<input type="hidden" name="sesskey" value="{$sesskey}" />
536<input type="hidden" name="returnurl" value="{$returnurl}" />
537<input type="submit" value="{$strsubmit}" />
538</form>
539EOD;
540 if ($return) {
541 return $html;
542 } else {
543 echo $html;
544 }
545 }
546
547 public function print_comment($cmt) {
548 $patterns = array();
549 $replacements = array();
550
551 $patterns[] = '___picture___';
552 $patterns[] = '___name___';
553 $patterns[] = '___content___';
554 $patterns[] = '___time___';
555 $replacements[] = $cmt->avatar;
556 $replacements[] = fullname($cmt);
557 $replacements[] = $cmt->content;
558 $replacements[] = userdate($cmt->timecreated, get_string('strftimerecent', 'langconfig'));
559
560 // use html template to format a single comment.
561 return str_replace($patterns, $replacements, $this->template);
562 }
563}
564
565class comment_exception extends moodle_exception {
566 public $message;
567 function __construct($errorcode) {
568 $this->errorcode = $errorcode;
569 $this->message = get_string($errorcode, 'error');
1bcb7eb5 570 }
571}