MDL-50576 mod_forum: Correct use of movedicussions cap when posting This is a partial...
[moodle.git] / blog / locallib.php
blob556105006c5951b4fc01d9f12aa8a3098a643ac1
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, 'core', context_user::instance($this->userid)->id);
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_blog_entry($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, 'core', context_user::instance($this->userid)->id);
308 $event = \core\event\blog_entry_updated::create(array(
309 'objectid' => $entry->id,
310 'relateduserid' => $entry->userid
312 $event->set_blog_entry($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(), 'core', context_user::instance($this->userid)->id);
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_blog_entry($this);
338 $event->trigger();
342 * Function to add all context associations to an entry.
343 * TODO : Remove $action in 2.9 (MDL-41330)
345 * @param string $action - This does nothing, do not use it. This is present only for Backward compatibility.
347 public function add_associations($action = null) {
349 if (!empty($action)) {
350 debugging('blog_entry->add_associations() does not accept any argument', DEBUG_DEVELOPER);
353 $this->remove_associations();
355 if (!empty($this->courseassoc)) {
356 $this->add_association($this->courseassoc);
359 if (!empty($this->modassoc)) {
360 $this->add_association($this->modassoc);
365 * Add a single association for a blog entry
366 * TODO : Remove $action in 2.9 (MDL-41330)
368 * @param int $contextid - id of context to associate with the blog entry.
369 * @param string $action - This does nothing, do not use it. This is present only for Backward compatibility.
371 public function add_association($contextid, $action = null) {
372 global $DB;
374 if (!empty($action)) {
375 debugging('blog_entry->add_association() accepts only one argument', DEBUG_DEVELOPER);
378 $assocobject = new StdClass;
379 $assocobject->contextid = $contextid;
380 $assocobject->blogid = $this->id;
381 $id = $DB->insert_record('blog_association', $assocobject);
383 // Trigger an association created event.
384 $context = context::instance_by_id($contextid);
385 $eventparam = array(
386 'objectid' => $id,
387 'other' => array('associateid' => $context->instanceid, 'subject' => $this->subject, 'blogid' => $this->id),
388 'relateduserid' => $this->userid
390 if ($context->contextlevel == CONTEXT_COURSE) {
391 $eventparam['other']['associatetype'] = 'course';
393 } else if ($context->contextlevel == CONTEXT_MODULE) {
394 $eventparam['other']['associatetype'] = 'coursemodule';
396 $event = \core\event\blog_association_created::create($eventparam);
397 $event->trigger();
401 * remove all associations for a blog entry
402 * @return voic
404 public function remove_associations() {
405 global $DB;
406 $DB->delete_records('blog_association', array('blogid' => $this->id));
410 * Deletes all the user files in the attachments area for an entry
412 * @return void
414 public function delete_attachments() {
415 $fs = get_file_storage();
416 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
417 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
421 * function to attach tags into an entry
422 * @return void
424 public function add_tags_info() {
426 $tags = array();
428 if ($otags = optional_param('otags', '', PARAM_INT)) {
429 foreach ($otags as $tagid) {
430 // TODO : make this use the tag name in the form
431 if ($tag = tag_get('id', $tagid)) {
432 $tags[] = $tag->name;
437 tag_set('post', $this->id, $tags, 'core', context_user::instance($this->userid)->id);
441 * User can edit a blog entry if this is their own blog entry and they have
442 * the capability moodle/blog:create, or if they have the capability
443 * moodle/blog:manageentries.
444 * This also applies to deleting of entries.
446 * @param int $userid Optional. If not given, $USER is used
447 * @return boolean
449 public function can_user_edit($userid=null) {
450 global $CFG, $USER;
452 if (empty($userid)) {
453 $userid = $USER->id;
456 $sitecontext = context_system::instance();
458 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
459 return true; // can edit any blog entry
462 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
463 return true; // can edit own when having blog:create capability
466 return false;
470 * Checks to see if a user can view the blogs of another user.
471 * Only blog level is checked here, the capabilities are enforced
472 * in blog/index.php
474 * @param int $targetuserid ID of the user we are checking
476 * @return bool
478 public function can_user_view($targetuserid) {
479 global $CFG, $USER, $DB;
480 $sitecontext = context_system::instance();
482 if (empty($CFG->enableblogs) || !has_capability('moodle/blog:view', $sitecontext)) {
483 return false; // blog system disabled or user has no blog view capability
486 if (isloggedin() && $USER->id == $targetuserid) {
487 return true; // can view own entries in any case
490 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
491 return true; // can manage all entries
494 // coming for 1 entry, make sure it's not a draft
495 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
496 return false; // can not view draft of others
499 // coming for 1 entry, make sure user is logged in, if not a public blog
500 if ($this->publishstate != 'public' && !isloggedin()) {
501 return false;
504 switch ($CFG->bloglevel) {
505 case BLOG_GLOBAL_LEVEL:
506 return true;
507 break;
509 case BLOG_SITE_LEVEL:
510 if (isloggedin()) { // not logged in viewers forbidden
511 return true;
513 return false;
514 break;
516 case BLOG_USER_LEVEL:
517 default:
518 $personalcontext = context_user::instance($targetuserid);
519 return has_capability('moodle/user:readuserblogs', $personalcontext);
520 break;
525 * Use this function to retrieve a list of publish states available for
526 * the currently logged in user.
528 * @return array This function returns an array ideal for sending to moodles'
529 * choose_from_menu function.
532 public static function get_applicable_publish_states() {
533 global $CFG;
534 $options = array();
536 // everyone gets draft access
537 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
538 $options['draft'] = get_string('publishtonoone', 'blog');
541 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
542 $options['site'] = get_string('publishtosite', 'blog');
545 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
546 $options['public'] = get_string('publishtoworld', 'blog');
549 return $options;
554 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
556 * @package moodlecore
557 * @subpackage blog
558 * @copyright 2009 Nicolas Connault
559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
561 class blog_listing {
563 * Array of blog_entry objects.
564 * @var array $entries
566 public $entries = array();
569 * An array of blog_filter_* objects
570 * @var array $filters
572 public $filters = array();
575 * Constructor
577 * @param array $filters An associative array of filtername => filterid
579 public function __construct($filters=array()) {
580 // Unset filters overridden by more specific filters
581 foreach ($filters as $type => $id) {
582 if (!empty($type) && !empty($id)) {
583 $this->filters[$type] = blog_filter::get_instance($id, $type);
587 foreach ($this->filters as $type => $filter) {
588 foreach ($filter->overrides as $override) {
589 if (array_key_exists($override, $this->filters)) {
590 unset($this->filters[$override]);
597 * Fetches the array of blog entries.
599 * @return array
601 public function get_entries($start=0, $limit=10) {
602 global $DB;
604 if (empty($this->entries)) {
605 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
606 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
607 } else {
608 return false;
612 return $this->entries;
615 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
616 global $DB, $USER, $CFG;
618 if(!$userid) {
619 $userid = $USER->id;
622 $allnamefields = get_all_user_name_fields(true, 'u');
623 // The query used to locate blog entries is complicated. It will be built from the following components:
624 $requiredfields = "p.*, $allnamefields, u.email"; // the SELECT clause
625 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
626 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
628 // build up a clause for permission constraints
630 $params = array();
632 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
633 // admins can see all blogs regardless of publish states, as described on the help page
634 if (has_capability('moodle/user:readuserblogs', context_system::instance())) {
635 // don't add permission constraints
637 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
638 context_user::instance((empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
639 // don't add permission constraints
641 } else {
642 if (isloggedin() and !isguestuser()) {
643 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
645 //begin permission sql clause
646 $permissionsql = '(p.userid = ? ';
647 $params[] = $userid;
649 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
650 $permissionsql .= " OR p.publishstate = 'site' ";
653 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
654 $permissionsql .= " OR p.publishstate = 'public' ";
657 $permissionsql .= ') '; //close permissions sql clause
658 } else { // default is access to public entries
659 $permissionsql = "p.publishstate = 'public'";
661 $conditions[] = $permissionsql; //add permission constraints
664 foreach ($this->filters as $type => $blogfilter) {
665 $conditions = array_merge($conditions, $blogfilter->conditions);
666 $params = array_merge($params, $blogfilter->params);
667 $tables = array_merge($tables, $blogfilter->tables);
670 $tablessql = ''; // build up the FROM clause
671 foreach ($tables as $tablename => $table) {
672 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
675 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
676 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
677 $sql .= ($count) ? '' : " ORDER BY $sort";
679 return array('sql' => $sql, 'params' => $params);
683 * Outputs all the blog entries aggregated by this blog listing.
685 * @return void
687 public function print_entries() {
688 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
689 $sitecontext = context_system::instance();
691 // Blog renderer
692 $output = $PAGE->get_renderer('blog');
694 $page = optional_param('blogpage', 0, PARAM_INT);
695 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
696 $start = $page * $limit;
698 $morelink = '<br />&nbsp;&nbsp;';
700 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
701 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
702 } else {
703 $totalentries = 0;
706 $entries = $this->get_entries($start, $limit);
707 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
708 $pagingbar->pagevar = 'blogpage';
709 $blogheaders = blog_get_headers();
711 echo $OUTPUT->render($pagingbar);
713 if (has_capability('moodle/blog:create', $sitecontext)) {
714 //the user's blog is enabled and they are viewing their own blog
715 $userid = optional_param('userid', null, PARAM_INT);
717 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
719 $courseid = optional_param('courseid', null, PARAM_INT);
720 $modid = optional_param('modid', null, PARAM_INT);
722 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
723 $urlparams = array('action' => 'add',
724 'userid' => $userid,
725 'courseid' => $courseid,
726 'groupid' => optional_param('groupid', null, PARAM_INT),
727 'modid' => $modid,
728 'tagid' => optional_param('tagid', null, PARAM_INT),
729 'tag' => optional_param('tag', null, PARAM_INT),
730 'search' => optional_param('search', null, PARAM_INT));
732 $urlparams = array_filter($urlparams);
733 $addurl->params($urlparams);
735 $addlink = '<div class="addbloglink">';
736 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
737 $addlink .= '</div>';
738 echo $addlink;
742 if ($entries) {
743 $count = 0;
744 foreach ($entries as $entry) {
745 $blogentry = new blog_entry(null, $entry);
747 // Get the required blog entry data to render it
748 $blogentry->prepare_render();
749 echo $output->render($blogentry);
751 $count++;
754 echo $OUTPUT->render($pagingbar);
756 if (!$count) {
757 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
760 print $morelink.'<br />'."\n";
761 return;
765 /// Find the base url from $_GET variables, for print_paging_bar
766 public function get_baseurl() {
767 $getcopy = $_GET;
769 unset($getcopy['blogpage']);
771 if (!empty($getcopy)) {
772 $first = false;
773 $querystring = '';
775 foreach ($getcopy as $var => $val) {
776 if (!$first) {
777 $first = true;
778 $querystring .= "?$var=$val";
779 } else {
780 $querystring .= '&amp;'.$var.'='.$val;
781 $hasparam = true;
784 } else {
785 $querystring = '?';
788 return strip_querystring(qualified_me()) . $querystring;
794 * Abstract class for blog_filter objects.
795 * A set of core filters are implemented here. To write new filters, you need to subclass
796 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
797 * The blog_filter abstract class will automatically use it when the filter is added to the
798 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
799 * or have any other meaning you wish it to have. The second parameter is called $type and is
800 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
802 abstract class blog_filter {
804 * An array of strings representing the available filter types for each blog_filter.
805 * @var array $availabletypes
807 public $availabletypes = array();
810 * The type of filter (for example, types of blog_filter_context are site, course and module)
811 * @var string $type
813 public $type;
816 * The unique ID for a filter's associated record
817 * @var int $id
819 public $id;
822 * An array of table aliases that are used in the WHERE conditions
823 * @var array $tables
825 public $tables = array();
828 * An array of WHERE conditions
829 * @var array $conditions
831 public $conditions = array();
834 * An array of SQL params
835 * @var array $params
837 public $params = array();
840 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
842 public $overrides = array();
844 public function __construct($id, $type=null) {
845 $this->id = $id;
846 $this->type = $type;
850 * TODO This is poor design. A parent class should not know anything about its children.
851 * The default case helps to resolve this design issue
853 public static function get_instance($id, $type) {
855 switch ($type) {
856 case 'site':
857 case 'course':
858 case 'module':
859 return new blog_filter_context($id, $type);
860 break;
862 case 'group':
863 case 'user':
864 return new blog_filter_user($id, $type);
865 break;
867 case 'tag':
868 return new blog_filter_tag($id);
869 break;
871 default:
872 $classname = "blog_filter_$type";
873 if (class_exists($classname)) {
874 return new $classname($id, $type);
881 * This filter defines the context level of the blog entries being searched: site, course, module
883 class blog_filter_context extends blog_filter {
885 * Constructor
887 * @param string $type
888 * @param int $id
890 public function __construct($id=null, $type='site') {
891 global $SITE, $CFG, $DB;
893 if (empty($id)) {
894 $this->type = 'site';
895 } else {
896 $this->id = $id;
897 $this->type = $type;
900 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
902 switch ($this->type) {
903 case 'course': // Careful of site course!
904 // Ignore course filter if blog associations are not enabled
905 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
906 $this->overrides = array('site');
907 $context = context_course::instance($this->id);
908 $this->tables['ba'] = 'blog_association';
909 $this->conditions[] = 'p.id = ba.blogid';
910 $this->conditions[] = 'ba.contextid = '.$context->id;
911 break;
912 } else {
913 // We are dealing with the site course, do not break from the current case
916 case 'site':
917 // No special constraints
918 break;
919 case 'module':
920 if (!empty($CFG->useblogassociations)) {
921 $this->overrides = array('course', 'site');
923 $context = context_module::instance($this->id);
924 $this->tables['ba'] = 'blog_association';
925 $this->tables['p'] = 'post';
926 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
927 $this->params = array($context->id);
929 break;
935 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
936 * It can be combined with a context filter in order to refine the search.
938 class blog_filter_user extends blog_filter {
939 public $tables = array('u' => 'user');
942 * Constructor
944 * @param string $type
945 * @param int $id
947 public function __construct($id=null, $type='user') {
948 global $CFG, $DB, $USER;
949 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
951 if (empty($id)) {
952 $this->id = $USER->id;
953 $this->type = 'user';
954 } else {
955 $this->id = $id;
956 $this->type = $type;
959 if ($this->type == 'user') {
960 $this->conditions = array('u.id = ?');
961 $this->params = array($this->id);
962 $this->overrides = array('group');
964 } elseif ($this->type == 'group') {
965 $this->overrides = array('course', 'site');
967 $this->tables['gm'] = 'groups_members';
968 $this->conditions[] = 'p.userid = gm.userid';
969 $this->conditions[] = 'gm.groupid = ?';
970 $this->params[] = $this->id;
972 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
973 $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id)));
974 $this->tables['ba'] = 'blog_association';
975 $this->conditions[] = 'gm.groupid = ?';
976 $this->conditions[] = 'ba.contextid = ?';
977 $this->conditions[] = 'ba.blogid = p.id';
978 $this->params[] = $this->id;
979 $this->params[] = $coursecontext->id;
987 * This filter defines a tag by which blog entries should be searched.
989 class blog_filter_tag extends blog_filter {
990 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
993 * Constructor
995 * @return void
997 public function __construct($id) {
998 global $DB;
999 $this->id = $id;
1001 $this->conditions = array('ti.tagid = t.id',
1002 "ti.itemtype = 'post'",
1003 'ti.itemid = p.id',
1004 't.id = ?');
1005 $this->params = array($this->id);
1010 * This filter defines a specific blog entry id.
1012 class blog_filter_entry extends blog_filter {
1013 public $conditions = array('p.id = ?');
1014 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1016 public function __construct($id) {
1017 $this->id = $id;
1018 $this->params[] = $this->id;
1023 * This filter restricts the results to a time interval in seconds up to time()
1025 class blog_filter_since extends blog_filter {
1026 public function __construct($interval) {
1027 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1028 $this->params[] = time() - $interval;
1029 $this->params[] = time();
1034 * Filter used to perform full-text search on an entry's subject, summary and content
1036 class blog_filter_search extends blog_filter {
1038 public function __construct($searchterm) {
1039 global $DB;
1040 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1041 ".$DB->sql_like('p.content', '?', false)." OR
1042 ".$DB->sql_like('p.subject', '?', false).")");
1043 $this->params[] = "%$searchterm%";
1044 $this->params[] = "%$searchterm%";
1045 $this->params[] = "%$searchterm%";
1051 * Renderable class to represent an entry attachment
1053 class blog_entry_attachment implements renderable {
1055 public $filename;
1056 public $url;
1057 public $file;
1060 * Gets the file data
1062 * @param stored_file $file
1063 * @param int $entryid Attachment entry id
1065 public function __construct($file, $entryid) {
1067 global $CFG;
1069 $this->file = $file;
1070 $this->filename = $file->get_filename();
1071 $this->url = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$entryid.'/'.$this->filename);