Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
   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   * Forum posts search area
  19   *
  20   * @package    mod_forum
  21   * @copyright  2015 David Monllao {@link http://www.davidmonllao.com}
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace mod_forum\search;
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  require_once($CFG->dirroot . '/mod/forum/lib.php');
  30  
  31  /**
  32   * Forum posts search area.
  33   *
  34   * @package    mod_forum
  35   * @copyright  2015 David Monllao {@link http://www.davidmonllao.com}
  36   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class post extends \core_search\base_mod {
  39  
  40      /**
  41       * @var array Internal quick static cache.
  42       */
  43      protected $forumsdata = array();
  44  
  45      /**
  46       * @var array Internal quick static cache.
  47       */
  48      protected $discussionsdata = array();
  49  
  50      /**
  51       * @var array Internal quick static cache.
  52       */
  53      protected $postsdata = array();
  54  
  55      /**
  56       * Returns recordset containing required data for indexing forum posts.
  57       *
  58       * @param int $modifiedfrom timestamp
  59       * @param \context|null $context Optional context to restrict scope of returned results
  60       * @return moodle_recordset|null Recordset (or null if no results)
  61       */
  62      public function get_document_recordset($modifiedfrom = 0, \context $context = null) {
  63          global $DB;
  64  
  65          list ($contextjoin, $contextparams) = $this->get_context_restriction_sql(
  66                  $context, 'forum', 'f');
  67          if ($contextjoin === null) {
  68              return null;
  69          }
  70  
  71          $sql = "SELECT fp.*, f.id AS forumid, f.course AS courseid, fd.groupid AS groupid
  72                    FROM {forum_posts} fp
  73                    JOIN {forum_discussions} fd ON fd.id = fp.discussion
  74                    JOIN {forum} f ON f.id = fd.forum
  75            $contextjoin
  76                   WHERE fp.modified >= ? ORDER BY fp.modified ASC";
  77          return $DB->get_recordset_sql($sql, array_merge($contextparams, [$modifiedfrom]));
  78      }
  79  
  80      /**
  81       * Returns the document associated with this post id.
  82       *
  83       * @param stdClass $record Post info.
  84       * @param array    $options
  85       * @return \core_search\document
  86       */
  87      public function get_document($record, $options = array()) {
  88  
  89          try {
  90              $cm = $this->get_cm('forum', $record->forumid, $record->courseid);
  91              $context = \context_module::instance($cm->id);
  92          } catch (\dml_missing_record_exception $ex) {
  93              // Notify it as we run here as admin, we should see everything.
  94              debugging('Error retrieving ' . $this->areaid . ' ' . $record->id . ' document, not all required data is available: ' .
  95                  $ex->getMessage(), DEBUG_DEVELOPER);
  96              return false;
  97          } catch (\dml_exception $ex) {
  98              // Notify it as we run here as admin, we should see everything.
  99              debugging('Error retrieving ' . $this->areaid . ' ' . $record->id . ' document: ' . $ex->getMessage(), DEBUG_DEVELOPER);
 100              return false;
 101          }
 102  
 103          // Prepare associative array with data from DB.
 104          $doc = \core_search\document_factory::instance($record->id, $this->componentname, $this->areaname);
 105          $doc->set('title', content_to_text($record->subject, false));
 106          $doc->set('content', content_to_text($record->message, $record->messageformat));
 107          $doc->set('contextid', $context->id);
 108          $doc->set('courseid', $record->courseid);
 109          $doc->set('userid', $record->userid);
 110          $doc->set('owneruserid', \core_search\manager::NO_OWNER_ID);
 111          $doc->set('modified', $record->modified);
 112  
 113          // Store group id if there is one. (0 and -1 both mean not restricted to group.)
 114          if ($record->groupid > 0) {
 115              $doc->set('groupid', $record->groupid);
 116          }
 117  
 118          // Check if this document should be considered new.
 119          if (isset($options['lastindexedtime']) && ($options['lastindexedtime'] < $record->created)) {
 120              // If the document was created after the last index time, it must be new.
 121              $doc->set_is_new(true);
 122          }
 123  
 124          return $doc;
 125      }
 126  
 127      /**
 128       * Returns true if this area uses file indexing.
 129       *
 130       * @return bool
 131       */
 132      public function uses_file_indexing() {
 133          return true;
 134      }
 135  
 136      /**
 137       * Return the context info required to index files for
 138       * this search area.
 139       *
 140       * @return array
 141       */
 142      public function get_search_fileareas() {
 143          $fileareas = array(
 144              'attachment',
 145              'post'
 146          );
 147  
 148          return $fileareas;
 149      }
 150  
 151      /**
 152       * Add the forum post attachments.
 153       *
 154       * @param document $document The current document
 155       * @return null
 156       */
 157      public function attach_files($document) {
 158          global $DB;
 159  
 160          $postid = $document->get('itemid');
 161  
 162          try {
 163              $post = $this->get_post($postid);
 164          } catch (\dml_missing_record_exception $e) {
 165              unset($this->postsdata[$postid]);
 166              debugging('Could not get record to attach files to '.$document->get('id'), DEBUG_DEVELOPER);
 167              return;
 168          }
 169  
 170          // Because this is used during indexing, we don't want to cache posts. Would result in memory leak.
 171          unset($this->postsdata[$postid]);
 172  
 173          $cm = $this->get_cm($this->get_module_name(), $post->forum, $document->get('courseid'));
 174          $context = \context_module::instance($cm->id);
 175          $contextid = $context->id;
 176  
 177          $fileareas = $this->get_search_fileareas();
 178          $component = $this->get_component_name();
 179  
 180          // Get the files and attach them.
 181          foreach ($fileareas as $filearea) {
 182              $fs = get_file_storage();
 183              $files = $fs->get_area_files($contextid, $component, $filearea, $postid, '', false);
 184  
 185              foreach ($files as $file) {
 186                  $document->add_stored_file($file);
 187              }
 188          }
 189      }
 190  
 191      /**
 192       * Whether the user can access the document or not.
 193       *
 194       * @throws \dml_missing_record_exception
 195       * @throws \dml_exception
 196       * @param int $id Forum post id
 197       * @return bool
 198       */
 199      public function check_access($id) {
 200          global $USER;
 201  
 202          try {
 203              $post = $this->get_post($id);
 204              $forum = $this->get_forum($post->forum);
 205              $discussion = $this->get_discussion($post->discussion);
 206              $cminfo = $this->get_cm('forum', $forum->id, $forum->course);
 207              $cm = $cminfo->get_course_module_record();
 208          } catch (\dml_missing_record_exception $ex) {
 209              return \core_search\manager::ACCESS_DELETED;
 210          } catch (\dml_exception $ex) {
 211              return \core_search\manager::ACCESS_DENIED;
 212          }
 213  
 214          // Recheck uservisible although it should have already been checked in core_search.
 215          if ($cminfo->uservisible === false) {
 216              return \core_search\manager::ACCESS_DENIED;
 217          }
 218  
 219          if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
 220              return \core_search\manager::ACCESS_DENIED;
 221          }
 222  
 223          return \core_search\manager::ACCESS_GRANTED;
 224      }
 225  
 226      /**
 227       * Link to the forum post discussion
 228       *
 229       * @param \core_search\document $doc
 230       * @return \moodle_url
 231       */
 232      public function get_doc_url(\core_search\document $doc) {
 233          // The post is already in static cache, we fetch it in self::search_access.
 234          $post = $this->get_post($doc->get('itemid'));
 235          return new \moodle_url('/mod/forum/discuss.php', array('d' => $post->discussion));
 236      }
 237  
 238      /**
 239       * Link to the forum.
 240       *
 241       * @param \core_search\document $doc
 242       * @return \moodle_url
 243       */
 244      public function get_context_url(\core_search\document $doc) {
 245          $contextmodule = \context::instance_by_id($doc->get('contextid'));
 246          return new \moodle_url('/mod/forum/view.php', array('id' => $contextmodule->instanceid));
 247      }
 248  
 249      /**
 250       * Returns the specified forum post from its internal cache.
 251       *
 252       * @throws \dml_missing_record_exception
 253       * @param int $postid
 254       * @return stdClass
 255       */
 256      protected function get_post($postid) {
 257          if (empty($this->postsdata[$postid])) {
 258              $this->postsdata[$postid] = forum_get_post_full($postid);
 259              if (!$this->postsdata[$postid]) {
 260                  throw new \dml_missing_record_exception('forum_posts');
 261              }
 262          }
 263          return $this->postsdata[$postid];
 264      }
 265  
 266      /**
 267       * Returns the specified forum checking the internal cache.
 268       *
 269       * Store minimal information as this might grow.
 270       *
 271       * @throws \dml_exception
 272       * @param int $forumid
 273       * @return stdClass
 274       */
 275      protected function get_forum($forumid) {
 276          global $DB;
 277  
 278          if (empty($this->forumsdata[$forumid])) {
 279              $this->forumsdata[$forumid] = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
 280          }
 281          return $this->forumsdata[$forumid];
 282      }
 283  
 284      /**
 285       * Returns the discussion checking the internal cache.
 286       *
 287       * @throws \dml_missing_record_exception
 288       * @param int $discussionid
 289       * @return stdClass
 290       */
 291      protected function get_discussion($discussionid) {
 292          global $DB;
 293  
 294          if (empty($this->discussionsdata[$discussionid])) {
 295              $this->discussionsdata[$discussionid] = $DB->get_record('forum_discussions',
 296                  array('id' => $discussionid), '*', MUST_EXIST);
 297          }
 298          return $this->discussionsdata[$discussionid];
 299      }
 300  
 301      /**
 302       * Changes the context ordering so that the forums with most recent discussions are indexed
 303       * first.
 304       *
 305       * @return string[] SQL join and ORDER BY
 306       */
 307      protected function get_contexts_to_reindex_extra_sql() {
 308          return [
 309              'JOIN {forum_discussions} fd ON fd.course = cm.course AND fd.forum = cm.instance',
 310              'MAX(fd.timemodified) DESC'
 311          ];
 312      }
 313  
 314      /**
 315       * Confirms that data entries support group restrictions.
 316       *
 317       * @return bool True
 318       */
 319      public function supports_group_restriction() {
 320          return true;
 321      }
 322  }