Merge branch 'MDL-29821' of git://github.com/bostelm/moodle
[moodle.git] / blog / locallib.php
blob19b01ca322cd03de11e21b7024325ab32d2b0029
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 {
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 // Methods
70 /**
71 * Constructor. If given an id, will fetch the corresponding record from the DB.
73 * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
75 public function __construct($id=null, $params=null, $form=null) {
76 global $DB, $PAGE;
78 if (!empty($id)) {
79 $object = $DB->get_record('post', array('id' => $id));
80 foreach ($object as $var => $val) {
81 $this->$var = $val;
83 } else if (!empty($params) && (is_array($params) || is_object($params))) {
84 foreach ($params as $var => $val) {
85 $this->$var = $val;
89 $this->form = $form;
92 /**
93 * Prints or returns the HTML for this blog entry.
95 * @param bool $return
96 * @return string
98 public function print_html($return=false) {
100 global $USER, $CFG, $COURSE, $DB, $OUTPUT, $PAGE;
102 $user = $DB->get_record('user', array('id'=>$this->userid));
103 $cmttext = '';
104 if (!empty($CFG->usecomments) and $CFG->blogusecomments) {
105 require_once($CFG->dirroot . '/comment/lib.php');
106 // Comments
107 $cmt = new stdClass();
108 $cmt->context = get_context_instance(CONTEXT_USER, $user->id);
109 $cmt->courseid = $PAGE->course->id;
110 $cmt->area = 'format_blog';
111 $cmt->itemid = $this->id;
112 $cmt->showcount = $CFG->blogshowcommentscount;
113 $cmt->component = 'blog';
114 $comment = new comment($cmt);
115 $cmttext = $comment->output(true);
117 $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);
119 $options = array('overflowdiv'=>true);
120 $template['body'] = format_text($this->summary, $this->summaryformat, $options);
121 $template['title'] = format_string($this->subject);
122 $template['userid'] = $user->id;
123 $template['author'] = fullname($user);
124 $template['created'] = userdate($this->created);
126 if ($this->created != $this->lastmodified) {
127 $template['lastmod'] = userdate($this->lastmodified);
130 $template['publishstate'] = $this->publishstate;
132 $stredit = get_string('edit');
133 $strdelete = get_string('delete');
135 // Check to see if the entry is unassociated with group/course level access
136 $unassociatedentry = false;
137 if (!empty($CFG->useblogassociations) && ($this->publishstate == 'group' || $this->publishstate == 'course')) {
138 if (!$DB->record_exists('blog_association', array('blogid' => $this->id))) {
139 $unassociatedentry = true;
143 // Start printing of the blog
144 $table = new html_table();
145 $table->cellspacing = 0;
146 $table->attributes['class'] = 'forumpost blog_entry blog'. ($unassociatedentry ? 'draft' : $template['publishstate']);
147 $table->attributes['id'] = 'b'.$this->id;
148 $table->width = '100%';
150 $picturecell = new html_table_cell();
151 $picturecell->attributes['class'] = 'picture left';
152 $picturecell->text = $OUTPUT->user_picture($user);
154 $table->head[] = $picturecell;
156 $topiccell = new html_table_cell();
157 $topiccell->attributes['class'] = 'topic starter';
158 $titlelink = html_writer::link(new moodle_url('/blog/index.php', array('entryid' => $this->id)), $template['title']);
159 $topiccell->text = $OUTPUT->container($titlelink, 'subject');
160 $topiccell->text .= $OUTPUT->container_start('author');
162 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $PAGE->course->id)));
163 $by = new stdClass();
164 $by->name = html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $PAGE->course->id)), $fullname);
165 $by->date = $template['created'];
167 $topiccell->text .= get_string('bynameondate', 'forum', $by);
168 $topiccell->text .= $OUTPUT->container_end();
170 if ($this->uniquehash && $this->content) {
171 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {
172 $urlparts = parse_url($externalblog->url);
173 $topiccell->text .= $OUTPUT->container(get_string('retrievedfrom', 'blog').get_string('labelsep', 'langconfig').html_writer::link($urlparts['scheme'].'://'.$urlparts['host'], $externalblog->name), 'externalblog');
177 $topiccell->header = false;
178 $table->head[] = $topiccell;
180 // Actual content
181 $mainrow = new html_table_row();
183 $leftsidecell = new html_table_cell();
184 $leftsidecell->attributes['class'] = 'left side';
185 $mainrow->cells[] = $leftsidecell;
187 $contentcell = new html_table_cell();
188 $contentcell->attributes['class'] = 'content';
190 $attachedimages = $OUTPUT->container($this->print_attachments(), 'attachments');
192 // retrieve associations in case they're needed early
193 $blogassociations = $DB->get_records('blog_association', array('blogid' => $this->id));
195 // determine text for publish state
196 switch ($template['publishstate']) {
197 case 'draft':
198 $blogtype = get_string('publishtonoone', 'blog');
199 break;
200 case 'site':
201 $blogtype = get_string('publishtosite', 'blog');
202 break;
203 case 'public':
204 $blogtype = get_string('publishtoworld', 'blog');
205 break;
206 default:
207 $blogtype = '';
208 break;
212 $contentcell->text .= $OUTPUT->container($blogtype, 'audience');
214 $contentcell->text .= $template['body'];
215 $contentcell->text .= $attachedimages;
217 // Uniquehash is used as a link to an external blog
218 if (!empty($this->uniquehash)) {
219 $contentcell->text .= $OUTPUT->container_start('externalblog');
220 $contentcell->text .= html_writer::link($this->uniquehash, get_string('linktooriginalentry', 'blog'));
221 $contentcell->text .= $OUTPUT->container_end();
224 // Links to tags
225 $officialtags = tag_get_tags_csv('post', $this->id, TAG_RETURN_HTML, 'official');
226 $defaulttags = tag_get_tags_csv('post', $this->id, TAG_RETURN_HTML, 'default');
228 if (!empty($CFG->usetags) && ($officialtags || $defaulttags) ) {
229 $contentcell->text .= $OUTPUT->container_start('tags');
231 if ($officialtags) {
232 $contentcell->text .= get_string('tags', 'tag') .': '. $OUTPUT->container($officialtags, 'officialblogtags');
233 if ($defaulttags) {
234 $contentcell->text .= ', ';
237 $contentcell->text .= $defaulttags;
238 $contentcell->text .= $OUTPUT->container_end();
241 // Add associations
242 if (!empty($CFG->useblogassociations) && $blogassociations) {
243 $contentcell->text .= $OUTPUT->container_start('tags');
244 $assocstr = '';
245 $hascourseassocs = false;
246 $assoctype = '';
248 // First find and show the associated course
249 foreach ($blogassociations as $assocrec) {
250 $context = get_context_instance_by_id($assocrec->contextid);
251 if ($context->contextlevel == CONTEXT_COURSE) {
252 $assocurl = new moodle_url('/course/view.php', array('id' => $context->instanceid));
253 $text = $DB->get_field('course', 'shortname', array('id' => $context->instanceid)); //TODO: performance!!!!
254 $assocstr .= $OUTPUT->action_icon($assocurl, new pix_icon('i/course', $text), null, array(), true);
255 $hascourseassocs = true;
256 $assoctype = get_string('course');
260 // Now show mod association
261 foreach ($blogassociations as $assocrec) {
262 $context = get_context_instance_by_id($assocrec->contextid);
264 if ($context->contextlevel == CONTEXT_MODULE) {
265 if ($hascourseassocs) {
266 $assocstr .= ', ';
267 $hascourseassocs = false;
270 $modinfo = $DB->get_record('course_modules', array('id' => $context->instanceid));
271 $modname = $DB->get_field('modules', 'name', array('id' => $modinfo->module));
273 $assocurl = new moodle_url('/mod/'.$modname.'/view.php', array('id' => $modinfo->id));
274 $text = $DB->get_field($modname, 'name', array('id' => $modinfo->instance)); //TODO: performance!!!!
275 $assocstr .= $OUTPUT->action_icon($assocurl, new pix_icon('icon', $text, $modname), null, array(), true);
276 $assocstr .= ', ';
277 $assoctype = get_string('modulename', $modname);
281 $assocstr = substr($assocstr, 0, -2);
282 $contentcell->text .= get_string('associated', 'blog', $assoctype) . ': '. $assocstr;
284 $contentcell->text .= $OUTPUT->container_end();
287 if ($unassociatedentry) {
288 $contentcell->text .= $OUTPUT->container(get_string('associationunviewable', 'blog'), 'noticebox');
291 /// Commands
293 $contentcell->text .= $OUTPUT->container_start('commands');
295 if (blog_user_can_edit_entry($this) && empty($this->uniquehash)) {
296 $contentcell->text .= html_writer::link(new moodle_url('/blog/edit.php', array('action' => 'edit', 'entryid' => $this->id)), $stredit) . ' | ';
297 $contentcell->text .= html_writer::link(new moodle_url('/blog/edit.php', array('action' => 'delete', 'entryid' => $this->id)), $strdelete) . ' | ';
300 $contentcell->text .= html_writer::link(new moodle_url('/blog/index.php', array('entryid' => $this->id)), get_string('permalink', 'blog'));
302 $contentcell->text .= $OUTPUT->container_end();
304 if (isset($template['lastmod']) ){
305 $contentcell->text .= '<div style="font-size: 55%;">';
306 $contentcell->text .= ' [ '.get_string('modified').': '.$template['lastmod'].' ]';
307 $contentcell->text .= '</div>';
310 //add comments under everything
311 $contentcell->text .= $cmttext;
313 $mainrow->cells[] = $contentcell;
314 $table->data = array($mainrow);
316 if ($return) {
317 return html_writer::table($table);
318 } else {
319 echo html_writer::table($table);
324 * Inserts this entry in the database. Access control checks must be done by calling code.
326 * @param mform $form Used for attachments
327 * @return void
329 public function process_attachment($form) {
330 $this->form = $form;
334 * Inserts this entry in the database. Access control checks must be done by calling code.
335 * TODO Set the publishstate correctly
336 * @param mform $form Used for attachments
337 * @return void
339 public function add() {
340 global $CFG, $USER, $DB;
342 unset($this->id);
343 $this->module = 'blog';
344 $this->userid = (empty($this->userid)) ? $USER->id : $this->userid;
345 $this->lastmodified = time();
346 $this->created = time();
348 // Insert the new blog entry.
349 $this->id = $DB->insert_record('post', $this);
351 // Update tags.
352 $this->add_tags_info();
354 if (!empty($CFG->useblogassociations)) {
355 $this->add_associations();
356 add_to_log(SITEID, 'blog', 'add', 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
359 tag_set('post', $this->id, $this->tags);
363 * Updates this entry in the database. Access control checks must be done by calling code.
365 * @param mform $form Used for attachments
366 * @return void
368 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
369 global $CFG, $USER, $DB, $PAGE;
371 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
372 $entry = $this;
374 $this->form = $form;
375 foreach ($params as $var => $val) {
376 $entry->$var = $val;
379 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
380 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
382 if (!empty($CFG->useblogassociations)) {
383 $entry->add_associations();
386 $entry->lastmodified = time();
388 // Update record
389 $DB->update_record('post', $entry);
390 tag_set('post', $entry->id, $entry->tags);
392 add_to_log(SITEID, 'blog', 'update', 'index.php?userid='.$USER->id.'&entryid='.$entry->id, $entry->subject);
396 * Deletes this entry from the database. Access control checks must be done by calling code.
398 * @return void
400 public function delete() {
401 global $DB, $USER;
403 $returnurl = '';
405 $this->delete_attachments();
407 $DB->delete_records('post', array('id' => $this->id));
408 tag_set('post', $this->id, array());
410 add_to_log(SITEID, 'blog', 'delete', 'index.php?userid='. $this->userid, 'deleted blog entry with entry id# '. $this->id);
414 * function to add all context associations to an entry
415 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
417 public function add_associations($action='add') {
418 global $DB, $USER;
420 $this->remove_associations();
422 if (!empty($this->courseassoc)) {
423 $this->add_association($this->courseassoc, $action);
426 if (!empty($this->modassoc)) {
427 $this->add_association($this->modassoc, $action);
432 * add a single association for a blog entry
433 * @param int contextid - id of context to associate with the blog entry
435 public function add_association($contextid, $action='add') {
436 global $DB, $USER;
438 $assocobject = new StdClass;
439 $assocobject->contextid = $contextid;
440 $assocobject->blogid = $this->id;
441 $DB->insert_record('blog_association', $assocobject);
443 $context = get_context_instance_by_id($contextid);
444 $courseid = null;
446 if ($context->contextlevel == CONTEXT_COURSE) {
447 $courseid = $context->instanceid;
448 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
449 } else if ($context->contextlevel == CONTEXT_MODULE) {
450 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
451 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
452 add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
457 * remove all associations for a blog entry
458 * @return voic
460 public function remove_associations() {
461 global $DB;
462 $DB->delete_records('blog_association', array('blogid' => $this->id));
466 * Deletes all the user files in the attachments area for an entry
468 * @return void
470 public function delete_attachments() {
471 $fs = get_file_storage();
472 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
473 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
477 * if return=html, then return a html string.
478 * if return=text, then return a text-only string.
479 * otherwise, print HTML for non-images, and return image HTML
481 * @param bool $return Whether to return or print the generated code
482 * @return void
484 public function print_attachments($return=false) {
485 global $CFG, $OUTPUT;
487 require_once($CFG->libdir.'/filelib.php');
489 $fs = get_file_storage();
491 $syscontext = get_context_instance(CONTEXT_SYSTEM);
493 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
495 $imagereturn = "";
496 $output = "";
498 $strattachment = get_string("attachment", "forum");
500 foreach ($files as $file) {
501 if ($file->is_directory()) {
502 continue;
505 $filename = $file->get_filename();
506 $ffurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$this->id.'/'.$filename);
507 $mimetype = $file->get_mimetype();
509 $icon = mimeinfo_from_type("icon", $mimetype);
510 $type = mimeinfo_from_type("type", $mimetype);
512 $image = $OUTPUT->pix_icon("f/$icon", $filename, 'moodle', array('class'=>'icon'));
514 if ($return == "html") {
515 $output .= html_writer::link($ffurl, $image);
516 $output .= html_writer::link($ffurl, $filename);
518 } else if ($return == "text") {
519 $output .= "$strattachment $filename:\n$ffurl\n";
521 } else {
522 if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) { // Image attachments don't get printed as links
523 $imagereturn .= '<br /><img src="'.$ffurl.'" alt="" />';
524 } else {
525 $imagereturn .= html_writer::link($ffurl, $image);
526 $imagereturn .= format_text(html_writer::link($ffurl, $filename), FORMAT_HTML, array('context'=>$syscontext));
531 if ($return) {
532 return $output;
535 return $imagereturn;
540 * function to attach tags into an entry
541 * @return void
543 public function add_tags_info() {
545 $tags = array();
547 if ($otags = optional_param('otags', '', PARAM_INT)) {
548 foreach ($otags as $tagid) {
549 // TODO : make this use the tag name in the form
550 if ($tag = tag_get('id', $tagid)) {
551 $tags[] = $tag->name;
556 tag_set('post', $this->id, $tags);
560 * User can edit a blog entry if this is their own blog entry and they have
561 * the capability moodle/blog:create, or if they have the capability
562 * moodle/blog:manageentries.
563 * This also applies to deleting of entries.
565 * @param int $userid Optional. If not given, $USER is used
566 * @return boolean
568 public function can_user_edit($userid=null) {
569 global $CFG, $USER;
571 if (empty($userid)) {
572 $userid = $USER->id;
575 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
577 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
578 return true; // can edit any blog entry
581 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
582 return true; // can edit own when having blog:create capability
585 return false;
589 * Checks to see if a user can view the blogs of another user.
590 * Only blog level is checked here, the capabilities are enforced
591 * in blog/index.php
593 * @param int $targetuserid ID of the user we are checking
595 * @return bool
597 public function can_user_view($targetuserid) {
598 global $CFG, $USER, $DB;
599 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
601 if (empty($CFG->bloglevel) || !has_capability('moodle/blog:view', $sitecontext)) {
602 return false; // blog system disabled or user has no blog view capability
605 if (isloggedin() && $USER->id == $targetuserid) {
606 return true; // can view own entries in any case
609 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
610 return true; // can manage all entries
613 // coming for 1 entry, make sure it's not a draft
614 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
615 return false; // can not view draft of others
618 // coming for 1 entry, make sure user is logged in, if not a public blog
619 if ($this->publishstate != 'public' && !isloggedin()) {
620 return false;
623 switch ($CFG->bloglevel) {
624 case BLOG_GLOBAL_LEVEL:
625 return true;
626 break;
628 case BLOG_SITE_LEVEL:
629 if (isloggedin()) { // not logged in viewers forbidden
630 return true;
632 return false;
633 break;
635 case BLOG_USER_LEVEL:
636 default:
637 $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
638 return has_capability('moodle/user:readuserblogs', $personalcontext);
639 break;
644 * Use this function to retrieve a list of publish states available for
645 * the currently logged in user.
647 * @return array This function returns an array ideal for sending to moodles'
648 * choose_from_menu function.
651 public static function get_applicable_publish_states() {
652 global $CFG;
653 $options = array();
655 // everyone gets draft access
656 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
657 $options['draft'] = get_string('publishtonoone', 'blog');
660 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
661 $options['site'] = get_string('publishtosite', 'blog');
664 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
665 $options['public'] = get_string('publishtoworld', 'blog');
668 return $options;
673 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
675 * @package moodlecore
676 * @subpackage blog
677 * @copyright 2009 Nicolas Connault
678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
680 class blog_listing {
682 * Array of blog_entry objects.
683 * @var array $entries
685 public $entries = array();
688 * An array of blog_filter_* objects
689 * @var array $filters
691 public $filters = array();
694 * Constructor
696 * @param array $filters An associative array of filtername => filterid
698 public function __construct($filters=array()) {
699 // Unset filters overridden by more specific filters
700 foreach ($filters as $type => $id) {
701 if (!empty($type) && !empty($id)) {
702 $this->filters[$type] = blog_filter::get_instance($id, $type);
706 foreach ($this->filters as $type => $filter) {
707 foreach ($filter->overrides as $override) {
708 if (array_key_exists($override, $this->filters)) {
709 unset($this->filters[$override]);
716 * Fetches the array of blog entries.
718 * @return array
720 public function get_entries($start=0, $limit=10) {
721 global $DB;
723 if (empty($this->entries)) {
724 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
725 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
726 } else {
727 return false;
731 return $this->entries;
734 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
735 global $DB, $USER, $CFG;
737 if(!$userid) {
738 $userid = $USER->id;
741 // The query used to locate blog entries is complicated. It will be built from the following components:
742 $requiredfields = "p.*, u.firstname, u.lastname, u.email"; // the SELECT clause
743 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
744 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
746 // build up a clause for permission constraints
748 $params = array();
750 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
751 // admins can see all blogs regardless of publish states, as described on the help page
752 if (has_capability('moodle/user:readuserblogs', get_context_instance(CONTEXT_SYSTEM))) {
753 // don't add permission constraints
755 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
756 get_context_instance(CONTEXT_USER, (empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
757 // don't add permission constraints
759 } else {
760 if (isloggedin() and !isguestuser()) {
761 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
763 //begin permission sql clause
764 $permissionsql = '(p.userid = ? ';
765 $params[] = $userid;
767 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
768 $permissionsql .= " OR p.publishstate = 'site' ";
771 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
772 $permissionsql .= " OR p.publishstate = 'public' ";
775 $permissionsql .= ') '; //close permissions sql clause
776 } else { // default is access to public entries
777 $permissionsql = "p.publishstate = 'public'";
779 $conditions[] = $permissionsql; //add permission constraints
782 foreach ($this->filters as $type => $blogfilter) {
783 $conditions = array_merge($conditions, $blogfilter->conditions);
784 $params = array_merge($params, $blogfilter->params);
785 $tables = array_merge($tables, $blogfilter->tables);
788 $tablessql = ''; // build up the FROM clause
789 foreach ($tables as $tablename => $table) {
790 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
793 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
794 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
795 $sql .= ($count) ? '' : " ORDER BY $sort";
797 return array('sql' => $sql, 'params' => $params);
801 * Outputs all the blog entries aggregated by this blog listing.
803 * @return void
805 public function print_entries() {
806 global $CFG, $USER, $DB, $OUTPUT;
807 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
809 $page = optional_param('blogpage', 0, PARAM_INT);
810 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
811 $start = $page * $limit;
813 $morelink = '<br />&nbsp;&nbsp;';
815 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
816 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
817 } else {
818 $totalentries = 0;
821 $entries = $this->get_entries($start, $limit);
822 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
823 $pagingbar->pagevar = 'blogpage';
824 $blogheaders = blog_get_headers();
826 echo $OUTPUT->render($pagingbar);
828 if (has_capability('moodle/blog:create', $sitecontext)) {
829 //the user's blog is enabled and they are viewing their own blog
830 $userid = optional_param('userid', null, PARAM_INT);
832 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
833 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
834 $urlparams = array('action' => 'add',
835 'userid' => $userid,
836 'courseid' => optional_param('courseid', null, PARAM_INT),
837 'groupid' => optional_param('groupid', null, PARAM_INT),
838 'modid' => optional_param('modid', null, PARAM_INT),
839 'tagid' => optional_param('tagid', null, PARAM_INT),
840 'tag' => optional_param('tag', null, PARAM_INT),
841 'search' => optional_param('search', null, PARAM_INT));
843 foreach ($urlparams as $var => $val) {
844 if (empty($val)) {
845 unset($urlparams[$var]);
848 $addurl->params($urlparams);
850 $addlink = '<div class="addbloglink">';
851 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
852 $addlink .= '</div>';
853 echo $addlink;
857 if ($entries) {
858 $count = 0;
860 foreach ($entries as $entry) {
861 $blogentry = new blog_entry(null, $entry);
862 $blogentry->print_html();
863 $count++;
866 echo $OUTPUT->render($pagingbar);
868 if (!$count) {
869 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
872 print $morelink.'<br />'."\n";
873 return;
877 /// Find the base url from $_GET variables, for print_paging_bar
878 public function get_baseurl() {
879 $getcopy = $_GET;
881 unset($getcopy['blogpage']);
883 if (!empty($getcopy)) {
884 $first = false;
885 $querystring = '';
887 foreach ($getcopy as $var => $val) {
888 if (!$first) {
889 $first = true;
890 $querystring .= "?$var=$val";
891 } else {
892 $querystring .= '&amp;'.$var.'='.$val;
893 $hasparam = true;
896 } else {
897 $querystring = '?';
900 return strip_querystring(qualified_me()) . $querystring;
906 * Abstract class for blog_filter objects.
907 * A set of core filters are implemented here. To write new filters, you need to subclass
908 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
909 * The blog_filter abstract class will automatically use it when the filter is added to the
910 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
911 * or have any other meaning you wish it to have. The second parameter is called $type and is
912 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
914 abstract class blog_filter {
916 * An array of strings representing the available filter types for each blog_filter.
917 * @var array $availabletypes
919 public $availabletypes = array();
922 * The type of filter (for example, types of blog_filter_context are site, course and module)
923 * @var string $type
925 public $type;
928 * The unique ID for a filter's associated record
929 * @var int $id
931 public $id;
934 * An array of table aliases that are used in the WHERE conditions
935 * @var array $tables
937 public $tables = array();
940 * An array of WHERE conditions
941 * @var array $conditions
943 public $conditions = array();
946 * An array of SQL params
947 * @var array $params
949 public $params = array();
952 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
954 public $overrides = array();
956 public function __construct($id, $type=null) {
957 $this->id = $id;
958 $this->type = $type;
962 * TODO This is poor design. A parent class should not know anything about its children.
963 * The default case helps to resolve this design issue
965 public static function get_instance($id, $type) {
967 switch ($type) {
968 case 'site':
969 case 'course':
970 case 'module':
971 return new blog_filter_context($id, $type);
972 break;
974 case 'group':
975 case 'user':
976 return new blog_filter_user($id, $type);
977 break;
979 case 'tag':
980 return new blog_filter_tag($id);
981 break;
983 default:
984 $classname = "blog_filter_$type";
985 if (class_exists($classname)) {
986 return new $classname($id, $type);
993 * This filter defines the context level of the blog entries being searched: site, course, module
995 class blog_filter_context extends blog_filter {
997 * Constructor
999 * @param string $type
1000 * @param int $id
1002 public function __construct($id=null, $type='site') {
1003 global $SITE, $CFG, $DB;
1005 if (empty($id)) {
1006 $this->type = 'site';
1007 } else {
1008 $this->id = $id;
1009 $this->type = $type;
1012 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
1014 switch ($this->type) {
1015 case 'course': // Careful of site course!
1016 // Ignore course filter if blog associations are not enabled
1017 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
1018 $this->overrides = array('site');
1019 $context = get_context_instance(CONTEXT_COURSE, $this->id);
1020 $this->tables['ba'] = 'blog_association';
1021 $this->conditions[] = 'p.id = ba.blogid';
1022 $this->conditions[] = 'ba.contextid = '.$context->id;
1023 break;
1024 } else {
1025 // We are dealing with the site course, do not break from the current case
1028 case 'site':
1029 // No special constraints
1030 break;
1031 case 'module':
1032 if (!empty($CFG->useblogassociations)) {
1033 $this->overrides = array('course', 'site');
1035 $context = get_context_instance(CONTEXT_MODULE, $this->id);
1036 $this->tables['ba'] = 'blog_association';
1037 $this->tables['p'] = 'post';
1038 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
1039 $this->params = array($context->id);
1041 break;
1047 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
1048 * It can be combined with a context filter in order to refine the search.
1050 class blog_filter_user extends blog_filter {
1051 public $tables = array('u' => 'user');
1054 * Constructor
1056 * @param string $type
1057 * @param int $id
1059 public function __construct($id=null, $type='user') {
1060 global $CFG, $DB, $USER;
1061 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
1063 if (empty($id)) {
1064 $this->id = $USER->id;
1065 $this->type = 'user';
1066 } else {
1067 $this->id = $id;
1068 $this->type = $type;
1071 if ($this->type == 'user') {
1072 $this->conditions = array('u.id = ?');
1073 $this->params = array($this->id);
1074 $this->overrides = array('group');
1076 } elseif ($this->type == 'group') {
1077 $this->overrides = array('course', 'site');
1079 $this->tables['gm'] = 'groups_members';
1080 $this->conditions[] = 'p.userid = gm.userid';
1081 $this->conditions[] = 'gm.groupid = ?';
1082 $this->params[] = $this->id;
1084 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
1085 $coursecontext = get_context_instance(CONTEXT_COURSE, $DB->get_field('groups', 'courseid', array('id' => $this->id)));
1086 $this->tables['ba'] = 'blog_association';
1087 $this->conditions[] = 'gm.groupid = ?';
1088 $this->conditions[] = 'ba.contextid = ?';
1089 $this->conditions[] = 'ba.blogid = p.id';
1090 $this->params[] = $this->id;
1091 $this->params[] = $coursecontext->id;
1099 * This filter defines a tag by which blog entries should be searched.
1101 class blog_filter_tag extends blog_filter {
1102 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
1105 * Constructor
1107 * @return void
1109 public function __construct($id) {
1110 global $DB;
1111 $this->id = $id;
1113 $this->conditions = array('ti.tagid = t.id',
1114 "ti.itemtype = 'post'",
1115 'ti.itemid = p.id',
1116 't.id = ?');
1117 $this->params = array($this->id);
1122 * This filter defines a specific blog entry id.
1124 class blog_filter_entry extends blog_filter {
1125 public $conditions = array('p.id = ?');
1126 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1128 public function __construct($id) {
1129 $this->id = $id;
1130 $this->params[] = $this->id;
1135 * This filter restricts the results to a time interval in seconds up to mktime()
1137 class blog_filter_since extends blog_filter {
1138 public function __construct($interval) {
1139 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1140 $this->params[] = mktime() - $interval;
1141 $this->params[] = mktime();
1146 * Filter used to perform full-text search on an entry's subject, summary and content
1148 class blog_filter_search extends blog_filter {
1150 public function __construct($searchterm) {
1151 global $DB;
1152 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1153 ".$DB->sql_like('p.content', '?', false)." OR
1154 ".$DB->sql_like('p.subject', '?', false).")");
1155 $this->params[] = "%$searchterm%";
1156 $this->params[] = "%$searchterm%";
1157 $this->params[] = "%$searchterm%";