3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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');
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.
39 * @copyright 2009 Nicolas Connault
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 // Public Database fields
52 // Locked Database fields (Don't touch these)
55 public $module = 'blog';
57 public $coursemoduleid = 0;
60 public $uniquehash = '';
65 // Other class variables
67 public $tags = array();
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) {
79 $object = $DB->get_record('post', array('id' => $id));
80 foreach ($object as $var => $val) {
83 } else if (!empty($params) && (is_array($params) ||
is_object($params))) {
84 foreach ($params as $var => $val) {
93 * Prints or returns the HTML for this blog entry.
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
));
104 if (!empty($CFG->usecomments
) and $CFG->blogusecomments
) {
105 require_once($CFG->dirroot
. '/comment/lib.php');
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;
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']) {
198 $blogtype = get_string('publishtonoone', 'blog');
201 $blogtype = get_string('publishtosite', 'blog');
204 $blogtype = get_string('publishtoworld', 'blog');
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();
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');
232 $contentcell->text
.= get_string('tags', 'tag') .': '. $OUTPUT->container($officialtags, 'officialblogtags');
234 $contentcell->text
.= ', ';
237 $contentcell->text
.= $defaulttags;
238 $contentcell->text
.= $OUTPUT->container_end();
242 if (!empty($CFG->useblogassociations
) && $blogassociations) {
243 $contentcell->text
.= $OUTPUT->container_start('tags');
245 $hascourseassocs = false;
248 // First find and show the associated course
249 foreach ($blogassociations as $assocrec) {
250 $contextrec = $DB->get_record('context', array('id' => $assocrec->contextid
));
251 if ($contextrec->contextlevel
== CONTEXT_COURSE
) {
252 $assocurl = new moodle_url('/course/view.php', array('id' => $contextrec->instanceid
));
253 $text = $DB->get_field('course', 'shortname', array('id' => $contextrec->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 $contextrec = $DB->get_record('context', array('id' => $assocrec->contextid
));
264 if ($contextrec->contextlevel
== CONTEXT_MODULE
) {
265 if ($hascourseassocs) {
267 $hascourseassocs = false;
270 $modinfo = $DB->get_record('course_modules', array('id' => $contextrec->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);
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');
293 $contentcell->text
.= $OUTPUT->container_start('commands');
295 if (blog_user_can_edit_entry($this)) {
296 if (empty($this->uniquehash
)) {
297 //External blog entries should not be edited
298 $contentcell->text
.= html_writer
::link(new moodle_url('/blog/edit.php',
299 array('action' => 'edit', 'entryid' => $this->id
)),
302 $contentcell->text
.= html_writer
::link(new moodle_url('/blog/edit.php',
303 array('action' => 'delete', 'entryid' => $this->id
)),
307 $contentcell->text
.= html_writer
::link(new moodle_url('/blog/index.php', array('entryid' => $this->id
)), get_string('permalink', 'blog'));
309 $contentcell->text
.= $OUTPUT->container_end();
311 if (isset($template['lastmod']) ){
312 $contentcell->text
.= '<div style="font-size: 55%;">';
313 $contentcell->text
.= ' [ '.get_string('modified').': '.$template['lastmod'].' ]';
314 $contentcell->text
.= '</div>';
317 //add comments under everything
318 $contentcell->text
.= $cmttext;
320 $mainrow->cells
[] = $contentcell;
321 $table->data
= array($mainrow);
324 return html_writer
::table($table);
326 echo html_writer
::table($table);
331 * Inserts this entry in the database. Access control checks must be done by calling code.
333 * @param mform $form Used for attachments
336 public function process_attachment($form) {
341 * Inserts this entry in the database. Access control checks must be done by calling code.
342 * TODO Set the publishstate correctly
343 * @param mform $form Used for attachments
346 public function add() {
347 global $CFG, $USER, $DB;
350 $this->module
= 'blog';
351 $this->userid
= (empty($this->userid
)) ?
$USER->id
: $this->userid
;
352 $this->lastmodified
= time();
353 $this->created
= time();
355 // Insert the new blog entry.
356 $this->id
= $DB->insert_record('post', $this);
359 $this->add_tags_info();
361 if (!empty($CFG->useblogassociations
)) {
362 $this->add_associations();
363 add_to_log(SITEID
, 'blog', 'add', 'index.php?userid='.$this->userid
.'&entryid='.$this->id
, $this->subject
);
366 tag_set('post', $this->id
, $this->tags
);
370 * Updates this entry in the database. Access control checks must be done by calling code.
372 * @param mform $form Used for attachments
375 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
376 global $CFG, $USER, $DB, $PAGE;
378 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
382 foreach ($params as $var => $val) {
386 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id
);
387 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id
);
389 if (!empty($CFG->useblogassociations
)) {
390 $entry->add_associations();
393 $entry->lastmodified
= time();
396 $DB->update_record('post', $entry);
397 tag_set('post', $entry->id
, $entry->tags
);
399 add_to_log(SITEID
, 'blog', 'update', 'index.php?userid='.$USER->id
.'&entryid='.$entry->id
, $entry->subject
);
403 * Deletes this entry from the database. Access control checks must be done by calling code.
407 public function delete() {
412 $this->delete_attachments();
414 $DB->delete_records('post', array('id' => $this->id
));
415 tag_set('post', $this->id
, array());
417 add_to_log(SITEID
, 'blog', 'delete', 'index.php?userid='. $this->userid
, 'deleted blog entry with entry id# '. $this->id
);
421 * function to add all context associations to an entry
422 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
424 public function add_associations($action='add') {
427 $this->remove_associations();
429 if (!empty($this->courseassoc
)) {
430 $this->add_association($this->courseassoc
, $action);
433 if (!empty($this->modassoc
)) {
434 $this->add_association($this->modassoc
, $action);
439 * add a single association for a blog entry
440 * @param int contextid - id of context to associate with the blog entry
442 public function add_association($contextid, $action='add') {
445 $assocobject = new StdClass
;
446 $assocobject->contextid
= $contextid;
447 $assocobject->blogid
= $this->id
;
448 $DB->insert_record('blog_association', $assocobject);
450 $context = get_context_instance_by_id($contextid);
453 if ($context->contextlevel
== CONTEXT_COURSE
) {
454 $courseid = $context->instanceid
;
455 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid
.'&entryid='.$this->id
, $this->subject
);
456 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
457 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid
));
458 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
));
459 add_to_log($cm->course
, 'blog', $action, 'index.php?userid='.$this->userid
.'&entryid='.$this->id
, $this->subject
, $cm->id
, $this->userid
);
464 * remove all associations for a blog entry
467 public function remove_associations() {
469 $DB->delete_records('blog_association', array('blogid' => $this->id
));
473 * Deletes all the user files in the attachments area for an entry
477 public function delete_attachments() {
478 $fs = get_file_storage();
479 $fs->delete_area_files(SYSCONTEXTID
, 'blog', 'attachment', $this->id
);
480 $fs->delete_area_files(SYSCONTEXTID
, 'blog', 'post', $this->id
);
484 * if return=html, then return a html string.
485 * if return=text, then return a text-only string.
486 * otherwise, print HTML for non-images, and return image HTML
488 * @param bool $return Whether to return or print the generated code
491 public function print_attachments($return=false) {
492 global $CFG, $OUTPUT;
494 require_once($CFG->libdir
.'/filelib.php');
496 $fs = get_file_storage();
498 $syscontext = get_context_instance(CONTEXT_SYSTEM
);
500 $files = $fs->get_area_files($syscontext->id
, 'blog', 'attachment', $this->id
);
505 $strattachment = get_string("attachment", "forum");
507 foreach ($files as $file) {
508 if ($file->is_directory()) {
512 $filename = $file->get_filename();
513 $ffurl = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.SYSCONTEXTID
.'/blog/attachment/'.$this->id
.'/'.$filename);
514 $mimetype = $file->get_mimetype();
516 $icon = mimeinfo_from_type("icon", $mimetype);
517 $type = mimeinfo_from_type("type", $mimetype);
519 $image = $OUTPUT->pix_icon("f/$icon", $filename, 'moodle', array('class'=>'icon'));
521 if ($return == "html") {
522 $output .= html_writer
::link($ffurl, $image);
523 $output .= html_writer
::link($ffurl, $filename);
525 } else if ($return == "text") {
526 $output .= "$strattachment $filename:\n$ffurl\n";
529 if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) { // Image attachments don't get printed as links
530 $imagereturn .= '<br /><img src="'.$ffurl.'" alt="" />';
532 $imagereturn .= html_writer
::link($ffurl, $image);
533 $imagereturn .= format_text(html_writer
::link($ffurl, $filename), FORMAT_HTML
, array('context'=>$syscontext));
547 * function to attach tags into an entry
550 public function add_tags_info() {
554 if ($otags = optional_param('otags', '', PARAM_INT
)) {
555 foreach ($otags as $tagid) {
556 // TODO : make this use the tag name in the form
557 if ($tag = tag_get('id', $tagid)) {
558 $tags[] = $tag->name
;
563 tag_set('post', $this->id
, $tags);
567 * User can edit a blog entry if this is their own blog entry and they have
568 * the capability moodle/blog:create, or if they have the capability
569 * moodle/blog:manageentries.
570 * This also applies to deleting of entries.
572 * @param int $userid Optional. If not given, $USER is used
575 public function can_user_edit($userid=null) {
578 if (empty($userid)) {
582 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
584 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
585 return true; // can edit any blog entry
588 if ($this->userid
== $userid && has_capability('moodle/blog:create', $sitecontext)) {
589 return true; // can edit own when having blog:create capability
596 * Checks to see if a user can view the blogs of another user.
597 * Only blog level is checked here, the capabilities are enforced
600 * @param int $targetuserid ID of the user we are checking
604 public function can_user_view($targetuserid) {
605 global $CFG, $USER, $DB;
606 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
608 if (empty($CFG->bloglevel
) ||
!has_capability('moodle/blog:view', $sitecontext)) {
609 return false; // blog system disabled or user has no blog view capability
612 if (isloggedin() && $USER->id
== $targetuserid) {
613 return true; // can view own entries in any case
616 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
617 return true; // can manage all entries
620 // coming for 1 entry, make sure it's not a draft
621 if ($this->publishstate
== 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
622 return false; // can not view draft of others
625 // coming for 1 entry, make sure user is logged in, if not a public blog
626 if ($this->publishstate
!= 'public' && !isloggedin()) {
630 switch ($CFG->bloglevel
) {
631 case BLOG_GLOBAL_LEVEL
:
635 case BLOG_SITE_LEVEL
:
636 if (isloggedin()) { // not logged in viewers forbidden
642 case BLOG_USER_LEVEL
:
644 $personalcontext = get_context_instance(CONTEXT_USER
, $targetuserid);
645 return has_capability('moodle/user:readuserblogs', $personalcontext);
651 * Use this function to retrieve a list of publish states available for
652 * the currently logged in user.
654 * @return array This function returns an array ideal for sending to moodles'
655 * choose_from_menu function.
658 public static function get_applicable_publish_states() {
662 // everyone gets draft access
663 if ($CFG->bloglevel
>= BLOG_USER_LEVEL
) {
664 $options['draft'] = get_string('publishtonoone', 'blog');
667 if ($CFG->bloglevel
> BLOG_USER_LEVEL
) {
668 $options['site'] = get_string('publishtosite', 'blog');
671 if ($CFG->bloglevel
>= BLOG_GLOBAL_LEVEL
) {
672 $options['public'] = get_string('publishtoworld', 'blog');
680 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
682 * @package moodlecore
684 * @copyright 2009 Nicolas Connault
685 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
689 * Array of blog_entry objects.
690 * @var array $entries
692 public $entries = array();
695 * An array of blog_filter_* objects
696 * @var array $filters
698 public $filters = array();
703 * @param array $filters An associative array of filtername => filterid
705 public function __construct($filters=array()) {
706 // Unset filters overridden by more specific filters
707 foreach ($filters as $type => $id) {
708 if (!empty($type) && !empty($id)) {
709 $this->filters
[$type] = blog_filter
::get_instance($id, $type);
713 foreach ($this->filters
as $type => $filter) {
714 foreach ($filter->overrides
as $override) {
715 if (array_key_exists($override, $this->filters
)) {
716 unset($this->filters
[$override]);
723 * Fetches the array of blog entries.
727 public function get_entries($start=0, $limit=10) {
730 if (empty($this->entries
)) {
731 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
732 $this->entries
= $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
738 return $this->entries
;
741 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
742 global $DB, $USER, $CFG;
748 // The query used to locate blog entries is complicated. It will be built from the following components:
749 $requiredfields = "p.*, u.firstname, u.lastname, u.email"; // the SELECT clause
750 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
751 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
753 // build up a clause for permission constraints
757 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
758 // admins can see all blogs regardless of publish states, as described on the help page
759 if (has_capability('moodle/user:readuserblogs', get_context_instance(CONTEXT_SYSTEM
))) {
760 // don't add permission constraints
762 } else if(!empty($this->filters
['user']) && has_capability('moodle/user:readuserblogs',
763 get_context_instance(CONTEXT_USER
, (empty($this->filters
['user']->id
) ?
0 : $this->filters
['user']->id
)))) {
764 // don't add permission constraints
767 if (isloggedin() and !isguestuser()) {
768 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
770 //begin permission sql clause
771 $permissionsql = '(p.userid = ? ';
774 if ($CFG->bloglevel
>= BLOG_SITE_LEVEL
) { // add permission to view site-level entries
775 $permissionsql .= " OR p.publishstate = 'site' ";
778 if ($CFG->bloglevel
>= BLOG_GLOBAL_LEVEL
) { // add permission to view global entries
779 $permissionsql .= " OR p.publishstate = 'public' ";
782 $permissionsql .= ') '; //close permissions sql clause
783 } else { // default is access to public entries
784 $permissionsql = "p.publishstate = 'public'";
786 $conditions[] = $permissionsql; //add permission constraints
789 foreach ($this->filters
as $type => $blogfilter) {
790 $conditions = array_merge($conditions, $blogfilter->conditions
);
791 $params = array_merge($params, $blogfilter->params
);
792 $tables = array_merge($tables, $blogfilter->tables
);
795 $tablessql = ''; // build up the FROM clause
796 foreach ($tables as $tablename => $table) {
797 $tablessql .= ($tablessql ?
', ' : '').'{'.$table.'} '.$tablename;
800 $sql = ($count) ?
'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
801 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
802 $sql .= ($count) ?
'' : " ORDER BY $sort";
804 return array('sql' => $sql, 'params' => $params);
808 * Outputs all the blog entries aggregated by this blog listing.
812 public function print_entries() {
813 global $CFG, $USER, $DB, $OUTPUT;
814 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
816 $page = optional_param('blogpage', 0, PARAM_INT
);
817 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT
);
818 $start = $page * $limit;
820 $morelink = '<br /> ';
822 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
823 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
828 $entries = $this->get_entries($start, $limit);
829 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
830 $pagingbar->pagevar
= 'blogpage';
831 $blogheaders = blog_get_headers();
833 echo $OUTPUT->render($pagingbar);
835 if (has_capability('moodle/blog:create', $sitecontext)) {
836 //the user's blog is enabled and they are viewing their own blog
837 $userid = optional_param('userid', null, PARAM_INT
);
839 if (empty($userid) ||
(!empty($userid) && $userid == $USER->id
)) {
840 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
841 $urlparams = array('action' => 'add',
843 'courseid' => optional_param('courseid', null, PARAM_INT
),
844 'groupid' => optional_param('groupid', null, PARAM_INT
),
845 'modid' => optional_param('modid', null, PARAM_INT
),
846 'tagid' => optional_param('tagid', null, PARAM_INT
),
847 'tag' => optional_param('tag', null, PARAM_INT
),
848 'search' => optional_param('search', null, PARAM_INT
));
850 foreach ($urlparams as $var => $val) {
852 unset($urlparams[$var]);
855 $addurl->params($urlparams);
857 $addlink = '<div class="addbloglink">';
858 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
859 $addlink .= '</div>';
867 foreach ($entries as $entry) {
868 $blogentry = new blog_entry(null, $entry);
869 $blogentry->print_html();
873 echo $OUTPUT->render($pagingbar);
876 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
879 print $morelink.'<br />'."\n";
884 /// Find the base url from $_GET variables, for print_paging_bar
885 public function get_baseurl() {
888 unset($getcopy['blogpage']);
890 if (!empty($getcopy)) {
894 foreach ($getcopy as $var => $val) {
897 $querystring .= "?$var=$val";
899 $querystring .= '&'.$var.'='.$val;
907 return strip_querystring(qualified_me()) . $querystring;
913 * Abstract class for blog_filter objects.
914 * A set of core filters are implemented here. To write new filters, you need to subclass
915 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
916 * The blog_filter abstract class will automatically use it when the filter is added to the
917 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
918 * or have any other meaning you wish it to have. The second parameter is called $type and is
919 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
921 abstract class blog_filter
{
923 * An array of strings representing the available filter types for each blog_filter.
924 * @var array $availabletypes
926 public $availabletypes = array();
929 * The type of filter (for example, types of blog_filter_context are site, course and module)
935 * The unique ID for a filter's associated record
941 * An array of table aliases that are used in the WHERE conditions
944 public $tables = array();
947 * An array of WHERE conditions
948 * @var array $conditions
950 public $conditions = array();
953 * An array of SQL params
956 public $params = array();
959 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
961 public $overrides = array();
963 public function __construct($id, $type=null) {
969 * TODO This is poor design. A parent class should not know anything about its children.
970 * The default case helps to resolve this design issue
972 public static function get_instance($id, $type) {
978 return new blog_filter_context($id, $type);
983 return new blog_filter_user($id, $type);
987 return new blog_filter_tag($id);
991 $classname = "blog_filter_$type";
992 if (class_exists($classname)) {
993 return new $classname($id, $type);
1000 * This filter defines the context level of the blog entries being searched: site, course, module
1002 class blog_filter_context
extends blog_filter
{
1006 * @param string $type
1009 public function __construct($id=null, $type='site') {
1010 global $SITE, $CFG, $DB;
1013 $this->type
= 'site';
1016 $this->type
= $type;
1019 $this->availabletypes
= array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
1021 switch ($this->type
) {
1022 case 'course': // Careful of site course!
1023 // Ignore course filter if blog associations are not enabled
1024 if ($this->id
!= $SITE->id
&& !empty($CFG->useblogassociations
)) {
1025 $this->overrides
= array('site');
1026 $context = get_context_instance(CONTEXT_COURSE
, $this->id
);
1027 $this->tables
['ba'] = 'blog_association';
1028 $this->conditions
[] = 'p.id = ba.blogid';
1029 $this->conditions
[] = 'ba.contextid = '.$context->id
;
1032 // We are dealing with the site course, do not break from the current case
1036 // No special constraints
1039 if (!empty($CFG->useblogassociations
)) {
1040 $this->overrides
= array('course', 'site');
1042 $context = get_context_instance(CONTEXT_MODULE
, $this->id
);
1043 $this->tables
['ba'] = 'blog_association';
1044 $this->tables
['p'] = 'post';
1045 $this->conditions
= array('p.id = ba.blogid', 'ba.contextid = ?');
1046 $this->params
= array($context->id
);
1054 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
1055 * It can be combined with a context filter in order to refine the search.
1057 class blog_filter_user
extends blog_filter
{
1058 public $tables = array('u' => 'user');
1063 * @param string $type
1066 public function __construct($id=null, $type='user') {
1067 global $CFG, $DB, $USER;
1068 $this->availabletypes
= array('user' => get_string('user'), 'group' => get_string('group'));
1071 $this->id
= $USER->id
;
1072 $this->type
= 'user';
1075 $this->type
= $type;
1078 if ($this->type
== 'user') {
1079 $this->conditions
= array('u.id = ?');
1080 $this->params
= array($this->id
);
1081 $this->overrides
= array('group');
1083 } elseif ($this->type
== 'group') {
1084 $this->overrides
= array('course', 'site');
1086 $this->tables
['gm'] = 'groups_members';
1087 $this->conditions
[] = 'p.userid = gm.userid';
1088 $this->conditions
[] = 'gm.groupid = ?';
1089 $this->params
[] = $this->id
;
1091 if (!empty($CFG->useblogassociations
)) { // only show blog entries associated with this course
1092 $coursecontext = get_context_instance(CONTEXT_COURSE
, $DB->get_field('groups', 'courseid', array('id' => $this->id
)));
1093 $this->tables
['ba'] = 'blog_association';
1094 $this->conditions
[] = 'gm.groupid = ?';
1095 $this->conditions
[] = 'ba.contextid = ?';
1096 $this->conditions
[] = 'ba.blogid = p.id';
1097 $this->params
[] = $this->id
;
1098 $this->params
[] = $coursecontext->id
;
1106 * This filter defines a tag by which blog entries should be searched.
1108 class blog_filter_tag
extends blog_filter
{
1109 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
1116 public function __construct($id) {
1120 $this->conditions
= array('ti.tagid = t.id',
1121 "ti.itemtype = 'post'",
1124 $this->params
= array($this->id
);
1129 * This filter defines a specific blog entry id.
1131 class blog_filter_entry
extends blog_filter
{
1132 public $conditions = array('p.id = ?');
1133 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1135 public function __construct($id) {
1137 $this->params
[] = $this->id
;
1142 * This filter restricts the results to a time interval in seconds up to mktime()
1144 class blog_filter_since
extends blog_filter
{
1145 public function __construct($interval) {
1146 $this->conditions
[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1147 $this->params
[] = mktime() - $interval;
1148 $this->params
[] = mktime();
1153 * Filter used to perform full-text search on an entry's subject, summary and content
1155 class blog_filter_search
extends blog_filter
{
1157 public function __construct($searchterm) {
1159 $this->conditions
= array("(".$DB->sql_like('p.summary', '?', false)." OR
1160 ".$DB->sql_like('p.content', '?', false)." OR
1161 ".$DB->sql_like('p.subject', '?', false).")");
1162 $this->params
[] = "%$searchterm%";
1163 $this->params
[] = "%$searchterm%";
1164 $this->params
[] = "%$searchterm%";