MDL-10910 Corrected two errors committed while fixing MDL-10870
[moodle-pu.git] / blog / lib.php
blobb77f8c1bd72c0bda843e9777f5fc06346cbf001b
1 <?php //$Id$
3 /**
4 * Library of functions and constants for blog
5 */
6 require_once($CFG->libdir .'/blocklib.php');
7 require_once($CFG->libdir .'/pagelib.php');
8 require_once($CFG->dirroot .'/blog/rsslib.php');
9 require_once($CFG->dirroot .'/blog/blogpage.php');
12 /**
13 * Definition of blogcourse page type (blog page with course id present).
15 //not used at the moment, and may not need to be
16 define('PAGE_BLOG_COURSE_VIEW', 'blog_course-view');
19 /**
20 * Checks to see if user has visited blogpages before, if not, install 2
21 * default blocks (blog_menu and blog_tags).
23 function blog_check_and_install_blocks() {
24 global $USER;
25 if (isloggedin() && !isguest()) {
26 // if this user has not visited this page before
27 if (!get_user_preferences('blogpagesize')) {
28 // find the correct ids for blog_menu and blog_from blocks
29 $menublock = get_record('block','name','blog_menu');
30 $tagsblock = get_record('block','name','blog_tags');
31 // add those 2 into block_instance page
33 // add blog_menu block
34 $newblock = new object();
35 $newblock->blockid = $menublock->id;
36 $newblock->pageid = $USER->id;
37 $newblock->pagetype = 'blog-view';
38 $newblock->position = 'r';
39 $newblock->weight = 0;
40 $newblock->visible = 1;
41 insert_record('block_instance', $newblock);
43 // add blog_tags menu
44 $newblock -> blockid = $tagsblock->id;
45 $newblock -> weight = 1;
46 insert_record('block_instance', $newblock);
48 // finally we set the page size pref
49 set_user_preference('blogpagesize', 10);
55 /**
56 * Adaptation of isediting in moodlelib.php for blog module
57 * @return bool
59 function blog_isediting() {
60 global $SESSION;
62 return !empty($SESSION->blog_editing_enabled);
66 /**
67 * This function is in lib and not in BlogInfo because entries being searched
68 * might be found in any number of blogs rather than just one.
70 * $@param ...
72 function blog_print_html_formatted_entries($postid, $filtertype, $filterselect, $tagid, $tag) {
74 global $CFG, $USER;
76 $blogpage = optional_param('blogpage', 0, PARAM_INT);
77 $bloglimit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
78 $start = $blogpage * $bloglimit;
80 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
82 $morelink = '<br />&nbsp;&nbsp;';
84 $totalentries = get_viewable_entry_count($postid, $bloglimit, $start, $filtertype, $filterselect, $tagid, $tag, $sort='lastmodified DESC');
85 $blogEntries = fetch_entries($postid, $bloglimit, $start, $filtertype, $filterselect, $tagid, $tag, $sort='lastmodified DESC', true);
87 print_paging_bar($totalentries, $blogpage, $bloglimit, get_baseurl($filtertype, $filterselect), 'blogpage');
89 if ($CFG->enablerssfeeds) {
90 blog_rss_print_link($filtertype, $filterselect, $tag);
93 if (has_capability('moodle/blog:create', $sitecontext)) {
94 //the user's blog is enabled and they are viewing their own blog
95 $addlink = '<div class="addbloglink">';
96 $addlink .= '<a href="'.$CFG->wwwroot .'/blog/edit.php?action=add'.'">'. get_string('addnewentry', 'blog').'</a>';
97 $addlink .= '</div>';
98 echo $addlink;
101 if ($blogEntries) {
103 $count = 0;
104 foreach ($blogEntries as $blogEntry) {
105 blog_print_entry($blogEntry, 'list', $filtertype, $filterselect); //print this entry.
106 $count++;
109 print_paging_bar($totalentries, $blogpage, $bloglimit, get_baseurl($filtertype, $filterselect), 'blogpage');
111 if (!$count) {
112 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
116 print $morelink.'<br />'."\n";
117 return;
120 $output = '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
122 print $output;
128 * This function is in lib and not in BlogInfo because entries being searched
129 * might be found in any number of blogs rather than just one.
131 * This function builds an array which can be used by the included
132 * template file, making predefined and nicely formatted variables available
133 * to the template. Template creators will not need to become intimate
134 * with the internal objects and vars of moodle blog nor will they need to worry
135 * about properly formatting their data
137 * @param BlogEntry blogEntry - a hopefully fully populated BlogEntry object
138 * @param string viewtype Default is 'full'. If 'full' then display this blog entry
139 * in its complete form (eg. archive page). If anything other than 'full'
140 * display the entry in its abbreviated format (eg. index page)
142 function blog_print_entry($blogEntry, $viewtype='full', $filtertype='', $filterselect='', $mode='loud') {
144 global $USER, $CFG, $COURSE, $ME;
146 $template['body'] = format_text($blogEntry->summary, $blogEntry->format);
147 //$template['title'] = '<a name="'. $blogEntry->subject .'"></a>';
148 //enclose the title in nolink tags so that moodle formatting doesn't autolink the text
149 $template['title'] = '<span class="nolink">'.$blogEntry->subject.'</span>';
150 $template['userid'] = $blogEntry->userid;
151 $template['author'] = fullname(get_record('user','id',$blogEntry->userid));
152 $template['lastmod'] = userdate($blogEntry->lastmodified);
153 $template['created'] = userdate($blogEntry->created);
154 $template['publishstate'] = $blogEntry->publishstate;
156 /// preventing user to browse blogs that they aren't supposed to see
157 /// This might not be too good since there are multiple calls per page
160 if (!blog_user_can_view_user_post($template['userid'])) {
161 error ('you can not view this post');
164 $stredit = get_string('edit');
165 $strdelete = get_string('delete');
167 $user = get_record('user','id',$template['userid']);
169 /// Start printing of the blog
171 echo '<table cellspacing="0" class="forumpost blogpost blog'.$template['publishstate'].'" width="100%">';
173 echo '<tr class="header"><td class="picture left">';
174 print_user_picture($template['userid'], SITEID, $user->picture);
175 echo '</td>';
177 echo '<td class="topic starter"><div class="subject">'.$template['title'].'</div><div class="author">';
178 $fullname = fullname($user, $template['userid']);
179 $by = new object();
180 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.
181 $user->id.'&amp;course='.$COURSE->id.'">'.$fullname.'</a>';
182 $by->date = $template['lastmod'];
183 print_string('bynameondate', 'forum', $by);
184 echo '</div></td></tr>';
186 echo '<tr><td class="left side">';
188 /// Actual content
190 echo '</td><td class="content">'."\n";
192 if ($blogEntry->attachment) {
193 echo '<div class="attachments">';
194 $attachedimages = blog_print_attachments($blogEntry);
195 echo '</div>';
196 } else {
197 $attachedimages = '';
200 switch ($template['publishstate']) {
201 case 'draft':
202 $blogtype = get_string('publishtonoone', 'blog');
203 break;
204 case 'site':
205 $blogtype = get_string('publishtosite', 'blog');
206 break;
207 case 'public':
208 $blogtype = get_string('publishtoworld', 'blog');
209 break;
210 default:
211 $blogtype = '';
212 break;
216 echo '<div class="audience">'.$blogtype.'</div>';
218 // Print whole message
219 echo format_text($template['body']);
221 /// Print attachments
222 echo $attachedimages;
223 /// Links to tags
225 if ($blogtags = get_records_sql('SELECT t.* FROM '.$CFG->prefix.'tags t, '.$CFG->prefix.'blog_tag_instance ti
226 WHERE t.id = ti.tagid
227 AND ti.entryid = '.$blogEntry->id)) {
228 echo '<div class="tags">';
229 if ($blogtags) {
230 print_string('tags');
231 echo ': ';
232 foreach ($blogtags as $key => $blogtag) {
233 $taglist[] = '<a href="index.php?filtertype='.$filtertype.'&amp;filterselect='.$filterselect.'&amp;tagid='.$blogtag->id.'">'.$blogtag->text.'</a>';
235 echo implode(', ', $taglist);
237 echo '</div>';
240 /// Commands
242 echo '<div class="commands">';
244 if (blog_user_can_edit_post($blogEntry)) {
245 echo '<a href="'.$CFG->wwwroot.'/blog/edit.php?action=edit&amp;id='.$blogEntry->id.'">'.$stredit.'</a>';
246 echo '| <a href="'.$CFG->wwwroot.'/blog/edit.php?action=delete&amp;id='.$blogEntry->id.'">'.$strdelete.'</a>';
249 echo '</div>';
251 echo '</td></tr></table>'."\n\n";
255 function blog_file_area_name($blogentry) {
256 // Creates a directory file name, suitable for make_upload_directory()
257 global $CFG;
258 // $CFG->dataroot/blog/attachments/xxxx/file.jpg
259 return "blog/attachments/$blogentry->id";
262 function blog_file_area($blogentry) {
263 return make_upload_directory( blog_file_area_name($blogentry) );
266 function blog_delete_old_attachments($post, $exception="") {
267 // Deletes all the user files in the attachments area for a post
268 // EXCEPT for any file named $exception
270 if ($basedir = blog_file_area($post)) {
271 if ($files = get_directory_list($basedir)) {
272 foreach ($files as $file) {
273 if ($file != $exception) {
274 unlink("$basedir/$file");
275 notify("Existing file '$file' has been deleted!");
279 if (!$exception) { // Delete directory as well, if empty
280 rmdir("$basedir");
285 function blog_print_attachments($blogentry, $return=NULL) {
286 // if return=html, then return a html string.
287 // if return=text, then return a text-only string.
288 // otherwise, print HTML for non-images, and return image HTML
290 global $CFG;
292 $filearea = blog_file_area_name($blogentry);
294 $imagereturn = "";
295 $output = "";
297 if ($basedir = blog_file_area($blogentry)) {
298 if ($files = get_directory_list($basedir)) {
299 $strattachment = get_string("attachment", "forum");
300 foreach ($files as $file) {
301 include_once($CFG->libdir.'/filelib.php');
302 $icon = mimeinfo("icon", $file);
303 $type = mimeinfo("type", $file);
304 if ($CFG->slasharguments) {
305 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
306 } else {
307 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
309 $image = "<img src=\"$CFG->pixpath/f/$icon\" class=\"icon\" alt=\"\" />";
311 if ($return == "html") {
312 $output .= "<a href=\"$ffurl\">$image</a> ";
313 $output .= "<a href=\"$ffurl\">$file</a><br />";
315 } else if ($return == "text") {
316 $output .= "$strattachment $file:\n$ffurl\n";
318 } else {
319 if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) { // Image attachments don't get printed as links
320 $imagereturn .= "<br /><img src=\"$ffurl\" alt=\"\" />";
321 } else {
322 echo "<a href=\"$ffurl\">$image</a> ";
323 echo filter_text("<a href=\"$ffurl\">$file</a><br />");
330 if ($return) {
331 return $output;
334 return $imagereturn;
339 * Use this function to retrieve a list of publish states available for
340 * the currently logged in user.
342 * @return array This function returns an array ideal for sending to moodles'
343 * choose_from_menu function.
345 function blog_applicable_publish_states($courseid='') {
347 global $CFG;
349 // everyone gets draft access
350 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
351 $options = array ( 'draft' => get_string('publishtonoone', 'blog') );
354 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
355 $options['site'] = get_string('publishtosite', 'blog');
358 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
359 $options['public'] = get_string('publishtoworld', 'blog');
362 return $options;
367 * User can edit a blog entry if this is their own blog post and they have
368 * the capability moodle/blog:create, or if they have the capability
369 * moodle/blog:manageentries.
371 * This also applies to deleting of posts.
373 function blog_user_can_edit_post($blogEntry) {
375 global $CFG, $USER;
377 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
379 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
380 return true; // can edit any blog post
383 if ($blogEntry->userid == $USER->id
384 and has_capability('moodle/blog:create', $sitecontext)) {
385 return true; // can edit own when having blog:create capability
388 return false;
393 * Checks to see if a user can view the blogs of another user.
394 * Only blog level is checked here, the capabilities are enforced
395 * in blog/index.php
397 function blog_user_can_view_user_post($targetuserid, $blogEntry=null) {
398 global $CFG, $USER;
400 if (empty($CFG->bloglevel)) {
401 return false; // blog system disabled
404 if (!empty($USER->id) and $USER->id == $targetuserid) {
405 return true; // can view own posts in any case
408 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
409 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
410 return true; // can manage all posts
413 // coming for 1 post, make sure it's not a draft
414 if ($blogEntry and $blogEntry->publishstate == 'draft') {
415 return false; // can not view draft of others
418 // coming for 1 post, make sure user is logged in, if not a public blog
419 if ($blogEntry && $blogEntry->publishstate != 'public' && !isloggedin()) {
420 return false;
423 switch ($CFG->bloglevel) {
424 case BLOG_GLOBAL_LEVEL:
425 return true;
426 break;
428 case BLOG_SITE_LEVEL:
429 if (!empty($USER->id)) { // not logged in viewers forbidden
430 return true;
432 return false;
433 break;
435 case BLOG_COURSE_LEVEL:
436 $mycourses = array_keys(get_my_courses($USER->id));
437 $usercourses = array_keys(get_my_courses($targetuserid));
438 $shared = array_intersect($mycourses, $usercourses);
439 if (!empty($shared)) {
440 return true;
442 return false;
443 break;
445 case BLOG_GROUP_LEVEL:
446 $mycourses = array_keys(get_my_courses($USER->id));
447 $usercourses = array_keys(get_my_courses($targetuserid));
448 $shared = array_intersect($mycourses, $usercourses);
449 foreach ($shared as $courseid) {
450 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
451 if (has_capability('moodle/site:accessallgroups', $coursecontext)
452 or groupmode($courseid) != SEPARATEGROUPS) {
453 return true;
454 } else {
455 if ($usergroups = groups_get_all_groups($courseid, $targetuserid)) {
456 foreach ($usergroups as $usergroup) {
457 if (groups_is_member($usergroup->id)) {
458 return true;
464 return false;
465 break;
467 case BLOG_USER_LEVEL:
468 default:
469 $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
470 return has_capability('moodle/user:readuserblogs', $personalcontext);
471 break;
478 * Main filter function.
480 function fetch_entries($postid='', $fetchlimit=10, $fetchstart='', $filtertype='', $filterselect='', $tagid='', $tag ='', $sort='lastmodified DESC', $limit=true) {
482 global $CFG, $USER;
484 /// the post table will be used for other things too
485 $typesql = " AND p.module = 'blog' ";
487 /// set the tag id for searching
488 if ($tagid) {
489 $tag = $tagid;
490 } else if ($tag) {
491 if ($tagrec = get_record_sql('SELECT * FROM '.$CFG->prefix.'tags WHERE text LIKE "'.$tag.'"')) {
492 $tag = $tagrec->id;
493 } else {
494 $tag = -1; //no records found
498 // If we have specified an ID
499 // Just return 1 entry
501 if ($postid) {
503 if ($post = get_record('post', 'id', $postid)) {
505 if (blog_user_can_view_user_post($post->userid, $post)) {
507 if ($user = get_record('user', 'id', $post->userid)) {
508 $post->email = $user->email;
509 $post->firstname = $user->firstname;
510 $post->lastname = $user->lastname;
512 $retarray[] = $post;
513 return $retarray;
514 } else {
515 return null;
518 } else { // bad postid
519 return null;
523 if ($tag) {
524 $tagtablesql = $CFG->prefix.'blog_tag_instance bt, ';
525 $tagquerysql = ' AND bt.entryid = p.id AND bt.tagid = '.$tag.' ';
526 } else {
527 $tagtablesql = '';
528 $tagquerysql = '';
531 if (isloggedin() && !has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM, SITEID), $USER->id, false)) {
532 $permissionsql = 'AND (p.publishstate = \'site\' OR p.publishstate = \'public\' OR p.userid = '.$USER->id.')';
533 } else {
534 $permissionsql = 'AND p.publishstate = \'public\'';
537 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
538 // admins can see all blogs regardless of publish states, as described on the help page
539 if (has_capability('moodle/user:readuserblogs', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
540 $permissionsql = '';
541 } else if ($filtertype=='user' && has_capability('moodle/user:readuserblogs', get_context_instance(CONTEXT_USER, $filterselect))) {
542 $permissionsql = '';
544 /****************************************
545 * depending on the type, there are 4 *
546 * different possible sqls *
547 ****************************************/
549 $requiredfields = 'p.*, u.firstname,u.lastname,u.email';
551 if ($filtertype == 'course' && $filterselect == SITEID) { // Really a site
552 $filtertype = 'site';
555 switch ($filtertype) {
557 case 'site':
559 $SQL = 'SELECT '.$requiredfields.' FROM '.$CFG->prefix.'post p, '.$tagtablesql
560 .$CFG->prefix.'user u
561 WHERE p.userid = u.id '.$tagquerysql.'
562 AND u.deleted = 0
563 '.$permissionsql.$typesql;
565 break;
567 case 'course':
568 // all users with a role assigned
569 $context = get_context_instance(CONTEXT_COURSE, $filterselect);
571 // MDL-10037, hidden users' blogs should not appear
572 if (has_capability('moodle/role:viewhiddenassigns', $context)) {
573 $hiddensql = '';
574 } else {
575 $hiddensql = ' AND ra.hidden = 0 ';
578 $SQL = 'SELECT '.$requiredfields.' FROM '.$CFG->prefix.'post p, '.$tagtablesql
579 .$CFG->prefix.'role_assignments ra, '.$CFG->prefix.'user u
580 WHERE p.userid = ra.userid '.$tagquerysql.'
581 AND ra.contextid '.get_related_contexts_string($context).'
582 AND u.id = p.userid
583 AND u.deleted = 0
584 '.$hiddensql.$permissionsql.$typesql;
586 break;
588 case 'group':
590 $SQL = 'SELECT '.$requiredfields.' FROM '.$CFG->prefix.'post p, '.$tagtablesql
591 .$CFG->prefix.'groups_members gm, '.$CFG->prefix.'user u
592 WHERE p.userid =g m.userid AND u.id = p.userid
593 AND gm.groupid = '.$filterselect.'
594 AND u.deleted = 0
595 '.$permissionsql.$typesql;
596 break;
598 case 'user':
600 $SQL = 'SELECT '.$requiredfields.' FROM '.$CFG->prefix.'post p, '.$tagtablesql
601 .$CFG->prefix.'user u
602 WHERE p.userid = u.id '.$tagquerysql.'
603 AND u.id = '.$filterselect.'
604 AND u.deleted = 0
605 '.$permissionsql.$typesql;
606 break;
609 $limitfrom = 0;
610 $limitnum = 0;
612 if ($fetchstart !== '' && $limit) {
613 $limitfrom = $fetchstart;
614 $limitnum = $fetchlimit;
617 $orderby = ' ORDER BY '. $sort .' ';
619 //global $db; $db->debug = true;
620 $records = get_records_sql($SQL . $orderby, $limitfrom, $limitnum);
621 //$db->debug = false;
623 if (empty($records)) {
624 return array();
627 return $records;
632 * get the count of viewable entries, easiest way is to count fetch_entries
633 * this is used for print_paging_bar
634 * this is not ideal, but because of the UNION in the sql in fetch_entries,
635 * it is hard to use count_records_sql
637 function get_viewable_entry_count($postid='', $fetchlimit=10,
638 $fetchstart='', $filtertype='', $filterselect='', $tagid='',
639 $tag ='', $sort='lastmodified DESC') {
641 $blogEntries = fetch_entries($postid, $fetchlimit,
642 $fetchstart, $filtertype, $filterselect, $tagid, $tag,
643 $sort='lastmodified DESC', false);
645 return count($blogEntries);
649 /// Find the base url from $_GET variables, for print_paging_bar
650 function get_baseurl($filtertype, $filterselect) {
652 $getcopy = $_GET;
654 unset($getcopy['blogpage']);
656 $strippedurl = strip_querystring(qualified_me());
657 if(!empty($getcopy)) {
658 $first = false;
659 $querystring = '';
660 foreach($getcopy as $var => $val) {
661 if(!$first) {
662 $first = true;
663 if ($var != 'filterselect' && $var != 'filtertype') {
664 $querystring .= '?'.$var.'='.$val;
665 $hasparam = true;
666 } else {
667 $querystring .= '?';
669 } else {
670 if ($var != 'filterselect' && $var != 'filtertype') {
671 $querystring .= '&amp;'.$var.'='.$val;
672 $hasparam = true;
676 if (isset($hasparam)) {
677 $querystring .= '&amp;';
678 } else {
679 $querystring = '?';
681 } else {
682 $querystring = '?';
685 return strip_querystring(qualified_me()) . $querystring. 'filtertype='.
686 $filtertype.'&amp;filterselect='.$filterselect.'&amp;';