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