Moodle release 2.4.11
[moodle.git] / blog / locallib.php
blob13c764bb25154d16694d37af3b49f7a59fdbd078
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;
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 $this->form = $form;
96 /**
97 * Gets the required data to print the entry
99 public function prepare_render() {
101 global $DB, $CFG, $PAGE;
103 $this->renderable = new StdClass();
105 $this->renderable->user = $DB->get_record('user', array('id'=>$this->userid));
107 // Entry comments.
108 if (!empty($CFG->usecomments) and $CFG->blogusecomments) {
109 require_once($CFG->dirroot . '/comment/lib.php');
111 $cmt = new stdClass();
112 $cmt->context = context_user::instance($this->userid);
113 $cmt->courseid = $PAGE->course->id;
114 $cmt->area = 'format_blog';
115 $cmt->itemid = $this->id;
116 $cmt->showcount = $CFG->blogshowcommentscount;
117 $cmt->component = 'blog';
118 $this->renderable->comment = new comment($cmt);
121 $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);
123 // External blog link.
124 if ($this->uniquehash && $this->content) {
125 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {
126 $urlparts = parse_url($externalblog->url);
127 $this->renderable->externalblogtext = get_string('retrievedfrom', 'blog') . get_string('labelsep', 'langconfig');
128 $this->renderable->externalblogtext .= html_writer::link($urlparts['scheme'] . '://'.$urlparts['host'], $externalblog->name);
132 // Retrieve associations
133 $this->renderable->unassociatedentry = false;
134 if (!empty($CFG->useblogassociations)) {
136 // Adding the entry associations data.
137 if ($associations = $associations = $DB->get_records('blog_association', array('blogid' => $this->id))) {
139 // Check to see if the entry is unassociated with group/course level access.
140 if ($this->publishstate == 'group' || $this->publishstate == 'course') {
141 $this->renderable->unassociatedentry = true;
144 foreach ($associations as $key => $assocrec) {
146 if (!$context = context::instance_by_id($assocrec->contextid, IGNORE_MISSING)) {
147 unset($associations[$key]);
148 continue;
151 // The renderer will need the contextlevel of the association.
152 $associations[$key]->contextlevel = $context->contextlevel;
154 // Course associations.
155 if ($context->contextlevel == CONTEXT_COURSE) {
156 $instancename = $DB->get_field('course', 'shortname', array('id' => $context->instanceid)); //TODO: performance!!!!
158 $associations[$key]->url = $assocurl = new moodle_url('/course/view.php', array('id' => $context->instanceid));
159 $associations[$key]->text = $instancename;
160 $associations[$key]->icon = new pix_icon('i/course', $associations[$key]->text);
163 // Mod associations.
164 if ($context->contextlevel == CONTEXT_MODULE) {
166 // Getting the activity type and the activity instance id
167 $sql = 'SELECT cm.instance, m.name FROM {course_modules} cm
168 JOIN {modules} m ON m.id = cm.module
169 WHERE cm.id = :cmid';
170 $modinfo = $DB->get_record_sql($sql, array('cmid' => $context->instanceid));
171 $instancename = $DB->get_field($modinfo->name, 'name', array('id' => $modinfo->instance)); //TODO: performance!!!!
173 $associations[$key]->type = get_string('modulename', $modinfo->name);
174 $associations[$key]->url = new moodle_url('/mod/' . $modinfo->name . '/view.php', array('id' => $context->instanceid));
175 $associations[$key]->text = $instancename;
176 $associations[$key]->icon = new pix_icon('icon', $associations[$key]->text, $modinfo->name);
180 $this->renderable->blogassociations = $associations;
183 // Entry attachments.
184 $this->renderable->attachments = $this->get_attachments();
186 $this->renderable->usercanedit = blog_user_can_edit_entry($this);
191 * Gets the entry attachments list
192 * @return array List of blog_entry_attachment instances
194 function get_attachments() {
196 global $CFG;
198 require_once($CFG->libdir.'/filelib.php');
200 $syscontext = context_system::instance();
202 $fs = get_file_storage();
203 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
205 // Adding a blog_entry_attachment for each non-directory file.
206 $attachments = array();
207 foreach ($files as $file) {
208 if ($file->is_directory()) {
209 continue;
211 $attachments[] = new blog_entry_attachment($file, $this->id);
214 return $attachments;
218 * Inserts this entry in the database. Access control checks must be done by calling code.
220 * @param mform $form Used for attachments
221 * @return void
223 public function process_attachment($form) {
224 $this->form = $form;
228 * Inserts this entry in the database. Access control checks must be done by calling code.
229 * TODO Set the publishstate correctly
230 * @param mform $form Used for attachments
231 * @return void
233 public function add() {
234 global $CFG, $USER, $DB;
236 unset($this->id);
237 $this->module = 'blog';
238 $this->userid = (empty($this->userid)) ? $USER->id : $this->userid;
239 $this->lastmodified = time();
240 $this->created = time();
242 // Insert the new blog entry.
243 $this->id = $DB->insert_record('post', $this);
245 // Update tags.
246 $this->add_tags_info();
248 if (!empty($CFG->useblogassociations)) {
249 $this->add_associations();
250 add_to_log(SITEID, 'blog', 'add', 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
253 tag_set('post', $this->id, $this->tags);
257 * Updates this entry in the database. Access control checks must be done by calling code.
259 * @param mform $form Used for attachments
260 * @return void
262 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
263 global $CFG, $USER, $DB, $PAGE;
265 $sitecontext = context_system::instance();
266 $entry = $this;
268 $this->form = $form;
269 foreach ($params as $var => $val) {
270 $entry->$var = $val;
273 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
274 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
276 if (!empty($CFG->useblogassociations)) {
277 $entry->add_associations();
280 $entry->lastmodified = time();
282 // Update record
283 $DB->update_record('post', $entry);
284 tag_set('post', $entry->id, $entry->tags);
286 add_to_log(SITEID, 'blog', 'update', 'index.php?userid='.$USER->id.'&entryid='.$entry->id, $entry->subject);
290 * Deletes this entry from the database. Access control checks must be done by calling code.
292 * @return void
294 public function delete() {
295 global $DB;
297 $this->delete_attachments();
298 $this->remove_associations();
300 $DB->delete_records('post', array('id' => $this->id));
301 tag_set('post', $this->id, array());
303 add_to_log(SITEID, 'blog', 'delete', 'index.php?userid='. $this->userid, 'deleted blog entry with entry id# '. $this->id);
307 * function to add all context associations to an entry
308 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
310 public function add_associations($action='add') {
311 global $DB, $USER;
313 $this->remove_associations();
315 if (!empty($this->courseassoc)) {
316 $this->add_association($this->courseassoc, $action);
319 if (!empty($this->modassoc)) {
320 $this->add_association($this->modassoc, $action);
325 * add a single association for a blog entry
326 * @param int contextid - id of context to associate with the blog entry
328 public function add_association($contextid, $action='add') {
329 global $DB, $USER;
331 $assocobject = new StdClass;
332 $assocobject->contextid = $contextid;
333 $assocobject->blogid = $this->id;
334 $DB->insert_record('blog_association', $assocobject);
336 $context = context::instance_by_id($contextid);
337 $courseid = null;
339 if ($context->contextlevel == CONTEXT_COURSE) {
340 $courseid = $context->instanceid;
341 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
342 } else if ($context->contextlevel == CONTEXT_MODULE) {
343 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
344 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
345 add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
350 * remove all associations for a blog entry
351 * @return voic
353 public function remove_associations() {
354 global $DB;
355 $DB->delete_records('blog_association', array('blogid' => $this->id));
359 * Deletes all the user files in the attachments area for an entry
361 * @return void
363 public function delete_attachments() {
364 $fs = get_file_storage();
365 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
366 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
370 * function to attach tags into an entry
371 * @return void
373 public function add_tags_info() {
375 $tags = array();
377 if ($otags = optional_param('otags', '', PARAM_INT)) {
378 foreach ($otags as $tagid) {
379 // TODO : make this use the tag name in the form
380 if ($tag = tag_get('id', $tagid)) {
381 $tags[] = $tag->name;
386 tag_set('post', $this->id, $tags);
390 * User can edit a blog entry if this is their own blog entry and they have
391 * the capability moodle/blog:create, or if they have the capability
392 * moodle/blog:manageentries.
393 * This also applies to deleting of entries.
395 * @param int $userid Optional. If not given, $USER is used
396 * @return boolean
398 public function can_user_edit($userid=null) {
399 global $CFG, $USER;
401 if (empty($userid)) {
402 $userid = $USER->id;
405 $sitecontext = context_system::instance();
407 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
408 return true; // can edit any blog entry
411 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
412 return true; // can edit own when having blog:create capability
415 return false;
419 * Checks to see if a user can view the blogs of another user.
420 * Only blog level is checked here, the capabilities are enforced
421 * in blog/index.php
423 * @param int $targetuserid ID of the user we are checking
425 * @return bool
427 public function can_user_view($targetuserid) {
428 global $CFG, $USER, $DB;
429 $sitecontext = context_system::instance();
431 if (empty($CFG->enableblogs) || !has_capability('moodle/blog:view', $sitecontext)) {
432 return false; // blog system disabled or user has no blog view capability
435 if (isloggedin() && $USER->id == $targetuserid) {
436 return true; // can view own entries in any case
439 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
440 return true; // can manage all entries
443 // coming for 1 entry, make sure it's not a draft
444 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
445 return false; // can not view draft of others
448 // coming for 1 entry, make sure user is logged in, if not a public blog
449 if ($this->publishstate != 'public' && !isloggedin()) {
450 return false;
453 switch ($CFG->bloglevel) {
454 case BLOG_GLOBAL_LEVEL:
455 return true;
456 break;
458 case BLOG_SITE_LEVEL:
459 if (isloggedin()) { // not logged in viewers forbidden
460 return true;
462 return false;
463 break;
465 case BLOG_USER_LEVEL:
466 default:
467 $personalcontext = context_user::instance($targetuserid);
468 return has_capability('moodle/user:readuserblogs', $personalcontext);
469 break;
474 * Use this function to retrieve a list of publish states available for
475 * the currently logged in user.
477 * @return array This function returns an array ideal for sending to moodles'
478 * choose_from_menu function.
481 public static function get_applicable_publish_states() {
482 global $CFG;
483 $options = array();
485 // everyone gets draft access
486 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
487 $options['draft'] = get_string('publishtonoone', 'blog');
490 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
491 $options['site'] = get_string('publishtosite', 'blog');
494 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
495 $options['public'] = get_string('publishtoworld', 'blog');
498 return $options;
503 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
505 * @package moodlecore
506 * @subpackage blog
507 * @copyright 2009 Nicolas Connault
508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
510 class blog_listing {
512 * Array of blog_entry objects.
513 * @var array $entries
515 public $entries = array();
518 * An array of blog_filter_* objects
519 * @var array $filters
521 public $filters = array();
524 * Constructor
526 * @param array $filters An associative array of filtername => filterid
528 public function __construct($filters=array()) {
529 // Unset filters overridden by more specific filters
530 foreach ($filters as $type => $id) {
531 if (!empty($type) && !empty($id)) {
532 $this->filters[$type] = blog_filter::get_instance($id, $type);
536 foreach ($this->filters as $type => $filter) {
537 foreach ($filter->overrides as $override) {
538 if (array_key_exists($override, $this->filters)) {
539 unset($this->filters[$override]);
546 * Fetches the array of blog entries.
548 * @return array
550 public function get_entries($start=0, $limit=10) {
551 global $DB;
553 if (empty($this->entries)) {
554 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
555 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
556 } else {
557 return false;
561 return $this->entries;
564 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
565 global $DB, $USER, $CFG;
567 if(!$userid) {
568 $userid = $USER->id;
571 // The query used to locate blog entries is complicated. It will be built from the following components:
572 $requiredfields = "p.*, u.firstname, u.lastname, u.email"; // the SELECT clause
573 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
574 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
576 // build up a clause for permission constraints
578 $params = array();
580 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
581 // admins can see all blogs regardless of publish states, as described on the help page
582 if (has_capability('moodle/user:readuserblogs', context_system::instance())) {
583 // don't add permission constraints
585 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
586 context_user::instance((empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
587 // don't add permission constraints
589 } else {
590 if (isloggedin() and !isguestuser()) {
591 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
593 //begin permission sql clause
594 $permissionsql = '(p.userid = ? ';
595 $params[] = $userid;
597 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
598 $permissionsql .= " OR p.publishstate = 'site' ";
601 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
602 $permissionsql .= " OR p.publishstate = 'public' ";
605 $permissionsql .= ') '; //close permissions sql clause
606 } else { // default is access to public entries
607 $permissionsql = "p.publishstate = 'public'";
609 $conditions[] = $permissionsql; //add permission constraints
612 foreach ($this->filters as $type => $blogfilter) {
613 $conditions = array_merge($conditions, $blogfilter->conditions);
614 $params = array_merge($params, $blogfilter->params);
615 $tables = array_merge($tables, $blogfilter->tables);
618 $tablessql = ''; // build up the FROM clause
619 foreach ($tables as $tablename => $table) {
620 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
623 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
624 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
625 $sql .= ($count) ? '' : " ORDER BY $sort";
627 return array('sql' => $sql, 'params' => $params);
631 * Outputs all the blog entries aggregated by this blog listing.
633 * @return void
635 public function print_entries() {
636 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
637 $sitecontext = context_system::instance();
639 // Blog renderer
640 $output = $PAGE->get_renderer('blog');
642 $page = optional_param('blogpage', 0, PARAM_INT);
643 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
644 $start = $page * $limit;
646 $morelink = '<br />&nbsp;&nbsp;';
648 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
649 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
650 } else {
651 $totalentries = 0;
654 $entries = $this->get_entries($start, $limit);
655 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
656 $pagingbar->pagevar = 'blogpage';
657 $blogheaders = blog_get_headers();
659 echo $OUTPUT->render($pagingbar);
661 if (has_capability('moodle/blog:create', $sitecontext)) {
662 //the user's blog is enabled and they are viewing their own blog
663 $userid = optional_param('userid', null, PARAM_INT);
665 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
667 $canaddentries = true;
668 $courseid = optional_param('courseid', null, PARAM_INT);
669 if ($modid = optional_param('modid', null, PARAM_INT)) {
670 if (!has_capability('moodle/blog:associatemodule', context_module::instance($modid))) {
671 $canaddentries = false;
673 } else if ($courseid) {
674 if (!has_capability('moodle/blog:associatecourse', context_course::instance($courseid))) {
675 $canaddentries = false;
679 if ($canaddentries) {
680 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
681 $urlparams = array('action' => 'add',
682 'userid' => $userid,
683 'courseid' => $courseid,
684 'groupid' => optional_param('groupid', null, PARAM_INT),
685 'modid' => $modid,
686 'tagid' => optional_param('tagid', null, PARAM_INT),
687 'tag' => optional_param('tag', null, PARAM_INT),
688 'search' => optional_param('search', null, PARAM_INT));
690 foreach ($urlparams as $var => $val) {
691 if (empty($val)) {
692 unset($urlparams[$var]);
695 $addurl->params($urlparams);
697 $addlink = '<div class="addbloglink">';
698 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
699 $addlink .= '</div>';
700 echo $addlink;
705 if ($entries) {
706 $count = 0;
707 foreach ($entries as $entry) {
708 $blogentry = new blog_entry(null, $entry);
710 // Get the required blog entry data to render it
711 $blogentry->prepare_render();
712 echo $output->render($blogentry);
714 $count++;
717 echo $OUTPUT->render($pagingbar);
719 if (!$count) {
720 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
723 print $morelink.'<br />'."\n";
724 return;
728 /// Find the base url from $_GET variables, for print_paging_bar
729 public function get_baseurl() {
730 $getcopy = $_GET;
732 unset($getcopy['blogpage']);
734 if (!empty($getcopy)) {
735 $first = false;
736 $querystring = '';
738 foreach ($getcopy as $var => $val) {
739 if (!$first) {
740 $first = true;
741 $querystring .= "?$var=$val";
742 } else {
743 $querystring .= '&amp;'.$var.'='.$val;
744 $hasparam = true;
747 } else {
748 $querystring = '?';
751 return strip_querystring(qualified_me()) . $querystring;
757 * Abstract class for blog_filter objects.
758 * A set of core filters are implemented here. To write new filters, you need to subclass
759 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
760 * The blog_filter abstract class will automatically use it when the filter is added to the
761 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
762 * or have any other meaning you wish it to have. The second parameter is called $type and is
763 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
765 abstract class blog_filter {
767 * An array of strings representing the available filter types for each blog_filter.
768 * @var array $availabletypes
770 public $availabletypes = array();
773 * The type of filter (for example, types of blog_filter_context are site, course and module)
774 * @var string $type
776 public $type;
779 * The unique ID for a filter's associated record
780 * @var int $id
782 public $id;
785 * An array of table aliases that are used in the WHERE conditions
786 * @var array $tables
788 public $tables = array();
791 * An array of WHERE conditions
792 * @var array $conditions
794 public $conditions = array();
797 * An array of SQL params
798 * @var array $params
800 public $params = array();
803 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
805 public $overrides = array();
807 public function __construct($id, $type=null) {
808 $this->id = $id;
809 $this->type = $type;
813 * TODO This is poor design. A parent class should not know anything about its children.
814 * The default case helps to resolve this design issue
816 public static function get_instance($id, $type) {
818 switch ($type) {
819 case 'site':
820 case 'course':
821 case 'module':
822 return new blog_filter_context($id, $type);
823 break;
825 case 'group':
826 case 'user':
827 return new blog_filter_user($id, $type);
828 break;
830 case 'tag':
831 return new blog_filter_tag($id);
832 break;
834 default:
835 $classname = "blog_filter_$type";
836 if (class_exists($classname)) {
837 return new $classname($id, $type);
844 * This filter defines the context level of the blog entries being searched: site, course, module
846 class blog_filter_context extends blog_filter {
848 * Constructor
850 * @param string $type
851 * @param int $id
853 public function __construct($id=null, $type='site') {
854 global $SITE, $CFG, $DB;
856 if (empty($id)) {
857 $this->type = 'site';
858 } else {
859 $this->id = $id;
860 $this->type = $type;
863 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
865 switch ($this->type) {
866 case 'course': // Careful of site course!
867 // Ignore course filter if blog associations are not enabled
868 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
869 $this->overrides = array('site');
870 $context = context_course::instance($this->id);
871 $this->tables['ba'] = 'blog_association';
872 $this->conditions[] = 'p.id = ba.blogid';
873 $this->conditions[] = 'ba.contextid = '.$context->id;
874 break;
875 } else {
876 // We are dealing with the site course, do not break from the current case
879 case 'site':
880 // No special constraints
881 break;
882 case 'module':
883 if (!empty($CFG->useblogassociations)) {
884 $this->overrides = array('course', 'site');
886 $context = context_module::instance($this->id);
887 $this->tables['ba'] = 'blog_association';
888 $this->tables['p'] = 'post';
889 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
890 $this->params = array($context->id);
892 break;
898 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
899 * It can be combined with a context filter in order to refine the search.
901 class blog_filter_user extends blog_filter {
902 public $tables = array('u' => 'user');
905 * Constructor
907 * @param string $type
908 * @param int $id
910 public function __construct($id=null, $type='user') {
911 global $CFG, $DB, $USER;
912 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
914 if (empty($id)) {
915 $this->id = $USER->id;
916 $this->type = 'user';
917 } else {
918 $this->id = $id;
919 $this->type = $type;
922 if ($this->type == 'user') {
923 $this->conditions = array('u.id = ?');
924 $this->params = array($this->id);
925 $this->overrides = array('group');
927 } elseif ($this->type == 'group') {
928 $this->overrides = array('course', 'site');
930 $this->tables['gm'] = 'groups_members';
931 $this->conditions[] = 'p.userid = gm.userid';
932 $this->conditions[] = 'gm.groupid = ?';
933 $this->params[] = $this->id;
935 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
936 $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id)));
937 $this->tables['ba'] = 'blog_association';
938 $this->conditions[] = 'gm.groupid = ?';
939 $this->conditions[] = 'ba.contextid = ?';
940 $this->conditions[] = 'ba.blogid = p.id';
941 $this->params[] = $this->id;
942 $this->params[] = $coursecontext->id;
950 * This filter defines a tag by which blog entries should be searched.
952 class blog_filter_tag extends blog_filter {
953 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
956 * Constructor
958 * @return void
960 public function __construct($id) {
961 global $DB;
962 $this->id = $id;
964 $this->conditions = array('ti.tagid = t.id',
965 "ti.itemtype = 'post'",
966 'ti.itemid = p.id',
967 't.id = ?');
968 $this->params = array($this->id);
973 * This filter defines a specific blog entry id.
975 class blog_filter_entry extends blog_filter {
976 public $conditions = array('p.id = ?');
977 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
979 public function __construct($id) {
980 $this->id = $id;
981 $this->params[] = $this->id;
986 * This filter restricts the results to a time interval in seconds up to time()
988 class blog_filter_since extends blog_filter {
989 public function __construct($interval) {
990 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
991 $this->params[] = time() - $interval;
992 $this->params[] = time();
997 * Filter used to perform full-text search on an entry's subject, summary and content
999 class blog_filter_search extends blog_filter {
1001 public function __construct($searchterm) {
1002 global $DB;
1003 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1004 ".$DB->sql_like('p.content', '?', false)." OR
1005 ".$DB->sql_like('p.subject', '?', false).")");
1006 $this->params[] = "%$searchterm%";
1007 $this->params[] = "%$searchterm%";
1008 $this->params[] = "%$searchterm%";
1014 * Renderable class to represent an entry attachment
1016 class blog_entry_attachment implements renderable {
1018 public $filename;
1019 public $url;
1020 public $file;
1023 * Gets the file data
1025 * @param stored_file $file
1026 * @param int $entryid Attachment entry id
1028 public function __construct($file, $entryid) {
1030 global $CFG;
1032 $this->file = $file;
1033 $this->filename = $file->get_filename();
1034 $this->url = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$entryid.'/'.$this->filename);