3d1afd95b8b91adb6fa6ecaefb23c24088601a4a
[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         }
110         
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         // 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         }
130         if (!empty($options->pluginname)) {
131             $this->pluginname = $options->pluginname;
132         }
133         
134         // setup coursemodule
135         if (!empty($options->cm)) {
136             $this->cm = $options->cm;
137         } else {
138             $this->cm = null;
139         }
141         // setup commentarea
142         if (!empty($options->area)) {
143             $this->commentarea = $options->area;
144         }
146         // setup itemid
147         if (!empty($options->itemid)) {
148             $this->itemid = $options->itemid;
149         }
151         // setup env
152         if (!empty($options->env)) {
153             $this->env = $options->env;
154         } else {
155             $this->env = '';
156         }
158         // setup customized linktext
159         if (!empty($options->linktext)) {
160             $this->linktext = $options->linktext;
161         } else {
162             $this->linktext = get_string('comments');
163         }
164         // setting post and view permissions
165         $this->check_permissions();
167         if (!empty($options->showcount)) {
168             $count = $this->count();
169             if (empty($count)) {
170                 $this->count = '';
171             } else {
172                 $this->count = '('.$count.')';
173             }
174         } else {
175             $this->count = '';
176         }
178         $this->setup_plugin();
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         // load template
189         $this->template = <<<EOD
190 <div class="comment-userpicture">___picture___</div>
191 <div class="comment-content">
192     ___name___ - <span>___time___</span>
193     <div>___content___</div>
194 </div>
195 EOD;
196         if (!empty($this->plugintype)) {
197             $this->template = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'template', $this->args, $this->template);
198         }
200         unset($options);
201     }
203     /**
204      * Receive nonjs comment parameters
205      */
206     public static function init() {
207         global $PAGE, $CFG;
208         // setup variables for non-js interface
209         self::$nonjs = optional_param('nonjscomment', '', PARAM_ALPHA);
210         self::$comment_itemid  = optional_param('comment_itemid',  '', PARAM_INT);
211         self::$comment_context = optional_param('comment_context', '', PARAM_INT);
212                 self::$comment_page    = optional_param('comment_page',    '', PARAM_INT);
213         self::$comment_area    = optional_param('comment_area',    '', PARAM_ALPHAEXT);
215         $PAGE->requires->string_for_js('addcomment', 'moodle');
216         $PAGE->requires->string_for_js('deletecomment', 'moodle');
217         $PAGE->requires->string_for_js('comments', 'moodle');
218     }
220     /**
221      * Setup plugin type and plugin name
222      */
223     private function setup_plugin() {
224         global $DB;
225         // blog needs to set env as "blog"
226         if ($this->env == 'blog') {
227             $this->plugintype = 'moodle';
228             $this->pluginname = 'blog';
229         }
230         // tag page needs to set env as "tag"
231         if ($this->env == 'tag') {
232             $this->plugintype = 'moodle';
233             $this->pluginname = 'tag';
234         }
235         if ($this->context->contextlevel == CONTEXT_BLOCK) {
236             if ($block = $DB->get_record('block_instances', array('id'=>$this->context->instanceid))) {
237                 $this->plugintype = 'block';
238                 $this->pluginname = $block->blockname;
239             }
240         }
242         if ($this->context->contextlevel == CONTEXT_MODULE) {
243             $this->plugintype = 'mod';
244             // to improve performance, pluginname should be assigned before initilise comment object
245             // if it is empty, we will try to guess, it will rarely be used.
246             if (empty($this->pluginname)) {
247                 if (empty($this->course)) {
248                     $this->course = $DB->get_record('course', array('id'=>$this->courseid), '*', MUST_EXIST);
249                 }
250                 $this->modinfo = get_fast_modinfo($this->course);
251                 $this->pluginname = $this->modinfo->cms[$this->cm->id]->modname;
252             }
253         }
254     }
256     /**
257      * check posting comments permission
258      * It will check based on user roles and ask modules
259      * If you need to check permission by modules, a
260      * function named $pluginname_check_comment_post must be implemented
261      */
262     private function check_permissions() {
263         global $CFG;
264         $this->postcap = has_capability('moodle/comment:post', $this->context);
265         $this->viewcap = has_capability('moodle/comment:view', $this->context);
266         if (!empty($this->plugintype)) {
267             $permissions = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'permissions', $this->args, array('post'=>true, 'view'=>true));
268             $this->postcap = $this->postcap && $permissions['post'];
269             $this->viewcap = $this->viewcap && $permissions['view'];
270         }
271     }
273     /**
274      * Prepare comment code in html
275      * @param  boolean $return
276      * @return mixed
277      */
278     public function output($return = true) {
279         global $PAGE, $OUTPUT;
280                 static $template_printed;
282         $this->link = $PAGE->url;
283         $murl = new moodle_url($this->link);
284         $murl->remove_params('nonjscomment');
285         $murl->param('nonjscomment', 'true');
286         $murl->param('comment_itemid', $this->itemid);
287         $murl->param('comment_context', $this->context->id);
288         $murl->param('comment_area', $this->commentarea);
289         $murl->remove_params('comment_page');
290         $this->link = $murl->out();
292         $options = new stdclass;
293         $options->client_id = $this->cid;
294         $options->commentarea = $this->commentarea;
295         $options->itemid = $this->itemid;
296         $options->page   = 0;
297         $options->courseid = $this->courseid;
298         $options->contextid = $this->contextid;
299         $options->env = $this->env;
300         if ($this->env == 'block_comments') {
301             $options->autostart = true;
302             $options->notoggle = true;
303         }
305         $PAGE->requires->js_init_call('M.core_comment.init', array($options), true);
307         if (!empty(self::$nonjs)) {
308             // return non js comments interface
309             return $this->print_comments(self::$comment_page, $return, true);
310         }
312         $strsubmit = get_string('submit');
313         $strcancel = get_string('cancel');
314         $sesskey = sesskey();
315         $html = '';
316         // print html template
317         // Javascript will use the template to render new comments
318         if (empty($template_printed) && !empty($this->viewcap)) {
319             $html .= '<div style="display:none" id="cmt-tmpl">' . $this->template . '</div>';
320             $template_printed = true;
321         }
323         if (!empty($this->viewcap)) {
324             // print commenting icon and tooltip
325             $icon = $OUTPUT->pix_url('t/collapsed');
326             $html .= <<<EOD
327 <div class="mdl-left">
328 <a id="comment-link-{$this->cid}" href="{$this->link}">
329     <img id="comment-img-{$this->cid}" src="$icon" alt="{$this->linktext}" title="{$this->linktext}" />
330     <span id="comment-link-text-{$this->cid}">{$this->linktext} {$this->count}</span>
331 </a>
332 <div id="comment-ctrl-{$this->cid}" class="comment-ctrl">
333     <ul id="comment-list-{$this->cid}" class="comment-list">
334 EOD;
335             // in comments block, we print comments list right away
336             if ($this->env == 'block_comments') {
337                 $html .= $this->print_comments(0, true, false);
338                 $html .= '</ul>';
339                 $html .= $this->get_pagination(0);
340             } else {
341                 $html .= <<<EOD
342     </ul>
343     <div id="comment-pagination-{$this->cid}" class="comment-pagination"></div>
344 EOD;
345             }
347             // print posting textarea
348             if (!empty($this->postcap)) {
349                 $html .= <<<EOD
350 <div class='comment-area'>
351     <div class="bd">
352         <textarea name="content" rows="2" id="dlg-content-{$this->cid}"></textarea>
353     </div>
354     <div class="fd" id="comment-action-{$this->cid}">
355         <a href="#" id="comment-action-post-{$this->cid}"> {$strsubmit} </a>
356 EOD;
357         if ($this->env != 'block_comments') {
358             $html .= <<<EOD
359         <span> | </span>
360         <a href="#" id="comment-action-cancel-{$this->cid}"> {$strcancel} </a>
361 EOD;
362         }
364         $html .= <<<EOD
365     </div>
366 </div>
367 <div class="clearer"></div>
368 EOD;
369             }
371             $html .= <<<EOD
372 </div><!-- end of comment-ctrl -->
373 </div>
374 EOD;
375         } else {
376             $html = '';
377         }
379         if ($return) {
380             return $html;
381         } else {
382             echo $html;
383         }
384     }
386     /**
387      * Return matched comments
388      * @param  int $page
389      * @return mixed
390      */
391     public function get_comments($page = '') {
392         global $DB, $CFG, $USER, $OUTPUT;
393         if (empty($this->viewcap)) {
394             return false;
395         }
396         if (!is_numeric($page)) {
397             $page = 0;
398         }
399         $this->page = $page;
400         $params = array();
401         $start = $page * $CFG->commentsperpage;
402         $sql = "SELECT c.id, c.userid, c.content, c.format, c.timecreated, u.picture, u.imagealt, u.username, u.firstname, u.lastname
403             FROM {comments} c, {user} u WHERE u.id=c.userid AND c.contextid=? AND c.commentarea=? AND c.itemid=?
404             ORDER BY c.timecreated DESC";
405         $params[] = $this->contextid;
406         $params[] = $this->commentarea;
407         $params[] = $this->itemid;
409         $comments = array();
410         $candelete = has_capability('moodle/comment:delete', $this->context);
411         if ($records = $DB->get_records_sql($sql, $params, $start, $CFG->commentsperpage)) {
412             foreach ($records as &$c) {
413                 $url = $CFG->httpswwwroot.'/user/view.php?id='.$c->userid.'&amp;course='.$this->courseid;
414                 $c->username = '<a href="'.$url.'">'.fullname($c).'</a>';
415                 $c->time = userdate($c->timecreated, get_string('strftimerecent', 'langconfig'));
416                 $user = new stdclass;
417                 $user->id = $c->userid;
418                 $user->picture = $c->picture;
419                 $user->firstname = $c->firstname;
420                 $user->lastname  = $c->lastname;
421                 $user->imagealt  = $c->imagealt;
422                 $c->content = format_text($c->content, $c->format);
423                 $c->avatar = $OUTPUT->user_picture($user, array('size'=>18));
424                 if (($USER->id == $c->userid) || !empty($candelete)) {
425                     $c->delete = true;
426                 }
427                 $comments[] = $c;
428             }
429         }
430         if (!empty($this->plugintype)) {
431             // moodle module will filter comments
432             $comments = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'display', array($comments, $this->args), $comments);
433         }
435         return $comments;
436     }
438     public function count() {
439         global $DB;
440         if ($count = $DB->count_records('comments', array('itemid'=>$this->itemid, 'commentarea'=>$this->commentarea, 'contextid'=>$this->context->id))) {
441             return $count;
442         } else {
443             return 0;
444         }
445     }
447     public function get_pagination($page = 0) {
448         global $DB, $CFG, $OUTPUT;
449         $count = $this->count();
450         $pages = (int)ceil($count/$CFG->commentsperpage);
451         if ($pages == 1 || $pages == 0) {
452             return '';
453         }
454         if (!empty(self::$nonjs)) {
455             // used in non-js interface
456             return $OUTPUT->paging_bar($count, $page, $CFG->commentsperpage, $this->link, 'comment_page');
457         } else {
458             // return ajax paging bar
459             $str = '';
460             $str .= '<div class="comment-paging" id="comment-pagination-'.$this->cid.'">';
461             for ($p=0; $p<$pages; $p++) {
462                 if ($p == $page) {
463                     $class = 'curpage';
464                 } else {
465                     $class = 'pageno';
466                 }
467                 $str .= '<a href="#" class="'.$class.'" id="comment-page-'.$this->cid.'-'.$p.'">'.($p+1).'</a> ';
468             }
469             $str .= '</div>';
470         }
471         return $str;
472     }
474     /**
475      * Add a new comment
476      * @param string $content
477      * @return mixed
478      */
479     public function add($content, $format = FORMAT_MOODLE) {
480         global $CFG, $DB, $USER, $OUTPUT;
481         if (empty($this->postcap)) {
482             throw new comment_exception('nopermissiontocomment');
483         }
484         $now = time();
485         $newcmt = new stdclass;
486         $newcmt->contextid    = $this->contextid;
487         $newcmt->commentarea  = $this->commentarea;
488         $newcmt->itemid       = $this->itemid;
489         $newcmt->content      = $content;
490         $newcmt->format       = $format;
491         $newcmt->userid       = $USER->id;
492         $newcmt->timecreated  = $now;
494         if (!empty($this->plugintype)) {
495             // moodle module will check content
496             $ret = plugin_callback($this->plugintype, $this->pluginname, FEATURE_COMMENT, 'add', array(&$newcmt, $this->args), true);
497             if (!$ret) {
498                 throw new comment_exception('modulererejectcomment');
499             }
500         }
502         $cmt_id = $DB->insert_record('comments', $newcmt);
503         if (!empty($cmt_id)) {
504             $newcmt->id = $cmt_id;
505             $newcmt->time = userdate($now, get_string('strftimerecent', 'langconfig'));
506             $newcmt->username = fullname($USER);
507             $newcmt->content = format_text($newcmt->content);
508             $newcmt->avatar = $OUTPUT->user_picture($USER, array('size'=>16));
509             return $newcmt;
510         } else {
511             throw new comment_exception('dbupdatefailed');
512         }
513     }
515     /**
516      * delete by context, commentarea and itemid
517      *
518      */
519     public function delete_comments() {
520         global $DB;
521         $DB->delete_records('comments', array(
522             'contextid'=>$this->context->id,
523             'commentarea'=>$this->commentarea,
524             'itemid'=>$this->itemid)
525         );
526         return true;
527     }
529     /**
530      * Delete a comment
531      * @param  int $commentid
532      * @return mixed
533      */
534     public function delete($commentid) {
535         global $DB, $USER;
536         $candelete = has_capability('moodle/comment:delete', $this->context);
537         if (!$comment = $DB->get_record('comments', array('id'=>$commentid))) {
538             throw new comment_exception('dbupdatefailed');
539         }
540         if (!($USER->id == $comment->userid || !empty($candelete))) {
541             throw new comment_exception('nopermissiontocomment');
542         }
543         $DB->delete_records('comments', array('id'=>$commentid));
544         return true;
545     }
547     /**
548      * Print comments
549      * @param int $page
550      * @param boolean $return return comments list string or print it out
551      * @param boolean $nonjs print nonjs comments list or not?
552      * @return mixed
553      */
554     public function print_comments($page = 0, $return = true, $nonjs = true) {
555         global $DB, $CFG, $PAGE;
556         $html = '';
557         if (!(self::$comment_itemid == $this->itemid &&
558             self::$comment_context == $this->context->id &&
559             self::$comment_area == $this->commentarea)) {
560             $page = 0;
561         }
562         $comments = $this->get_comments($page);
564         $html = '';
565         if ($nonjs) {
566             $html .= '<h3>'.get_string('comments').'</h3>';
567             $html .= "<ul id='comment-list-$this->cid' class='comment-list'>";
568         }
569         $results = array();
570         $list = '';
572         foreach ($comments as $cmt) {
573             $list = '<li id="comment-'.$cmt->id.'-'.$this->cid.'">'.$this->print_comment($cmt, $nonjs).'</li>' . $list;
574         }
575         $html .= $list;
576         if ($nonjs) {
577             $html .= '</ul>';
578             $html .= $this->get_pagination($page);
579         }
580         $sesskey = sesskey();
581         $returnurl = $PAGE->url;
582         $strsubmit = get_string('submit');
583         if ($nonjs) {
584         $html .= <<<EOD
585 <form method="POST" action="{$CFG->wwwroot}/comment/comment_post.php">
586 <textarea name="content" rows="2"></textarea>
587 <input type="hidden" name="contextid" value="$this->contextid" />
588 <input type="hidden" name="action" value="add" />
589 <input type="hidden" name="area" value="$this->commentarea" />
590 <input type="hidden" name="itemid" value="$this->itemid" />
591 <input type="hidden" name="courseid" value="{$this->courseid}" />
592 <input type="hidden" name="sesskey" value="{$sesskey}" />
593 <input type="hidden" name="returnurl" value="{$returnurl}" />
594 <input type="submit" value="{$strsubmit}" />
595 </form>
596 EOD;
597         }
598         if ($return) {
599             return $html;
600         } else {
601             echo $html;
602         }
603     }
605     public function print_comment($cmt, $nonjs = true) {
606         global $OUTPUT;
607         $patterns = array();
608         $replacements = array();
610         if (!empty($cmt->delete) && empty($nonjs)) {
611             $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;
612             // add the button
613         }
614         $patterns[] = '___picture___';
615         $patterns[] = '___name___';
616         $patterns[] = '___content___';
617         $patterns[] = '___time___';
618         $replacements[] = $cmt->avatar;
619         $replacements[] = fullname($cmt);
620         $replacements[] = $cmt->content;
621         $replacements[] = userdate($cmt->timecreated, get_string('strftimerecent', 'langconfig'));
623         // use html template to format a single comment.
624         return str_replace($patterns, $replacements, $this->template);
625     }
628 class comment_exception extends moodle_exception {
629     public $message;
630     function __construct($errorcode) {
631         $this->errorcode = $errorcode;
632         $this->message = get_string($errorcode, 'error');
633     }