Merge branch 'wip-MDL-34318-master' of git://github.com/abgreeve/moodle
[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)) {
1c7b8b93
NC
666 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
667 $urlparams = array('action' => 'add',
668 'userid' => $userid,
669 'courseid' => optional_param('courseid', null, PARAM_INT),
670 'groupid' => optional_param('groupid', null, PARAM_INT),
671 'modid' => optional_param('modid', null, PARAM_INT),
672 'tagid' => optional_param('tagid', null, PARAM_INT),
673 'tag' => optional_param('tag', null, PARAM_INT),
674 'search' => optional_param('search', null, PARAM_INT));
675
676 foreach ($urlparams as $var => $val) {
cae83708 677 if (empty($val)) {
1c7b8b93 678 unset($urlparams[$var]);
cae83708 679 }
680 }
1c7b8b93 681 $addurl->params($urlparams);
cae83708 682
683 $addlink = '<div class="addbloglink">';
1c7b8b93 684 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
cae83708 685 $addlink .= '</div>';
686 echo $addlink;
687 }
688 }
689
690 if ($entries) {
691 $count = 0;
cae83708 692 foreach ($entries as $entry) {
1c7b8b93 693 $blogentry = new blog_entry(null, $entry);
2591c7ae
DM
694
695 // Get the required blog entry data to render it
696 $blogentry->prepare_render();
697 echo $output->render($blogentry);
698
cae83708 699 $count++;
700 }
701
929d7a83 702 echo $OUTPUT->render($pagingbar);
cae83708 703
704 if (!$count) {
705 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
706 }
707
708 print $morelink.'<br />'."\n";
709 return;
710 }
711 }
712
713 /// Find the base url from $_GET variables, for print_paging_bar
714 public function get_baseurl() {
715 $getcopy = $_GET;
716
717 unset($getcopy['blogpage']);
718
719 if (!empty($getcopy)) {
720 $first = false;
721 $querystring = '';
722
723 foreach ($getcopy as $var => $val) {
724 if (!$first) {
725 $first = true;
726 $querystring .= "?$var=$val";
727 } else {
728 $querystring .= '&amp;'.$var.'='.$val;
729 $hasparam = true;
730 }
731 }
732 } else {
733 $querystring = '?';
734 }
735
736 return strip_querystring(qualified_me()) . $querystring;
737
738 }
739}
740
741/**
742 * Abstract class for blog_filter objects.
743 * A set of core filters are implemented here. To write new filters, you need to subclass
744 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
745 * The blog_filter abstract class will automatically use it when the filter is added to the
746 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
747 * or have any other meaning you wish it to have. The second parameter is called $type and is
748 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
749 */
750abstract class blog_filter {
751 /**
752 * An array of strings representing the available filter types for each blog_filter.
1c7b8b93 753 * @var array $availabletypes
cae83708 754 */
1c7b8b93 755 public $availabletypes = array();
cae83708 756
757 /**
758 * The type of filter (for example, types of blog_filter_context are site, course and module)
759 * @var string $type
760 */
761 public $type;
762
763 /**
764 * The unique ID for a filter's associated record
765 * @var int $id
766 */
767 public $id;
768
769 /**
770 * An array of table aliases that are used in the WHERE conditions
771 * @var array $tables
772 */
773 public $tables = array();
774
775 /**
776 * An array of WHERE conditions
777 * @var array $conditions
778 */
779 public $conditions = array();
780
781 /**
782 * An array of SQL params
783 * @var array $params
784 */
785 public $params = array();
786
787 /**
788 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
789 */
790 public $overrides = array();
791
792 public function __construct($id, $type=null) {
793 $this->id = $id;
794 $this->type = $type;
795 }
796
797 /**
798 * TODO This is poor design. A parent class should not know anything about its children.
799 * The default case helps to resolve this design issue
800 */
801 public static function get_instance($id, $type) {
802
803 switch ($type) {
804 case 'site':
805 case 'course':
806 case 'module':
807 return new blog_filter_context($id, $type);
808 break;
809
810 case 'group':
811 case 'user':
812 return new blog_filter_user($id, $type);
813 break;
814
815 case 'tag':
816 return new blog_filter_tag($id);
817 break;
818
819 default:
1c7b8b93
NC
820 $classname = "blog_filter_$type";
821 if (class_exists($classname)) {
822 return new $classname($id, $type);
cae83708 823 }
824 }
825 }
826}
827
828/**
829 * This filter defines the context level of the blog entries being searched: site, course, module
830 */
831class blog_filter_context extends blog_filter {
832 /**
833 * Constructor
834 *
835 * @param string $type
836 * @param int $id
837 */
838 public function __construct($id=null, $type='site') {
839 global $SITE, $CFG, $DB;
840
841 if (empty($id)) {
842 $this->type = 'site';
843 } else {
844 $this->id = $id;
845 $this->type = $type;
846 }
847
8eaf1ba1 848 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
cae83708 849
850 switch ($this->type) {
851 case 'course': // Careful of site course!
852 // Ignore course filter if blog associations are not enabled
853 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
854 $this->overrides = array('site');
41b38360 855 $context = context_course::instance($this->id);
cae83708 856 $this->tables['ba'] = 'blog_association';
1c7b8b93 857 $this->conditions[] = 'p.id = ba.blogid';
cae83708 858 $this->conditions[] = 'ba.contextid = '.$context->id;
859 break;
860 } else {
861 // We are dealing with the site course, do not break from the current case
862 }
863
864 case 'site':
865 // No special constraints
866 break;
867 case 'module':
868 if (!empty($CFG->useblogassociations)) {
869 $this->overrides = array('course', 'site');
870
41b38360 871 $context = context_module::instance($this->id);
cae83708 872 $this->tables['ba'] = 'blog_association';
1c7b8b93
NC
873 $this->tables['p'] = 'post';
874 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
cae83708 875 $this->params = array($context->id);
876 }
877 break;
878 }
879 }
880}
881
882/**
883 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
884 * It can be combined with a context filter in order to refine the search.
885 */
886class blog_filter_user extends blog_filter {
887 public $tables = array('u' => 'user');
888
889 /**
890 * Constructor
891 *
892 * @param string $type
893 * @param int $id
894 */
895 public function __construct($id=null, $type='user') {
320ae23a 896 global $CFG, $DB, $USER;
1c7b8b93 897 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
cae83708 898
899 if (empty($id)) {
900 $this->id = $USER->id;
901 $this->type = 'user';
902 } else {
903 $this->id = $id;
904 $this->type = $type;
905 }
906
907 if ($this->type == 'user') {
908 $this->conditions = array('u.id = ?');
909 $this->params = array($this->id);
910 $this->overrides = array('group');
911
912 } elseif ($this->type == 'group') {
913 $this->overrides = array('course', 'site');
914
915 $this->tables['gm'] = 'groups_members';
1c7b8b93 916 $this->conditions[] = 'p.userid = gm.userid';
cae83708 917 $this->conditions[] = 'gm.groupid = ?';
918 $this->params[] = $this->id;
919
920 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
41b38360 921 $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id)));
cae83708 922 $this->tables['ba'] = 'blog_association';
923 $this->conditions[] = 'gm.groupid = ?';
924 $this->conditions[] = 'ba.contextid = ?';
1c7b8b93 925 $this->conditions[] = 'ba.blogid = p.id';
cae83708 926 $this->params[] = $this->id;
1c7b8b93 927 $this->params[] = $coursecontext->id;
cae83708 928 }
929 }
b73d1ca4 930
cae83708 931 }
932}
933
934/**
935 * This filter defines a tag by which blog entries should be searched.
936 */
937class blog_filter_tag extends blog_filter {
1c7b8b93 938 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
cae83708 939
940 /**
941 * Constructor
942 *
943 * @return void
944 */
945 public function __construct($id) {
946 global $DB;
947 $this->id = $id;
948
949 $this->conditions = array('ti.tagid = t.id',
1c7b8b93
NC
950 "ti.itemtype = 'post'",
951 'ti.itemid = p.id',
cae83708 952 't.id = ?');
953 $this->params = array($this->id);
954 }
955}
956
957/**
958 * This filter defines a specific blog entry id.
959 */
960class blog_filter_entry extends blog_filter {
961 public $conditions = array('p.id = ?');
962 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
963
964 public function __construct($id) {
965 $this->id = $id;
966 $this->params[] = $this->id;
967 }
968}
969
1c7b8b93 970/**
caee6e6c 971 * This filter restricts the results to a time interval in seconds up to time()
1c7b8b93
NC
972 */
973class blog_filter_since extends blog_filter {
974 public function __construct($interval) {
975 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
caee6e6c
PS
976 $this->params[] = time() - $interval;
977 $this->params[] = time();
1c7b8b93
NC
978 }
979}
980
cae83708 981/**
982 * Filter used to perform full-text search on an entry's subject, summary and content
983 */
984class blog_filter_search extends blog_filter {
985
1c7b8b93 986 public function __construct($searchterm) {
cae83708 987 global $DB;
c014d57c
PS
988 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
989 ".$DB->sql_like('p.content', '?', false)." OR
990 ".$DB->sql_like('p.subject', '?', false).")");
1c7b8b93
NC
991 $this->params[] = "%$searchterm%";
992 $this->params[] = "%$searchterm%";
993 $this->params[] = "%$searchterm%";
cae83708 994 }
995}
2591c7ae
DM
996
997
998/**
999 * Renderable class to represent an entry attachment
1000 */
1001class blog_entry_attachment implements renderable {
1002
1003 public $filename;
1004 public $url;
1005 public $file;
1006
1007 /**
f8133217
DM
1008 * Gets the file data
1009 *
2591c7ae
DM
1010 * @param stored_file $file
1011 * @param int $entryid Attachment entry id
1012 */
1013 public function __construct($file, $entryid) {
1014
f8133217 1015 global $CFG;
2591c7ae
DM
1016
1017 $this->file = $file;
1018 $this->filename = $file->get_filename();\r
f8133217 1019 $this->url = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$entryid.'/'.$this->filename);\r
2591c7ae
DM
1020 }
1021
1022}