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