3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
23 * @copyright 2009 Nicolas Connault
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 * Blog_entry class. Represents an entry in a user's blog. Contains all methods for managing this entry.
31 * This class does not contain any HTML-generating code. See blog_listing sub-classes for such code.
32 * This class follows the Object Relational Mapping technique, its member variables being mapped to
33 * the fields of the post table.
37 * @copyright 2009 Nicolas Connault
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 // Public Database fields
50 // Locked Database fields (Don't touch these)
53 public $module = 'blog';
55 public $coursemoduleid = 0;
58 public $uniquehash = '';
63 // Other class variables
65 public $tags = array();
69 * Constructor. If given an id, will fetch the corresponding record from the DB.
71 * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
73 public function __construct($id=null, $params=null, $form=null) {
77 $object = $DB->get_record('post', array('id' => $id));
78 foreach ($object as $var => $val) {
81 } else if (!empty($params) && (is_array($params) || is_object($params))) {
82 foreach ($params as $var => $val) {
91 * Prints or returns the HTML for this blog entry.
96 public function print_html($return=false) {
98 global $USER, $CFG, $COURSE, $DB, $OUTPUT, $PAGE;
100 $user = $DB->get_record('user', array('id'=>$this->userid));
102 if (!empty($CFG->usecomments) and $CFG->blogusecomments) {
103 require_once($CFG->dirroot . '/comment/lib.php');
105 $cmt = new stdClass();
106 $cmt->context = get_context_instance(CONTEXT_USER, $user->id);
107 $cmt->courseid = $PAGE->course->id;
108 $cmt->area = 'format_blog';
109 $cmt->itemid = $this->id;
110 $cmt->showcount = $CFG->blogshowcommentscount;
111 $cmt->component = 'blog';
112 $comment = new comment($cmt);
113 $cmttext = $comment->output(true);
115 $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);
117 $template['body'] = format_text($this->summary, $this->summaryformat).$cmttext;
118 $template['title'] = format_string($this->subject);
119 $template['userid'] = $user->id;
120 $template['author'] = fullname($user);
121 $template['created'] = userdate($this->created);
123 if ($this->created != $this->lastmodified) {
124 $template['lastmod'] = userdate($this->lastmodified);
127 $template['publishstate'] = $this->publishstate;
129 $stredit = get_string('edit');
130 $strdelete = get_string('delete');
132 // Check to see if the entry is unassociated with group/course level access
133 $unassociatedentry = false;
134 if (!empty($CFG->useblogassociations) && ($this->publishstate == 'group' || $this->publishstate == 'course')) {
135 if (!$DB->record_exists('blog_association', array('blogid' => $this->id))) {
136 $unassociatedentry = true;
140 // Start printing of the blog
141 $table = new html_table();
142 $table->cellspacing = 0;
143 $table->attributes['class'] = 'forumpost blog_entry blog'. ($unassociatedentry ? 'draft' : $template['publishstate']);
144 $table->attributes['id'] = 'b'.$this->id;
145 $table->width = '100%';
147 $picturecell = new html_table_cell();
148 $picturecell->attributes['class'] = 'picture left';
149 $picturecell->text = $OUTPUT->user_picture($user);
151 $table->head[] = $picturecell;
153 $topiccell = new html_table_cell();
154 $topiccell->attributes['class'] = 'topic starter';
155 $titlelink = html_writer::link(new moodle_url('/blog/index.php', array('entryid' => $this->id)), $template['title']);
156 $topiccell->text = $OUTPUT->container($titlelink, 'subject');
157 $topiccell->text .= $OUTPUT->container_start('author');
159 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $PAGE->course->id)));
161 $by->name = html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $PAGE->course->id)), $fullname);
162 $by->date = $template['created'];
164 $topiccell->text .= get_string('bynameondate', 'forum', $by);
165 $topiccell->text .= $OUTPUT->container_end();
167 if ($this->uniquehash && $this->content) {
168 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {
169 $urlparts = parse_url($externalblog->url);
170 $topiccell->text .= $OUTPUT->container(get_string('retrievedfrom', 'blog').get_string('labelsep', 'langconfig').html_writer::link($urlparts['scheme'].'://'.$urlparts['host'], $externalblog->name), 'externalblog');
174 $topiccell->header = false;
175 $table->head[] = $topiccell;
178 $mainrow = new html_table_row();
180 $leftsidecell = new html_table_cell();
181 $leftsidecell->attributes['class'] = 'left side';
182 $mainrow->cells[] = $leftsidecell;
184 $contentcell = new html_table_cell();
185 $contentcell->attributes['class'] = 'content';
187 $attachedimages = $OUTPUT->container($this->print_attachments(), 'attachments');
189 // retrieve associations in case they're needed early
190 $blogassociations = $DB->get_records('blog_association', array('blogid' => $this->id));
192 // determine text for publish state
193 switch ($template['publishstate']) {
195 $blogtype = get_string('publishtonoone', 'blog');
198 $blogtype = get_string('publishtosite', 'blog');
201 $blogtype = get_string('publishtoworld', 'blog');
209 $contentcell->text .= $OUTPUT->container($blogtype, 'audience');
211 $contentcell->text .= $template['body'];
212 $contentcell->text .= $attachedimages;
214 // Uniquehash is used as a link to an external blog
215 if (!empty($this->uniquehash)) {
216 $contentcell->text .= $OUTPUT->container_start('externalblog');
217 $contentcell->text .= html_writer::link($this->uniquehash, get_string('linktooriginalentry', 'blog'));
218 $contentcell->text .= $OUTPUT->container_end();
222 $officialtags = tag_get_tags_csv('post', $this->id, TAG_RETURN_HTML, 'official');
223 $defaulttags = tag_get_tags_csv('post', $this->id, TAG_RETURN_HTML, 'default');
225 if (!empty($CFG->usetags) && ($officialtags || $defaulttags) ) {
226 $contentcell->text .= $OUTPUT->container_start('tags');
229 $contentcell->text .= get_string('tags', 'tag') .': '. $OUTPUT->container($officialtags, 'officialblogtags');
231 $contentcell->text .= ', ';
234 $contentcell->text .= $defaulttags;
235 $contentcell->text .= $OUTPUT->container_end();
239 if (!empty($CFG->useblogassociations) && $blogassociations) {
240 $contentcell->text .= $OUTPUT->container_start('tags');
242 $hascourseassocs = false;
245 // First find and show the associated course
246 foreach ($blogassociations as $assocrec) {
247 $contextrec = $DB->get_record('context', array('id' => $assocrec->contextid));
248 if ($contextrec->contextlevel == CONTEXT_COURSE) {
249 $assocurl = new moodle_url('/course/view.php', array('id' => $contextrec->instanceid));
250 $text = $DB->get_field('course', 'shortname', array('id' => $contextrec->instanceid)); //TODO: performance!!!!
251 $assocstr .= $OUTPUT->action_icon($assocurl, new pix_icon('i/course', $text), null, array(), true);
252 $hascourseassocs = true;
253 $assoctype = get_string('course');
257 // Now show mod association
258 foreach ($blogassociations as $assocrec) {
259 $contextrec = $DB->get_record('context', array('id' => $assocrec->contextid));
261 if ($contextrec->contextlevel == CONTEXT_MODULE) {
262 if ($hascourseassocs) {
264 $hascourseassocs = false;
267 $modinfo = $DB->get_record('course_modules', array('id' => $contextrec->instanceid));
268 $modname = $DB->get_field('modules', 'name', array('id' => $modinfo->module));
270 $assocurl = new moodle_url('/mod/'.$modname.'/view.php', array('id' => $modinfo->id));
271 $text = $DB->get_field($modname, 'name', array('id' => $modinfo->instance)); //TODO: performance!!!!
272 $assocstr .= $OUTPUT->action_icon($assocurl, new pix_icon('icon', $text, $modname), null, array(), true);
274 $assoctype = get_string('modulename', $modname);
278 $assocstr = substr($assocstr, 0, -2);
279 $contentcell->text .= get_string('associated', 'blog', $assoctype) . ': '. $assocstr;
281 $contentcell->text .= $OUTPUT->container_end();
284 if ($unassociatedentry) {
285 $contentcell->text .= $OUTPUT->container(get_string('associationunviewable', 'blog'), 'noticebox');
290 $contentcell->text .= $OUTPUT->container_start('commands');
292 if (blog_user_can_edit_entry($this) && empty($this->uniquehash)) {
293 $contentcell->text .= html_writer::link(new moodle_url('/blog/edit.php', array('action' => 'edit', 'entryid' => $this->id)), $stredit) . ' | ';
294 $contentcell->text .= html_writer::link(new moodle_url('/blog/edit.php', array('action' => 'delete', 'entryid' => $this->id)), $strdelete) . ' | ';
297 $contentcell->text .= html_writer::link(new moodle_url('/blog/index.php', array('entryid' => $this->id)), get_string('permalink', 'blog'));
299 $contentcell->text .= $OUTPUT->container_end();
301 if (isset($template['lastmod']) ){
302 $contentcell->text .= '<div style="font-size: 55%;">';
303 $contentcell->text .= ' [ '.get_string('modified').': '.$template['lastmod'].' ]';
304 $contentcell->text .= '</div>';
307 $mainrow->cells[] = $contentcell;
308 $table->data = array($mainrow);
311 return html_writer::table($table);
313 echo html_writer::table($table);
318 * Inserts this entry in the database. Access control checks must be done by calling code.
320 * @param mform $form Used for attachments
323 public function process_attachment($form) {
328 * Inserts this entry in the database. Access control checks must be done by calling code.
329 * TODO Set the publishstate correctly
330 * @param mform $form Used for attachments
333 public function add() {
334 global $CFG, $USER, $DB;
337 $this->module = 'blog';
338 $this->userid = (empty($this->userid)) ? $USER->id : $this->userid;
339 $this->lastmodified = time();
340 $this->created = time();
342 // Insert the new blog entry.
343 $this->id = $DB->insert_record('post', $this);
346 $this->add_tags_info();
348 if (!empty($CFG->useblogassociations)) {
349 $this->add_associations();
350 add_to_log(SITEID, 'blog', 'add', 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
353 tag_set('post', $this->id, $this->tags);
357 * Updates this entry in the database. Access control checks must be done by calling code.
359 * @param mform $form Used for attachments
362 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
363 global $CFG, $USER, $DB, $PAGE;
365 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
369 foreach ($params as $var => $val) {
373 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
374 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
376 if (!empty($CFG->useblogassociations)) {
377 $entry->add_associations();
380 $entry->lastmodified = time();
383 $DB->update_record('post', $entry);
384 tag_set('post', $entry->id, $entry->tags);
386 add_to_log(SITEID, 'blog', 'update', 'index.php?userid='.$USER->id.'&entryid='.$entry->id, $entry->subject);
390 * Deletes this entry from the database. Access control checks must be done by calling code.
394 public function delete() {
399 $this->delete_attachments();
401 $DB->delete_records('post', array('id' => $this->id));
402 tag_set('post', $this->id, array());
404 add_to_log(SITEID, 'blog', 'delete', 'index.php?userid='. $this->userid, 'deleted blog entry with entry id# '. $this->id);
408 * function to add all context associations to an entry
409 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
411 public function add_associations($action='add') {
414 $this->remove_associations();
416 if (!empty($this->courseassoc)) {
417 $this->add_association($this->courseassoc, $action);
420 if (!empty($this->modassoc)) {
421 $this->add_association($this->modassoc, $action);
426 * add a single association for a blog entry
427 * @param int contextid - id of context to associate with the blog entry
429 public function add_association($contextid, $action='add') {
432 $assocobject = new StdClass;
433 $assocobject->contextid = $contextid;
434 $assocobject->blogid = $this->id;
435 $DB->insert_record('blog_association', $assocobject);
437 $context = get_context_instance_by_id($contextid);
440 if ($context->contextlevel == CONTEXT_COURSE) {
441 $courseid = $context->instanceid;
442 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
443 } else if ($context->contextlevel == CONTEXT_MODULE) {
444 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
445 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
446 add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
451 * remove all associations for a blog entry
454 public function remove_associations() {
456 $DB->delete_records('blog_association', array('blogid' => $this->id));
460 * Deletes all the user files in the attachments area for an entry
464 public function delete_attachments() {
465 $fs = get_file_storage();
466 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
467 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
471 * if return=html, then return a html string.
472 * if return=text, then return a text-only string.
473 * otherwise, print HTML for non-images, and return image HTML
475 * @param bool $return Whether to return or print the generated code
478 public function print_attachments($return=false) {
479 global $CFG, $OUTPUT;
481 require_once($CFG->libdir.'/filelib.php');
483 $fs = get_file_storage();
485 $syscontext = get_context_instance(CONTEXT_SYSTEM);
487 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
492 $strattachment = get_string("attachment", "forum");
494 foreach ($files as $file) {
495 if ($file->is_directory()) {
499 $filename = $file->get_filename();
500 $ffurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$this->id.'/'.$filename);
501 $mimetype = $file->get_mimetype();
503 $icon = mimeinfo_from_type("icon", $mimetype);
504 $type = mimeinfo_from_type("type", $mimetype);
506 $image = $OUTPUT->pix_icon("f/$icon", $filename, 'moodle', array('class'=>'icon'));
508 if ($return == "html") {
509 $output .= html_writer::link($ffurl, $image);
510 $output .= html_writer::link($ffurl, $filename);
512 } else if ($return == "text") {
513 $output .= "$strattachment $filename:\n$ffurl\n";
516 if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) { // Image attachments don't get printed as links
517 $imagereturn .= "<br />" . $OUTPUT->pix_icon($ffurl, $filename);
519 $imagereturn .= html_writer::link($ffurl, $image);
520 $imagereturn .= format_text(html_writer::link($ffurl, $filename), FORMAT_HTML, array('context'=>$syscontext));
534 * function to attach tags into an entry
537 public function add_tags_info() {
541 if ($otags = optional_param('otags', '', PARAM_INT)) {
542 foreach ($otags as $tagid) {
543 // TODO : make this use the tag name in the form
544 if ($tag = tag_get('id', $tagid)) {
545 $tags[] = $tag->name;
550 tag_set('post', $this->id, $tags);
554 * User can edit a blog entry if this is their own blog entry and they have
555 * the capability moodle/blog:create, or if they have the capability
556 * moodle/blog:manageentries.
557 * This also applies to deleting of entries.
559 * @param int $userid Optional. If not given, $USER is used
562 public function can_user_edit($userid=null) {
565 if (empty($userid)) {
569 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
571 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
572 return true; // can edit any blog entry
575 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
576 return true; // can edit own when having blog:create capability
583 * Checks to see if a user can view the blogs of another user.
584 * Only blog level is checked here, the capabilities are enforced
587 * @param int $targetuserid ID of the user we are checking
591 public function can_user_view($targetuserid) {
592 global $CFG, $USER, $DB;
593 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
595 if (empty($CFG->bloglevel) || !has_capability('moodle/blog:view', $sitecontext)) {
596 return false; // blog system disabled or user has no blog view capability
599 if (isloggedin() && $USER->id == $targetuserid) {
600 return true; // can view own entries in any case
603 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
604 return true; // can manage all entries
607 // coming for 1 entry, make sure it's not a draft
608 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
609 return false; // can not view draft of others
612 // coming for 1 entry, make sure user is logged in, if not a public blog
613 if ($this->publishstate != 'public' && !isloggedin()) {
617 switch ($CFG->bloglevel) {
618 case BLOG_GLOBAL_LEVEL:
622 case BLOG_SITE_LEVEL:
623 if (isloggedin()) { // not logged in viewers forbidden
629 case BLOG_USER_LEVEL:
631 $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
632 return has_capability('moodle/user:readuserblogs', $personalcontext);
638 * Use this function to retrieve a list of publish states available for
639 * the currently logged in user.
641 * @return array This function returns an array ideal for sending to moodles'
642 * choose_from_menu function.
645 public static function get_applicable_publish_states() {
649 // everyone gets draft access
650 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
651 $options['draft'] = get_string('publishtonoone', 'blog');
654 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
655 $options['site'] = get_string('publishtosite', 'blog');
658 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
659 $options['public'] = get_string('publishtoworld', 'blog');
667 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
669 * @package moodlecore
671 * @copyright 2009 Nicolas Connault
672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
676 * Array of blog_entry objects.
677 * @var array $entries
679 public $entries = array();
682 * An array of blog_filter_* objects
683 * @var array $filters
685 public $filters = array();
690 * @param array $filters An associative array of filtername => filterid
692 public function __construct($filters=array()) {
693 // Unset filters overridden by more specific filters
694 foreach ($filters as $type => $id) {
695 if (!empty($type) && !empty($id)) {
696 $this->filters[$type] = blog_filter::get_instance($id, $type);
700 foreach ($this->filters as $type => $filter) {
701 foreach ($filter->overrides as $override) {
702 if (array_key_exists($override, $this->filters)) {
703 unset($this->filters[$override]);
710 * Fetches the array of blog entries.
714 public function get_entries($start=0, $limit=10) {
717 if (empty($this->entries)) {
718 if ($sqlarray = $this->get_entry_fetch_sql()) {
719 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
725 return $this->entries;
728 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
729 global $DB, $USER, $CFG;
735 // The query used to locate blog entries is complicated. It will be built from the following components:
736 $requiredfields = "p.*, u.firstname, u.lastname, u.email"; // the SELECT clause
737 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
738 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
740 // build up a clause for permission constraints
744 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
745 // admins can see all blogs regardless of publish states, as described on the help page
746 if (has_capability('moodle/user:readuserblogs', get_context_instance(CONTEXT_SYSTEM))) {
747 // don't add permission constraints
749 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
750 get_context_instance(CONTEXT_USER, (empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
751 // don't add permission constraints
754 if (isloggedin() and !isguestuser()) {
755 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
757 //begin permission sql clause
758 $permissionsql = '(p.userid = ? ';
761 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
762 $permissionsql .= " OR p.publishstate = 'site' ";
765 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
766 $permissionsql .= " OR p.publishstate = 'public' ";
769 $permissionsql .= ') '; //close permissions sql clause
770 } else { // default is access to public entries
771 $permissionsql = "p.publishstate = 'public'";
773 $conditions[] = $permissionsql; //add permission constraints
776 foreach ($this->filters as $type => $blogfilter) {
777 $conditions = array_merge($conditions, $blogfilter->conditions);
778 $params = array_merge($params, $blogfilter->params);
779 $tables = array_merge($tables, $blogfilter->tables);
782 $tablessql = ''; // build up the FROM clause
783 foreach ($tables as $tablename => $table) {
784 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
787 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
788 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
789 $sql .= ($count) ? '' : " ORDER BY $sort";
791 return array('sql' => $sql, 'params' => $params);
795 * Outputs all the blog entries aggregated by this blog listing.
799 public function print_entries() {
800 global $CFG, $USER, $DB, $OUTPUT;
801 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
803 $page = optional_param('blogpage', 0, PARAM_INT);
804 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
805 $start = $page * $limit;
807 $morelink = '<br /> ';
809 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
810 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
815 $entries = $this->get_entries($start, $limit);
816 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
817 $pagingbar->pagevar = 'blogpage';
818 $blogheaders = blog_get_headers();
820 echo $OUTPUT->render($pagingbar);
822 if (has_capability('moodle/blog:create', $sitecontext)) {
823 //the user's blog is enabled and they are viewing their own blog
824 $userid = optional_param('userid', null, PARAM_INT);
826 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
827 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
828 $urlparams = array('action' => 'add',
830 'courseid' => optional_param('courseid', null, PARAM_INT),
831 'groupid' => optional_param('groupid', null, PARAM_INT),
832 'modid' => optional_param('modid', null, PARAM_INT),
833 'tagid' => optional_param('tagid', null, PARAM_INT),
834 'tag' => optional_param('tag', null, PARAM_INT),
835 'search' => optional_param('search', null, PARAM_INT));
837 foreach ($urlparams as $var => $val) {
839 unset($urlparams[$var]);
842 $addurl->params($urlparams);
844 $addlink = '<div class="addbloglink">';
845 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
846 $addlink .= '</div>';
854 foreach ($entries as $entry) {
855 $blogentry = new blog_entry(null, $entry);
856 $blogentry->print_html();
860 echo $OUTPUT->render($pagingbar);
863 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
866 print $morelink.'<br />'."\n";
871 /// Find the base url from $_GET variables, for print_paging_bar
872 public function get_baseurl() {
875 unset($getcopy['blogpage']);
877 if (!empty($getcopy)) {
881 foreach ($getcopy as $var => $val) {
884 $querystring .= "?$var=$val";
886 $querystring .= '&'.$var.'='.$val;
894 return strip_querystring(qualified_me()) . $querystring;
900 * Abstract class for blog_filter objects.
901 * A set of core filters are implemented here. To write new filters, you need to subclass
902 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
903 * The blog_filter abstract class will automatically use it when the filter is added to the
904 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
905 * or have any other meaning you wish it to have. The second parameter is called $type and is
906 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
908 abstract class blog_filter {
910 * An array of strings representing the available filter types for each blog_filter.
911 * @var array $availabletypes
913 public $availabletypes = array();
916 * The type of filter (for example, types of blog_filter_context are site, course and module)
922 * The unique ID for a filter's associated record
928 * An array of table aliases that are used in the WHERE conditions
931 public $tables = array();
934 * An array of WHERE conditions
935 * @var array $conditions
937 public $conditions = array();
940 * An array of SQL params
943 public $params = array();
946 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
948 public $overrides = array();
950 public function __construct($id, $type=null) {
956 * TODO This is poor design. A parent class should not know anything about its children.
957 * The default case helps to resolve this design issue
959 public static function get_instance($id, $type) {
965 return new blog_filter_context($id, $type);
970 return new blog_filter_user($id, $type);
974 return new blog_filter_tag($id);
978 $classname = "blog_filter_$type";
979 if (class_exists($classname)) {
980 return new $classname($id, $type);
987 * This filter defines the context level of the blog entries being searched: site, course, module
989 class blog_filter_context extends blog_filter {
993 * @param string $type
996 public function __construct($id=null, $type='site') {
997 global $SITE, $CFG, $DB;
1000 $this->type = 'site';
1003 $this->type = $type;
1006 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
1008 switch ($this->type) {
1009 case 'course': // Careful of site course!
1010 // Ignore course filter if blog associations are not enabled
1011 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
1012 $this->overrides = array('site');
1013 $context = get_context_instance(CONTEXT_COURSE, $this->id);
1014 $this->tables['ba'] = 'blog_association';
1015 $this->conditions[] = 'p.id = ba.blogid';
1016 $this->conditions[] = 'ba.contextid = '.$context->id;
1019 // We are dealing with the site course, do not break from the current case
1023 // No special constraints
1026 if (!empty($CFG->useblogassociations)) {
1027 $this->overrides = array('course', 'site');
1029 $context = get_context_instance(CONTEXT_MODULE, $this->id);
1030 $this->tables['ba'] = 'blog_association';
1031 $this->tables['p'] = 'post';
1032 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
1033 $this->params = array($context->id);
1041 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
1042 * It can be combined with a context filter in order to refine the search.
1044 class blog_filter_user extends blog_filter {
1045 public $tables = array('u' => 'user');
1050 * @param string $type
1053 public function __construct($id=null, $type='user') {
1054 global $CFG, $DB, $USER;
1055 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
1058 $this->id = $USER->id;
1059 $this->type = 'user';
1062 $this->type = $type;
1065 if ($this->type == 'user') {
1066 $this->conditions = array('u.id = ?');
1067 $this->params = array($this->id);
1068 $this->overrides = array('group');
1070 } elseif ($this->type == 'group') {
1071 $this->overrides = array('course', 'site');
1073 $this->tables['gm'] = 'groups_members';
1074 $this->conditions[] = 'p.userid = gm.userid';
1075 $this->conditions[] = 'gm.groupid = ?';
1076 $this->params[] = $this->id;
1078 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
1079 $coursecontext = get_context_instance(CONTEXT_COURSE, $DB->get_field('groups', 'courseid', array('id' => $this->id)));
1080 $this->tables['ba'] = 'blog_association';
1081 $this->conditions[] = 'gm.groupid = ?';
1082 $this->conditions[] = 'ba.contextid = ?';
1083 $this->conditions[] = 'ba.blogid = p.id';
1084 $this->params[] = $this->id;
1085 $this->params[] = $coursecontext->id;
1093 * This filter defines a tag by which blog entries should be searched.
1095 class blog_filter_tag extends blog_filter {
1096 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
1103 public function __construct($id) {
1107 $this->conditions = array('ti.tagid = t.id',
1108 "ti.itemtype = 'post'",
1111 $this->params = array($this->id);
1116 * This filter defines a specific blog entry id.
1118 class blog_filter_entry extends blog_filter {
1119 public $conditions = array('p.id = ?');
1120 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1122 public function __construct($id) {
1124 $this->params[] = $this->id;
1129 * This filter restricts the results to a time interval in seconds up to mktime()
1131 class blog_filter_since extends blog_filter {
1132 public function __construct($interval) {
1133 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1134 $this->params[] = mktime() - $interval;
1135 $this->params[] = mktime();
1140 * Filter used to perform full-text search on an entry's subject, summary and content
1142 class blog_filter_search extends blog_filter {
1144 public function __construct($searchterm) {
1146 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1147 ".$DB->sql_like('p.content', '?', false)." OR
1148 ".$DB->sql_like('p.subject', '?', false).")");
1149 $this->params[] = "%$searchterm%";
1150 $this->params[] = "%$searchterm%";
1151 $this->params[] = "%$searchterm%";