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 if ($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);
358 * Updates this entry in the database. Access control checks must be done by calling code.
360 * @param mform $form Used for attachments
363 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
364 global $CFG, $USER, $DB, $PAGE;
366 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
370 foreach ($params as $var => $val) {
374 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
375 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
377 if (!empty($CFG->useblogassociations)) {
378 $entry->add_associations();
381 $entry->lastmodified = time();
384 $DB->update_record('post', $entry);
385 tag_set('post', $entry->id, $entry->tags);
387 add_to_log(SITEID, 'blog', 'update', 'index.php?userid='.$USER->id.'&entryid='.$entry->id, $entry->subject);
391 * Deletes this entry from the database. Access control checks must be done by calling code.
395 public function delete() {
400 $this->delete_attachments();
402 $DB->delete_records('post', array('id' => $this->id));
403 tag_set('post', $this->id, array());
405 add_to_log(SITEID, 'blog', 'delete', 'index.php?userid='. $this->userid, 'deleted blog entry with entry id# '. $this->id);
409 * function to add all context associations to an entry
410 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
412 public function add_associations($action='add') {
415 $this->remove_associations();
417 if (!empty($this->courseassoc)) {
418 $this->add_association($this->courseassoc, $action);
421 if (!empty($this->modassoc)) {
422 $this->add_association($this->modassoc, $action);
427 * add a single association for a blog entry
428 * @param int contextid - id of context to associate with the blog entry
430 public function add_association($contextid, $action='add') {
433 $assocobject = new StdClass;
434 $assocobject->contextid = $contextid;
435 $assocobject->blogid = $this->id;
436 $DB->insert_record('blog_association', $assocobject);
438 $context = get_context_instance_by_id($contextid);
441 if ($context->contextlevel == CONTEXT_COURSE) {
442 $courseid = $context->instanceid;
443 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
444 } else if ($context->contextlevel == CONTEXT_MODULE) {
445 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
446 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
447 add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
452 * remove all associations for a blog entry
455 public function remove_associations() {
457 $DB->delete_records('blog_association', array('blogid' => $this->id));
461 * Deletes all the user files in the attachments area for an entry
465 public function delete_attachments() {
466 $fs = get_file_storage();
467 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
468 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
472 * if return=html, then return a html string.
473 * if return=text, then return a text-only string.
474 * otherwise, print HTML for non-images, and return image HTML
476 * @param bool $return Whether to return or print the generated code
479 public function print_attachments($return=false) {
480 global $CFG, $OUTPUT;
482 require_once($CFG->libdir.'/filelib.php');
484 $fs = get_file_storage();
486 $syscontext = get_context_instance(CONTEXT_SYSTEM);
488 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
493 $strattachment = get_string("attachment", "forum");
495 foreach ($files as $file) {
496 if ($file->is_directory()) {
500 $filename = $file->get_filename();
501 $ffurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$this->id.'/'.$filename);
502 $mimetype = $file->get_mimetype();
504 $icon = mimeinfo_from_type("icon", $mimetype);
505 $type = mimeinfo_from_type("type", $mimetype);
507 $image = $OUTPUT->pix_icon("f/$icon", $filename, 'moodle', array('class'=>'icon'));
509 if ($return == "html") {
510 $output .= html_writer::link($ffurl, $image);
511 $output .= html_writer::link($ffurl, $filename);
513 } else if ($return == "text") {
514 $output .= "$strattachment $filename:\n$ffurl\n";
517 if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) { // Image attachments don't get printed as links
518 $imagereturn .= "<br />" . $OUTPUT->pix_icon($ffurl, $filename);
520 $imagereturn .= html_writer::link($ffurl, $image);
521 $imagereturn .= format_text(html_writer::link($ffurl, $filename), FORMAT_HTML, array('context'=>$syscontext));
535 * function to attach tags into an entry
538 public function add_tags_info() {
542 if ($otags = optional_param('otags', '', PARAM_INT)) {
543 foreach ($otags as $tagid) {
544 // TODO : make this use the tag name in the form
545 if ($tag = tag_get('id', $tagid)) {
546 $tags[] = $tag->name;
551 tag_set('post', $this->id, $tags);
555 * User can edit a blog entry if this is their own blog entry and they have
556 * the capability moodle/blog:create, or if they have the capability
557 * moodle/blog:manageentries.
558 * This also applies to deleting of entries.
560 * @param int $userid Optional. If not given, $USER is used
563 public function can_user_edit($userid=null) {
566 if (empty($userid)) {
570 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
572 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
573 return true; // can edit any blog entry
576 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
577 return true; // can edit own when having blog:create capability
584 * Checks to see if a user can view the blogs of another user.
585 * Only blog level is checked here, the capabilities are enforced
588 * @param int $targetuserid ID of the user we are checking
592 public function can_user_view($targetuserid) {
593 global $CFG, $USER, $DB;
594 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
596 if (empty($CFG->bloglevel) || !has_capability('moodle/blog:view', $sitecontext)) {
597 return false; // blog system disabled or user has no blog view capability
600 if (isloggedin() && $USER->id == $targetuserid) {
601 return true; // can view own entries in any case
604 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
605 return true; // can manage all entries
608 // coming for 1 entry, make sure it's not a draft
609 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
610 return false; // can not view draft of others
613 // coming for 1 entry, make sure user is logged in, if not a public blog
614 if ($this->publishstate != 'public' && !isloggedin()) {
618 switch ($CFG->bloglevel) {
619 case BLOG_GLOBAL_LEVEL:
623 case BLOG_SITE_LEVEL:
624 if (isloggedin()) { // not logged in viewers forbidden
630 case BLOG_USER_LEVEL:
632 $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
633 return has_capability('moodle/user:readuserblogs', $personalcontext);
639 * Use this function to retrieve a list of publish states available for
640 * the currently logged in user.
642 * @return array This function returns an array ideal for sending to moodles'
643 * choose_from_menu function.
646 public static function get_applicable_publish_states() {
650 // everyone gets draft access
651 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
652 $options['draft'] = get_string('publishtonoone', 'blog');
655 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
656 $options['site'] = get_string('publishtosite', 'blog');
659 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
660 $options['public'] = get_string('publishtoworld', 'blog');
668 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
670 * @package moodlecore
672 * @copyright 2009 Nicolas Connault
673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
677 * Array of blog_entry objects.
678 * @var array $entries
680 public $entries = array();
683 * An array of blog_filter_* objects
684 * @var array $filters
686 public $filters = array();
691 * @param array $filters An associative array of filtername => filterid
693 public function __construct($filters=array()) {
694 // Unset filters overridden by more specific filters
695 foreach ($filters as $type => $id) {
696 if (!empty($type) && !empty($id)) {
697 $this->filters[$type] = blog_filter::get_instance($id, $type);
701 foreach ($this->filters as $type => $filter) {
702 foreach ($filter->overrides as $override) {
703 if (array_key_exists($override, $this->filters)) {
704 unset($this->filters[$override]);
711 * Fetches the array of blog entries.
715 public function get_entries($start=0, $limit=10) {
718 if (empty($this->entries)) {
719 if ($sqlarray = $this->get_entry_fetch_sql()) {
720 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
726 return $this->entries;
729 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
730 global $DB, $USER, $CFG;
736 // The query used to locate blog entries is complicated. It will be built from the following components:
737 $requiredfields = "p.*, u.firstname, u.lastname, u.email"; // the SELECT clause
738 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
739 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
741 // build up a clause for permission constraints
745 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
746 // admins can see all blogs regardless of publish states, as described on the help page
747 if (has_capability('moodle/user:readuserblogs', get_context_instance(CONTEXT_SYSTEM))) {
748 // don't add permission constraints
750 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
751 get_context_instance(CONTEXT_USER, (empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
752 // don't add permission constraints
755 if (isloggedin() and !isguestuser()) {
756 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
758 //begin permission sql clause
759 $permissionsql = '(p.userid = ? ';
762 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
763 $permissionsql .= " OR p.publishstate = 'site' ";
766 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
767 $permissionsql .= " OR p.publishstate = 'public' ";
770 $permissionsql .= ') '; //close permissions sql clause
771 } else { // default is access to public entries
772 $permissionsql = "p.publishstate = 'public'";
774 $conditions[] = $permissionsql; //add permission constraints
777 foreach ($this->filters as $type => $blogfilter) {
778 $conditions = array_merge($conditions, $blogfilter->conditions);
779 $params = array_merge($params, $blogfilter->params);
780 $tables = array_merge($tables, $blogfilter->tables);
783 $tablessql = ''; // build up the FROM clause
784 foreach ($tables as $tablename => $table) {
785 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
788 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
789 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
790 $sql .= ($count) ? '' : " ORDER BY $sort";
792 return array('sql' => $sql, 'params' => $params);
796 * Outputs all the blog entries aggregated by this blog listing.
800 public function print_entries() {
801 global $CFG, $USER, $DB, $OUTPUT;
802 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
804 $page = optional_param('blogpage', 0, PARAM_INT);
805 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
806 $start = $page * $limit;
808 $morelink = '<br /> ';
810 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
811 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
816 $entries = $this->get_entries($start, $limit);
817 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
818 $pagingbar->pagevar = 'blogpage';
819 $blogheaders = blog_get_headers();
821 echo $OUTPUT->render($pagingbar);
823 if (has_capability('moodle/blog:create', $sitecontext)) {
824 //the user's blog is enabled and they are viewing their own blog
825 $userid = optional_param('userid', null, PARAM_INT);
827 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
828 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
829 $urlparams = array('action' => 'add',
831 'courseid' => optional_param('courseid', null, PARAM_INT),
832 'groupid' => optional_param('groupid', null, PARAM_INT),
833 'modid' => optional_param('modid', null, PARAM_INT),
834 'tagid' => optional_param('tagid', null, PARAM_INT),
835 'tag' => optional_param('tag', null, PARAM_INT),
836 'search' => optional_param('search', null, PARAM_INT));
838 foreach ($urlparams as $var => $val) {
840 unset($urlparams[$var]);
843 $addurl->params($urlparams);
845 $addlink = '<div class="addbloglink">';
846 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
847 $addlink .= '</div>';
855 foreach ($entries as $entry) {
856 $blogentry = new blog_entry(null, $entry);
857 $blogentry->print_html();
861 echo $OUTPUT->render($pagingbar);
864 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
867 print $morelink.'<br />'."\n";
872 /// Find the base url from $_GET variables, for print_paging_bar
873 public function get_baseurl() {
876 unset($getcopy['blogpage']);
878 if (!empty($getcopy)) {
882 foreach ($getcopy as $var => $val) {
885 $querystring .= "?$var=$val";
887 $querystring .= '&'.$var.'='.$val;
895 return strip_querystring(qualified_me()) . $querystring;
901 * Abstract class for blog_filter objects.
902 * A set of core filters are implemented here. To write new filters, you need to subclass
903 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
904 * The blog_filter abstract class will automatically use it when the filter is added to the
905 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
906 * or have any other meaning you wish it to have. The second parameter is called $type and is
907 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
909 abstract class blog_filter {
911 * An array of strings representing the available filter types for each blog_filter.
912 * @var array $availabletypes
914 public $availabletypes = array();
917 * The type of filter (for example, types of blog_filter_context are site, course and module)
923 * The unique ID for a filter's associated record
929 * An array of table aliases that are used in the WHERE conditions
932 public $tables = array();
935 * An array of WHERE conditions
936 * @var array $conditions
938 public $conditions = array();
941 * An array of SQL params
944 public $params = array();
947 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
949 public $overrides = array();
951 public function __construct($id, $type=null) {
957 * TODO This is poor design. A parent class should not know anything about its children.
958 * The default case helps to resolve this design issue
960 public static function get_instance($id, $type) {
966 return new blog_filter_context($id, $type);
971 return new blog_filter_user($id, $type);
975 return new blog_filter_tag($id);
979 $classname = "blog_filter_$type";
980 if (class_exists($classname)) {
981 return new $classname($id, $type);
988 * This filter defines the context level of the blog entries being searched: site, course, module
990 class blog_filter_context extends blog_filter {
994 * @param string $type
997 public function __construct($id=null, $type='site') {
998 global $SITE, $CFG, $DB;
1001 $this->type = 'site';
1004 $this->type = $type;
1007 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
1009 switch ($this->type) {
1010 case 'course': // Careful of site course!
1011 // Ignore course filter if blog associations are not enabled
1012 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
1013 $this->overrides = array('site');
1014 $context = get_context_instance(CONTEXT_COURSE, $this->id);
1015 $this->tables['ba'] = 'blog_association';
1016 $this->conditions[] = 'p.id = ba.blogid';
1017 $this->conditions[] = 'ba.contextid = '.$context->id;
1020 // We are dealing with the site course, do not break from the current case
1024 // No special constraints
1027 if (!empty($CFG->useblogassociations)) {
1028 $this->overrides = array('course', 'site');
1030 $context = get_context_instance(CONTEXT_MODULE, $this->id);
1031 $this->tables['ba'] = 'blog_association';
1032 $this->tables['p'] = 'post';
1033 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
1034 $this->params = array($context->id);
1042 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
1043 * It can be combined with a context filter in order to refine the search.
1045 class blog_filter_user extends blog_filter {
1046 public $tables = array('u' => 'user');
1051 * @param string $type
1054 public function __construct($id=null, $type='user') {
1056 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
1059 $this->id = $USER->id;
1060 $this->type = 'user';
1063 $this->type = $type;
1066 if ($this->type == 'user') {
1067 $this->conditions = array('u.id = ?');
1068 $this->params = array($this->id);
1069 $this->overrides = array('group');
1071 } elseif ($this->type == 'group') {
1072 $this->overrides = array('course', 'site');
1074 $this->tables['gm'] = 'groups_members';
1075 $this->conditions[] = 'p.userid = gm.userid';
1076 $this->conditions[] = 'gm.groupid = ?';
1077 $this->params[] = $this->id;
1079 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
1080 $coursecontext = get_context_instance(CONTEXT_COURSE, $DB->get_field('groups', 'courseid', array('id' => $this->id)));
1081 $this->tables['ba'] = 'blog_association';
1082 $this->conditions[] = 'gm.groupid = ?';
1083 $this->conditions[] = 'ba.contextid = ?';
1084 $this->conditions[] = 'ba.blogid = p.id';
1085 $this->params[] = $this->id;
1086 $this->params[] = $coursecontext->id;
1094 * This filter defines a tag by which blog entries should be searched.
1096 class blog_filter_tag extends blog_filter {
1097 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
1104 public function __construct($id) {
1108 $this->conditions = array('ti.tagid = t.id',
1109 "ti.itemtype = 'post'",
1112 $this->params = array($this->id);
1117 * This filter defines a specific blog entry id.
1119 class blog_filter_entry extends blog_filter {
1120 public $conditions = array('p.id = ?');
1121 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1123 public function __construct($id) {
1125 $this->params[] = $this->id;
1130 * This filter restricts the results to a time interval in seconds up to mktime()
1132 class blog_filter_since extends blog_filter {
1133 public function __construct($interval) {
1134 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1135 $this->params[] = mktime() - $interval;
1136 $this->params[] = mktime();
1141 * Filter used to perform full-text search on an entry's subject, summary and content
1143 class blog_filter_search extends blog_filter {
1145 public function __construct($searchterm) {
1147 $ilike = $DB->sql_ilike();
1148 $this->conditions = array("(p.summary $ilike ? OR
1149 p.content $ilike ? OR
1150 p.subject $ilike ?)");
1151 $this->params[] = "%$searchterm%";
1152 $this->params[] = "%$searchterm%";
1153 $this->params[] = "%$searchterm%";