Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • /blog/ -> lib.php (source)

    Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

       1  <?php
       2  // This file is part of Moodle - http://moodle.org/
       3  //
       4  // Moodle is free software: you can redistribute it and/or modify
       5  // it under the terms of the GNU General Public License as published by
       6  // the Free Software Foundation, either version 3 of the License, or
       7  // (at your option) any later version.
       8  //
       9  // Moodle is distributed in the hope that it will be useful,
      10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
      11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12  // GNU General Public License for more details.
      13  //
      14  // You should have received a copy of the GNU General Public License
      15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
      16  
      17  /**
      18   * Core global functions for Blog.
      19   *
      20   * @package    moodlecore
      21   * @subpackage blog
      22   * @copyright  2009 Nicolas Connault
      23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      24   */
      25  
      26  defined('MOODLE_INTERNAL') || die();
      27  
      28  /*
      29   * Library of functions and constants for blog
      30   */
      31  require_once($CFG->dirroot .'/blog/rsslib.php');
      32  require_once($CFG->dirroot.'/tag/lib.php');
      33  
      34  /**
      35   * User can edit a blog entry if this is their own blog entry and they have
      36   * the capability moodle/blog:create, or if they have the capability
      37   * moodle/blog:manageentries.
      38   *
      39   * This also applies to deleting of entries.
      40   */
      41  function blog_user_can_edit_entry($blogentry) {
      42      global $USER;
      43  
      44      $sitecontext = context_system::instance();
      45  
      46      if (has_capability('moodle/blog:manageentries', $sitecontext)) {
      47          return true; // Can edit any blog entry.
      48      }
      49  
      50      if ($blogentry->userid == $USER->id && has_capability('moodle/blog:create', $sitecontext)) {
      51          return true; // Can edit own when having blog:create capability.
      52      }
      53  
      54      return false;
      55  }
      56  
      57  
      58  /**
      59   * Checks to see if a user can view the blogs of another user.
      60   * Only blog level is checked here, the capabilities are enforced
      61   * in blog/index.php
      62   */
      63  function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
      64      global $CFG, $USER, $DB;
      65  
      66      if (empty($CFG->enableblogs)) {
      67          return false; // Blog system disabled.
      68      }
      69  
      70      if (isloggedin() && $USER->id == $targetuserid) {
      71          return true; // Can view own entries in any case.
      72      }
      73  
      74      $sitecontext = context_system::instance();
      75      if (has_capability('moodle/blog:manageentries', $sitecontext)) {
      76          return true; // Can manage all entries.
      77      }
      78  
      79      // If blog is in draft state, then make sure user have proper capability.
      80      if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
      81          return false;  // Can not view draft of others.
      82      }
      83  
      84      // If blog entry is not public, make sure user is logged in.
      85      if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
      86          return false;
      87      }
      88  
      89      // If blogentry is not passed or all above checks pass, then check capability based on system config.
      90      switch ($CFG->bloglevel) {
      91          case BLOG_GLOBAL_LEVEL:
      92              return true;
      93          break;
      94  
      95          case BLOG_SITE_LEVEL:
      96              if (isloggedin()) { // Not logged in viewers forbidden.
      97                  return true;
      98              }
      99              return false;
     100          break;
     101  
     102          case BLOG_USER_LEVEL:
     103          default:
     104              // If user is viewing other user blog, then user should have user:readuserblogs capability.
     105              $personalcontext = context_user::instance($targetuserid);
     106              return has_capability('moodle/user:readuserblogs', $personalcontext);
     107          break;
     108  
     109      }
     110  }
     111  
     112  /**
     113   * remove all associations for the blog entries of a particular user
     114   * @param int userid - id of user whose blog associations will be deleted
     115   */
     116  function blog_remove_associations_for_user($userid) {
     117      global $DB;
     118      throw new coding_exception('function blog_remove_associations_for_user() is not finished');
     119      /*
     120      $blogentries = blog_fetch_entries(array('user' => $userid), 'lasmodified DESC');
     121      foreach ($blogentries as $entry) {
     122          if (blog_user_can_edit_entry($entry)) {
     123              blog_remove_associations_for_entry($entry->id);
     124          }
     125      }
     126       */
     127  }
     128  
     129  /**
     130   * remove all associations for the blog entries of a particular course
     131   * @param int courseid - id of user whose blog associations will be deleted
     132   */
     133  function blog_remove_associations_for_course($courseid) {
     134      global $DB;
     135      $context = context_course::instance($courseid);
     136      $DB->delete_records('blog_association', array('contextid' => $context->id));
     137  }
     138  
     139  /**
     140   * Given a record in the {blog_external} table, checks the blog's URL
     141   * for new entries not yet copied into Moodle.
     142   * Also attempts to identify and remove deleted blog entries
     143   *
     144   * @param object $externalblog
     145   * @return boolean False if the Feed is invalid
     146   */
     147  function blog_sync_external_entries($externalblog) {
     148      global $CFG, $DB;
     149      require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
     150  
     151      $rss = new moodle_simplepie();
     152      $rssfile = $rss->registry->create('File', array($externalblog->url));
     153      $filetest = $rss->registry->create('Locator', array($rssfile));
     154  
     155      if (!$filetest->is_feed($rssfile)) {
     156          $externalblog->failedlastsync = 1;
     157          $DB->update_record('blog_external', $externalblog);
     158          return false;
     159      } else if (!empty($externalblog->failedlastsync)) {
     160          $externalblog->failedlastsync = 0;
     161          $DB->update_record('blog_external', $externalblog);
     162      }
     163  
     164      $rss->set_feed_url($externalblog->url);
     165      $rss->init();
     166  
     167      if (empty($rss->data)) {
     168          return null;
     169      }
     170      // Used to identify blog posts that have been deleted from the source feed.
     171      $oldesttimestamp = null;
     172      $uniquehashes = array();
     173  
     174      foreach ($rss->get_items() as $entry) {
     175          // If filtertags are defined, use them to filter the entries by RSS category.
     176          if (!empty($externalblog->filtertags)) {
     177              $containsfiltertag = false;
     178              $categories = $entry->get_categories();
     179              $filtertags = explode(',', $externalblog->filtertags);
     180              $filtertags = array_map('trim', $filtertags);
     181              $filtertags = array_map('strtolower', $filtertags);
     182  
     183              if (!empty($categories)) {
     184                  foreach ($categories as $category) {
     185                      if (in_array(trim(strtolower($category->term)), $filtertags)) {
     186                          $containsfiltertag = true;
     187                      }
     188                  }
     189              }
     190  
     191              if (!$containsfiltertag) {
     192                  continue;
     193              }
     194          }
     195  
     196          $uniquehashes[] = $entry->get_permalink();
     197  
     198          $newentry = new stdClass();
     199          $newentry->userid = $externalblog->userid;
     200          $newentry->module = 'blog_external';
     201          $newentry->content = $externalblog->id;
     202          $newentry->uniquehash = $entry->get_permalink();
     203          $newentry->publishstate = 'site';
     204          $newentry->format = FORMAT_HTML;
     205          // Clean subject of html, just in case.
     206          $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
     207          // Observe 128 max chars in DB.
     208          // TODO: +1 to raise this to 255.
     209          if (core_text::strlen($newentry->subject) > 128) {
     210              $newentry->subject = core_text::substr($newentry->subject, 0, 125) . '...';
     211          }
     212          $newentry->summary = $entry->get_description();
     213  
     214          // Used to decide whether to insert or update.
     215          // Uses enty permalink plus creation date if available.
     216          $existingpostconditions = array('uniquehash' => $entry->get_permalink());
     217  
     218          // Our DB doesnt allow null creation or modified timestamps so check the external blog supplied one.
     219          $entrydate = $entry->get_date('U');
     220          if (!empty($entrydate)) {
     221              $existingpostconditions['created'] = $entrydate;
     222          }
     223  
     224          // The post ID or false if post not found in DB.
     225          $postid = $DB->get_field('post', 'id', $existingpostconditions);
     226  
     227          $timestamp = null;
     228          if (empty($entrydate)) {
     229              $timestamp = time();
     230          } else {
     231              $timestamp = $entrydate;
     232          }
     233  
     234          // Only set created if its a new post so we retain the original creation timestamp if the post is edited.
     235          if ($postid === false) {
     236              $newentry->created = $timestamp;
     237          }
     238          $newentry->lastmodified = $timestamp;
     239  
     240          if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
     241              // Found an older post.
     242              $oldesttimestamp = $timestamp;
     243          }
     244  
     245          if (core_text::strlen($newentry->uniquehash) > 255) {
     246              // The URL for this item is too long for the field. Rather than add
     247              // the entry without the link we will skip straight over it.
     248              // RSS spec says recommended length 500, we use 255.
     249              debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
     250              continue;
     251          }
     252  
     253          if ($postid === false) {
     254              $id = $DB->insert_record('post', $newentry);
     255  
     256              // Set tags.
     257              if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
     258                  tag_set('post', $id, $tags, 'core', context_user::instance($externalblog->userid)->id);
     259              }
     260          } else {
     261              $newentry->id = $postid;
     262              $DB->update_record('post', $newentry);
     263          }
     264      }
     265  
     266      // Look at the posts we have in the database to check if any of them have been deleted from the feed.
     267      // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
     268      // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
     269      $sql = "SELECT id, uniquehash
     270                FROM {post}
     271               WHERE module = 'blog_external'
     272                     AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
     273                     AND created > :ts";
     274      $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
     275  
     276      $todelete = array();
     277      foreach ($dbposts as $dbpost) {
     278          if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
     279              $todelete[] = $dbpost->id;
     280          }
     281      }
     282      $DB->delete_records_list('post', 'id', $todelete);
     283  
     284      $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
     285  }
     286  
     287  /**
     288   * Given an external blog object, deletes all related blog entries from the post table.
     289   * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
     290   * @param object $externablog
     291   */
     292  function blog_delete_external_entries($externalblog) {
     293      global $DB;
     294      require_capability('moodle/blog:manageexternal', context_system::instance());
     295      $DB->delete_records_select('post',
     296                                 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
     297                                 array($externalblog->id));
     298  }
     299  
     300  /**
     301   * This function checks that blogs are enabled, and that the user can see blogs at all
     302   * @return bool
     303   */
     304  function blog_is_enabled_for_user() {
     305      global $CFG;
     306      return (!empty($CFG->enableblogs) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
     307  }
     308  
     309  /**
     310   * This function gets all of the options available for the current user in respect
     311   * to blogs.
     312   *
     313   * It loads the following if applicable:
     314   * -  Module options {@see blog_get_options_for_module}
     315   * -  Course options {@see blog_get_options_for_course}
     316   * -  User specific options {@see blog_get_options_for_user}
     317   * -  General options (BLOG_LEVEL_GLOBAL)
     318   *
     319   * @param moodle_page $page The page to load for (normally $PAGE)
     320   * @param stdClass $userid Load for a specific user
     321   * @return array An array of options organised by type.
     322   */
     323  function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
     324      global $CFG, $DB, $USER;
     325  
     326      $options = array();
     327  
     328      // If blogs are enabled and the user is logged in and not a guest.
     329      if (blog_is_enabled_for_user()) {
     330          // If the context is the user then assume we want to load for the users context.
     331          if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
     332              $userid = $page->context->instanceid;
     333          }
     334          // Check the userid var.
     335          if (!is_null($userid) && $userid!==$USER->id) {
     336              // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
     337              $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
     338          } else {
     339              $user = null;
     340          }
     341  
     342          if ($CFG->useblogassociations && $page->cm !== null) {
     343              // Load for the module associated with the page.
     344              $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
     345          } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
     346              // Load the options for the course associated with the page.
     347              $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
     348          }
     349  
     350          // Get the options for the user.
     351          if ($user !== null and !isguestuser($user)) {
     352              // Load for the requested user.
     353              $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
     354          }
     355          // Load for the current user.
     356          if (isloggedin() and !isguestuser()) {
     357              $options[CONTEXT_USER] = blog_get_options_for_user();
     358          }
     359      }
     360  
     361      // If blog level is global then display a link to view all site entries.
     362      if (!empty($CFG->enableblogs)
     363          && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL
     364          && has_capability('moodle/blog:view', context_system::instance())) {
     365  
     366          $options[CONTEXT_SYSTEM] = array('viewsite' => array(
     367              'string' => get_string('viewsiteentries', 'blog'),
     368              'link' => new moodle_url('/blog/index.php')
     369          ));
     370      }
     371  
     372      // Return the options.
     373      return $options;
     374  }
     375  
     376  /**
     377   * Get all of the blog options that relate to the passed user.
     378   *
     379   * If no user is passed the current user is assumed.
     380   *
     381   * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
     382   * @param stdClass $user
     383   * @return array The array of options for the requested user
     384   */
     385  function blog_get_options_for_user(stdClass $user=null) {
     386      global $CFG, $USER;
     387      // Cache.
     388      static $useroptions = array();
     389  
     390      $options = array();
     391      // Blogs must be enabled and the user must be logged in.
     392      if (!blog_is_enabled_for_user()) {
     393          return $options;
     394      }
     395  
     396      // Sort out the user var.
     397      if ($user === null || $user->id == $USER->id) {
     398          $user = $USER;
     399          $iscurrentuser = true;
     400      } else {
     401          $iscurrentuser = false;
     402      }
     403  
     404      // If we've already generated serve from the cache.
     405      if (array_key_exists($user->id, $useroptions)) {
     406          return $useroptions[$user->id];
     407      }
     408  
     409      $sitecontext = context_system::instance();
     410      $canview = has_capability('moodle/blog:view', $sitecontext);
     411  
     412      if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
     413          // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL.
     414          $options['userentries'] = array(
     415              'string' => get_string('viewuserentries', 'blog', fullname($user)),
     416              'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
     417          );
     418      } else {
     419          // It's the current user.
     420          if ($canview) {
     421              // We can view our own blogs .... BIG surprise.
     422              $options['view'] = array(
     423                  'string' => get_string('viewallmyentries', 'blog'),
     424                  'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
     425              );
     426          }
     427          if (has_capability('moodle/blog:create', $sitecontext)) {
     428              // We can add to our own blog.
     429              $options['add'] = array(
     430                  'string' => get_string('addnewentry', 'blog'),
     431                  'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
     432              );
     433          }
     434      }
     435      if ($canview && $CFG->enablerssfeeds) {
     436          $options['rss'] = array(
     437              'string' => get_string('rssfeed', 'blog'),
     438              'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
     439          );
     440      }
     441  
     442      // Cache the options.
     443      $useroptions[$user->id] = $options;
     444      // Return the options.
     445      return $options;
     446  }
     447  
     448  /**
     449   * Get the blog options that relate to the given course for the given user.
     450   *
     451   * @staticvar array $courseoptions A cache so we can save regenerating multiple times
     452   * @param stdClass $course The course to load options for
     453   * @param stdClass $user The user to load options for null == current user
     454   * @return array The array of options
     455   */
     456  function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
     457      global $CFG, $USER;
     458      // Cache.
     459      static $courseoptions = array();
     460  
     461      $options = array();
     462  
     463      // User must be logged in and blogs must be enabled.
     464      if (!blog_is_enabled_for_user()) {
     465          return $options;
     466      }
     467  
     468      // Check that the user can associate with the course.
     469      $sitecontext = context_system::instance();
     470      // Generate the cache key.
     471      $key = $course->id.':';
     472      if (!empty($user)) {
     473          $key .= $user->id;
     474      } else {
     475          $key .= $USER->id;
     476      }
     477      // Serve from the cache if we've already generated for this course.
     478      if (array_key_exists($key, $courseoptions)) {
     479          return $courseoptions[$key];
     480      }
     481  
     482      if (has_capability('moodle/blog:view', $sitecontext)) {
     483          // We can view!
     484          if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
     485              // View entries about this course.
     486              $options['courseview'] = array(
     487                  'string' => get_string('viewcourseblogs', 'blog'),
     488                  'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id))
     489              );
     490          }
     491          // View MY entries about this course.
     492          $options['courseviewmine'] = array(
     493              'string' => get_string('viewmyentriesaboutcourse', 'blog'),
     494              'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $USER->id))
     495          );
     496          if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
     497              // View the provided users entries about this course.
     498              $options['courseviewuser'] = array(
     499                  'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
     500                  'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $user->id))
     501              );
     502          }
     503      }
     504  
     505      if (has_capability('moodle/blog:create', $sitecontext)) {
     506          // We can blog about this course.
     507          $options['courseadd'] = array(
     508              'string' => get_string('blogaboutthiscourse', 'blog'),
     509              'link' => new moodle_url('/blog/edit.php', array('action' => 'add', 'courseid' => $course->id))
     510          );
     511      }
     512  
     513      // Cache the options for this course.
     514      $courseoptions[$key] = $options;
     515      // Return the options.
     516      return $options;
     517  }
     518  
     519  /**
     520   * Get the blog options relating to the given module for the given user
     521   *
     522   * @staticvar array $moduleoptions Cache
     523   * @param stdClass|cm_info $module The module to get options for
     524   * @param stdClass $user The user to get options for null == currentuser
     525   * @return array
     526   */
     527  function blog_get_options_for_module($module, $user=null) {
     528      global $CFG, $USER;
     529      // Cache.
     530      static $moduleoptions = array();
     531  
     532      $options = array();
     533      // User must be logged in, blogs must be enabled.
     534      if (!blog_is_enabled_for_user()) {
     535          return $options;
     536      }
     537  
     538      $sitecontext = context_system::instance();
     539  
     540      // Generate the cache key.
     541      $key = $module->id.':';
     542      if (!empty($user)) {
     543          $key .= $user->id;
     544      } else {
     545          $key .= $USER->id;
     546      }
     547      if (array_key_exists($key, $moduleoptions)) {
     548          // Serve from the cache so we don't have to regenerate.
     549          return $moduleoptions[$key];
     550      }
     551  
     552      if (has_capability('moodle/blog:view', $sitecontext)) {
     553          // Save correct module name for later usage.
     554          $modulename = get_string('modulename', $module->modname);
     555  
     556          // We can view!
     557          if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
     558              // View all entries about this module.
     559              $a = new stdClass;
     560              $a->type = $modulename;
     561              $options['moduleview'] = array(
     562                  'string' => get_string('viewallmodentries', 'blog', $a),
     563                  'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
     564              );
     565          }
     566          // View MY entries about this module.
     567          $options['moduleviewmine'] = array(
     568              'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
     569              'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
     570          );
     571          if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
     572              // View the given users entries about this module.
     573              $a = new stdClass;
     574              $a->mod = $modulename;
     575              $a->user = fullname($user);
     576              $options['moduleviewuser'] = array(
     577                  'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
     578                  'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
     579              );
     580          }
     581      }
     582  
     583      if (has_capability('moodle/blog:create', $sitecontext)) {
     584          // The user can blog about this module.
     585          $options['moduleadd'] = array(
     586              'string' => get_string('blogaboutthismodule', 'blog', $modulename),
     587              'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
     588          );
     589      }
     590      // Cache the options.
     591      $moduleoptions[$key] = $options;
     592      // Return the options.
     593      return $options;
     594  }
     595  
     596  /**
     597   * This function encapsulates all the logic behind the complex
     598   * navigation, titles and headings of the blog listing page, depending
     599   * on URL params. It looks at URL params and at the current context level.
     600   * It builds and returns an array containing:
     601   *
     602   * 1. heading: The heading displayed above the blog entries
     603   * 2. stradd:  The text to be used as the "Add entry" link
     604   * 3. strview: The text to be used as the "View entries" link
     605   * 4. url:     The moodle_url object used as the base for add and view links
     606   * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
     607   *
     608   * All other variables are set directly in $PAGE
     609   *
     610   * It uses the current URL to build these variables.
     611   * A number of mutually exclusive use cases are used to structure this function.
     612   *
     613   * @return array
     614   */
     615  function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
     616      global $CFG, $PAGE, $DB, $USER;
     617  
     618      $id       = optional_param('id', null, PARAM_INT);
     619      $tag      = optional_param('tag', null, PARAM_NOTAGS);
     620      $tagid    = optional_param('tagid', $tagid, PARAM_INT);
     621      $userid   = optional_param('userid', $userid, PARAM_INT);
     622      $modid    = optional_param('modid', null, PARAM_INT);
     623      $entryid  = optional_param('entryid', null, PARAM_INT);
     624      $groupid  = optional_param('groupid', $groupid, PARAM_INT);
     625      $courseid = optional_param('courseid', $courseid, PARAM_INT);
     626      $search   = optional_param('search', null, PARAM_RAW);
     627      $action   = optional_param('action', null, PARAM_ALPHA);
     628      $confirm  = optional_param('confirm', false, PARAM_BOOL);
     629  
     630      // Ignore userid when action == add.
     631      if ($action == 'add' && $userid) {
     632          unset($userid);
     633          $PAGE->url->remove_params(array('userid'));
     634      } else if ($action == 'add' && $entryid) {
     635          unset($entryid);
     636          $PAGE->url->remove_params(array('entryid'));
     637      }
     638  
     639      $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
     640  
     641      $blogurl = new moodle_url('/blog/index.php');
     642  
     643      $headers['stradd'] = get_string('addnewentry', 'blog');
     644      $headers['strview'] = null;
     645  
     646      $site = $DB->get_record('course', array('id' => SITEID));
     647      $sitecontext = context_system::instance();
     648      // Common Lang strings.
     649      $strparticipants = get_string("participants");
     650      $strblogentries  = get_string("blogentries", 'blog');
     651  
     652      // Prepare record objects as needed.
     653      if (!empty($courseid)) {
     654          $headers['filters']['course'] = $courseid;
     655          $course = $DB->get_record('course', array('id' => $courseid));
     656      }
     657  
     658      if (!empty($userid)) {
     659          $headers['filters']['user'] = $userid;
     660          $user = $DB->get_record('user', array('id' => $userid));
     661      }
     662  
     663      if (!empty($groupid)) { // The groupid always overrides courseid.
     664          $headers['filters']['group'] = $groupid;
     665          $group = $DB->get_record('groups', array('id' => $groupid));
     666          $course = $DB->get_record('course', array('id' => $group->courseid));
     667      }
     668  
     669      $PAGE->set_pagelayout('standard');
     670  
     671      // The modid always overrides courseid, so the $course object may be reset here.
     672      if (!empty($modid) && $CFG->useblogassociations) {
     673  
     674          $headers['filters']['module'] = $modid;
     675          // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case.
     676          $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
     677          $course = $DB->get_record('course', array('id' => $courseid));
     678          $cm = $DB->get_record('course_modules', array('id' => $modid));
     679          $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
     680          $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
     681          $a = new stdClass();
     682          $a->type = get_string('modulename', $cm->modname);
     683          $PAGE->set_cm($cm, $course);
     684          $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
     685          $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
     686      }
     687  
     688      // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
     689      // Note: if action is set to 'add' or 'edit', we do this at the end.
     690      if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
     691          $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     692          $PAGE->navbar->add($strblogentries, $blogurl);
     693          $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
     694          $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
     695          $headers['heading'] = get_string('siteblog', 'blog', $shortname);
     696      }
     697  
     698      // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information.
     699      if (!empty($entryid)) {
     700          $headers['filters']['entry'] = $entryid;
     701          $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
     702          $user = $DB->get_record_sql($sql, array($entryid));
     703          $entry = $DB->get_record('post', array('id' => $entryid));
     704  
     705          $blogurl->param('userid', $user->id);
     706  
     707          if (!empty($course)) {
     708              $mycourseid = $course->id;
     709              $blogurl->param('courseid', $mycourseid);
     710          } else {
     711              $mycourseid = $site->id;
     712          }
     713          $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     714  
     715          $PAGE->navbar->add($strblogentries, $blogurl);
     716  
     717          $blogurl->remove_params('userid');
     718          $PAGE->navbar->add($entry->subject, $blogurl);
     719          $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
     720          $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
     721          $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
     722  
     723          // We ignore tag and search params.
     724          if (empty($action) || !$CFG->useblogassociations) {
     725              $headers['url'] = $blogurl;
     726              return $headers;
     727          }
     728      }
     729  
     730      if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
     731          // Case 3: A user's blog entries.
     732  
     733          $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     734          $blogurl->param('userid', $userid);
     735          $PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
     736          $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
     737          $headers['heading'] = get_string('userblog', 'blog', fullname($user));
     738          $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
     739  
     740      } else if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
     741          // Case 4: No blog associations, no userid.
     742  
     743          $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     744          $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
     745          $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
     746          $headers['heading'] = get_string('siteblog', 'blog', $shortname);
     747      } else if (!empty($userid) && !empty($modid) && empty($entryid)) {
     748          // Case 5: Blog entries associated with an activity by a specific user (courseid ignored).
     749  
     750          $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     751          $blogurl->param('userid', $userid);
     752          $blogurl->param('modid', $modid);
     753  
     754          // Course module navigation is handled by build_navigation as the second param.
     755          $headers['cm'] = $cm;
     756          $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
     757          $PAGE->navbar->add($strblogentries, $blogurl);
     758  
     759          $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
     760          $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
     761  
     762          $a = new stdClass();
     763          $a->user = fullname($user);
     764          $a->mod = $cm->name;
     765          $a->type = get_string('modulename', $cm->modname);
     766          $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
     767          $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
     768          $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
     769      } else if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
     770          // Case 6: Blog entries associated with a course by a specific user.
     771  
     772          $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     773          $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
     774          $blogurl->param('userid', $userid);
     775          $blogurl->param('courseid', $courseid);
     776  
     777          $PAGE->navbar->add($strblogentries, $blogurl);
     778  
     779          $PAGE->set_title("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
     780          $PAGE->set_heading("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
     781  
     782          $a = new stdClass();
     783          $a->user = fullname($user);
     784          $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
     785          $a->type = get_string('course');
     786          $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
     787          $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
     788          $headers['strview'] = get_string('viewblogentries', 'blog', $a);
     789  
     790          // Remove the userid from the URL to inform the blog_menu block correctly.
     791          $blogurl->remove_params(array('userid'));
     792      } else if (!empty($groupid) && empty($modid) && empty($entryid)) {
     793          // Case 7: Blog entries by members of a group, associated with that group's course.
     794  
     795          $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     796          $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
     797          $blogurl->param('courseid', $course->id);
     798  
     799          $PAGE->navbar->add($strblogentries, $blogurl);
     800          $blogurl->remove_params(array('courseid'));
     801          $blogurl->param('groupid', $groupid);
     802          $PAGE->navbar->add($group->name, $blogurl);
     803  
     804          $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
     805          $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
     806  
     807          $a = new stdClass();
     808          $a->group = $group->name;
     809          $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
     810          $a->type = get_string('course');
     811          $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
     812          $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
     813          $headers['strview'] = get_string('viewblogentries', 'blog', $a);
     814      } else if (!empty($groupid) && !empty($modid) && empty($entryid)) {
     815          // Case 8: Blog entries by members of a group, associated with an activity in that course.
     816  
     817          $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     818          $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
     819          $headers['cm'] = $cm;
     820          $blogurl->param('modid', $modid);
     821          $PAGE->navbar->add($strblogentries, $blogurl);
     822  
     823          $blogurl->param('groupid', $groupid);
     824          $PAGE->navbar->add($group->name, $blogurl);
     825  
     826          $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
     827          $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
     828  
     829          $a = new stdClass();
     830          $a->group = $group->name;
     831          $a->mod = $cm->name;
     832          $a->type = get_string('modulename', $cm->modname);
     833          $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
     834          $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
     835          $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
     836  
     837      } else if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
     838          // Case 9: All blog entries associated with an activity.
     839  
     840          $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     841          $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
     842          $PAGE->set_cm($cm, $course);
     843          $blogurl->param('modid', $modid);
     844          $PAGE->navbar->add($strblogentries, $blogurl);
     845          $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
     846          $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
     847          $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
     848          $a = new stdClass();
     849          $a->type = get_string('modulename', $cm->modname);
     850          $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
     851          $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
     852      } else if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
     853          // Case 10: All blog entries associated with a course.
     854  
     855          $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
     856          $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
     857          $blogurl->param('courseid', $courseid);
     858          $PAGE->navbar->add($strblogentries, $blogurl);
     859          $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
     860          $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
     861          $a = new stdClass();
     862          $a->type = get_string('course');
     863          $headers['heading'] = get_string('blogentriesabout',
     864                                           'blog',
     865                                           format_string($course->fullname,
     866                                                         true,
     867                                                         array('context' => context_course::instance($course->id))));
     868          $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
     869          $headers['strview'] = get_string('viewblogentries', 'blog', $a);
     870          $blogurl->remove_params(array('userid'));
     871      }
     872  
     873      if (!in_array($action, array('edit', 'add'))) {
     874          // Append Tag info.
     875          if (!empty($tagid)) {
     876              $headers['filters']['tag'] = $tagid;
     877              $blogurl->param('tagid', $tagid);
     878              $tagrec = $DB->get_record('tag', array('id'=>$tagid));
     879              $PAGE->navbar->add($tagrec->name, $blogurl);
     880          } else if (!empty($tag)) {
     881              if ($tagrec = $DB->get_record('tag', array('name' => $tag))) {
     882                  $tagid = $tagrec->id;
     883                  $headers['filters']['tag'] = $tagid;
     884                  $blogurl->param('tag', $tag);
     885                  $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
     886              }
     887          }
     888  
     889          // Append Search info.
     890          if (!empty($search)) {
     891              $headers['filters']['search'] = $search;
     892              $blogurl->param('search', $search);
     893              $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
     894          }
     895      }
     896  
     897      // Append edit mode info.
     898      if (!empty($action) && $action == 'add') {
     899  
     900      } else if (!empty($action) && $action == 'edit') {
     901          $PAGE->navbar->add(get_string('editentry', 'blog'));
     902      }
     903  
     904      if (empty($headers['url'])) {
     905          $headers['url'] = $blogurl;
     906      }
     907      return $headers;
     908  }
     909  
     910  /**
     911   * Shortcut function for getting a count of blog entries associated with a course or a module
     912   * @param int $courseid The ID of the course
     913   * @param int $cmid The ID of the course_modules
     914   * @return string The number of associated entries
     915   */
     916  function blog_get_associated_count($courseid, $cmid=null) {
     917      global $DB;
     918      $context = context_course::instance($courseid);
     919      if ($cmid) {
     920          $context = context_module::instance($cmid);
     921      }
     922      return $DB->count_records('blog_association', array('contextid' => $context->id));
     923  }
     924  
     925  /**
     926   * Running addtional permission check on plugin, for example, plugins
     927   * may have switch to turn on/off comments option, this callback will
     928   * affect UI display, not like pluginname_comment_validate only throw
     929   * exceptions.
     930   * blog_comment_validate will be called before viewing/adding/deleting
     931   * comment, so don't repeat checks.
     932   * Capability check has been done in comment->check_permissions(), we
     933   * don't need to do it again here.
     934   *
     935   * @package  core_blog
     936   * @category comment
     937   *
     938   * @param stdClass $comment_param {
     939   *              context  => context the context object
     940   *              courseid => int course id
     941   *              cm       => stdClass course module object
     942   *              commentarea => string comment area
     943   *              itemid      => int itemid
     944   * }
     945   * @return array
     946   */
     947  function blog_comment_permissions($comment_param) {
     948      global $DB;
     949  
     950      // If blog is public and current user is guest, then don't let him post comments.
     951      $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), 'publishstate', MUST_EXIST);
     952  
     953      if ($blogentry->publishstate != 'public') {
     954          if (!isloggedin() || isguestuser()) {
     955              return array('post' => false, 'view' => true);
     956          }
     957      }
     958      return array('post' => true, 'view' => true);
     959  }
     960  
     961  /**
     962   * Validate comment parameter before perform other comments actions
     963   *
     964   * @package  core_blog
     965   * @category comment
     966   *
     967   * @param stdClass $comment {
     968   *              context  => context the context object
     969   *              courseid => int course id
     970   *              cm       => stdClass course module object
     971   *              commentarea => string comment area
     972   *              itemid      => int itemid
     973   * }
     974   * @return boolean
     975   */
     976  function blog_comment_validate($comment_param) {
     977      global $CFG, $DB, $USER;
     978  
     979      // Check if blogs are enabled user can comment.
     980      if (empty($CFG->enableblogs) || empty($CFG->blogusecomments)) {
     981          throw new comment_exception('nopermissiontocomment');
     982      }
     983  
     984      // Validate comment area.
     985      if ($comment_param->commentarea != 'format_blog') {
     986          throw new comment_exception('invalidcommentarea');
     987      }
     988  
     989      $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), '*', MUST_EXIST);
     990  
     991      // Validation for comment deletion.
     992      if (!empty($comment_param->commentid)) {
     993          if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
     994              if ($record->commentarea != 'format_blog') {
     995                  throw new comment_exception('invalidcommentarea');
     996              }
     997              if ($record->contextid != $comment_param->context->id) {
     998                  throw new comment_exception('invalidcontext');
     999              }
    1000              if ($record->itemid != $comment_param->itemid) {
    1001                  throw new comment_exception('invalidcommentitemid');
    1002              }
    1003          } else {
    1004              throw new comment_exception('invalidcommentid');
    1005          }
    1006      }
    1007  
    1008      // Validate if user has blog view permission.
    1009      $sitecontext = context_system::instance();
    1010      return has_capability('moodle/blog:view', $sitecontext) &&
    1011              blog_user_can_view_user_entry($blogentry->userid, $blogentry);
    1012  }
    1013  
    1014  /**
    1015   * Return a list of page types
    1016   * @param string $pagetype current page type
    1017   * @param stdClass $parentcontext Block's parent context
    1018   * @param stdClass $currentcontext Current context of block
    1019   */
    1020  function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
    1021      return array(
    1022          '*'=>get_string('page-x', 'pagetype'),
    1023          'blog-*'=>get_string('page-blog-x', 'blog'),
    1024          'blog-index'=>get_string('page-blog-index', 'blog'),
    1025          'blog-edit'=>get_string('page-blog-edit', 'blog')
    1026      );
    1027  }
    

    Search This Site: