"MDL-23917, added component parameter to comment api"
[moodle.git] / comment / lib.php
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.
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/>.
18 /**
19  * Comment is helper class to add/delete comments anywhere in moodle
20  *
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
24  */
26 class comment {
27     /**
28      * @var integer
29      */
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;
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 $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
62      */
63     private $cm;
64     private $plugintype;
65     /**
66      * When used in module, it is recommended to use it
67      * @var string
68      */
69     private $pluginname;
70     private $viewcap;
71     private $postcap;
72     /**
73      * to tell comments api where it is used
74      * @var string
75      */
76     private $env;
77     /**
78      * to costomize link text
79      * @var string
80      */
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
93      */
94     public function __construct($options) {
95         global $CFG, $DB;
97         if (empty($CFG->commentsperpage)) {
98             $CFG->commentsperpage = 15;
99         }
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();
109         }
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');
120         }
122         if (!empty($options->component)) {
123             $this->set_component($options->component);
124         }
126         // setup course
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;
132         } else {
133             $this->courseid = SITEID;
134         }
136         // setup coursemodule
137         if (!empty($options->cm)) {
138             $this->cm = $options->cm;
139         } else {
140             $this->cm = null;
141         }
143         // setup commentarea
144         if (!empty($options->area)) {
145             $this->commentarea = $options->area;
146         }
148         // setup itemid
149         if (!empty($options->itemid)) {
150             $this->itemid = $options->itemid;
151         } else {
152             $this->itemid = 0;
153         }
155         // setup env
156         if (!empty($options->env)) {
157             $this->env = $options->env;
158         } else {
159             $this->env = '';
160         }
162         // setup customized linktext
163         if (!empty($options->linktext)) {
164             $this->linktext = $options->linktext;
165         } else {
166             $this->linktext = get_string('comments');
167         }
169         if (!empty($options->showcount)) {
170             $count = $this->count();
171             if (empty($count)) {
172                 $this->count = '';
173             } else {
174                 $this->count = '('.$count.')';
175             }
176         } else {
177             $this->count = '';
178         }
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();
191         // load template
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>
197 </div>
198 EOD;
199         if (!empty($this->plugintype)) {
200             $this->template = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'template', $this->args, $this->template);
201         }
203         unset($options);
204     }
206     /**
207      * Receive nonjs comment parameters
208      */
209     public static function init() {
210         global $PAGE, $CFG;
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');
221     }
223     public function set_component($component) {
224         $this->component = $component;
225         list($this->plugintype, $this->pluginname) = normalize_component($component);
226         return null;
227     }
229     public function set_view_permission($value) {
230         $this->viewcap = $value;
231     }
233     public function set_post_permission($value) {
234         $this->postcap = $value;
235     }
237     /**
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
242      */
243     private function check_permissions() {
244         global $CFG;
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'];
251         }
252     }
254     /**
255      * Prepare comment code in html
256      * @param  boolean $return
257      * @return mixed
258      */
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;
277         $options->page   = 0;
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;
285         }
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);
292         }
294         $strsubmit = get_string('savecomment');
295         $strcancel = get_string('cancel');
296         $strshowcomments = get_string('showcommentsnonjs');
297         $sesskey = sesskey();
298         $html = '';
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;
304         }
306         if (!empty($this->viewcap)) {
307             // print commenting icon and tooltip
308             $icon = $OUTPUT->pix_url('t/collapsed');
309             $html .= <<<EOD
310 <div class="mdl-left">
311 <noscript>
312 <a href="{$this->link}">{$strshowcomments}</a>
313 </noscript>
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>
317 </a>
318 <div id="comment-ctrl-{$this->cid}" class="comment-ctrl">
319     <ul id="comment-list-{$this->cid}" class="comment-list">
320 EOD;
321             // in comments block, we print comments list right away
322             if ($this->env == 'block_comments') {
323                 $html .= $this->print_comments(0, true, false);
324                 $html .= '</ul>';
325                 $html .= $this->get_pagination(0);
326             } else {
327                 $html .= <<<EOD
328     </ul>
329     <div id="comment-pagination-{$this->cid}" class="comment-pagination"></div>
330 EOD;
331             }
333             // print posting textarea
334             if (!empty($this->postcap)) {
335                 $html .= <<<EOD
336 <div class='comment-area'>
337     <div class="bd">
338         <textarea name="content" rows="2" id="dlg-content-{$this->cid}"></textarea>
339     </div>
340     <div class="fd" id="comment-action-{$this->cid}">
341         <a href="#" id="comment-action-post-{$this->cid}"> {$strsubmit} </a>
342 EOD;
343         if ($this->env != 'block_comments') {
344             $html .= <<<EOD
345         <span> | </span>
346         <a href="#" id="comment-action-cancel-{$this->cid}"> {$strcancel} </a>
347 EOD;
348         }
350         $html .= <<<EOD
351     </div>
352 </div>
353 <div class="clearer"></div>
354 EOD;
355             }
357             $html .= <<<EOD
358 </div><!-- end of comment-ctrl -->
359 </div>
360 EOD;
361         } else {
362             $html = '';
363         }
365         if ($return) {
366             return $html;
367         } else {
368             echo $html;
369         }
370     }
372     /**
373      * Return matched comments
374      *
375      * @param  int $page
376      * @return mixed
377      */
378     public function get_comments($page = '') {
379         global $DB, $CFG, $USER, $OUTPUT;
380         if (empty($this->viewcap)) {
381             return false;
382         }
383         if (!is_numeric($page)) {
384             $page = 0;
385         }
386         $this->page = $page;
387         $params = array();
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
391                   FROM {comments} c
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;
399         $comments = array();
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) {
403             $c = new object();
404             $c->id          = $u->cid;
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)) {
417                 $c->delete = true;
418             }
419             $comments[] = $c;
420         }
421         $rs->close();
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);
426         }
428         return $comments;
429     }
431     public function count() {
432         global $DB;
433         if ($count = $DB->count_records('comments', array('itemid'=>$this->itemid, 'commentarea'=>$this->commentarea, 'contextid'=>$this->context->id))) {
434             return $count;
435         } else {
436             return 0;
437         }
438     }
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) {
445             return '';
446         }
447         if (!empty(self::$nonjs)) {
448             // used in non-js interface
449             return $OUTPUT->paging_bar($count, $page, $CFG->commentsperpage, $this->link, 'comment_page');
450         } else {
451             // return ajax paging bar
452             $str = '';
453             $str .= '<div class="comment-paging" id="comment-pagination-'.$this->cid.'">';
454             for ($p=0; $p<$pages; $p++) {
455                 if ($p == $page) {
456                     $class = 'curpage';
457                 } else {
458                     $class = 'pageno';
459                 }
460                 $str .= '<a href="#" class="'.$class.'" id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
461             }
462             $str .= '</div>';
463         }
464         return $str;
465     }
467     /**
468      * Add a new comment
469      * @param string $content
470      * @return mixed
471      */
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');
476         }
477         $now = time();
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);
490             if (!$ret) {
491                 throw new comment_exception('modulererejectcomment');
492             }
493         }
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));
505             return $newcmt;
506         } else {
507             throw new comment_exception('dbupdatefailed');
508         }
509     }
511     /**
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]
517     * }
518      * @return boolean
519      */
520     public function delete_comments($param) {
521         global $DB;
522         $param = (array)$param;
523         if (empty($param['contextid'])) {
524             return false;
525         }
526         $DB->delete_records('comments', $param);
527         return true;
528     }
530     /**
531      * Delete a comment
532      * @param  int $commentid
533      * @return mixed
534      */
535     public function delete($commentid) {
536         global $DB, $USER;
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');
540         }
541         if (!($USER->id == $comment->userid || !empty($candelete))) {
542             throw new comment_exception('nopermissiontocomment');
543         }
544         $DB->delete_records('comments', array('id'=>$commentid));
545         return true;
546     }
548     /**
549      * Print comments
550      * @param int $page
551      * @param boolean $return return comments list string or print it out
552      * @param boolean $nonjs print nonjs comments list or not?
553      * @return mixed
554      */
555     public function print_comments($page = 0, $return = true, $nonjs = true) {
556         global $DB, $CFG, $PAGE;
557         $html = '';
558         if (!(self::$comment_itemid == $this->itemid &&
559             self::$comment_context == $this->context->id &&
560             self::$comment_area == $this->commentarea)) {
561             $page = 0;
562         }
563         $comments = $this->get_comments($page);
565         $html = '';
566         if ($nonjs) {
567             $html .= '<h3>'.get_string('comments').'</h3>';
568             $html .= "<ul id='comment-list-$this->cid' class='comment-list'>";
569         }
570         $results = array();
571         $list = '';
573         foreach ($comments as $cmt) {
574             $list = '<li id="comment-'.$cmt->id.'-'.$this->cid.'">'.$this->print_comment($cmt, $nonjs).'</li>' . $list;
575         }
576         $html .= $list;
577         if ($nonjs) {
578             $html .= '</ul>';
579             $html .= $this->get_pagination($page);
580         }
581         $sesskey = sesskey();
582         $returnurl = $PAGE->url;
583         $strsubmit = get_string('submit');
584         if ($nonjs) {
585         $html .= <<<EOD
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}" />
596 </form>
597 EOD;
598         }
599         if ($return) {
600             return $html;
601         } else {
602             echo $html;
603         }
604     }
606     public function print_comment($cmt, $nonjs = true) {
607         global $OUTPUT;
608         $patterns = array();
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;
613             // add the button
614         }
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);
626     }
629 class comment_exception extends moodle_exception {
630     public $message;
631     function __construct($errorcode) {
632         $this->errorcode = $errorcode;
633         $this->message = get_string($errorcode, 'error');
634     }