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