Merge branch 'MDL-39489_master' of git://github.com/dmonllao/moodle
[moodle.git] / blog / locallib.php
bloba4e42105b9c922733b381a3391c0910f12f1e9de
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.
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.
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
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.
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
42 class blog_entry implements renderable {
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 /** @var StdClass Data needed to render the entry */
70 public $renderable;
72 // Methods
73 /**
74 * Constructor. If given an id, will fetch the corresponding record from the DB.
76 * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
78 public function __construct($id=null, $params=null, $form=null) {
79 global $DB, $PAGE, $CFG;
81 if (!empty($id)) {
82 $object = $DB->get_record('post', array('id' => $id));
83 foreach ($object as $var => $val) {
84 $this->$var = $val;
86 } else if (!empty($params) && (is_array($params) || is_object($params))) {
87 foreach ($params as $var => $val) {
88 $this->$var = $val;
92 if (!empty($CFG->useblogassociations)) {
93 $associations = $DB->get_records('blog_association', array('blogid' => $this->id));
94 foreach ($associations as $association) {
95 $context = context::instance_by_id($association->contextid);
96 if ($context->contextlevel == CONTEXT_COURSE) {
97 $this->courseassoc = $association->contextid;
98 } else if ($context->contextlevel == CONTEXT_MODULE) {
99 $this->modassoc = $association->contextid;
104 $this->form = $form;
109 * Gets the required data to print the entry
111 public function prepare_render() {
113 global $DB, $CFG, $PAGE;
115 $this->renderable = new StdClass();
117 $this->renderable->user = $DB->get_record('user', array('id'=>$this->userid));
119 // Entry comments.
120 if (!empty($CFG->usecomments) and $CFG->blogusecomments) {
121 require_once($CFG->dirroot . '/comment/lib.php');
123 $cmt = new stdClass();
124 $cmt->context = context_user::instance($this->userid);
125 $cmt->courseid = $PAGE->course->id;
126 $cmt->area = 'format_blog';
127 $cmt->itemid = $this->id;
128 $cmt->showcount = $CFG->blogshowcommentscount;
129 $cmt->component = 'blog';
130 $this->renderable->comment = new comment($cmt);
133 $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);
135 // External blog link.
136 if ($this->uniquehash && $this->content) {
137 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {
138 $urlparts = parse_url($externalblog->url);
139 $this->renderable->externalblogtext = get_string('retrievedfrom', 'blog') . get_string('labelsep', 'langconfig');
140 $this->renderable->externalblogtext .= html_writer::link($urlparts['scheme'] . '://'.$urlparts['host'], $externalblog->name);
144 // Retrieve associations
145 $this->renderable->unassociatedentry = false;
146 if (!empty($CFG->useblogassociations)) {
148 // Adding the entry associations data.
149 if ($associations = $associations = $DB->get_records('blog_association', array('blogid' => $this->id))) {
151 // Check to see if the entry is unassociated with group/course level access.
152 if ($this->publishstate == 'group' || $this->publishstate == 'course') {
153 $this->renderable->unassociatedentry = true;
156 foreach ($associations as $key => $assocrec) {
158 if (!$context = context::instance_by_id($assocrec->contextid, IGNORE_MISSING)) {
159 unset($associations[$key]);
160 continue;
163 // The renderer will need the contextlevel of the association.
164 $associations[$key]->contextlevel = $context->contextlevel;
166 // Course associations.
167 if ($context->contextlevel == CONTEXT_COURSE) {
168 $instancename = $DB->get_field('course', 'shortname', array('id' => $context->instanceid)); //TODO: performance!!!!
170 $associations[$key]->url = $assocurl = new moodle_url('/course/view.php', array('id' => $context->instanceid));
171 $associations[$key]->text = $instancename;
172 $associations[$key]->icon = new pix_icon('i/course', $associations[$key]->text);
175 // Mod associations.
176 if ($context->contextlevel == CONTEXT_MODULE) {
178 // Getting the activity type and the activity instance id
179 $sql = 'SELECT cm.instance, m.name FROM {course_modules} cm
180 JOIN {modules} m ON m.id = cm.module
181 WHERE cm.id = :cmid';
182 $modinfo = $DB->get_record_sql($sql, array('cmid' => $context->instanceid));
183 $instancename = $DB->get_field($modinfo->name, 'name', array('id' => $modinfo->instance)); //TODO: performance!!!!
185 $associations[$key]->type = get_string('modulename', $modinfo->name);
186 $associations[$key]->url = new moodle_url('/mod/' . $modinfo->name . '/view.php', array('id' => $context->instanceid));
187 $associations[$key]->text = $instancename;
188 $associations[$key]->icon = new pix_icon('icon', $associations[$key]->text, $modinfo->name);
192 $this->renderable->blogassociations = $associations;
195 // Entry attachments.
196 $this->renderable->attachments = $this->get_attachments();
198 $this->renderable->usercanedit = blog_user_can_edit_entry($this);
203 * Gets the entry attachments list
204 * @return array List of blog_entry_attachment instances
206 function get_attachments() {
208 global $CFG;
210 require_once($CFG->libdir.'/filelib.php');
212 $syscontext = context_system::instance();
214 $fs = get_file_storage();
215 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
217 // Adding a blog_entry_attachment for each non-directory file.
218 $attachments = array();
219 foreach ($files as $file) {
220 if ($file->is_directory()) {
221 continue;
223 $attachments[] = new blog_entry_attachment($file, $this->id);
226 return $attachments;
230 * Inserts this entry in the database. Access control checks must be done by calling code.
232 * @param mform $form Used for attachments
233 * @return void
235 public function process_attachment($form) {
236 $this->form = $form;
240 * Inserts this entry in the database. Access control checks must be done by calling code.
241 * TODO Set the publishstate correctly
242 * @return void
244 public function add() {
245 global $CFG, $USER, $DB;
247 unset($this->id);
248 $this->module = 'blog';
249 $this->userid = (empty($this->userid)) ? $USER->id : $this->userid;
250 $this->lastmodified = time();
251 $this->created = time();
253 // Insert the new blog entry.
254 $this->id = $DB->insert_record('post', $this);
256 // Update tags.
257 $this->add_tags_info();
259 if (!empty($CFG->useblogassociations)) {
260 $this->add_associations();
263 tag_set('post', $this->id, $this->tags);
265 // Trigger an event for the new entry.
266 $event = \core\event\blog_entry_created::create(array(
267 'objectid' => $this->id,
268 'relateduserid' => $this->userid
270 $event->set_custom_data($this);
271 $event->trigger();
275 * Updates this entry in the database. Access control checks must be done by calling code.
277 * @param array $params Entry parameters.
278 * @param moodleform $form Used for attachments.
279 * @param array $summaryoptions Summary options.
280 * @param array $attachmentoptions Attachment options.
282 * @return void
284 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
285 global $CFG, $DB;
287 $sitecontext = context_system::instance();
288 $entry = $this;
290 $this->form = $form;
291 foreach ($params as $var => $val) {
292 $entry->$var = $val;
295 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
296 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
298 if (!empty($CFG->useblogassociations)) {
299 $entry->add_associations();
302 $entry->lastmodified = time();
304 // Update record.
305 $DB->update_record('post', $entry);
306 tag_set('post', $entry->id, $entry->tags);
308 $event = \core\event\blog_entry_updated::create(array(
309 'objectid' => $entry->id,
310 'relateduserid' => $entry->userid
312 $event->set_custom_data($entry);
313 $event->trigger();
317 * Deletes this entry from the database. Access control checks must be done by calling code.
319 * @return void
321 public function delete() {
322 global $DB;
324 $this->delete_attachments();
325 $this->remove_associations();
327 // Get record to pass onto the event.
328 $record = $DB->get_record('post', array('id' => $this->id));
329 $DB->delete_records('post', array('id' => $this->id));
330 tag_set('post', $this->id, array());
332 $event = \core\event\blog_entry_deleted::create(array(
333 'objectid' => $this->id,
334 'relateduserid' => $this->userid
336 $event->add_record_snapshot("post", $record);
337 $event->set_custom_data($this);
338 $event->trigger();
342 * function to add all context associations to an entry
343 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
345 public function add_associations($action='add') {
346 global $DB, $USER;
348 $this->remove_associations();
350 if (!empty($this->courseassoc)) {
351 $this->add_association($this->courseassoc, $action);
354 if (!empty($this->modassoc)) {
355 $this->add_association($this->modassoc, $action);
360 * add a single association for a blog entry
361 * @param int contextid - id of context to associate with the blog entry
363 public function add_association($contextid, $action='add') {
364 global $DB, $USER;
366 $assocobject = new StdClass;
367 $assocobject->contextid = $contextid;
368 $assocobject->blogid = $this->id;
369 $DB->insert_record('blog_association', $assocobject);
371 $context = context::instance_by_id($contextid);
372 $courseid = null;
374 if ($context->contextlevel == CONTEXT_COURSE) {
375 $courseid = $context->instanceid;
376 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
377 } else if ($context->contextlevel == CONTEXT_MODULE) {
378 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
379 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
380 add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
385 * remove all associations for a blog entry
386 * @return voic
388 public function remove_associations() {
389 global $DB;
390 $DB->delete_records('blog_association', array('blogid' => $this->id));
394 * Deletes all the user files in the attachments area for an entry
396 * @return void
398 public function delete_attachments() {
399 $fs = get_file_storage();
400 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
401 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
405 * function to attach tags into an entry
406 * @return void
408 public function add_tags_info() {
410 $tags = array();
412 if ($otags = optional_param('otags', '', PARAM_INT)) {
413 foreach ($otags as $tagid) {
414 // TODO : make this use the tag name in the form
415 if ($tag = tag_get('id', $tagid)) {
416 $tags[] = $tag->name;
421 tag_set('post', $this->id, $tags);
425 * User can edit a blog entry if this is their own blog entry and they have
426 * the capability moodle/blog:create, or if they have the capability
427 * moodle/blog:manageentries.
428 * This also applies to deleting of entries.
430 * @param int $userid Optional. If not given, $USER is used
431 * @return boolean
433 public function can_user_edit($userid=null) {
434 global $CFG, $USER;
436 if (empty($userid)) {
437 $userid = $USER->id;
440 $sitecontext = context_system::instance();
442 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
443 return true; // can edit any blog entry
446 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
447 return true; // can edit own when having blog:create capability
450 return false;
454 * Checks to see if a user can view the blogs of another user.
455 * Only blog level is checked here, the capabilities are enforced
456 * in blog/index.php
458 * @param int $targetuserid ID of the user we are checking
460 * @return bool
462 public function can_user_view($targetuserid) {
463 global $CFG, $USER, $DB;
464 $sitecontext = context_system::instance();
466 if (empty($CFG->enableblogs) || !has_capability('moodle/blog:view', $sitecontext)) {
467 return false; // blog system disabled or user has no blog view capability
470 if (isloggedin() && $USER->id == $targetuserid) {
471 return true; // can view own entries in any case
474 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
475 return true; // can manage all entries
478 // coming for 1 entry, make sure it's not a draft
479 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
480 return false; // can not view draft of others
483 // coming for 1 entry, make sure user is logged in, if not a public blog
484 if ($this->publishstate != 'public' && !isloggedin()) {
485 return false;
488 switch ($CFG->bloglevel) {
489 case BLOG_GLOBAL_LEVEL:
490 return true;
491 break;
493 case BLOG_SITE_LEVEL:
494 if (isloggedin()) { // not logged in viewers forbidden
495 return true;
497 return false;
498 break;
500 case BLOG_USER_LEVEL:
501 default:
502 $personalcontext = context_user::instance($targetuserid);
503 return has_capability('moodle/user:readuserblogs', $personalcontext);
504 break;
509 * Use this function to retrieve a list of publish states available for
510 * the currently logged in user.
512 * @return array This function returns an array ideal for sending to moodles'
513 * choose_from_menu function.
516 public static function get_applicable_publish_states() {
517 global $CFG;
518 $options = array();
520 // everyone gets draft access
521 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
522 $options['draft'] = get_string('publishtonoone', 'blog');
525 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
526 $options['site'] = get_string('publishtosite', 'blog');
529 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
530 $options['public'] = get_string('publishtoworld', 'blog');
533 return $options;
538 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
540 * @package moodlecore
541 * @subpackage blog
542 * @copyright 2009 Nicolas Connault
543 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
545 class blog_listing {
547 * Array of blog_entry objects.
548 * @var array $entries
550 public $entries = array();
553 * An array of blog_filter_* objects
554 * @var array $filters
556 public $filters = array();
559 * Constructor
561 * @param array $filters An associative array of filtername => filterid
563 public function __construct($filters=array()) {
564 // Unset filters overridden by more specific filters
565 foreach ($filters as $type => $id) {
566 if (!empty($type) && !empty($id)) {
567 $this->filters[$type] = blog_filter::get_instance($id, $type);
571 foreach ($this->filters as $type => $filter) {
572 foreach ($filter->overrides as $override) {
573 if (array_key_exists($override, $this->filters)) {
574 unset($this->filters[$override]);
581 * Fetches the array of blog entries.
583 * @return array
585 public function get_entries($start=0, $limit=10) {
586 global $DB;
588 if (empty($this->entries)) {
589 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
590 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
591 } else {
592 return false;
596 return $this->entries;
599 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
600 global $DB, $USER, $CFG;
602 if(!$userid) {
603 $userid = $USER->id;
606 $allnamefields = get_all_user_name_fields(true, 'u');
607 // The query used to locate blog entries is complicated. It will be built from the following components:
608 $requiredfields = "p.*, $allnamefields, u.email"; // the SELECT clause
609 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
610 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
612 // build up a clause for permission constraints
614 $params = array();
616 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
617 // admins can see all blogs regardless of publish states, as described on the help page
618 if (has_capability('moodle/user:readuserblogs', context_system::instance())) {
619 // don't add permission constraints
621 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
622 context_user::instance((empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
623 // don't add permission constraints
625 } else {
626 if (isloggedin() and !isguestuser()) {
627 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
629 //begin permission sql clause
630 $permissionsql = '(p.userid = ? ';
631 $params[] = $userid;
633 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
634 $permissionsql .= " OR p.publishstate = 'site' ";
637 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
638 $permissionsql .= " OR p.publishstate = 'public' ";
641 $permissionsql .= ') '; //close permissions sql clause
642 } else { // default is access to public entries
643 $permissionsql = "p.publishstate = 'public'";
645 $conditions[] = $permissionsql; //add permission constraints
648 foreach ($this->filters as $type => $blogfilter) {
649 $conditions = array_merge($conditions, $blogfilter->conditions);
650 $params = array_merge($params, $blogfilter->params);
651 $tables = array_merge($tables, $blogfilter->tables);
654 $tablessql = ''; // build up the FROM clause
655 foreach ($tables as $tablename => $table) {
656 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
659 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
660 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
661 $sql .= ($count) ? '' : " ORDER BY $sort";
663 return array('sql' => $sql, 'params' => $params);
667 * Outputs all the blog entries aggregated by this blog listing.
669 * @return void
671 public function print_entries() {
672 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
673 $sitecontext = context_system::instance();
675 // Blog renderer
676 $output = $PAGE->get_renderer('blog');
678 $page = optional_param('blogpage', 0, PARAM_INT);
679 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
680 $start = $page * $limit;
682 $morelink = '<br />&nbsp;&nbsp;';
684 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
685 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
686 } else {
687 $totalentries = 0;
690 $entries = $this->get_entries($start, $limit);
691 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
692 $pagingbar->pagevar = 'blogpage';
693 $blogheaders = blog_get_headers();
695 echo $OUTPUT->render($pagingbar);
697 if (has_capability('moodle/blog:create', $sitecontext)) {
698 //the user's blog is enabled and they are viewing their own blog
699 $userid = optional_param('userid', null, PARAM_INT);
701 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
703 $courseid = optional_param('courseid', null, PARAM_INT);
704 $modid = optional_param('modid', null, PARAM_INT);
706 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
707 $urlparams = array('action' => 'add',
708 'userid' => $userid,
709 'courseid' => $courseid,
710 'groupid' => optional_param('groupid', null, PARAM_INT),
711 'modid' => $modid,
712 'tagid' => optional_param('tagid', null, PARAM_INT),
713 'tag' => optional_param('tag', null, PARAM_INT),
714 'search' => optional_param('search', null, PARAM_INT));
716 $urlparams = array_filter($urlparams);
717 $addurl->params($urlparams);
719 $addlink = '<div class="addbloglink">';
720 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
721 $addlink .= '</div>';
722 echo $addlink;
726 if ($entries) {
727 $count = 0;
728 foreach ($entries as $entry) {
729 $blogentry = new blog_entry(null, $entry);
731 // Get the required blog entry data to render it
732 $blogentry->prepare_render();
733 echo $output->render($blogentry);
735 $count++;
738 echo $OUTPUT->render($pagingbar);
740 if (!$count) {
741 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
744 print $morelink.'<br />'."\n";
745 return;
749 /// Find the base url from $_GET variables, for print_paging_bar
750 public function get_baseurl() {
751 $getcopy = $_GET;
753 unset($getcopy['blogpage']);
755 if (!empty($getcopy)) {
756 $first = false;
757 $querystring = '';
759 foreach ($getcopy as $var => $val) {
760 if (!$first) {
761 $first = true;
762 $querystring .= "?$var=$val";
763 } else {
764 $querystring .= '&amp;'.$var.'='.$val;
765 $hasparam = true;
768 } else {
769 $querystring = '?';
772 return strip_querystring(qualified_me()) . $querystring;
778 * Abstract class for blog_filter objects.
779 * A set of core filters are implemented here. To write new filters, you need to subclass
780 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
781 * The blog_filter abstract class will automatically use it when the filter is added to the
782 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
783 * or have any other meaning you wish it to have. The second parameter is called $type and is
784 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
786 abstract class blog_filter {
788 * An array of strings representing the available filter types for each blog_filter.
789 * @var array $availabletypes
791 public $availabletypes = array();
794 * The type of filter (for example, types of blog_filter_context are site, course and module)
795 * @var string $type
797 public $type;
800 * The unique ID for a filter's associated record
801 * @var int $id
803 public $id;
806 * An array of table aliases that are used in the WHERE conditions
807 * @var array $tables
809 public $tables = array();
812 * An array of WHERE conditions
813 * @var array $conditions
815 public $conditions = array();
818 * An array of SQL params
819 * @var array $params
821 public $params = array();
824 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
826 public $overrides = array();
828 public function __construct($id, $type=null) {
829 $this->id = $id;
830 $this->type = $type;
834 * TODO This is poor design. A parent class should not know anything about its children.
835 * The default case helps to resolve this design issue
837 public static function get_instance($id, $type) {
839 switch ($type) {
840 case 'site':
841 case 'course':
842 case 'module':
843 return new blog_filter_context($id, $type);
844 break;
846 case 'group':
847 case 'user':
848 return new blog_filter_user($id, $type);
849 break;
851 case 'tag':
852 return new blog_filter_tag($id);
853 break;
855 default:
856 $classname = "blog_filter_$type";
857 if (class_exists($classname)) {
858 return new $classname($id, $type);
865 * This filter defines the context level of the blog entries being searched: site, course, module
867 class blog_filter_context extends blog_filter {
869 * Constructor
871 * @param string $type
872 * @param int $id
874 public function __construct($id=null, $type='site') {
875 global $SITE, $CFG, $DB;
877 if (empty($id)) {
878 $this->type = 'site';
879 } else {
880 $this->id = $id;
881 $this->type = $type;
884 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
886 switch ($this->type) {
887 case 'course': // Careful of site course!
888 // Ignore course filter if blog associations are not enabled
889 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
890 $this->overrides = array('site');
891 $context = context_course::instance($this->id);
892 $this->tables['ba'] = 'blog_association';
893 $this->conditions[] = 'p.id = ba.blogid';
894 $this->conditions[] = 'ba.contextid = '.$context->id;
895 break;
896 } else {
897 // We are dealing with the site course, do not break from the current case
900 case 'site':
901 // No special constraints
902 break;
903 case 'module':
904 if (!empty($CFG->useblogassociations)) {
905 $this->overrides = array('course', 'site');
907 $context = context_module::instance($this->id);
908 $this->tables['ba'] = 'blog_association';
909 $this->tables['p'] = 'post';
910 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
911 $this->params = array($context->id);
913 break;
919 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
920 * It can be combined with a context filter in order to refine the search.
922 class blog_filter_user extends blog_filter {
923 public $tables = array('u' => 'user');
926 * Constructor
928 * @param string $type
929 * @param int $id
931 public function __construct($id=null, $type='user') {
932 global $CFG, $DB, $USER;
933 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
935 if (empty($id)) {
936 $this->id = $USER->id;
937 $this->type = 'user';
938 } else {
939 $this->id = $id;
940 $this->type = $type;
943 if ($this->type == 'user') {
944 $this->conditions = array('u.id = ?');
945 $this->params = array($this->id);
946 $this->overrides = array('group');
948 } elseif ($this->type == 'group') {
949 $this->overrides = array('course', 'site');
951 $this->tables['gm'] = 'groups_members';
952 $this->conditions[] = 'p.userid = gm.userid';
953 $this->conditions[] = 'gm.groupid = ?';
954 $this->params[] = $this->id;
956 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
957 $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id)));
958 $this->tables['ba'] = 'blog_association';
959 $this->conditions[] = 'gm.groupid = ?';
960 $this->conditions[] = 'ba.contextid = ?';
961 $this->conditions[] = 'ba.blogid = p.id';
962 $this->params[] = $this->id;
963 $this->params[] = $coursecontext->id;
971 * This filter defines a tag by which blog entries should be searched.
973 class blog_filter_tag extends blog_filter {
974 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
977 * Constructor
979 * @return void
981 public function __construct($id) {
982 global $DB;
983 $this->id = $id;
985 $this->conditions = array('ti.tagid = t.id',
986 "ti.itemtype = 'post'",
987 'ti.itemid = p.id',
988 't.id = ?');
989 $this->params = array($this->id);
994 * This filter defines a specific blog entry id.
996 class blog_filter_entry extends blog_filter {
997 public $conditions = array('p.id = ?');
998 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1000 public function __construct($id) {
1001 $this->id = $id;
1002 $this->params[] = $this->id;
1007 * This filter restricts the results to a time interval in seconds up to time()
1009 class blog_filter_since extends blog_filter {
1010 public function __construct($interval) {
1011 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1012 $this->params[] = time() - $interval;
1013 $this->params[] = time();
1018 * Filter used to perform full-text search on an entry's subject, summary and content
1020 class blog_filter_search extends blog_filter {
1022 public function __construct($searchterm) {
1023 global $DB;
1024 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1025 ".$DB->sql_like('p.content', '?', false)." OR
1026 ".$DB->sql_like('p.subject', '?', false).")");
1027 $this->params[] = "%$searchterm%";
1028 $this->params[] = "%$searchterm%";
1029 $this->params[] = "%$searchterm%";
1035 * Renderable class to represent an entry attachment
1037 class blog_entry_attachment implements renderable {
1039 public $filename;
1040 public $url;
1041 public $file;
1044 * Gets the file data
1046 * @param stored_file $file
1047 * @param int $entryid Attachment entry id
1049 public function __construct($file, $entryid) {
1051 global $CFG;
1053 $this->file = $file;
1054 $this->filename = $file->get_filename();
1055 $this->url = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$entryid.'/'.$this->filename);