1cc4b0c71f517921c1b05025d374dcb590fb6c15
[moodle.git] / blog / locallib.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  * Classes for Blogs.
20  *
21  * @package    moodlecore
22  * @subpackage blog
23  * @copyright  2009 Nicolas Connault
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->libdir . '/filelib.php');
31 /**
32  * Blog_entry class. Represents an entry in a user's blog. Contains all methods for managing this entry.
33  * This class does not contain any HTML-generating code. See blog_listing sub-classes for such code.
34  * This class follows the Object Relational Mapping technique, its member variables being mapped to
35  * the fields of the post table.
36  *
37  * @package    moodlecore
38  * @subpackage blog
39  * @copyright  2009 Nicolas Connault
40  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41  */
42 class blog_entry {
43     // Public Database fields
44     public $id;
45     public $userid;
46     public $subject;
47     public $summary;
48     public $rating = 0;
49     public $attachment;
50     public $publishstate;
52     // Locked Database fields (Don't touch these)
53     public $courseid = 0;
54     public $groupid = 0;
55     public $module = 'blog';
56     public $moduleid = 0;
57     public $coursemoduleid = 0;
58     public $content;
59     public $format = 1;
60     public $uniquehash = '';
61     public $lastmodified;
62     public $created;
63     public $usermodified;
65     // Other class variables
66     public $form;
67     public $tags = array();
69     // Methods
70     /**
71      * Constructor. If given an id, will fetch the corresponding record from the DB.
72      *
73      * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
74      */
75     public function __construct($id=null, $params=null, $form=null) {
76         global $DB, $PAGE;
78         if (!empty($id)) {
79             $object = $DB->get_record('post', array('id' => $id));
80             foreach ($object as $var => $val) {
81                 $this->$var = $val;
82             }
83         } else if (!empty($params) && (is_array($params) || is_object($params))) {
84             foreach ($params as $var => $val) {
85                 $this->$var = $val;
86             }
87         }
89         $this->form = $form;
90     }
92     /**
93      * Prints or returns the HTML for this blog entry.
94      *
95      * @param bool $return
96      * @return string
97      */
98     public function print_html($return=false) {
100         global $USER, $CFG, $COURSE, $DB, $OUTPUT, $PAGE;
102         $user = $DB->get_record('user', array('id'=>$this->userid));
103         $cmttext = '';
104         if (!empty($CFG->usecomments) and $CFG->blogusecomments) {
105             require_once($CFG->dirroot . '/comment/lib.php');
106             // Comments
107             $cmt = new stdClass();
108             $cmt->context = get_context_instance(CONTEXT_USER, $user->id);
109             $cmt->courseid = $PAGE->course->id;
110             $cmt->area = 'format_blog';
111             $cmt->itemid = $this->id;
112             $cmt->showcount = $CFG->blogshowcommentscount;
113             $cmt->component = 'blog';
114             $comment = new comment($cmt);
115             $cmttext = $comment->output(true);
116         }
117         $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);
119         $options = array('overflowdiv'=>true);
120         $template['body'] = format_text($this->summary, $this->summaryformat, $options).$cmttext;
121         $template['title'] = format_string($this->subject);
122         $template['userid'] = $user->id;
123         $template['author'] = fullname($user);
124         $template['created'] = userdate($this->created);
126         if ($this->created != $this->lastmodified) {
127             $template['lastmod'] = userdate($this->lastmodified);
128         }
130         $template['publishstate'] = $this->publishstate;
132         $stredit = get_string('edit');
133         $strdelete = get_string('delete');
135         // Check to see if the entry is unassociated with group/course level access
136         $unassociatedentry = false;
137         if (!empty($CFG->useblogassociations) && ($this->publishstate == 'group' || $this->publishstate == 'course')) {
138             if (!$DB->record_exists('blog_association', array('blogid' => $this->id))) {
139                 $unassociatedentry = true;
140             }
141         }
143         // Start printing of the blog
144         $table = new html_table();
145         $table->cellspacing = 0;
146         $table->attributes['class'] = 'forumpost blog_entry blog'. ($unassociatedentry ? 'draft' : $template['publishstate']);
147         $table->attributes['id'] = 'b'.$this->id;
148         $table->width = '100%';
150         $picturecell = new html_table_cell();
151         $picturecell->attributes['class'] = 'picture left';
152         $picturecell->text = $OUTPUT->user_picture($user);
154         $table->head[] = $picturecell;
156         $topiccell = new html_table_cell();
157         $topiccell->attributes['class'] = 'topic starter';
158         $titlelink =  html_writer::link(new moodle_url('/blog/index.php', array('entryid' => $this->id)), $template['title']);
159         $topiccell->text = $OUTPUT->container($titlelink, 'subject');
160         $topiccell->text .= $OUTPUT->container_start('author');
162         $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $PAGE->course->id)));
163         $by = new stdClass();
164         $by->name =  html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $PAGE->course->id)), $fullname);
165         $by->date = $template['created'];
167         $topiccell->text .= get_string('bynameondate', 'forum', $by);
168         $topiccell->text .= $OUTPUT->container_end();
170         if ($this->uniquehash && $this->content) {
171             if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {
172                 $urlparts = parse_url($externalblog->url);
173                 $topiccell->text .= $OUTPUT->container(get_string('retrievedfrom', 'blog').get_string('labelsep', 'langconfig').html_writer::link($urlparts['scheme'].'://'.$urlparts['host'], $externalblog->name), 'externalblog');
174             }
175         }
177         $topiccell->header = false;
178         $table->head[] = $topiccell;
180         // Actual content
181         $mainrow = new html_table_row();
183         $leftsidecell = new html_table_cell();
184         $leftsidecell->attributes['class'] = 'left side';
185         $mainrow->cells[] = $leftsidecell;
187         $contentcell = new html_table_cell();
188         $contentcell->attributes['class'] = 'content';
190         $attachedimages = $OUTPUT->container($this->print_attachments(), 'attachments');
192         // retrieve associations in case they're needed early
193         $blogassociations = $DB->get_records('blog_association', array('blogid' => $this->id));
195         // determine text for publish state
196         switch ($template['publishstate']) {
197             case 'draft':
198                 $blogtype = get_string('publishtonoone', 'blog');
199             break;
200             case 'site':
201                 $blogtype = get_string('publishtosite', 'blog');
202             break;
203             case 'public':
204                 $blogtype = get_string('publishtoworld', 'blog');
205             break;
206             default:
207                 $blogtype = '';
208             break;
210         }
212         $contentcell->text .= $OUTPUT->container($blogtype, 'audience');
214         $contentcell->text .= $template['body'];
215         $contentcell->text .= $attachedimages;
217         // Uniquehash is used as a link to an external blog
218         if (!empty($this->uniquehash)) {
219             $contentcell->text .= $OUTPUT->container_start('externalblog');
220             $contentcell->text .= html_writer::link($this->uniquehash, get_string('linktooriginalentry', 'blog'));
221             $contentcell->text .= $OUTPUT->container_end();
222         }
224         // Links to tags
225         $officialtags = tag_get_tags_csv('post', $this->id, TAG_RETURN_HTML, 'official');
226         $defaulttags = tag_get_tags_csv('post', $this->id, TAG_RETURN_HTML, 'default');
228         if (!empty($CFG->usetags) && ($officialtags || $defaulttags) ) {
229             $contentcell->text .= $OUTPUT->container_start('tags');
231             if ($officialtags) {
232                 $contentcell->text .= get_string('tags', 'tag') .': '. $OUTPUT->container($officialtags, 'officialblogtags');
233                 if ($defaulttags) {
234                     $contentcell->text .=  ', ';
235                 }
236             }
237             $contentcell->text .=  $defaulttags;
238             $contentcell->text .= $OUTPUT->container_end();
239         }
241         // Add associations
242         if (!empty($CFG->useblogassociations) && $blogassociations) {
243             $contentcell->text .= $OUTPUT->container_start('tags');
244             $assocstr = '';
245             $hascourseassocs = false;
246             $assoctype = '';
248             // First find and show the associated course
249             foreach ($blogassociations as $assocrec) {
250                 $contextrec = $DB->get_record('context', array('id' => $assocrec->contextid));
251                 if ($contextrec->contextlevel ==  CONTEXT_COURSE) {
252                     $assocurl = new moodle_url('/course/view.php', array('id' => $contextrec->instanceid));
253                     $text = $DB->get_field('course', 'shortname', array('id' => $contextrec->instanceid)); //TODO: performance!!!!
254                     $assocstr .= $OUTPUT->action_icon($assocurl, new pix_icon('i/course', $text), null, array(), true);
255                     $hascourseassocs = true;
256                     $assoctype = get_string('course');
257                 }
258             }
260             // Now show mod association
261             foreach ($blogassociations as $assocrec) {
262                 $contextrec = $DB->get_record('context', array('id' => $assocrec->contextid));
264                 if ($contextrec->contextlevel ==  CONTEXT_MODULE) {
265                     if ($hascourseassocs) {
266                         $assocstr .= ', ';
267                         $hascourseassocs = false;
268                     }
270                     $modinfo = $DB->get_record('course_modules', array('id' => $contextrec->instanceid));
271                     $modname = $DB->get_field('modules', 'name', array('id' => $modinfo->module));
273                     $assocurl = new moodle_url('/mod/'.$modname.'/view.php', array('id' => $modinfo->id));
274                     $text = $DB->get_field($modname, 'name', array('id' => $modinfo->instance)); //TODO: performance!!!!
275                     $assocstr .= $OUTPUT->action_icon($assocurl, new pix_icon('icon', $text, $modname), null, array(), true);
276                     $assocstr .= ', ';
277                     $assoctype = get_string('modulename', $modname);
279                 }
280             }
281             $assocstr = substr($assocstr, 0, -2);
282             $contentcell->text .= get_string('associated', 'blog', $assoctype) . ': '. $assocstr;
284             $contentcell->text .= $OUTPUT->container_end();
285         }
287         if ($unassociatedentry) {
288             $contentcell->text .= $OUTPUT->container(get_string('associationunviewable', 'blog'), 'noticebox');
289         }
291     /// Commands
293         $contentcell->text .= $OUTPUT->container_start('commands');
295         if (blog_user_can_edit_entry($this) && empty($this->uniquehash)) {
296             $contentcell->text .= html_writer::link(new moodle_url('/blog/edit.php', array('action' => 'edit', 'entryid' => $this->id)), $stredit) . ' | ';
297             $contentcell->text .= html_writer::link(new moodle_url('/blog/edit.php', array('action' => 'delete', 'entryid' => $this->id)), $strdelete) . ' | ';
298         }
300         $contentcell->text .= html_writer::link(new moodle_url('/blog/index.php', array('entryid' => $this->id)), get_string('permalink', 'blog'));
302         $contentcell->text .= $OUTPUT->container_end();
304         if (isset($template['lastmod']) ){
305             $contentcell->text .= '<div style="font-size: 55%;">';
306             $contentcell->text .= ' [ '.get_string('modified').': '.$template['lastmod'].' ]';
307             $contentcell->text .= '</div>';
308         }
310         $mainrow->cells[] = $contentcell;
311         $table->data = array($mainrow);
313         if ($return) {
314             return html_writer::table($table);
315         } else {
316             echo html_writer::table($table);
317         }
318     }
320     /**
321      * Inserts this entry in the database. Access control checks must be done by calling code.
322      *
323      * @param mform $form Used for attachments
324      * @return void
325      */
326     public function process_attachment($form) {
327         $this->form = $form;
328     }
330     /**
331      * Inserts this entry in the database. Access control checks must be done by calling code.
332      * TODO Set the publishstate correctly
333      * @param mform $form Used for attachments
334      * @return void
335      */
336     public function add() {
337         global $CFG, $USER, $DB;
339         unset($this->id);
340         $this->module       = 'blog';
341         $this->userid       = (empty($this->userid)) ? $USER->id : $this->userid;
342         $this->lastmodified = time();
343         $this->created      = time();
345         // Insert the new blog entry.
346         $this->id = $DB->insert_record('post', $this);
348         // Update tags.
349         $this->add_tags_info();
351         if (!empty($CFG->useblogassociations)) {
352             $this->add_associations();
353             add_to_log(SITEID, 'blog', 'add', 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
354         }
356         tag_set('post', $this->id, $this->tags);
357     }
359     /**
360      * Updates this entry in the database. Access control checks must be done by calling code.
361      *
362      * @param mform $form Used for attachments
363      * @return void
364      */
365     public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
366         global $CFG, $USER, $DB, $PAGE;
368         $sitecontext = get_context_instance(CONTEXT_SYSTEM);
369         $entry = $this;
371         $this->form = $form;
372         foreach ($params as $var => $val) {
373             $entry->$var = $val;
374         }
376         $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
377         $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
379         if (!empty($CFG->useblogassociations)) {
380             $entry->add_associations();
381         }
383         $entry->lastmodified = time();
385         // Update record
386         $DB->update_record('post', $entry);
387         tag_set('post', $entry->id, $entry->tags);
389         add_to_log(SITEID, 'blog', 'update', 'index.php?userid='.$USER->id.'&entryid='.$entry->id, $entry->subject);
390     }
392     /**
393      * Deletes this entry from the database. Access control checks must be done by calling code.
394      *
395      * @return void
396      */
397     public function delete() {
398         global $DB, $USER;
400         $returnurl = '';
402         $this->delete_attachments();
404         $DB->delete_records('post', array('id' => $this->id));
405         tag_set('post', $this->id, array());
407         add_to_log(SITEID, 'blog', 'delete', 'index.php?userid='. $this->userid, 'deleted blog entry with entry id# '. $this->id);
408     }
410     /**
411      * function to add all context associations to an entry
412      * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
413      */
414     public function add_associations($action='add') {
415         global $DB, $USER;
417         $this->remove_associations();
419         if (!empty($this->courseassoc)) {
420             $this->add_association($this->courseassoc, $action);
421         }
423         if (!empty($this->modassoc)) {
424             $this->add_association($this->modassoc, $action);
425         }
426     }
428     /**
429      * add a single association for a blog entry
430      * @param int contextid - id of context to associate with the blog entry
431      */
432     public function add_association($contextid, $action='add') {
433         global $DB, $USER;
435         $assocobject = new StdClass;
436         $assocobject->contextid = $contextid;
437         $assocobject->blogid = $this->id;
438         $DB->insert_record('blog_association', $assocobject);
440         $context = get_context_instance_by_id($contextid);
441         $courseid = null;
443         if ($context->contextlevel == CONTEXT_COURSE) {
444             $courseid = $context->instanceid;
445             add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
446         } else if ($context->contextlevel == CONTEXT_MODULE) {
447             $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
448             $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
449             add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
450         }
451     }
453     /**
454      * remove all associations for a blog entry
455      * @return voic
456      */
457     public function remove_associations() {
458         global $DB;
459         $DB->delete_records('blog_association', array('blogid' => $this->id));
460     }
462     /**
463      * Deletes all the user files in the attachments area for an entry
464      *
465      * @return void
466      */
467     public function delete_attachments() {
468         $fs = get_file_storage();
469         $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
470         $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
471     }
473     /**
474      * if return=html, then return a html string.
475      * if return=text, then return a text-only string.
476      * otherwise, print HTML for non-images, and return image HTML
477      *
478      * @param bool $return Whether to return or print the generated code
479      * @return void
480      */
481     public function print_attachments($return=false) {
482         global $CFG, $OUTPUT;
484         require_once($CFG->libdir.'/filelib.php');
486         $fs = get_file_storage();
488         $syscontext = get_context_instance(CONTEXT_SYSTEM);
490         $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
492         $imagereturn = "";
493         $output = "";
495         $strattachment = get_string("attachment", "forum");
497         foreach ($files as $file) {
498             if ($file->is_directory()) {
499                 continue;
500             }
502             $filename = $file->get_filename();
503             $ffurl    = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$this->id.'/'.$filename);
504             $mimetype = $file->get_mimetype();
506             $icon     = mimeinfo_from_type("icon", $mimetype);
507             $type     = mimeinfo_from_type("type", $mimetype);
509             $image = $OUTPUT->pix_icon("f/$icon", $filename, 'moodle', array('class'=>'icon'));
511             if ($return == "html") {
512                 $output .= html_writer::link($ffurl, $image);
513                 $output .= html_writer::link($ffurl, $filename);
515             } else if ($return == "text") {
516                 $output .= "$strattachment $filename:\n$ffurl\n";
518             } else {
519                 if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) {    // Image attachments don't get printed as links
520                     $imagereturn .= "<br />" . $OUTPUT->pix_icon($ffurl, $filename);
521                 } else {
522                     $imagereturn .= html_writer::link($ffurl, $image);
523                     $imagereturn .= format_text(html_writer::link($ffurl, $filename), FORMAT_HTML, array('context'=>$syscontext));
524                 }
525             }
526         }
528         if ($return) {
529             return $output;
530         }
532         return $imagereturn;
534     }
536     /**
537      * function to attach tags into an entry
538      * @return void
539      */
540     public function add_tags_info() {
542         $tags = array();
544         if ($otags = optional_param('otags', '', PARAM_INT)) {
545             foreach ($otags as $tagid) {
546                 // TODO : make this use the tag name in the form
547                 if ($tag = tag_get('id', $tagid)) {
548                     $tags[] = $tag->name;
549                 }
550             }
551         }
553         tag_set('post', $this->id, $tags);
554     }
556     /**
557      * User can edit a blog entry if this is their own blog entry and they have
558      * the capability moodle/blog:create, or if they have the capability
559      * moodle/blog:manageentries.
560      * This also applies to deleting of entries.
561      *
562      * @param int $userid Optional. If not given, $USER is used
563      * @return boolean
564      */
565     public function can_user_edit($userid=null) {
566         global $CFG, $USER;
568         if (empty($userid)) {
569             $userid = $USER->id;
570         }
572         $sitecontext = get_context_instance(CONTEXT_SYSTEM);
574         if (has_capability('moodle/blog:manageentries', $sitecontext)) {
575             return true; // can edit any blog entry
576         }
578         if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
579             return true; // can edit own when having blog:create capability
580         }
582         return false;
583     }
585     /**
586      * Checks to see if a user can view the blogs of another user.
587      * Only blog level is checked here, the capabilities are enforced
588      * in blog/index.php
589      *
590      * @param int $targetuserid ID of the user we are checking
591      *
592      * @return bool
593      */
594     public function can_user_view($targetuserid) {
595         global $CFG, $USER, $DB;
596         $sitecontext = get_context_instance(CONTEXT_SYSTEM);
598         if (empty($CFG->bloglevel) || !has_capability('moodle/blog:view', $sitecontext)) {
599             return false; // blog system disabled or user has no blog view capability
600         }
602         if (isloggedin() && $USER->id == $targetuserid) {
603             return true; // can view own entries in any case
604         }
606         if (has_capability('moodle/blog:manageentries', $sitecontext)) {
607             return true; // can manage all entries
608         }
610         // coming for 1 entry, make sure it's not a draft
611         if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
612             return false;  // can not view draft of others
613         }
615         // coming for 1 entry, make sure user is logged in, if not a public blog
616         if ($this->publishstate != 'public' && !isloggedin()) {
617             return false;
618         }
620         switch ($CFG->bloglevel) {
621             case BLOG_GLOBAL_LEVEL:
622                 return true;
623                 break;
625             case BLOG_SITE_LEVEL:
626                 if (isloggedin()) { // not logged in viewers forbidden
627                     return true;
628                 }
629                 return false;
630                 break;
632             case BLOG_USER_LEVEL:
633             default:
634                 $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
635                 return has_capability('moodle/user:readuserblogs', $personalcontext);
636                 break;
637         }
638     }
640     /**
641      * Use this function to retrieve a list of publish states available for
642      * the currently logged in user.
643      *
644      * @return array This function returns an array ideal for sending to moodles'
645      *                choose_from_menu function.
646      */
648     public static function get_applicable_publish_states() {
649         global $CFG;
650         $options = array();
652         // everyone gets draft access
653         if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
654             $options['draft'] = get_string('publishtonoone', 'blog');
655         }
657         if ($CFG->bloglevel > BLOG_USER_LEVEL) {
658             $options['site'] = get_string('publishtosite', 'blog');
659         }
661         if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
662             $options['public'] = get_string('publishtoworld', 'blog');
663         }
665         return $options;
666     }
669 /**
670  * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
671  *
672  * @package    moodlecore
673  * @subpackage blog
674  * @copyright  2009 Nicolas Connault
675  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
676  */
677 class blog_listing {
678     /**
679      * Array of blog_entry objects.
680      * @var array $entries
681      */
682     public $entries = array();
684     /**
685      * An array of blog_filter_* objects
686      * @var array $filters
687      */
688     public $filters = array();
690     /**
691      * Constructor
692      *
693      * @param array $filters An associative array of filtername => filterid
694      */
695     public function __construct($filters=array()) {
696         // Unset filters overridden by more specific filters
697         foreach ($filters as $type => $id) {
698             if (!empty($type) && !empty($id)) {
699                 $this->filters[$type] = blog_filter::get_instance($id, $type);
700             }
701         }
703         foreach ($this->filters as $type => $filter) {
704             foreach ($filter->overrides as $override) {
705                 if (array_key_exists($override, $this->filters)) {
706                     unset($this->filters[$override]);
707                 }
708             }
709         }
710     }
712     /**
713      * Fetches the array of blog entries.
714      *
715      * @return array
716      */
717     public function get_entries($start=0, $limit=10) {
718         global $DB;
720         if (empty($this->entries)) {
721             if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
722                 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
723             } else {
724                 return false;
725             }
726         }
728         return $this->entries;
729     }
731     public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
732         global $DB, $USER, $CFG;
734         if(!$userid) {
735             $userid = $USER->id;
736         }
738         // The query used to locate blog entries is complicated.  It will be built from the following components:
739         $requiredfields = "p.*, u.firstname, u.lastname, u.email";  // the SELECT clause
740         $tables = array('p' => 'post', 'u' => 'user');   // components of the FROM clause (table_id => table_name)
741         $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')');  // components of the WHERE clause (conjunction)
743         // build up a clause for permission constraints
745         $params = array();
747         // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
748         // admins can see all blogs regardless of publish states, as described on the help page
749         if (has_capability('moodle/user:readuserblogs', get_context_instance(CONTEXT_SYSTEM))) {
750             // don't add permission constraints
752         } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
753                 get_context_instance(CONTEXT_USER, (empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
754             // don't add permission constraints
756         } else {
757             if (isloggedin() and !isguestuser()) {
758                 $assocexists = $DB->record_exists('blog_association', array());  //dont check association records if there aren't any
760                 //begin permission sql clause
761                 $permissionsql =  '(p.userid = ? ';
762                 $params[] = $userid;
764                 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
765                     $permissionsql .= " OR p.publishstate = 'site' ";
766                 }
768                 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
769                     $permissionsql .= " OR p.publishstate = 'public' ";
770                 }
772                 $permissionsql .= ') ';   //close permissions sql clause
773             } else {  // default is access to public entries
774                 $permissionsql = "p.publishstate = 'public'";
775             }
776             $conditions[] = $permissionsql;  //add permission constraints
777         }
779         foreach ($this->filters as $type => $blogfilter) {
780             $conditions = array_merge($conditions, $blogfilter->conditions);
781             $params = array_merge($params, $blogfilter->params);
782             $tables = array_merge($tables, $blogfilter->tables);
783         }
785         $tablessql = '';  // build up the FROM clause
786         foreach ($tables as $tablename => $table) {
787             $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
788         }
790         $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
791         $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
792         $sql .= ($count) ? '' : " ORDER BY $sort";
794         return array('sql' => $sql, 'params' => $params);
795     }
797     /**
798      * Outputs all the blog entries aggregated by this blog listing.
799      *
800      * @return void
801      */
802     public function print_entries() {
803         global $CFG, $USER, $DB, $OUTPUT;
804         $sitecontext = get_context_instance(CONTEXT_SYSTEM);
806         $page  = optional_param('blogpage', 0, PARAM_INT);
807         $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
808         $start = $page * $limit;
810         $morelink = '<br />&nbsp;&nbsp;';
812         if ($sqlarray = $this->get_entry_fetch_sql(true)) {
813             $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
814         } else {
815             $totalentries = 0;
816         }
818         $entries = $this->get_entries($start, $limit);
819         $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
820         $pagingbar->pagevar = 'blogpage';
821         $blogheaders = blog_get_headers();
823         echo $OUTPUT->render($pagingbar);
825         if (has_capability('moodle/blog:create', $sitecontext)) {
826             //the user's blog is enabled and they are viewing their own blog
827             $userid = optional_param('userid', null, PARAM_INT);
829             if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
830                 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
831                 $urlparams = array('action' => 'add',
832                                    'userid' => $userid,
833                                    'courseid' => optional_param('courseid', null, PARAM_INT),
834                                    'groupid' => optional_param('groupid', null, PARAM_INT),
835                                    'modid' => optional_param('modid', null, PARAM_INT),
836                                    'tagid' => optional_param('tagid', null, PARAM_INT),
837                                    'tag' => optional_param('tag', null, PARAM_INT),
838                                    'search' => optional_param('search', null, PARAM_INT));
840                 foreach ($urlparams as $var => $val) {
841                     if (empty($val)) {
842                         unset($urlparams[$var]);
843                     }
844                 }
845                 $addurl->params($urlparams);
847                 $addlink = '<div class="addbloglink">';
848                 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
849                 $addlink .= '</div>';
850                 echo $addlink;
851             }
852         }
854         if ($entries) {
855             $count = 0;
857             foreach ($entries as $entry) {
858                 $blogentry = new blog_entry(null, $entry);
859                 $blogentry->print_html();
860                 $count++;
861             }
863             echo $OUTPUT->render($pagingbar);
865             if (!$count) {
866                 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
867             }
869             print $morelink.'<br />'."\n";
870             return;
871         }
872     }
874     /// Find the base url from $_GET variables, for print_paging_bar
875     public function get_baseurl() {
876         $getcopy  = $_GET;
878         unset($getcopy['blogpage']);
880         if (!empty($getcopy)) {
881             $first = false;
882             $querystring = '';
884             foreach ($getcopy as $var => $val) {
885                 if (!$first) {
886                     $first = true;
887                     $querystring .= "?$var=$val";
888                 } else {
889                     $querystring .= '&amp;'.$var.'='.$val;
890                     $hasparam = true;
891                 }
892             }
893         } else {
894             $querystring = '?';
895         }
897         return strip_querystring(qualified_me()) . $querystring;
899     }
902 /**
903  * Abstract class for blog_filter objects.
904  * A set of core filters are implemented here. To write new filters, you need to subclass
905  * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
906  * The blog_filter abstract class will automatically use it when the filter is added to the
907  * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
908  * or have any other meaning you wish it to have. The second parameter is called $type and is
909  * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
910  */
911 abstract class blog_filter {
912     /**
913      * An array of strings representing the available filter types for each blog_filter.
914      * @var array $availabletypes
915      */
916     public $availabletypes = array();
918     /**
919      * The type of filter (for example, types of blog_filter_context are site, course and module)
920      * @var string $type
921      */
922     public $type;
924     /**
925      * The unique ID for a filter's associated record
926      * @var int $id
927      */
928     public $id;
930     /**
931      * An array of table aliases that are used in the WHERE conditions
932      * @var array $tables
933      */
934     public $tables = array();
936     /**
937      * An array of WHERE conditions
938      * @var array $conditions
939      */
940     public $conditions = array();
942     /**
943      * An array of SQL params
944      * @var array $params
945      */
946     public $params = array();
948     /**
949      * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
950      */
951     public $overrides = array();
953     public function __construct($id, $type=null) {
954         $this->id = $id;
955         $this->type = $type;
956     }
958     /**
959      * TODO This is poor design. A parent class should not know anything about its children.
960      * The default case helps to resolve this design issue
961      */
962     public static function get_instance($id, $type) {
964         switch ($type) {
965             case 'site':
966             case 'course':
967             case 'module':
968                 return new blog_filter_context($id, $type);
969                 break;
971             case 'group':
972             case 'user':
973                 return new blog_filter_user($id, $type);
974                 break;
976             case 'tag':
977                 return new blog_filter_tag($id);
978                 break;
980             default:
981                 $classname = "blog_filter_$type";
982                 if (class_exists($classname)) {
983                     return new $classname($id, $type);
984                 }
985         }
986     }
989 /**
990  * This filter defines the context level of the blog entries being searched: site, course, module
991  */
992 class blog_filter_context extends blog_filter {
993     /**
994      * Constructor
995      *
996      * @param string $type
997      * @param int    $id
998      */
999     public function __construct($id=null, $type='site') {
1000         global $SITE, $CFG, $DB;
1002         if (empty($id)) {
1003             $this->type = 'site';
1004         } else {
1005             $this->id = $id;
1006             $this->type = $type;
1007         }
1009         $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
1011         switch ($this->type) {
1012             case 'course': // Careful of site course!
1013                 // Ignore course filter if blog associations are not enabled
1014                 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
1015                     $this->overrides = array('site');
1016                     $context = get_context_instance(CONTEXT_COURSE, $this->id);
1017                     $this->tables['ba'] = 'blog_association';
1018                     $this->conditions[] = 'p.id = ba.blogid';
1019                     $this->conditions[] = 'ba.contextid = '.$context->id;
1020                     break;
1021                 } else {
1022                     // We are dealing with the site course, do not break from the current case
1023                 }
1025             case 'site':
1026                 // No special constraints
1027                 break;
1028             case 'module':
1029                 if (!empty($CFG->useblogassociations)) {
1030                     $this->overrides = array('course', 'site');
1032                     $context = get_context_instance(CONTEXT_MODULE, $this->id);
1033                     $this->tables['ba'] = 'blog_association';
1034                     $this->tables['p']  = 'post';
1035                     $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
1036                     $this->params = array($context->id);
1037                 }
1038                 break;
1039         }
1040     }
1043 /**
1044  * This filter defines the user level of the blog entries being searched: a userid or a groupid.
1045  * It can be combined with a context filter in order to refine the search.
1046  */
1047 class blog_filter_user extends blog_filter {
1048     public $tables = array('u' => 'user');
1050     /**
1051      * Constructor
1052      *
1053      * @param string $type
1054      * @param int    $id
1055      */
1056     public function __construct($id=null, $type='user') {
1057         global $CFG, $DB, $USER;
1058         $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
1060         if (empty($id)) {
1061             $this->id = $USER->id;
1062             $this->type = 'user';
1063         } else {
1064             $this->id = $id;
1065             $this->type = $type;
1066         }
1068         if ($this->type == 'user') {
1069             $this->conditions = array('u.id = ?');
1070             $this->params = array($this->id);
1071             $this->overrides = array('group');
1073         } elseif ($this->type == 'group') {
1074             $this->overrides = array('course', 'site');
1076             $this->tables['gm'] = 'groups_members';
1077             $this->conditions[] = 'p.userid = gm.userid';
1078             $this->conditions[] = 'gm.groupid = ?';
1079             $this->params[]     = $this->id;
1081             if (!empty($CFG->useblogassociations)) {  // only show blog entries associated with this course
1082                 $coursecontext     = get_context_instance(CONTEXT_COURSE, $DB->get_field('groups', 'courseid', array('id' => $this->id)));
1083                 $this->tables['ba'] = 'blog_association';
1084                 $this->conditions[] = 'gm.groupid = ?';
1085                 $this->conditions[] = 'ba.contextid = ?';
1086                 $this->conditions[] = 'ba.blogid = p.id';
1087                 $this->params[]     = $this->id;
1088                 $this->params[]     = $coursecontext->id;
1089             }
1090         }
1092     }
1095 /**
1096  * This filter defines a tag by which blog entries should be searched.
1097  */
1098 class blog_filter_tag extends blog_filter {
1099     public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
1101     /**
1102      * Constructor
1103      *
1104      * @return void
1105      */
1106     public function __construct($id) {
1107         global $DB;
1108         $this->id = $id;
1110         $this->conditions = array('ti.tagid = t.id',
1111                                   "ti.itemtype = 'post'",
1112                                   'ti.itemid = p.id',
1113                                   't.id = ?');
1114         $this->params = array($this->id);
1115     }
1118 /**
1119  * This filter defines a specific blog entry id.
1120  */
1121 class blog_filter_entry extends blog_filter {
1122     public $conditions = array('p.id = ?');
1123     public $overrides  = array('site', 'course', 'module', 'group', 'user', 'tag');
1125     public function __construct($id) {
1126         $this->id = $id;
1127         $this->params[] = $this->id;
1128     }
1131 /**
1132  * This filter restricts the results to a time interval in seconds up to mktime()
1133  */
1134 class blog_filter_since extends blog_filter {
1135     public function __construct($interval) {
1136         $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1137         $this->params[] = mktime() - $interval;
1138         $this->params[] = mktime();
1139     }
1142 /**
1143  * Filter used to perform full-text search on an entry's subject, summary and content
1144  */
1145 class blog_filter_search extends blog_filter {
1147     public function __construct($searchterm) {
1148         global $DB;
1149         $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1150                                     ".$DB->sql_like('p.content', '?', false)." OR
1151                                     ".$DB->sql_like('p.subject', '?', false).")");
1152         $this->params[] = "%$searchterm%";
1153         $this->params[] = "%$searchterm%";
1154         $this->params[] = "%$searchterm%";
1155     }