MDL-32344 blog Adding a renderer to manage entries output
[moodle.git] / blog / locallib.php
CommitLineData
cae83708 1<?php
2
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.
14//
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/>.
17
cae83708 18/**
19 * Classes for Blogs.
20 *
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
25 */
26
35716b86 27defined('MOODLE_INTERNAL') || die();
cae83708 28
99d19c13
PS
29require_once($CFG->libdir . '/filelib.php');
30
cae83708 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
1c7b8b93 35 * the fields of the post table.
cae83708 36 *
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
41 */
2591c7ae 42class blog_entry implements renderable {
cae83708 43 // Public Database fields
44 public $id;
45 public $userid;
46 public $subject;
47 public $summary;
1c7b8b93
NC
48 public $rating = 0;
49 public $attachment;
cae83708 50 public $publishstate;
51
52 // Locked Database fields (Don't touch these)
1c7b8b93
NC
53 public $courseid = 0;
54 public $groupid = 0;
55 public $module = 'blog';
56 public $moduleid = 0;
57 public $coursemoduleid = 0;
cae83708 58 public $content;
59 public $format = 1;
1c7b8b93 60 public $uniquehash = '';
cae83708 61 public $lastmodified;
62 public $created;
63 public $usermodified;
64
65 // Other class variables
66 public $form;
67 public $tags = array();
68
2591c7ae
DM
69 // Data needed to render the entry
70 public $renderable;
71
cae83708 72 // Methods
73 /**
74 * Constructor. If given an id, will fetch the corresponding record from the DB.
75 *
b73d1ca4 76 * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
cae83708 77 */
1c7b8b93 78 public function __construct($id=null, $params=null, $form=null) {
b73d1ca4 79 global $DB, $PAGE;
cae83708 80
1c7b8b93
NC
81 if (!empty($id)) {
82 $object = $DB->get_record('post', array('id' => $id));
cae83708 83 foreach ($object as $var => $val) {
84 $this->$var = $val;
85 }
1c7b8b93
NC
86 } else if (!empty($params) && (is_array($params) || is_object($params))) {
87 foreach ($params as $var => $val) {
cae83708 88 $this->$var = $val;
89 }
90 }
91
92 $this->form = $form;
93 }
94
2591c7ae 95
cae83708 96 /**
2591c7ae 97 * Gets the required data to print the entry
cae83708 98 */
2591c7ae 99 public function prepare_render() {
cae83708 100
2591c7ae 101 global $DB, $CFG, $PAGE;
b73d1ca4 102
2591c7ae 103 $this->renderable = new StdClass();
cae83708 104
2591c7ae 105 $this->renderable->user = $DB->get_record('user', array('id'=>$this->userid));
cae83708 106
2591c7ae
DM
107 // Entry comments\r
108 if (!empty($CFG->usecomments) and $CFG->blogusecomments) {\r
109 require_once($CFG->dirroot . '/comment/lib.php');
110\r
111 $cmt = new stdClass();\r
112 $cmt->context = get_context_instance(CONTEXT_USER, $this->userid);\r
113 $cmt->courseid = $PAGE->course->id;\r
114 $cmt->area = 'format_blog';\r
115 $cmt->itemid = $this->id;\r
116 $cmt->showcount = $CFG->blogshowcommentscount;\r
117 $cmt->component = 'blog';\r
118 $this->renderable->comment = new comment($cmt);\r
cae83708 119 }
120
2591c7ae
DM
121 // Post data\r
122 $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);\r
123\r
124 $options = array('overflowdiv'=>true);\r
125 $this->renderable->body = format_text($this->summary, $this->summaryformat, $options);\r
126 $this->renderable->title = format_string($this->subject);\r
127 $this->renderable->userid = $this->userid;\r
128 $this->renderable->author = fullname($this->renderable->user);\r
129 $this->renderable->created = userdate($this->created);\r
130 if ($this->created != $this->lastmodified) {\r
131 $this->renderable->lastmod = userdate($this->lastmodified);\r
132 }\r
133 $this->renderable->publishstate = $this->publishstate;
134
135 // External blog\r
136 if ($this->uniquehash && $this->content) {\r
137 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {\r
138 $urlparts = parse_url($externalblog->url);\r
139 $this->renderable->externalblogtext = get_string('retrievedfrom', 'blog').get_string('labelsep', 'langconfig').html_writer::link($urlparts['scheme'].'://'.$urlparts['host'], $externalblog->name);\r
140 }\r
cae83708 141 }
2591c7ae
DM
142\r
143 // Check to see if the entry is unassociated with group/course level access\r
144 $this->renderable->unassociatedentry = false;\r
145 if (!empty($CFG->useblogassociations) && ($this->publishstate == 'group' || $this->publishstate == 'course')) {\r
146 if (!$DB->record_exists('blog_association', array('blogid' => $this->id))) {\r
147 $this->renderable->unassociatedentry = true;\r
148 }\r
1c7b8b93
NC
149 }
150
2591c7ae
DM
151 // Retrieve associations in case they're needed early
152 if (!empty($CFG->useblogassociations)) {\r
153 $associations = $DB->get_records('blog_association', array('blogid' => $this->id));
154
155 // Adding the entry associations data
156 if ($associations) {\r
157 foreach ($associations as $key => $assocrec) {\r
158 $context = get_context_instance_by_id($assocrec->contextid);
159\r
160 // Course associations\r
161 if ($context->contextlevel == CONTEXT_COURSE) {
162 $instancename = $DB->get_field('course', 'shortname', array('id' => $context->instanceid)); //TODO: performance!!!!
163\r
164 $associations[$key]->type = get_string('course');
165 $associations[$key]->url = $assocurl = new moodle_url('/course/view.php', array('id' => $context->instanceid));
166 $associations[$key]->text = $instancename;
167 $associations[$key]->icon = new pix_icon('i/course', $associations[$key]->text);\r
5f4d4d80 168 }
169
2591c7ae
DM
170 // Mod associations
171 if ($context->contextlevel == CONTEXT_MODULE) {
cae83708 172
2591c7ae
DM
173 $modinfo = $DB->get_record('course_modules', array('id' => $context->instanceid));
174 $modname = $DB->get_field('modules', 'name', array('id' => $modinfo->module));
175 $instancename = $DB->get_field($modname, 'name', array('id' => $modinfo->instance)); //TODO: performance!!!!
cae83708 176
2591c7ae
DM
177 $associations[$key]->type = get_string('modulename', $modname);
178 $associations[$key]->url = new moodle_url('/mod/'.$modname.'/view.php', array('id' => $modinfo->id));
179 $associations[$key]->text = $instancename;
180 $associations[$key]->icon = new pix_icon('icon', $associations[$key]->text, $modname);
181 }\r
cae83708 182 }
183 }
2591c7ae
DM
184 $this->renderable->blogassociations = $associations;\r
185 }\r
cae83708 186
2591c7ae
DM
187 // Entry attachments
188 $this->renderable->attachments = $this->get_attachments();
cae83708 189
2591c7ae
DM
190 $this->renderable->usercanedit = blog_user_can_edit_entry($this);
191 }
cae83708 192
cae83708 193
2591c7ae
DM
194 /**
195 * Gets the entry attachments list
196 * @return array List of blog_entry_attachment instances
197 */
198 function get_attachments() {
199
200 global $CFG;\r
201\r
202 require_once($CFG->libdir.'/filelib.php');\r
203\r
204 $syscontext = get_context_instance(CONTEXT_SYSTEM);
205\r
206 $fs = get_file_storage();
207 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);\r
cae83708 208
2591c7ae
DM
209 // Adding a blog_entry_attachment for each non-directory file
210 $attachments = array();\r
211 foreach ($files as $file) {\r
212 if ($file->is_directory()) {\r
213 continue;\r
4def8463 214 }
2591c7ae
DM
215 $attachments[] = new blog_entry_attachment($file, $this->id);\r
216 }\r
cae83708 217
2591c7ae 218 return $attachments;
cae83708 219 }
220
221 /**
222 * Inserts this entry in the database. Access control checks must be done by calling code.
223 *
224 * @param mform $form Used for attachments
225 * @return void
226 */
227 public function process_attachment($form) {
228 $this->form = $form;
229 }
230
231 /**
232 * Inserts this entry in the database. Access control checks must be done by calling code.
233 * TODO Set the publishstate correctly
234 * @param mform $form Used for attachments
235 * @return void
236 */
237 public function add() {
238 global $CFG, $USER, $DB;
239
240 unset($this->id);
241 $this->module = 'blog';
242 $this->userid = (empty($this->userid)) ? $USER->id : $this->userid;
243 $this->lastmodified = time();
244 $this->created = time();
245
246 // Insert the new blog entry.
9d97f08e 247 $this->id = $DB->insert_record('post', $this);
cae83708 248
9d97f08e
PS
249 // Update tags.
250 $this->add_tags_info();
cae83708 251
9d97f08e
PS
252 if (!empty($CFG->useblogassociations)) {
253 $this->add_associations();
254 add_to_log(SITEID, 'blog', 'add', 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
cae83708 255 }
9d97f08e
PS
256
257 tag_set('post', $this->id, $this->tags);
cae83708 258 }
259
260 /**
261 * Updates this entry in the database. Access control checks must be done by calling code.
262 *
263 * @param mform $form Used for attachments
264 * @return void
265 */
1c7b8b93 266 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
b73d1ca4 267 global $CFG, $USER, $DB, $PAGE;
cae83708 268
41b38360 269 $sitecontext = context_system::instance();
1c7b8b93
NC
270 $entry = $this;
271
cae83708 272 $this->form = $form;
273 foreach ($params as $var => $val) {
1c7b8b93 274 $entry->$var = $val;
cae83708 275 }
276
64f93798
PS
277 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
278 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
b73d1ca4 279
5f4d4d80 280 if (!empty($CFG->useblogassociations)) {
1c7b8b93 281 $entry->add_associations();
cae83708 282 }
283
1c7b8b93
NC
284 $entry->lastmodified = time();
285
cae83708 286 // Update record
1c7b8b93
NC
287 $DB->update_record('post', $entry);
288 tag_set('post', $entry->id, $entry->tags);
cae83708 289
1c7b8b93 290 add_to_log(SITEID, 'blog', 'update', 'index.php?userid='.$USER->id.'&entryid='.$entry->id, $entry->subject);
cae83708 291 }
292
293 /**
294 * Deletes this entry from the database. Access control checks must be done by calling code.
295 *
296 * @return void
297 */
298 public function delete() {
299 global $DB, $USER;
300
301 $returnurl = '';
302
cae83708 303 $this->delete_attachments();
304
1c7b8b93
NC
305 $DB->delete_records('post', array('id' => $this->id));
306 tag_set('post', $this->id, array());
cae83708 307
308 add_to_log(SITEID, 'blog', 'delete', 'index.php?userid='. $this->userid, 'deleted blog entry with entry id# '. $this->id);
309 }
310
311 /**
312 * function to add all context associations to an entry
313 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
314 */
1c7b8b93 315 public function add_associations($action='add') {
cae83708 316 global $DB, $USER;
317
cae83708 318 $this->remove_associations();
319
320 if (!empty($this->courseassoc)) {
1c7b8b93 321 $this->add_association($this->courseassoc, $action);
cae83708 322 }
323
324 if (!empty($this->modassoc)) {
1c7b8b93 325 $this->add_association($this->modassoc, $action);
cae83708 326 }
327 }
328
329 /**
330 * add a single association for a blog entry
331 * @param int contextid - id of context to associate with the blog entry
332 */
1c7b8b93
NC
333 public function add_association($contextid, $action='add') {
334 global $DB, $USER;
cae83708 335
1c7b8b93
NC
336 $assocobject = new StdClass;
337 $assocobject->contextid = $contextid;
338 $assocobject->blogid = $this->id;
339 $DB->insert_record('blog_association', $assocobject);
340
41b38360 341 $context = context::instance_by_id($contextid);
1c7b8b93
NC
342 $courseid = null;
343
344 if ($context->contextlevel == CONTEXT_COURSE) {
345 $courseid = $context->instanceid;
346 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
347 } else if ($context->contextlevel == CONTEXT_MODULE) {
348 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
349 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
350 add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
351 }
cae83708 352 }
353
354 /**
355 * remove all associations for a blog entry
356 * @return voic
357 */
358 public function remove_associations() {
359 global $DB;
360 $DB->delete_records('blog_association', array('blogid' => $this->id));
361 }
362
363 /**
364 * Deletes all the user files in the attachments area for an entry
365 *
366 * @return void
367 */
368 public function delete_attachments() {
369 $fs = get_file_storage();
64f93798
PS
370 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
371 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
cae83708 372 }
373
cae83708 374 /**
375 * function to attach tags into an entry
376 * @return void
377 */
378 public function add_tags_info() {
379
380 $tags = array();
381
382 if ($otags = optional_param('otags', '', PARAM_INT)) {
383 foreach ($otags as $tagid) {
384 // TODO : make this use the tag name in the form
385 if ($tag = tag_get('id', $tagid)) {
386 $tags[] = $tag->name;
387 }
388 }
389 }
390
1c7b8b93 391 tag_set('post', $this->id, $tags);
cae83708 392 }
393
394 /**
395 * User can edit a blog entry if this is their own blog entry and they have
396 * the capability moodle/blog:create, or if they have the capability
397 * moodle/blog:manageentries.
398 * This also applies to deleting of entries.
399 *
400 * @param int $userid Optional. If not given, $USER is used
401 * @return boolean
402 */
403 public function can_user_edit($userid=null) {
404 global $CFG, $USER;
405
406 if (empty($userid)) {
407 $userid = $USER->id;
408 }
409
41b38360 410 $sitecontext = context_system::instance();
cae83708 411
412 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
413 return true; // can edit any blog entry
414 }
415
416 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
417 return true; // can edit own when having blog:create capability
418 }
419
420 return false;
421 }
422
423 /**
424 * Checks to see if a user can view the blogs of another user.
425 * Only blog level is checked here, the capabilities are enforced
426 * in blog/index.php
427 *
428 * @param int $targetuserid ID of the user we are checking
429 *
430 * @return bool
431 */
432 public function can_user_view($targetuserid) {
433 global $CFG, $USER, $DB;
41b38360 434 $sitecontext = context_system::instance();
cae83708 435
1c7b8b93
NC
436 if (empty($CFG->bloglevel) || !has_capability('moodle/blog:view', $sitecontext)) {
437 return false; // blog system disabled or user has no blog view capability
cae83708 438 }
439
4f0c2d00 440 if (isloggedin() && $USER->id == $targetuserid) {
cae83708 441 return true; // can view own entries in any case
442 }
443
cae83708 444 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
445 return true; // can manage all entries
446 }
447
448 // coming for 1 entry, make sure it's not a draft
1c7b8b93 449 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
cae83708 450 return false; // can not view draft of others
451 }
452
453 // coming for 1 entry, make sure user is logged in, if not a public blog
1c7b8b93 454 if ($this->publishstate != 'public' && !isloggedin()) {
cae83708 455 return false;
456 }
457
458 switch ($CFG->bloglevel) {
459 case BLOG_GLOBAL_LEVEL:
460 return true;
461 break;
462
463 case BLOG_SITE_LEVEL:
4f0c2d00 464 if (isloggedin()) { // not logged in viewers forbidden
cae83708 465 return true;
466 }
467 return false;
468 break;
469
470 case BLOG_USER_LEVEL:
471 default:
41b38360 472 $personalcontext = context_user::instance($targetuserid);
cae83708 473 return has_capability('moodle/user:readuserblogs', $personalcontext);
474 break;
475 }
476 }
477
478 /**
479 * Use this function to retrieve a list of publish states available for
480 * the currently logged in user.
481 *
482 * @return array This function returns an array ideal for sending to moodles'
483 * choose_from_menu function.
484 */
485
486 public static function get_applicable_publish_states() {
487 global $CFG;
488 $options = array();
489
490 // everyone gets draft access
491 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
1c7b8b93 492 $options['draft'] = get_string('publishtonoone', 'blog');
cae83708 493 }
494
495 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
1c7b8b93 496 $options['site'] = get_string('publishtosite', 'blog');
cae83708 497 }
498
499 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
1c7b8b93 500 $options['public'] = get_string('publishtoworld', 'blog');
cae83708 501 }
502
503 return $options;
504 }
505}
506
507/**
508 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
509 *
510 * @package moodlecore
511 * @subpackage blog
512 * @copyright 2009 Nicolas Connault
513 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
514 */
515class blog_listing {
516 /**
517 * Array of blog_entry objects.
518 * @var array $entries
519 */
520 public $entries = array();
521
522 /**
523 * An array of blog_filter_* objects
524 * @var array $filters
525 */
526 public $filters = array();
527
528 /**
529 * Constructor
530 *
531 * @param array $filters An associative array of filtername => filterid
532 */
533 public function __construct($filters=array()) {
534 // Unset filters overridden by more specific filters
535 foreach ($filters as $type => $id) {
536 if (!empty($type) && !empty($id)) {
537 $this->filters[$type] = blog_filter::get_instance($id, $type);
538 }
539 }
540
541 foreach ($this->filters as $type => $filter) {
542 foreach ($filter->overrides as $override) {
543 if (array_key_exists($override, $this->filters)) {
544 unset($this->filters[$override]);
545 }
546 }
547 }
548 }
549
550 /**
551 * Fetches the array of blog entries.
552 *
553 * @return array
554 */
555 public function get_entries($start=0, $limit=10) {
556 global $DB;
557
558 if (empty($this->entries)) {
899d5e2d 559 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
af3158d8 560 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
cae83708 561 } else {
562 return false;
563 }
564 }
565
566 return $this->entries;
567 }
568
569 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
570 global $DB, $USER, $CFG;
571
572 if(!$userid) {
573 $userid = $USER->id;
574 }
575
576 // The query used to locate blog entries is complicated. It will be built from the following components:
1c7b8b93
NC
577 $requiredfields = "p.*, u.firstname, u.lastname, u.email"; // the SELECT clause
578 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
579 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
cae83708 580
581 // build up a clause for permission constraints
582
583 $params = array();
584
585 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
586 // admins can see all blogs regardless of publish states, as described on the help page
41b38360 587 if (has_capability('moodle/user:readuserblogs', context_system::instance())) {
cae83708 588 // don't add permission constraints
589
590 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
41b38360 591 context_user::instance((empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
cae83708 592 // don't add permission constraints
593
594 } else {
4f0c2d00 595 if (isloggedin() and !isguestuser()) {
cae83708 596 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
597
598 //begin permission sql clause
1c7b8b93 599 $permissionsql = '(p.userid = ? ';
cae83708 600 $params[] = $userid;
601
602 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
1c7b8b93 603 $permissionsql .= " OR p.publishstate = 'site' ";
cae83708 604 }
605
606 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
1c7b8b93 607 $permissionsql .= " OR p.publishstate = 'public' ";
cae83708 608 }
609
610 $permissionsql .= ') '; //close permissions sql clause
611 } else { // default is access to public entries
1c7b8b93 612 $permissionsql = "p.publishstate = 'public'";
cae83708 613 }
614 $conditions[] = $permissionsql; //add permission constraints
615 }
616
1c7b8b93
NC
617 foreach ($this->filters as $type => $blogfilter) {
618 $conditions = array_merge($conditions, $blogfilter->conditions);
619 $params = array_merge($params, $blogfilter->params);
620 $tables = array_merge($tables, $blogfilter->tables);
cae83708 621 }
622
623 $tablessql = ''; // build up the FROM clause
624 foreach ($tables as $tablename => $table) {
625 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
626 }
627
628 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
629 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
527761e0 630 $sql .= ($count) ? '' : " ORDER BY $sort";
cae83708 631
632 return array('sql' => $sql, 'params' => $params);
633 }
634
635 /**
636 * Outputs all the blog entries aggregated by this blog listing.
637 *
638 * @return void
639 */
640 public function print_entries() {
2591c7ae 641 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
41b38360 642 $sitecontext = context_system::instance();
cae83708 643
2591c7ae
DM
644 // Blog renderer\r
645 $output = $PAGE->get_renderer('blog');
646
cae83708 647 $page = optional_param('blogpage', 0, PARAM_INT);
648 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
649 $start = $page * $limit;
650
651 $morelink = '<br />&nbsp;&nbsp;';
652
1c7b8b93
NC
653 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
654 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
cae83708 655 } else {
656 $totalentries = 0;
657 }
658
659 $entries = $this->get_entries($start, $limit);
929d7a83 660 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
cae83708 661 $pagingbar->pagevar = 'blogpage';
1c7b8b93 662 $blogheaders = blog_get_headers();
cae83708 663
929d7a83 664 echo $OUTPUT->render($pagingbar);
cae83708 665
cae83708 666 if (has_capability('moodle/blog:create', $sitecontext)) {
667 //the user's blog is enabled and they are viewing their own blog
668 $userid = optional_param('userid', null, PARAM_INT);
669
670 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
1c7b8b93
NC
671 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
672 $urlparams = array('action' => 'add',
673 'userid' => $userid,
674 'courseid' => optional_param('courseid', null, PARAM_INT),
675 'groupid' => optional_param('groupid', null, PARAM_INT),
676 'modid' => optional_param('modid', null, PARAM_INT),
677 'tagid' => optional_param('tagid', null, PARAM_INT),
678 'tag' => optional_param('tag', null, PARAM_INT),
679 'search' => optional_param('search', null, PARAM_INT));
680
681 foreach ($urlparams as $var => $val) {
cae83708 682 if (empty($val)) {
1c7b8b93 683 unset($urlparams[$var]);
cae83708 684 }
685 }
1c7b8b93 686 $addurl->params($urlparams);
cae83708 687
688 $addlink = '<div class="addbloglink">';
1c7b8b93 689 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
cae83708 690 $addlink .= '</div>';
691 echo $addlink;
692 }
693 }
694
695 if ($entries) {
696 $count = 0;
cae83708 697 foreach ($entries as $entry) {
1c7b8b93 698 $blogentry = new blog_entry(null, $entry);
2591c7ae
DM
699
700 // Get the required blog entry data to render it
701 $blogentry->prepare_render();
702 echo $output->render($blogentry);
703
cae83708 704 $count++;
705 }
706
929d7a83 707 echo $OUTPUT->render($pagingbar);
cae83708 708
709 if (!$count) {
710 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
711 }
712
713 print $morelink.'<br />'."\n";
714 return;
715 }
716 }
717
718 /// Find the base url from $_GET variables, for print_paging_bar
719 public function get_baseurl() {
720 $getcopy = $_GET;
721
722 unset($getcopy['blogpage']);
723
724 if (!empty($getcopy)) {
725 $first = false;
726 $querystring = '';
727
728 foreach ($getcopy as $var => $val) {
729 if (!$first) {
730 $first = true;
731 $querystring .= "?$var=$val";
732 } else {
733 $querystring .= '&amp;'.$var.'='.$val;
734 $hasparam = true;
735 }
736 }
737 } else {
738 $querystring = '?';
739 }
740
741 return strip_querystring(qualified_me()) . $querystring;
742
743 }
744}
745
746/**
747 * Abstract class for blog_filter objects.
748 * A set of core filters are implemented here. To write new filters, you need to subclass
749 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
750 * The blog_filter abstract class will automatically use it when the filter is added to the
751 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
752 * or have any other meaning you wish it to have. The second parameter is called $type and is
753 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
754 */
755abstract class blog_filter {
756 /**
757 * An array of strings representing the available filter types for each blog_filter.
1c7b8b93 758 * @var array $availabletypes
cae83708 759 */
1c7b8b93 760 public $availabletypes = array();
cae83708 761
762 /**
763 * The type of filter (for example, types of blog_filter_context are site, course and module)
764 * @var string $type
765 */
766 public $type;
767
768 /**
769 * The unique ID for a filter's associated record
770 * @var int $id
771 */
772 public $id;
773
774 /**
775 * An array of table aliases that are used in the WHERE conditions
776 * @var array $tables
777 */
778 public $tables = array();
779
780 /**
781 * An array of WHERE conditions
782 * @var array $conditions
783 */
784 public $conditions = array();
785
786 /**
787 * An array of SQL params
788 * @var array $params
789 */
790 public $params = array();
791
792 /**
793 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
794 */
795 public $overrides = array();
796
797 public function __construct($id, $type=null) {
798 $this->id = $id;
799 $this->type = $type;
800 }
801
802 /**
803 * TODO This is poor design. A parent class should not know anything about its children.
804 * The default case helps to resolve this design issue
805 */
806 public static function get_instance($id, $type) {
807
808 switch ($type) {
809 case 'site':
810 case 'course':
811 case 'module':
812 return new blog_filter_context($id, $type);
813 break;
814
815 case 'group':
816 case 'user':
817 return new blog_filter_user($id, $type);
818 break;
819
820 case 'tag':
821 return new blog_filter_tag($id);
822 break;
823
824 default:
1c7b8b93
NC
825 $classname = "blog_filter_$type";
826 if (class_exists($classname)) {
827 return new $classname($id, $type);
cae83708 828 }
829 }
830 }
831}
832
833/**
834 * This filter defines the context level of the blog entries being searched: site, course, module
835 */
836class blog_filter_context extends blog_filter {
837 /**
838 * Constructor
839 *
840 * @param string $type
841 * @param int $id
842 */
843 public function __construct($id=null, $type='site') {
844 global $SITE, $CFG, $DB;
845
846 if (empty($id)) {
847 $this->type = 'site';
848 } else {
849 $this->id = $id;
850 $this->type = $type;
851 }
852
8eaf1ba1 853 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
cae83708 854
855 switch ($this->type) {
856 case 'course': // Careful of site course!
857 // Ignore course filter if blog associations are not enabled
858 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
859 $this->overrides = array('site');
41b38360 860 $context = context_course::instance($this->id);
cae83708 861 $this->tables['ba'] = 'blog_association';
1c7b8b93 862 $this->conditions[] = 'p.id = ba.blogid';
cae83708 863 $this->conditions[] = 'ba.contextid = '.$context->id;
864 break;
865 } else {
866 // We are dealing with the site course, do not break from the current case
867 }
868
869 case 'site':
870 // No special constraints
871 break;
872 case 'module':
873 if (!empty($CFG->useblogassociations)) {
874 $this->overrides = array('course', 'site');
875
41b38360 876 $context = context_module::instance($this->id);
cae83708 877 $this->tables['ba'] = 'blog_association';
1c7b8b93
NC
878 $this->tables['p'] = 'post';
879 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
cae83708 880 $this->params = array($context->id);
881 }
882 break;
883 }
884 }
885}
886
887/**
888 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
889 * It can be combined with a context filter in order to refine the search.
890 */
891class blog_filter_user extends blog_filter {
892 public $tables = array('u' => 'user');
893
894 /**
895 * Constructor
896 *
897 * @param string $type
898 * @param int $id
899 */
900 public function __construct($id=null, $type='user') {
320ae23a 901 global $CFG, $DB, $USER;
1c7b8b93 902 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
cae83708 903
904 if (empty($id)) {
905 $this->id = $USER->id;
906 $this->type = 'user';
907 } else {
908 $this->id = $id;
909 $this->type = $type;
910 }
911
912 if ($this->type == 'user') {
913 $this->conditions = array('u.id = ?');
914 $this->params = array($this->id);
915 $this->overrides = array('group');
916
917 } elseif ($this->type == 'group') {
918 $this->overrides = array('course', 'site');
919
920 $this->tables['gm'] = 'groups_members';
1c7b8b93 921 $this->conditions[] = 'p.userid = gm.userid';
cae83708 922 $this->conditions[] = 'gm.groupid = ?';
923 $this->params[] = $this->id;
924
925 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
41b38360 926 $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id)));
cae83708 927 $this->tables['ba'] = 'blog_association';
928 $this->conditions[] = 'gm.groupid = ?';
929 $this->conditions[] = 'ba.contextid = ?';
1c7b8b93 930 $this->conditions[] = 'ba.blogid = p.id';
cae83708 931 $this->params[] = $this->id;
1c7b8b93 932 $this->params[] = $coursecontext->id;
cae83708 933 }
934 }
b73d1ca4 935
cae83708 936 }
937}
938
939/**
940 * This filter defines a tag by which blog entries should be searched.
941 */
942class blog_filter_tag extends blog_filter {
1c7b8b93 943 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
cae83708 944
945 /**
946 * Constructor
947 *
948 * @return void
949 */
950 public function __construct($id) {
951 global $DB;
952 $this->id = $id;
953
954 $this->conditions = array('ti.tagid = t.id',
1c7b8b93
NC
955 "ti.itemtype = 'post'",
956 'ti.itemid = p.id',
cae83708 957 't.id = ?');
958 $this->params = array($this->id);
959 }
960}
961
962/**
963 * This filter defines a specific blog entry id.
964 */
965class blog_filter_entry extends blog_filter {
966 public $conditions = array('p.id = ?');
967 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
968
969 public function __construct($id) {
970 $this->id = $id;
971 $this->params[] = $this->id;
972 }
973}
974
1c7b8b93 975/**
caee6e6c 976 * This filter restricts the results to a time interval in seconds up to time()
1c7b8b93
NC
977 */
978class blog_filter_since extends blog_filter {
979 public function __construct($interval) {
980 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
caee6e6c
PS
981 $this->params[] = time() - $interval;
982 $this->params[] = time();
1c7b8b93
NC
983 }
984}
985
cae83708 986/**
987 * Filter used to perform full-text search on an entry's subject, summary and content
988 */
989class blog_filter_search extends blog_filter {
990
1c7b8b93 991 public function __construct($searchterm) {
cae83708 992 global $DB;
c014d57c
PS
993 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
994 ".$DB->sql_like('p.content', '?', false)." OR
995 ".$DB->sql_like('p.subject', '?', false).")");
1c7b8b93
NC
996 $this->params[] = "%$searchterm%";
997 $this->params[] = "%$searchterm%";
998 $this->params[] = "%$searchterm%";
cae83708 999 }
1000}
2591c7ae
DM
1001
1002
1003/**
1004 * Renderable class to represent an entry attachment
1005 */
1006class blog_entry_attachment implements renderable {
1007
1008 public $filename;
1009 public $url;
1010 public $file;
1011
1012 /**
1013 * @param stored_file $file
1014 * @param int $entryid Attachment entry id
1015 */
1016 public function __construct($file, $entryid) {
1017
1018 global $OUTPUT, $CFG;
1019
1020 $syscontext = get_context_instance(CONTEXT_SYSTEM);
1021
1022 $this->file = $file;
1023 $this->filename = $file->get_filename();\r
1024 $this->url = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$entryid.'/'.$this->filename);\r
1025 }
1026
1027}