MDL-52140 upgrade: add 3.0.0 separation line to all upgrade scripts
[moodle.git] / blog / locallib.php
blob114e38eb0d02fcad2a3ae0094e286e9e7576db09
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for Blogs.
20 * @package moodlecore
21 * @subpackage blog
22 * @copyright 2009 Nicolas Connault
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->libdir . '/filelib.php');
30 /**
31 * Blog_entry class. Represents an entry in a user's blog. Contains all methods for managing this entry.
32 * This class does not contain any HTML-generating code. See blog_listing sub-classes for such code.
33 * This class follows the Object Relational Mapping technique, its member variables being mapped to
34 * the fields of the post table.
36 * @package moodlecore
37 * @subpackage blog
38 * @copyright 2009 Nicolas Connault
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 class blog_entry implements renderable {
42 // Public Database fields.
43 public $id;
44 public $userid;
45 public $subject;
46 public $summary;
47 public $rating = 0;
48 public $attachment;
49 public $publishstate;
51 // Locked Database fields (Don't touch these).
52 public $courseid = 0;
53 public $groupid = 0;
54 public $module = 'blog';
55 public $moduleid = 0;
56 public $coursemoduleid = 0;
57 public $content;
58 public $format = 1;
59 public $uniquehash = '';
60 public $lastmodified;
61 public $created;
62 public $usermodified;
64 // Other class variables.
65 public $form;
66 public $tags = array();
68 /** @var StdClass Data needed to render the entry */
69 public $renderable;
71 /**
72 * Constructor. If given an id, will fetch the corresponding record from the DB.
74 * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
76 public function __construct($id=null, $params=null, $form=null) {
77 global $DB, $PAGE, $CFG;
79 if (!empty($id)) {
80 $object = $DB->get_record('post', array('id' => $id));
81 foreach ($object as $var => $val) {
82 $this->$var = $val;
84 } else if (!empty($params) && (is_array($params) || is_object($params))) {
85 foreach ($params as $var => $val) {
86 $this->$var = $val;
90 if (!empty($CFG->useblogassociations)) {
91 $associations = $DB->get_records('blog_association', array('blogid' => $this->id));
92 foreach ($associations as $association) {
93 $context = context::instance_by_id($association->contextid);
94 if ($context->contextlevel == CONTEXT_COURSE) {
95 $this->courseassoc = $association->contextid;
96 } else if ($context->contextlevel == CONTEXT_MODULE) {
97 $this->modassoc = $association->contextid;
102 $this->form = $form;
107 * Gets the required data to print the entry
109 public function prepare_render() {
111 global $DB, $CFG, $PAGE;
113 $this->renderable = new StdClass();
115 $this->renderable->user = $DB->get_record('user', array('id'=>$this->userid));
117 // Entry comments.
118 if (!empty($CFG->usecomments) and $CFG->blogusecomments) {
119 require_once($CFG->dirroot . '/comment/lib.php');
121 $cmt = new stdClass();
122 $cmt->context = context_user::instance($this->userid);
123 $cmt->courseid = $PAGE->course->id;
124 $cmt->area = 'format_blog';
125 $cmt->itemid = $this->id;
126 $cmt->showcount = $CFG->blogshowcommentscount;
127 $cmt->component = 'blog';
128 $this->renderable->comment = new comment($cmt);
131 $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);
133 // External blog link.
134 if ($this->uniquehash && $this->content) {
135 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {
136 $urlparts = parse_url($externalblog->url);
137 $this->renderable->externalblogtext = get_string('retrievedfrom', 'blog') . get_string('labelsep', 'langconfig');
138 $this->renderable->externalblogtext .= html_writer::link($urlparts['scheme'] . '://' . $urlparts['host'],
139 $externalblog->name);
143 // Retrieve associations.
144 $this->renderable->unassociatedentry = false;
145 if (!empty($CFG->useblogassociations)) {
147 // Adding the entry associations data.
148 if ($associations = $associations = $DB->get_records('blog_association', array('blogid' => $this->id))) {
150 // Check to see if the entry is unassociated with group/course level access.
151 if ($this->publishstate == 'group' || $this->publishstate == 'course') {
152 $this->renderable->unassociatedentry = true;
155 foreach ($associations as $key => $assocrec) {
157 if (!$context = context::instance_by_id($assocrec->contextid, IGNORE_MISSING)) {
158 unset($associations[$key]);
159 continue;
162 // The renderer will need the contextlevel of the association.
163 $associations[$key]->contextlevel = $context->contextlevel;
165 // Course associations.
166 if ($context->contextlevel == CONTEXT_COURSE) {
167 // TODO: performance!!!!
168 $instancename = $DB->get_field('course', 'shortname', array('id' => $context->instanceid));
170 $associations[$key]->url = $assocurl = new moodle_url('/course/view.php',
171 array('id' => $context->instanceid));
172 $associations[$key]->text = $instancename;
173 $associations[$key]->icon = new pix_icon('i/course', $associations[$key]->text);
176 // Mod associations.
177 if ($context->contextlevel == CONTEXT_MODULE) {
179 // Getting the activity type and the activity instance id.
180 $sql = 'SELECT cm.instance, m.name FROM {course_modules} cm
181 JOIN {modules} m ON m.id = cm.module
182 WHERE cm.id = :cmid';
183 $modinfo = $DB->get_record_sql($sql, array('cmid' => $context->instanceid));
184 // TODO: performance!!!!
185 $instancename = $DB->get_field($modinfo->name, 'name', array('id' => $modinfo->instance));
187 $associations[$key]->type = get_string('modulename', $modinfo->name);
188 $associations[$key]->url = new moodle_url('/mod/' . $modinfo->name . '/view.php',
189 array('id' => $context->instanceid));
190 $associations[$key]->text = $instancename;
191 $associations[$key]->icon = new pix_icon('icon', $associations[$key]->text, $modinfo->name);
195 $this->renderable->blogassociations = $associations;
198 // Entry attachments.
199 $this->renderable->attachments = $this->get_attachments();
201 $this->renderable->usercanedit = blog_user_can_edit_entry($this);
206 * Gets the entry attachments list
207 * @return array List of blog_entry_attachment instances
209 public function get_attachments() {
211 global $CFG;
213 require_once($CFG->libdir.'/filelib.php');
215 $syscontext = context_system::instance();
217 $fs = get_file_storage();
218 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
220 // Adding a blog_entry_attachment for each non-directory file.
221 $attachments = array();
222 foreach ($files as $file) {
223 if ($file->is_directory()) {
224 continue;
226 $attachments[] = new blog_entry_attachment($file, $this->id);
229 return $attachments;
233 * Inserts this entry in the database. Access control checks must be done by calling code.
235 * @param mform $form Used for attachments
236 * @return void
238 public function process_attachment($form) {
239 $this->form = $form;
243 * Inserts this entry in the database. Access control checks must be done by calling code.
244 * TODO Set the publishstate correctly
245 * @return void
247 public function add() {
248 global $CFG, $USER, $DB;
250 unset($this->id);
251 $this->module = 'blog';
252 $this->userid = (empty($this->userid)) ? $USER->id : $this->userid;
253 $this->lastmodified = time();
254 $this->created = time();
256 // Insert the new blog entry.
257 $this->id = $DB->insert_record('post', $this);
259 // Update tags.
260 $this->add_tags_info();
262 if (!empty($CFG->useblogassociations)) {
263 $this->add_associations();
266 tag_set('post', $this->id, $this->tags, 'core', context_user::instance($this->userid)->id);
268 // Trigger an event for the new entry.
269 $event = \core\event\blog_entry_created::create(array(
270 'objectid' => $this->id,
271 'relateduserid' => $this->userid
273 $event->set_blog_entry($this);
274 $event->trigger();
278 * Updates this entry in the database. Access control checks must be done by calling code.
280 * @param array $params Entry parameters.
281 * @param moodleform $form Used for attachments.
282 * @param array $summaryoptions Summary options.
283 * @param array $attachmentoptions Attachment options.
285 * @return void
287 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
288 global $CFG, $DB;
290 $sitecontext = context_system::instance();
291 $entry = $this;
293 $this->form = $form;
294 foreach ($params as $var => $val) {
295 $entry->$var = $val;
298 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
299 $entry = file_postupdate_standard_filemanager($entry,
300 'attachment',
301 $attachmentoptions,
302 $sitecontext,
303 'blog',
304 'attachment',
305 $entry->id);
307 if (!empty($CFG->useblogassociations)) {
308 $entry->add_associations();
311 $entry->lastmodified = time();
313 // Update record.
314 $DB->update_record('post', $entry);
315 tag_set('post', $entry->id, $entry->tags, 'core', context_user::instance($this->userid)->id);
317 $event = \core\event\blog_entry_updated::create(array(
318 'objectid' => $entry->id,
319 'relateduserid' => $entry->userid
321 $event->set_blog_entry($entry);
322 $event->trigger();
326 * Deletes this entry from the database. Access control checks must be done by calling code.
328 * @return void
330 public function delete() {
331 global $DB;
333 $this->delete_attachments();
334 $this->remove_associations();
336 // Get record to pass onto the event.
337 $record = $DB->get_record('post', array('id' => $this->id));
338 $DB->delete_records('post', array('id' => $this->id));
339 tag_set('post', $this->id, array(), 'core', context_user::instance($this->userid)->id);
341 $event = \core\event\blog_entry_deleted::create(array(
342 'objectid' => $this->id,
343 'relateduserid' => $this->userid
345 $event->add_record_snapshot("post", $record);
346 $event->set_blog_entry($this);
347 $event->trigger();
351 * Function to add all context associations to an entry.
353 * @param string $unused This does nothing, do not use it.
355 public function add_associations($unused = null) {
357 if ($unused !== null) {
358 debugging('Illegal argument used in blog_entry->add_associations()', DEBUG_DEVELOPER);
361 $this->remove_associations();
363 if (!empty($this->courseassoc)) {
364 $this->add_association($this->courseassoc);
367 if (!empty($this->modassoc)) {
368 $this->add_association($this->modassoc);
373 * Add a single association for a blog entry
375 * @param int $contextid - id of context to associate with the blog entry.
376 * @param string $unused This does nothing, do not use it.
378 public function add_association($contextid, $unused = null) {
379 global $DB;
381 if ($unused !== null) {
382 debugging('Illegal argument used in blog_entry->add_association()', DEBUG_DEVELOPER);
385 $assocobject = new StdClass;
386 $assocobject->contextid = $contextid;
387 $assocobject->blogid = $this->id;
388 $id = $DB->insert_record('blog_association', $assocobject);
390 // Trigger an association created event.
391 $context = context::instance_by_id($contextid);
392 $eventparam = array(
393 'objectid' => $id,
394 'other' => array('associateid' => $context->instanceid, 'subject' => $this->subject, 'blogid' => $this->id),
395 'relateduserid' => $this->userid
397 if ($context->contextlevel == CONTEXT_COURSE) {
398 $eventparam['other']['associatetype'] = 'course';
400 } else if ($context->contextlevel == CONTEXT_MODULE) {
401 $eventparam['other']['associatetype'] = 'coursemodule';
403 $event = \core\event\blog_association_created::create($eventparam);
404 $event->trigger();
408 * remove all associations for a blog entry
409 * @return voic
411 public function remove_associations() {
412 global $DB;
413 $DB->delete_records('blog_association', array('blogid' => $this->id));
417 * Deletes all the user files in the attachments area for an entry
419 * @return void
421 public function delete_attachments() {
422 $fs = get_file_storage();
423 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
424 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
428 * function to attach tags into an entry
429 * @return void
431 public function add_tags_info() {
433 $tags = array();
435 if ($otags = optional_param('otags', '', PARAM_INT)) {
436 foreach ($otags as $tagid) {
437 // TODO : make this use the tag name in the form.
438 if ($tag = tag_get('id', $tagid)) {
439 $tags[] = $tag->name;
444 tag_set('post', $this->id, $tags, 'core', context_user::instance($this->userid)->id);
448 * User can edit a blog entry if this is their own blog entry and they have
449 * the capability moodle/blog:create, or if they have the capability
450 * moodle/blog:manageentries.
451 * This also applies to deleting of entries.
453 * @param int $userid Optional. If not given, $USER is used
454 * @return boolean
456 public function can_user_edit($userid=null) {
457 global $CFG, $USER;
459 if (empty($userid)) {
460 $userid = $USER->id;
463 $sitecontext = context_system::instance();
465 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
466 return true; // Can edit any blog entry.
469 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
470 return true; // Can edit own when having blog:create capability.
473 return false;
477 * Checks to see if a user can view the blogs of another user.
478 * Only blog level is checked here, the capabilities are enforced
479 * in blog/index.php
481 * @param int $targetuserid ID of the user we are checking
483 * @return bool
485 public function can_user_view($targetuserid) {
486 global $CFG, $USER, $DB;
487 $sitecontext = context_system::instance();
489 if (empty($CFG->enableblogs) || !has_capability('moodle/blog:view', $sitecontext)) {
490 return false; // Blog system disabled or user has no blog view capability.
493 if (isloggedin() && $USER->id == $targetuserid) {
494 return true; // Can view own entries in any case.
497 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
498 return true; // Can manage all entries.
501 // Coming for 1 entry, make sure it's not a draft.
502 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
503 return false; // Can not view draft of others.
506 // Coming for 1 entry, make sure user is logged in, if not a public blog.
507 if ($this->publishstate != 'public' && !isloggedin()) {
508 return false;
511 switch ($CFG->bloglevel) {
512 case BLOG_GLOBAL_LEVEL:
513 return true;
514 break;
516 case BLOG_SITE_LEVEL:
517 if (isloggedin()) { // Not logged in viewers forbidden.
518 return true;
520 return false;
521 break;
523 case BLOG_USER_LEVEL:
524 default:
525 $personalcontext = context_user::instance($targetuserid);
526 return has_capability('moodle/user:readuserblogs', $personalcontext);
527 break;
532 * Use this function to retrieve a list of publish states available for
533 * the currently logged in user.
535 * @return array This function returns an array ideal for sending to moodles'
536 * choose_from_menu function.
539 public static function get_applicable_publish_states() {
540 global $CFG;
541 $options = array();
543 // Everyone gets draft access.
544 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
545 $options['draft'] = get_string('publishtonoone', 'blog');
548 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
549 $options['site'] = get_string('publishtosite', 'blog');
552 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
553 $options['public'] = get_string('publishtoworld', 'blog');
556 return $options;
561 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
563 * @package moodlecore
564 * @subpackage blog
565 * @copyright 2009 Nicolas Connault
566 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
568 class blog_listing {
570 * Array of blog_entry objects.
571 * @var array $entries
573 public $entries = array();
576 * An array of blog_filter_* objects
577 * @var array $filters
579 public $filters = array();
582 * Constructor
584 * @param array $filters An associative array of filtername => filterid
586 public function __construct($filters=array()) {
587 // Unset filters overridden by more specific filters.
588 foreach ($filters as $type => $id) {
589 if (!empty($type) && !empty($id)) {
590 $this->filters[$type] = blog_filter::get_instance($id, $type);
594 foreach ($this->filters as $type => $filter) {
595 foreach ($filter->overrides as $override) {
596 if (array_key_exists($override, $this->filters)) {
597 unset($this->filters[$override]);
604 * Fetches the array of blog entries.
606 * @return array
608 public function get_entries($start=0, $limit=10) {
609 global $DB;
611 if (empty($this->entries)) {
612 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
613 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
614 } else {
615 return false;
619 return $this->entries;
622 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
623 global $DB, $USER, $CFG;
625 if (!$userid) {
626 $userid = $USER->id;
629 $allnamefields = get_all_user_name_fields(true, 'u');
630 // The query used to locate blog entries is complicated. It will be built from the following components:
631 $requiredfields = "p.*, $allnamefields, u.email"; // The SELECT clause.
632 $tables = array('p' => 'post', 'u' => 'user'); // Components of the FROM clause (table_id => table_name).
633 // Components of the WHERE clause (conjunction).
634 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')');
636 // Build up a clause for permission constraints.
638 $params = array();
640 // Fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs.
641 // Admins can see all blogs regardless of publish states, as described on the help page.
642 if (has_capability('moodle/user:readuserblogs', context_system::instance())) {
643 // Don't add permission constraints.
645 } else if (!empty($this->filters['user'])
646 && has_capability('moodle/user:readuserblogs',
647 context_user::instance((empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
648 // Don't add permission constraints.
650 } else {
651 if (isloggedin() and !isguestuser()) {
652 // Dont check association records if there aren't any.
653 $assocexists = $DB->record_exists('blog_association', array());
655 // Begin permission sql clause.
656 $permissionsql = '(p.userid = ? ';
657 $params[] = $userid;
659 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // Add permission to view site-level entries.
660 $permissionsql .= " OR p.publishstate = 'site' ";
663 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // Add permission to view global entries.
664 $permissionsql .= " OR p.publishstate = 'public' ";
667 $permissionsql .= ') '; // Close permissions sql clause.
668 } else { // Default is access to public entries.
669 $permissionsql = "p.publishstate = 'public'";
671 $conditions[] = $permissionsql; // Add permission constraints.
674 foreach ($this->filters as $type => $blogfilter) {
675 $conditions = array_merge($conditions, $blogfilter->conditions);
676 $params = array_merge($params, $blogfilter->params);
677 $tables = array_merge($tables, $blogfilter->tables);
680 $tablessql = ''; // Build up the FROM clause.
681 foreach ($tables as $tablename => $table) {
682 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
685 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
686 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
687 $sql .= ($count) ? '' : " ORDER BY $sort";
689 return array('sql' => $sql, 'params' => $params);
693 * Outputs all the blog entries aggregated by this blog listing.
695 * @return void
697 public function print_entries() {
698 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
699 $sitecontext = context_system::instance();
701 // Blog renderer.
702 $output = $PAGE->get_renderer('blog');
704 $page = optional_param('blogpage', 0, PARAM_INT);
705 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
706 $start = $page * $limit;
708 $morelink = '<br />&nbsp;&nbsp;';
710 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
711 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
712 } else {
713 $totalentries = 0;
716 $entries = $this->get_entries($start, $limit);
717 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
718 $pagingbar->pagevar = 'blogpage';
719 $blogheaders = blog_get_headers();
721 echo $OUTPUT->render($pagingbar);
723 if (has_capability('moodle/blog:create', $sitecontext)) {
724 // The user's blog is enabled and they are viewing their own blog.
725 $userid = optional_param('userid', null, PARAM_INT);
727 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
729 $courseid = optional_param('courseid', null, PARAM_INT);
730 $modid = optional_param('modid', null, PARAM_INT);
732 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
733 $urlparams = array('action' => 'add',
734 'userid' => $userid,
735 'courseid' => $courseid,
736 'groupid' => optional_param('groupid', null, PARAM_INT),
737 'modid' => $modid,
738 'tagid' => optional_param('tagid', null, PARAM_INT),
739 'tag' => optional_param('tag', null, PARAM_INT),
740 'search' => optional_param('search', null, PARAM_INT));
742 $urlparams = array_filter($urlparams);
743 $addurl->params($urlparams);
745 $addlink = '<div class="addbloglink">';
746 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
747 $addlink .= '</div>';
748 echo $addlink;
752 if ($entries) {
753 $count = 0;
754 foreach ($entries as $entry) {
755 $blogentry = new blog_entry(null, $entry);
757 // Get the required blog entry data to render it.
758 $blogentry->prepare_render();
759 echo $output->render($blogentry);
761 $count++;
764 echo $OUTPUT->render($pagingbar);
766 if (!$count) {
767 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
770 print $morelink.'<br />'."\n";
771 return;
775 // Find the base url from $_GET variables, for print_paging_bar.
776 public function get_baseurl() {
777 $getcopy = $_GET;
779 unset($getcopy['blogpage']);
781 if (!empty($getcopy)) {
782 $first = false;
783 $querystring = '';
785 foreach ($getcopy as $var => $val) {
786 if (!$first) {
787 $first = true;
788 $querystring .= "?$var=$val";
789 } else {
790 $querystring .= '&amp;'.$var.'='.$val;
791 $hasparam = true;
794 } else {
795 $querystring = '?';
798 return strip_querystring(qualified_me()) . $querystring;
804 * Abstract class for blog_filter objects.
805 * A set of core filters are implemented here. To write new filters, you need to subclass
806 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
807 * The blog_filter abstract class will automatically use it when the filter is added to the
808 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
809 * or have any other meaning you wish it to have. The second parameter is called $type and is
810 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
812 abstract class blog_filter {
814 * An array of strings representing the available filter types for each blog_filter.
815 * @var array $availabletypes
817 public $availabletypes = array();
820 * The type of filter (for example, types of blog_filter_context are site, course and module)
821 * @var string $type
823 public $type;
826 * The unique ID for a filter's associated record
827 * @var int $id
829 public $id;
832 * An array of table aliases that are used in the WHERE conditions
833 * @var array $tables
835 public $tables = array();
838 * An array of WHERE conditions
839 * @var array $conditions
841 public $conditions = array();
844 * An array of SQL params
845 * @var array $params
847 public $params = array();
850 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
852 public $overrides = array();
854 public function __construct($id, $type=null) {
855 $this->id = $id;
856 $this->type = $type;
860 * TODO This is poor design. A parent class should not know anything about its children.
861 * The default case helps to resolve this design issue
863 public static function get_instance($id, $type) {
865 switch ($type) {
866 case 'site':
867 case 'course':
868 case 'module':
869 return new blog_filter_context($id, $type);
870 break;
872 case 'group':
873 case 'user':
874 return new blog_filter_user($id, $type);
875 break;
877 case 'tag':
878 return new blog_filter_tag($id);
879 break;
881 default:
882 $classname = "blog_filter_$type";
883 if (class_exists($classname)) {
884 return new $classname($id, $type);
891 * This filter defines the context level of the blog entries being searched: site, course, module
893 class blog_filter_context extends blog_filter {
895 * Constructor
897 * @param string $type
898 * @param int $id
900 public function __construct($id=null, $type='site') {
901 global $SITE, $CFG, $DB;
903 if (empty($id)) {
904 $this->type = 'site';
905 } else {
906 $this->id = $id;
907 $this->type = $type;
910 $this->availabletypes = array('site' => get_string('site'),
911 'course' => get_string('course'),
912 'module' => get_string('activity'));
914 switch ($this->type) {
915 case 'course': // Careful of site course!
916 // Ignore course filter if blog associations are not enabled.
917 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
918 $this->overrides = array('site');
919 $context = context_course::instance($this->id);
920 $this->tables['ba'] = 'blog_association';
921 $this->conditions[] = 'p.id = ba.blogid';
922 $this->conditions[] = 'ba.contextid = '.$context->id;
923 break;
924 } else {
925 // We are dealing with the site course, do not break from the current case.
928 case 'site':
929 // No special constraints.
930 break;
931 case 'module':
932 if (!empty($CFG->useblogassociations)) {
933 $this->overrides = array('course', 'site');
935 $context = context_module::instance($this->id);
936 $this->tables['ba'] = 'blog_association';
937 $this->tables['p'] = 'post';
938 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
939 $this->params = array($context->id);
941 break;
947 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
948 * It can be combined with a context filter in order to refine the search.
950 class blog_filter_user extends blog_filter {
951 public $tables = array('u' => 'user');
954 * Constructor
956 * @param string $type
957 * @param int $id
959 public function __construct($id=null, $type='user') {
960 global $CFG, $DB, $USER;
961 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
963 if (empty($id)) {
964 $this->id = $USER->id;
965 $this->type = 'user';
966 } else {
967 $this->id = $id;
968 $this->type = $type;
971 if ($this->type == 'user') {
972 $this->conditions = array('u.id = ?');
973 $this->params = array($this->id);
974 $this->overrides = array('group');
976 } else if ($this->type == 'group') {
977 $this->overrides = array('course', 'site');
979 $this->tables['gm'] = 'groups_members';
980 $this->conditions[] = 'p.userid = gm.userid';
981 $this->conditions[] = 'gm.groupid = ?';
982 $this->params[] = $this->id;
984 if (!empty($CFG->useblogassociations)) { // Only show blog entries associated with this course.
985 $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id)));
986 $this->tables['ba'] = 'blog_association';
987 $this->conditions[] = 'gm.groupid = ?';
988 $this->conditions[] = 'ba.contextid = ?';
989 $this->conditions[] = 'ba.blogid = p.id';
990 $this->params[] = $this->id;
991 $this->params[] = $coursecontext->id;
999 * This filter defines a tag by which blog entries should be searched.
1001 class blog_filter_tag extends blog_filter {
1002 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
1005 * Constructor
1007 * @return void
1009 public function __construct($id) {
1010 global $DB;
1011 $this->id = $id;
1013 $this->conditions = array('ti.tagid = t.id',
1014 "ti.itemtype = 'post'",
1015 'ti.itemid = p.id',
1016 't.id = ?');
1017 $this->params = array($this->id);
1022 * This filter defines a specific blog entry id.
1024 class blog_filter_entry extends blog_filter {
1025 public $conditions = array('p.id = ?');
1026 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1028 public function __construct($id) {
1029 $this->id = $id;
1030 $this->params[] = $this->id;
1035 * This filter restricts the results to a time interval in seconds up to time()
1037 class blog_filter_since extends blog_filter {
1038 public function __construct($interval) {
1039 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1040 $this->params[] = time() - $interval;
1041 $this->params[] = time();
1046 * Filter used to perform full-text search on an entry's subject, summary and content
1048 class blog_filter_search extends blog_filter {
1050 public function __construct($searchterm) {
1051 global $DB;
1052 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1053 ".$DB->sql_like('p.content', '?', false)." OR
1054 ".$DB->sql_like('p.subject', '?', false).")");
1055 $this->params[] = "%$searchterm%";
1056 $this->params[] = "%$searchterm%";
1057 $this->params[] = "%$searchterm%";
1063 * Renderable class to represent an entry attachment
1065 class blog_entry_attachment implements renderable {
1067 public $filename;
1068 public $url;
1069 public $file;
1072 * Gets the file data
1074 * @param stored_file $file
1075 * @param int $entryid Attachment entry id
1077 public function __construct($file, $entryid) {
1079 global $CFG;
1081 $this->file = $file;
1082 $this->filename = $file->get_filename();
1083 $this->url = file_encode_url($CFG->wwwroot . '/pluginfile.php',
1084 '/' . SYSCONTEXTID . '/blog/attachment/' . $entryid . '/' . $this->filename);