MDL-73975 course: Remove course_search_form template
[moodle.git] / blog / locallib.php
blobd6ad0880f481ff459ad1861e635fe13d72974a50
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 /** @var string summary format. */
72 public string $summaryformat;
74 /** @var array summary editor. */
75 public array $summary_editor;
77 /** @var string */
78 public $summarytrust;
80 /** @var int course associated with the blog post. */
81 public $courseassoc;
83 /** @var string module associated with the blog post. */
84 public $modassoc;
86 /** @var mixed attachment. */
87 public $attachment_filemanager;
89 /** @var string blog post body. */
90 public $body;
92 /** @var int attachment entry id. */
93 public $entryid;
95 /** @var string|null submit button. */
96 public $submitbutton;
98 /** @var string|null user alias. */
99 public $useridalias;
101 /** @var string|null user picture. */
102 public $picture;
104 /** @var string|null user first name. */
105 public $firstname;
107 /** @var string|null user middle name. */
108 public $middlename;
110 /** @var string|null user last name. */
111 public $lastname;
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. */
123 public $email;
125 /** @var string */
126 public $action;
128 /** @var string|null user picture description. */
129 public $imagealt;
131 /** @var int module instance id. */
132 public $modid;
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;
143 if (!empty($id)) {
144 $object = $DB->get_record('post', array('id' => $id), '*', MUST_EXIST);
145 foreach ($object as $var => $val) {
146 $this->$var = $val;
148 } else if (!empty($params) && (is_array($params) || is_object($params))) {
149 foreach ($params as $var => $val) {
150 $this->$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;
166 $this->form = $form;
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));
181 // Entry comments.
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]);
223 continue;
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);
240 // Mod associations.
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() {
275 global $CFG;
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()) {
288 continue;
290 $attachments[] = new blog_entry_attachment($file, $this->id);
293 return $attachments;
297 * Inserts this entry in the database. Access control checks must be done by calling code.
299 * @param mform $form Used for attachments
300 * @return void
302 public function process_attachment($form) {
303 $this->form = $form;
307 * Inserts this entry in the database. Access control checks must be done by calling code.
308 * TODO Set the publishstate correctly
309 * @return void
311 public function add() {
312 global $CFG, $USER, $DB;
314 unset($this->id);
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);
335 $event->trigger();
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.
346 * @return void
348 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
349 global $CFG, $DB;
351 $sitecontext = context_system::instance();
352 $entry = $this;
354 $this->form = $form;
355 foreach ($params as $var => $val) {
356 $entry->$var = $val;
359 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
360 $entry = file_postupdate_standard_filemanager($entry,
361 'attachment',
362 $attachmentoptions,
363 $sitecontext,
364 'blog',
365 'attachment',
366 $entry->id);
368 if (!empty($CFG->useblogassociations)) {
369 $entry->add_associations();
372 $entry->lastmodified = time();
374 // Update record.
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);
383 $event->trigger();
387 * Deletes this entry from the database. Access control checks must be done by calling code.
389 * @return void
391 public function delete() {
392 global $DB;
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);
408 $event->trigger();
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) {
440 global $DB;
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);
453 $eventparam = array(
454 'objectid' => $id,
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);
465 $event->trigger();
469 * remove all associations for a blog entry
471 * @return void
473 public function remove_associations() {
474 global $DB;
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);
481 $eventparam = array(
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);
488 $event->trigger();
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
498 * @return void
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
513 * @return boolean
515 public function can_user_edit($userid=null) {
516 global $CFG, $USER;
518 if (empty($userid)) {
519 $userid = $USER->id;
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.
532 return false;
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
538 * in blog/index.php
540 * @param int $targetuserid ID of the user we are checking
542 * @return bool
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()) {
567 return false;
570 switch ($CFG->bloglevel) {
571 case BLOG_GLOBAL_LEVEL:
572 return true;
573 break;
575 case BLOG_SITE_LEVEL:
576 if (isloggedin()) { // Not logged in viewers forbidden.
577 return true;
579 return false;
580 break;
582 case BLOG_USER_LEVEL:
583 default:
584 $personalcontext = context_user::instance($targetuserid);
585 return has_capability('moodle/user:readuserblogs', $personalcontext);
586 break;
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() {
599 global $CFG;
600 $options = array();
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');
615 return $options;
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
623 * @subpackage blog
624 * @copyright 2009 Nicolas Connault
625 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
627 class blog_listing {
629 * Array of blog_entry objects.
630 * @var array $entries
632 public $entries = null;
635 * Caches the total number of the entries.
636 * @var int
638 public $totalentries = null;
641 * An array of blog_filter_* objects
642 * @var array $filters
644 public $filters = array();
647 * Constructor
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.
671 * @return array
673 public function get_entries($start=0, $limit=10) {
674 global $DB;
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);
682 } else {
683 return false;
687 return $this->entries;
691 * Finds total number of blog entries
693 * @return int
695 public function count_entries() {
696 global $DB;
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']);
700 } else {
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;
710 if (!$userid) {
711 $userid = $USER->id;
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.
723 $params = array();
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.
735 } else {
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 = ? ';
742 $params[] = $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.
780 * @return void
782 public function print_entries() {
783 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
784 $sitecontext = context_system::instance();
786 // Blog renderer.
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 />&nbsp;&nbsp;';
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',
814 'userid' => $userid,
815 'courseid' => $courseid,
816 'groupid' => optional_param('groupid', null, PARAM_INT),
817 'modid' => $modid,
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>';
828 echo $addlink;
832 if ($entries) {
833 $count = 0;
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);
841 $count++;
844 echo $OUTPUT->render($pagingbar);
846 if (!$count) {
847 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
850 print $morelink.'<br />'."\n";
851 return;
855 // Find the base url from $_GET variables, for print_paging_bar.
856 public function get_baseurl() {
857 $getcopy = $_GET;
859 unset($getcopy['blogpage']);
861 if (!empty($getcopy)) {
862 $first = false;
863 $querystring = '';
865 foreach ($getcopy as $var => $val) {
866 if (!$first) {
867 $first = true;
868 $querystring .= "?$var=$val";
869 } else {
870 $querystring .= '&amp;'.$var.'='.$val;
871 $hasparam = true;
874 } else {
875 $querystring = '?';
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)
901 * @var string $type
903 public $type;
906 * The unique ID for a filter's associated record
907 * @var int $id
909 public $id;
912 * An array of table aliases that are used in the WHERE conditions
913 * @var array $tables
915 public $tables = array();
918 * An array of WHERE conditions
919 * @var array $conditions
921 public $conditions = array();
924 * An array of SQL params
925 * @var array $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) {
935 $this->id = $id;
936 $this->type = $type;
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) {
945 switch ($type) {
946 case 'site':
947 case 'course':
948 case 'module':
949 return new blog_filter_context($id, $type);
950 break;
952 case 'group':
953 case 'user':
954 return new blog_filter_user($id, $type);
955 break;
957 case 'tag':
958 return new blog_filter_tag($id);
959 break;
961 default:
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 {
975 * Constructor
977 * @param string $type
978 * @param int $id
980 public function __construct($id=null, $type='site') {
981 global $SITE, $CFG, $DB;
983 if (empty($id)) {
984 $this->type = 'site';
985 } else {
986 $this->id = $id;
987 $this->type = $type;
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;
1004 break;
1005 } else {
1006 // We are dealing with the site course, do not break from the current case.
1009 case 'site':
1010 // No special constraints.
1011 break;
1012 case 'module':
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);
1022 break;
1023 case 'context':
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 . '%');
1034 break;
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');
1048 * Constructor
1050 * @param string $type
1051 * @param int $id
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'));
1057 if (empty($id)) {
1058 $this->id = $USER->id;
1059 $this->type = 'user';
1060 } else {
1061 $this->id = $id;
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');
1099 * Constructor
1101 * @return void
1103 public function __construct($id) {
1104 global $DB;
1105 $this->id = $id;
1107 $this->conditions = array('ti.tagid = t.id',
1108 "ti.itemtype = 'post'",
1109 "ti.component = 'core'",
1110 'ti.itemid = p.id',
1111 't.id = ?');
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) {
1124 $this->id = $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) {
1146 global $DB;
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 {
1162 public $filename;
1163 public $url;
1164 public $file;
1167 * Gets the file data
1169 * @param stored_file $file
1170 * @param int $entryid Attachment entry id
1172 public function __construct($file, $entryid) {
1174 global $CFG;
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);