Search moodle.org's
Developer Documentation


Long Term Support Release

  • Bug fixes for general core bugs in 3.1.x ended 8 May 2017 (12 months).
  • Bug fixes for security issues in 3.1.x ended 13 May 2019 (36 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x , 5.5.x or 5.6.x on Windows - http://windows.php.net/download/). PHP 7.0.x is supported but has some engine limitations. PHP 7.1.x is not supported.
  • /blog/ -> locallib.php (source)

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

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

    Search This Site: