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