2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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');
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.
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.
51 // Locked Database fields (Don't touch these).
54 public $module = 'blog';
56 public $coursemoduleid = 0;
59 public $uniquehash = '';
64 // Other class variables.
66 public $tags = array();
68 /** @var StdClass Data needed to render the entry */
71 /** @var string summary format. */
72 public string $summaryformat;
74 /** @var array summary editor. */
75 public array $summary_editor;
80 /** @var int course associated with the blog post. */
83 /** @var string module associated with the blog post. */
86 /** @var mixed attachment. */
87 public $attachment_filemanager;
89 /** @var string blog post body. */
92 /** @var int attachment entry id. */
95 /** @var string|null submit button. */
98 /** @var string|null user alias. */
101 /** @var string|null user picture. */
104 /** @var string|null user first name. */
107 /** @var string|null user middle name. */
110 /** @var string|null user last name. */
113 /** @var string|null user first name phonetic. */
114 public $firstnamephonetic;
116 /** @var string|null user last name phonetic. */
117 public $lastnamephonetic;
119 /** @var string|null user alternate name. */
120 public $alternatename;
122 /** @var string|null user email address. */
128 /** @var string|null user picture description. */
131 /** @var int module instance id. */
135 * Constructor. If given an id, will fetch the corresponding record from the DB.
137 * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
138 * @throws moodle_exception
140 public function __construct($id=null, $params=null, $form=null) {
141 global $DB, $PAGE, $CFG;
144 $object = $DB->get_record('post', array('id' => $id), '*', MUST_EXIST
);
145 foreach ($object as $var => $val) {
148 } else if (!empty($params) && (is_array($params) ||
is_object($params))) {
149 foreach ($params as $var => $val) {
154 if (!empty($CFG->useblogassociations
)) {
155 $associations = $DB->get_records('blog_association', array('blogid' => $this->id
));
156 foreach ($associations as $association) {
157 $context = context
::instance_by_id($association->contextid
);
158 if ($context->contextlevel
== CONTEXT_COURSE
) {
159 $this->courseassoc
= $association->contextid
;
160 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
161 $this->modassoc
= $association->contextid
;
171 * Gets the required data to print the entry
173 public function prepare_render() {
175 global $DB, $CFG, $PAGE;
177 $this->renderable
= new StdClass();
179 $this->renderable
->user
= $DB->get_record('user', array('id' => $this->userid
));
182 if (!empty($CFG->usecomments
) and $CFG->blogusecomments
) {
183 require_once($CFG->dirroot
. '/comment/lib.php');
185 $cmt = new stdClass();
186 $cmt->context
= context_user
::instance($this->userid
);
187 $cmt->courseid
= $PAGE->course
->id
;
188 $cmt->area
= 'format_blog';
189 $cmt->itemid
= $this->id
;
190 $cmt->showcount
= $CFG->blogshowcommentscount
;
191 $cmt->component
= 'blog';
192 $this->renderable
->comment
= new comment($cmt);
195 $this->summary
= file_rewrite_pluginfile_urls($this->summary
, 'pluginfile.php', SYSCONTEXTID
, 'blog', 'post', $this->id
);
197 // External blog link.
198 if ($this->uniquehash
&& $this->content
) {
199 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content
))) {
200 $urlparts = parse_url($externalblog->url
);
201 $this->renderable
->externalblogtext
= get_string('retrievedfrom', 'blog') . get_string('labelsep', 'langconfig');
202 $this->renderable
->externalblogtext
.= html_writer
::link($urlparts['scheme'] . '://' . $urlparts['host'],
203 $externalblog->name
);
207 // Retrieve associations.
208 $this->renderable
->unassociatedentry
= false;
209 if (!empty($CFG->useblogassociations
)) {
211 // Adding the entry associations data.
212 if ($associations = $associations = $DB->get_records('blog_association', array('blogid' => $this->id
))) {
214 // Check to see if the entry is unassociated with group/course level access.
215 if ($this->publishstate
== 'group' ||
$this->publishstate
== 'course') {
216 $this->renderable
->unassociatedentry
= true;
219 foreach ($associations as $key => $assocrec) {
221 if (!$context = context
::instance_by_id($assocrec->contextid
, IGNORE_MISSING
)) {
222 unset($associations[$key]);
226 // The renderer will need the contextlevel of the association.
227 $associations[$key]->contextlevel
= $context->contextlevel
;
229 // Course associations.
230 if ($context->contextlevel
== CONTEXT_COURSE
) {
231 // TODO: performance!!!!
232 $instancename = $DB->get_field('course', 'shortname', array('id' => $context->instanceid
));
234 $associations[$key]->url
= $assocurl = new moodle_url('/course/view.php',
235 array('id' => $context->instanceid
));
236 $associations[$key]->text
= $instancename;
237 $associations[$key]->icon
= new pix_icon('i/course', $associations[$key]->text
);
241 if ($context->contextlevel
== CONTEXT_MODULE
) {
243 // Getting the activity type and the activity instance id.
244 $sql = 'SELECT cm.instance, m.name FROM {course_modules} cm
245 JOIN {modules} m ON m.id = cm.module
246 WHERE cm.id = :cmid';
247 $modinfo = $DB->get_record_sql($sql, array('cmid' => $context->instanceid
));
248 // TODO: performance!!!!
249 $instancename = $DB->get_field($modinfo->name
, 'name', array('id' => $modinfo->instance
));
251 $associations[$key]->type
= get_string('modulename', $modinfo->name
);
252 $associations[$key]->url
= new moodle_url('/mod/' . $modinfo->name
. '/view.php',
253 array('id' => $context->instanceid
));
254 $associations[$key]->text
= $instancename;
255 $associations[$key]->icon
= new pix_icon('icon', $associations[$key]->text
, $modinfo->name
);
259 $this->renderable
->blogassociations
= $associations;
262 // Entry attachments.
263 $this->renderable
->attachments
= $this->get_attachments();
265 $this->renderable
->usercanedit
= blog_user_can_edit_entry($this);
270 * Gets the entry attachments list
271 * @return array List of blog_entry_attachment instances
273 public function get_attachments() {
277 require_once($CFG->libdir
.'/filelib.php');
279 $syscontext = context_system
::instance();
281 $fs = get_file_storage();
282 $files = $fs->get_area_files($syscontext->id
, 'blog', 'attachment', $this->id
);
284 // Adding a blog_entry_attachment for each non-directory file.
285 $attachments = array();
286 foreach ($files as $file) {
287 if ($file->is_directory()) {
290 $attachments[] = new blog_entry_attachment($file, $this->id
);
297 * Inserts this entry in the database. Access control checks must be done by calling code.
299 * @param mform $form Used for attachments
302 public function process_attachment($form) {
307 * Inserts this entry in the database. Access control checks must be done by calling code.
308 * TODO Set the publishstate correctly
311 public function add() {
312 global $CFG, $USER, $DB;
315 $this->module
= 'blog';
316 $this->userid
= (empty($this->userid
)) ?
$USER->id
: $this->userid
;
317 $this->lastmodified
= time();
318 $this->created
= time();
320 // Insert the new blog entry.
321 $this->id
= $DB->insert_record('post', $this);
323 if (!empty($CFG->useblogassociations
)) {
324 $this->add_associations();
327 core_tag_tag
::set_item_tags('core', 'post', $this->id
, context_user
::instance($this->userid
), $this->tags
);
329 // Trigger an event for the new entry.
330 $event = \core\event\blog_entry_created
::create(array(
331 'objectid' => $this->id
,
332 'relateduserid' => $this->userid
334 $event->set_blog_entry($this);
339 * Updates this entry in the database. Access control checks must be done by calling code.
341 * @param array $params Entry parameters.
342 * @param moodleform $form Used for attachments.
343 * @param array $summaryoptions Summary options.
344 * @param array $attachmentoptions Attachment options.
348 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
351 $sitecontext = context_system
::instance();
355 foreach ($params as $var => $val) {
359 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id
);
360 $entry = file_postupdate_standard_filemanager($entry,
368 if (!empty($CFG->useblogassociations
)) {
369 $entry->add_associations();
372 $entry->lastmodified
= time();
375 $DB->update_record('post', $entry);
376 core_tag_tag
::set_item_tags('core', 'post', $entry->id
, context_user
::instance($this->userid
), $entry->tags
);
378 $event = \core\event\blog_entry_updated
::create(array(
379 'objectid' => $entry->id
,
380 'relateduserid' => $entry->userid
382 $event->set_blog_entry($entry);
387 * Deletes this entry from the database. Access control checks must be done by calling code.
391 public function delete() {
394 $this->delete_attachments();
395 $this->remove_associations();
397 // Get record to pass onto the event.
398 $record = $DB->get_record('post', array('id' => $this->id
));
399 $DB->delete_records('post', array('id' => $this->id
));
400 core_tag_tag
::remove_all_item_tags('core', 'post', $this->id
);
402 $event = \core\event\blog_entry_deleted
::create(array(
403 'objectid' => $this->id
,
404 'relateduserid' => $this->userid
406 $event->add_record_snapshot("post", $record);
407 $event->set_blog_entry($this);
412 * Function to add all context associations to an entry.
414 * @param string $unused This does nothing, do not use it.
416 public function add_associations($unused = null) {
418 if ($unused !== null) {
419 debugging('Illegal argument used in blog_entry->add_associations()', DEBUG_DEVELOPER
);
422 $this->remove_associations();
424 if (!empty($this->courseassoc
)) {
425 $this->add_association($this->courseassoc
);
428 if (!empty($this->modassoc
)) {
429 $this->add_association($this->modassoc
);
434 * Add a single association for a blog entry
436 * @param int $contextid - id of context to associate with the blog entry.
437 * @param string $unused This does nothing, do not use it.
439 public function add_association($contextid, $unused = null) {
442 if ($unused !== null) {
443 debugging('Illegal argument used in blog_entry->add_association()', DEBUG_DEVELOPER
);
446 $assocobject = new StdClass
;
447 $assocobject->contextid
= $contextid;
448 $assocobject->blogid
= $this->id
;
449 $id = $DB->insert_record('blog_association', $assocobject);
451 // Trigger an association created event.
452 $context = context
::instance_by_id($contextid);
455 'other' => array('associateid' => $context->instanceid
, 'subject' => $this->subject
, 'blogid' => $this->id
),
456 'relateduserid' => $this->userid
458 if ($context->contextlevel
== CONTEXT_COURSE
) {
459 $eventparam['other']['associatetype'] = 'course';
461 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
462 $eventparam['other']['associatetype'] = 'coursemodule';
464 $event = \core\event\blog_association_created
::create($eventparam);
469 * remove all associations for a blog entry
473 public function remove_associations() {
476 $associations = $DB->get_records('blog_association', array('blogid' => $this->id
));
477 foreach ($associations as $association) {
479 // Trigger an association deleted event.
480 $context = context
::instance_by_id($association->contextid
);
482 'objectid' => $this->id
,
483 'other' => array('subject' => $this->subject
, 'blogid' => $this->id
),
484 'relateduserid' => $this->userid
486 $event = \core\event\blog_association_deleted
::create($eventparam);
487 $event->add_record_snapshot('blog_association', $association);
490 // Now remove the association.
491 $DB->delete_records('blog_association', array('id' => $association->id
));
496 * Deletes all the user files in the attachments area for an entry
500 public function delete_attachments() {
501 $fs = get_file_storage();
502 $fs->delete_area_files(SYSCONTEXTID
, 'blog', 'attachment', $this->id
);
503 $fs->delete_area_files(SYSCONTEXTID
, 'blog', 'post', $this->id
);
507 * User can edit a blog entry if this is their own blog entry and they have
508 * the capability moodle/blog:create, or if they have the capability
509 * moodle/blog:manageentries.
510 * This also applies to deleting of entries.
512 * @param int $userid Optional. If not given, $USER is used
515 public function can_user_edit($userid=null) {
518 if (empty($userid)) {
522 $sitecontext = context_system
::instance();
524 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
525 return true; // Can edit any blog entry.
528 if ($this->userid
== $userid && has_capability('moodle/blog:create', $sitecontext)) {
529 return true; // Can edit own when having blog:create capability.
536 * Checks to see if a user can view the blogs of another user.
537 * Only blog level is checked here, the capabilities are enforced
540 * @param int $targetuserid ID of the user we are checking
544 public function can_user_view($targetuserid) {
545 global $CFG, $USER, $DB;
546 $sitecontext = context_system
::instance();
548 if (empty($CFG->enableblogs
) ||
!has_capability('moodle/blog:view', $sitecontext)) {
549 return false; // Blog system disabled or user has no blog view capability.
552 if (isloggedin() && $USER->id
== $targetuserid) {
553 return true; // Can view own entries in any case.
556 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
557 return true; // Can manage all entries.
560 // Coming for 1 entry, make sure it's not a draft.
561 if ($this->publishstate
== 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
562 return false; // Can not view draft of others.
565 // Coming for 1 entry, make sure user is logged in, if not a public blog.
566 if ($this->publishstate
!= 'public' && !isloggedin()) {
570 switch ($CFG->bloglevel
) {
571 case BLOG_GLOBAL_LEVEL
:
575 case BLOG_SITE_LEVEL
:
576 if (isloggedin()) { // Not logged in viewers forbidden.
582 case BLOG_USER_LEVEL
:
584 $personalcontext = context_user
::instance($targetuserid);
585 return has_capability('moodle/user:readuserblogs', $personalcontext);
591 * Use this function to retrieve a list of publish states available for
592 * the currently logged in user.
594 * @return array This function returns an array ideal for sending to moodles'
595 * choose_from_menu function.
598 public static function get_applicable_publish_states() {
602 // Everyone gets draft access.
603 if ($CFG->bloglevel
>= BLOG_USER_LEVEL
) {
604 $options['draft'] = get_string('publishtonoone', 'blog');
607 if ($CFG->bloglevel
> BLOG_USER_LEVEL
) {
608 $options['site'] = get_string('publishtosite', 'blog');
611 if ($CFG->bloglevel
>= BLOG_GLOBAL_LEVEL
) {
612 $options['public'] = get_string('publishtoworld', 'blog');
620 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
622 * @package moodlecore
624 * @copyright 2009 Nicolas Connault
625 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
629 * Array of blog_entry objects.
630 * @var array $entries
632 public $entries = null;
635 * Caches the total number of the entries.
638 public $totalentries = null;
641 * An array of blog_filter_* objects
642 * @var array $filters
644 public $filters = array();
649 * @param array $filters An associative array of filtername => filterid
651 public function __construct($filters=array()) {
652 // Unset filters overridden by more specific filters.
653 foreach ($filters as $type => $id) {
654 if (!empty($type) && !empty($id)) {
655 $this->filters
[$type] = blog_filter
::get_instance($id, $type);
659 foreach ($this->filters
as $type => $filter) {
660 foreach ($filter->overrides
as $override) {
661 if (array_key_exists($override, $this->filters
)) {
662 unset($this->filters
[$override]);
669 * Fetches the array of blog entries.
673 public function get_entries($start=0, $limit=10) {
676 if ($this->entries
=== null) {
677 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
678 $this->entries
= $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
679 if (!$start && count($this->entries
) < $limit) {
680 $this->totalentries
= count($this->entries
);
687 return $this->entries
;
691 * Finds total number of blog entries
695 public function count_entries() {
697 if ($this->totalentries
=== null) {
698 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
699 $this->totalentries
= $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
701 $this->totalentries
= 0;
704 return $this->totalentries
;
707 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
708 global $DB, $USER, $CFG;
713 $userfieldsapi = \core_user\fields
::for_userpic();
714 $allnamefields = $userfieldsapi->get_sql('u', false, '', 'useridalias', false)->selects
;
715 // The query used to locate blog entries is complicated. It will be built from the following components:
716 $requiredfields = "p.*, $allnamefields"; // The SELECT clause.
717 $tables = array('p' => 'post', 'u' => 'user'); // Components of the FROM clause (table_id => table_name).
718 // Components of the WHERE clause (conjunction).
719 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')');
721 // Build up a clause for permission constraints.
725 // Fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs.
726 // Admins can see all blogs regardless of publish states, as described on the help page.
727 if (has_capability('moodle/user:readuserblogs', context_system
::instance())) {
728 // Don't add permission constraints.
730 } else if (!empty($this->filters
['user'])
731 && has_capability('moodle/user:readuserblogs',
732 context_user
::instance((empty($this->filters
['user']->id
) ?
0 : $this->filters
['user']->id
)))) {
733 // Don't add permission constraints.
736 if (isloggedin() and !isguestuser()) {
737 // Dont check association records if there aren't any.
738 $assocexists = $DB->record_exists('blog_association', array());
740 // Begin permission sql clause.
741 $permissionsql = '(p.userid = ? ';
744 if ($CFG->bloglevel
>= BLOG_SITE_LEVEL
) { // Add permission to view site-level entries.
745 $permissionsql .= " OR p.publishstate = 'site' ";
748 if ($CFG->bloglevel
>= BLOG_GLOBAL_LEVEL
) { // Add permission to view global entries.
749 $permissionsql .= " OR p.publishstate = 'public' ";
752 $permissionsql .= ') '; // Close permissions sql clause.
753 } else { // Default is access to public entries.
754 $permissionsql = "p.publishstate = 'public'";
756 $conditions[] = $permissionsql; // Add permission constraints.
759 foreach ($this->filters
as $type => $blogfilter) {
760 $conditions = array_merge($conditions, $blogfilter->conditions
);
761 $params = array_merge($params, $blogfilter->params
);
762 $tables = array_merge($tables, $blogfilter->tables
);
765 $tablessql = ''; // Build up the FROM clause.
766 foreach ($tables as $tablename => $table) {
767 $tablessql .= ($tablessql ?
', ' : '').'{'.$table.'} '.$tablename;
770 $sql = ($count) ?
'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
771 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
772 $sql .= ($count) ?
'' : " ORDER BY $sort";
774 return array('sql' => $sql, 'params' => $params);
778 * Outputs all the blog entries aggregated by this blog listing.
782 public function print_entries() {
783 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
784 $sitecontext = context_system
::instance();
787 $output = $PAGE->get_renderer('blog');
789 $page = optional_param('blogpage', 0, PARAM_INT
);
790 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT
);
791 $start = $page * $limit;
793 $morelink = '<br /> ';
795 $entries = $this->get_entries($start, $limit);
796 $totalentries = $this->count_entries();
797 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
798 $pagingbar->pagevar
= 'blogpage';
799 $blogheaders = blog_get_headers();
801 echo $OUTPUT->render($pagingbar);
803 if (has_capability('moodle/blog:create', $sitecontext)) {
804 // The user's blog is enabled and they are viewing their own blog.
805 $userid = optional_param('userid', null, PARAM_INT
);
807 if (empty($userid) ||
(!empty($userid) && $userid == $USER->id
)) {
809 $courseid = optional_param('courseid', null, PARAM_INT
);
810 $modid = optional_param('modid', null, PARAM_INT
);
812 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
813 $urlparams = array('action' => 'add',
815 'courseid' => $courseid,
816 'groupid' => optional_param('groupid', null, PARAM_INT
),
818 'tagid' => optional_param('tagid', null, PARAM_INT
),
819 'tag' => optional_param('tag', null, PARAM_INT
),
820 'search' => optional_param('search', null, PARAM_INT
));
822 $urlparams = array_filter($urlparams);
823 $addurl->params($urlparams);
825 $addlink = '<div class="addbloglink">';
826 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
827 $addlink .= '</div>';
834 foreach ($entries as $entry) {
835 $blogentry = new blog_entry(null, $entry);
837 // Get the required blog entry data to render it.
838 $blogentry->prepare_render();
839 echo $output->render($blogentry);
844 echo $OUTPUT->render($pagingbar);
847 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
850 print $morelink.'<br />'."\n";
855 // Find the base url from $_GET variables, for print_paging_bar.
856 public function get_baseurl() {
859 unset($getcopy['blogpage']);
861 if (!empty($getcopy)) {
865 foreach ($getcopy as $var => $val) {
868 $querystring .= "?$var=$val";
870 $querystring .= '&'.$var.'='.$val;
878 return strip_querystring(qualified_me()) . $querystring;
884 * Abstract class for blog_filter objects.
885 * A set of core filters are implemented here. To write new filters, you need to subclass
886 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
887 * The blog_filter abstract class will automatically use it when the filter is added to the
888 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
889 * or have any other meaning you wish it to have. The second parameter is called $type and is
890 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
892 abstract class blog_filter
{
894 * An array of strings representing the available filter types for each blog_filter.
895 * @var array $availabletypes
897 public $availabletypes = array();
900 * The type of filter (for example, types of blog_filter_context are site, course and module)
906 * The unique ID for a filter's associated record
912 * An array of table aliases that are used in the WHERE conditions
915 public $tables = array();
918 * An array of WHERE conditions
919 * @var array $conditions
921 public $conditions = array();
924 * An array of SQL params
927 public $params = array();
930 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
932 public $overrides = array();
934 public function __construct($id, $type=null) {
940 * TODO This is poor design. A parent class should not know anything about its children.
941 * The default case helps to resolve this design issue
943 public static function get_instance($id, $type) {
949 return new blog_filter_context($id, $type);
954 return new blog_filter_user($id, $type);
958 return new blog_filter_tag($id);
962 $classname = "blog_filter_$type";
963 if (class_exists($classname)) {
964 return new $classname($id, $type);
971 * This filter defines the context level of the blog entries being searched: site, course, module
973 class blog_filter_context
extends blog_filter
{
977 * @param string $type
980 public function __construct($id=null, $type='site') {
981 global $SITE, $CFG, $DB;
984 $this->type
= 'site';
990 $this->availabletypes
= array('site' => get_string('site'),
991 'course' => get_string('course'),
992 'module' => get_string('activity'),
993 'context' => get_string('coresystem'));
995 switch ($this->type
) {
996 case 'course': // Careful of site course!
997 // Ignore course filter if blog associations are not enabled.
998 if ($this->id
!= $SITE->id
&& !empty($CFG->useblogassociations
)) {
999 $this->overrides
= array('site', 'context');
1000 $context = context_course
::instance($this->id
);
1001 $this->tables
['ba'] = 'blog_association';
1002 $this->conditions
[] = 'p.id = ba.blogid';
1003 $this->conditions
[] = 'ba.contextid = '.$context->id
;
1006 // We are dealing with the site course, do not break from the current case.
1010 // No special constraints.
1013 if (!empty($CFG->useblogassociations
)) {
1014 $this->overrides
= array('course', 'site', 'context');
1016 $context = context_module
::instance($this->id
);
1017 $this->tables
['ba'] = 'blog_association';
1018 $this->tables
['p'] = 'post';
1019 $this->conditions
= array('p.id = ba.blogid', 'ba.contextid = ?');
1020 $this->params
= array($context->id
);
1024 if ($id != context_system
::instance()->id
&& !empty($CFG->useblogassociations
)) {
1025 $this->overrides
= array('site');
1026 $context = context
::instance_by_id($this->id
);
1027 $this->tables
['ba'] = 'blog_association';
1028 $this->tables
['ctx'] = 'context';
1029 $this->conditions
[] = 'p.id = ba.blogid';
1030 $this->conditions
[] = 'ctx.id = ba.contextid';
1031 $this->conditions
[] = 'ctx.path LIKE ?';
1032 $this->params
= array($context->path
. '%');
1041 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
1042 * It can be combined with a context filter in order to refine the search.
1044 class blog_filter_user
extends blog_filter
{
1045 public $tables = array('u' => 'user');
1050 * @param string $type
1053 public function __construct($id=null, $type='user') {
1054 global $CFG, $DB, $USER;
1055 $this->availabletypes
= array('user' => get_string('user'), 'group' => get_string('group'));
1058 $this->id
= $USER->id
;
1059 $this->type
= 'user';
1062 $this->type
= $type;
1065 if ($this->type
== 'user') {
1066 $this->conditions
= array('u.id = ?');
1067 $this->params
= array($this->id
);
1068 $this->overrides
= array('group');
1070 } else if ($this->type
== 'group') {
1071 $this->overrides
= array('course', 'site');
1073 $this->tables
['gm'] = 'groups_members';
1074 $this->conditions
[] = 'p.userid = gm.userid';
1075 $this->conditions
[] = 'gm.groupid = ?';
1076 $this->params
[] = $this->id
;
1078 if (!empty($CFG->useblogassociations
)) { // Only show blog entries associated with this course.
1079 $coursecontext = context_course
::instance($DB->get_field('groups', 'courseid', array('id' => $this->id
)));
1080 $this->tables
['ba'] = 'blog_association';
1081 $this->conditions
[] = 'gm.groupid = ?';
1082 $this->conditions
[] = 'ba.contextid = ?';
1083 $this->conditions
[] = 'ba.blogid = p.id';
1084 $this->params
[] = $this->id
;
1085 $this->params
[] = $coursecontext->id
;
1093 * This filter defines a tag by which blog entries should be searched.
1095 class blog_filter_tag
extends blog_filter
{
1096 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
1103 public function __construct($id) {
1107 $this->conditions
= array('ti.tagid = t.id',
1108 "ti.itemtype = 'post'",
1109 "ti.component = 'core'",
1112 $this->params
= array($this->id
);
1117 * This filter defines a specific blog entry id.
1119 class blog_filter_entry
extends blog_filter
{
1120 public $conditions = array('p.id = ?');
1121 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1123 public function __construct($id) {
1125 $this->params
[] = $this->id
;
1130 * This filter restricts the results to a time interval in seconds up to time()
1132 class blog_filter_since
extends blog_filter
{
1133 public function __construct($interval) {
1134 $this->conditions
[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1135 $this->params
[] = time() - $interval;
1136 $this->params
[] = time();
1141 * Filter used to perform full-text search on an entry's subject, summary and content
1143 class blog_filter_search
extends blog_filter
{
1145 public function __construct($searchterm) {
1147 $this->conditions
= array("(".$DB->sql_like('p.summary', '?', false)." OR
1148 ".$DB->sql_like('p.content', '?', false)." OR
1149 ".$DB->sql_like('p.subject', '?', false).")");
1150 $this->params
[] = "%$searchterm%";
1151 $this->params
[] = "%$searchterm%";
1152 $this->params
[] = "%$searchterm%";
1158 * Renderable class to represent an entry attachment
1160 class blog_entry_attachment
implements renderable
{
1167 * Gets the file data
1169 * @param stored_file $file
1170 * @param int $entryid Attachment entry id
1172 public function __construct($file, $entryid) {
1176 $this->file
= $file;
1177 $this->filename
= $file->get_filename();
1178 $this->url
= file_encode_url($CFG->wwwroot
. '/pluginfile.php',
1179 '/' . SYSCONTEXTID
. '/blog/attachment/' . $entryid . '/' . $this->filename
);