Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402]

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * This contains functions and classes that will be used by scripts in wiki module
  20   *
  21   * @package mod_wiki
  22   * @copyright 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu
  23   * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
  24   *
  25   * @author Jordi Piguillem
  26   * @author Marc Alier
  27   * @author David Jimenez
  28   * @author Josep Arus
  29   * @author Daniel Serrano
  30   * @author Kenneth Riba
  31   *
  32   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33   */
  34  
  35  defined('MOODLE_INTERNAL') || die();
  36  
  37  require_once($CFG->dirroot . '/mod/wiki/lib.php');
  38  require_once($CFG->dirroot . '/mod/wiki/parser/parser.php');
  39  require_once($CFG->libdir . '/filelib.php');
  40  
  41  define('WIKI_REFRESH_CACHE_TIME', 30); // @TODO: To be deleted.
  42  define('FORMAT_CREOLE', '37');
  43  define('FORMAT_NWIKI', '38');
  44  define('NO_VALID_RATE', '-999');
  45  define('IMPROVEMENT', '+');
  46  define('EQUAL', '=');
  47  define('WORST', '-');
  48  
  49  define('LOCK_TIMEOUT', 30);
  50  
  51  /**
  52   * Get a wiki instance
  53   * @param int $wikiid the instance id of wiki
  54   */
  55  function wiki_get_wiki($wikiid) {
  56      global $DB;
  57  
  58      return $DB->get_record('wiki', array('id' => $wikiid));
  59  }
  60  
  61  /**
  62   * Get sub wiki instances with same wiki id
  63   * @param int $wikiid
  64   */
  65  function wiki_get_subwikis($wikiid) {
  66      global $DB;
  67      return $DB->get_records('wiki_subwikis', array('wikiid' => $wikiid));
  68  }
  69  
  70  /**
  71   * Get a sub wiki instance by wiki id and group id
  72   * @param int $wikiid
  73   * @param int $groupid
  74   * @return object
  75   */
  76  function wiki_get_subwiki_by_group($wikiid, $groupid, $userid = 0) {
  77      global $DB;
  78      return $DB->get_record('wiki_subwikis', array('wikiid' => $wikiid, 'groupid' => $groupid, 'userid' => $userid));
  79  }
  80  
  81  /**
  82   * Get a sub wiki instace by instance id
  83   * @param int $subwikiid
  84   * @return object
  85   */
  86  function wiki_get_subwiki($subwikiid) {
  87      global $DB;
  88      return $DB->get_record('wiki_subwikis', array('id' => $subwikiid));
  89  
  90  }
  91  
  92  /**
  93   * Add a new sub wiki instance
  94   * @param int $wikiid
  95   * @param int $groupid
  96   * @return int $insertid
  97   */
  98  function wiki_add_subwiki($wikiid, $groupid, $userid = 0) {
  99      global $DB;
 100  
 101      $record = new StdClass();
 102      $record->wikiid = $wikiid;
 103      $record->groupid = $groupid;
 104      $record->userid = $userid;
 105  
 106      $insertid = $DB->insert_record('wiki_subwikis', $record);
 107      return $insertid;
 108  }
 109  
 110  /**
 111   * Get a wiki instance by pageid
 112   * @param int $pageid
 113   * @return object
 114   */
 115  function wiki_get_wiki_from_pageid($pageid) {
 116      global $DB;
 117  
 118      $sql = "SELECT w.*
 119              FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p
 120              WHERE p.id = ? AND
 121              p.subwikiid = s.id AND
 122              s.wikiid = w.id";
 123  
 124      return $DB->get_record_sql($sql, array($pageid));
 125  }
 126  
 127  /**
 128   * Get a wiki page by pageid
 129   * @param int $pageid
 130   * @return object
 131   */
 132  function wiki_get_page($pageid) {
 133      global $DB;
 134      return $DB->get_record('wiki_pages', array('id' => $pageid));
 135  }
 136  
 137  /**
 138   * Get latest version of wiki page
 139   * @param int $pageid
 140   * @return object
 141   */
 142  function wiki_get_current_version($pageid) {
 143      global $DB;
 144  
 145      // @TODO: Fix this query
 146      $sql = "SELECT *
 147              FROM {wiki_versions}
 148              WHERE pageid = ?
 149              ORDER BY version DESC";
 150      $records = $DB->get_records_sql($sql, array($pageid), 0, 1);
 151      return array_pop($records);
 152  
 153  }
 154  
 155  /**
 156   * Alias of wiki_get_current_version
 157   * @TODO, does the exactly same thing as wiki_get_current_version, should be removed
 158   * @param int $pageid
 159   * @return object
 160   */
 161  function wiki_get_last_version($pageid) {
 162      return wiki_get_current_version($pageid);
 163  }
 164  
 165  /**
 166   * Get page section
 167   * @param int $pageid
 168   * @param string $section
 169   */
 170  function wiki_get_section_page($page, $section) {
 171  
 172      $version = wiki_get_current_version($page->id);
 173      return wiki_parser_proxy::get_section($version->content, $version->contentformat, $section);
 174  }
 175  
 176  /**
 177   * Get a wiki page by page title
 178   * @param int $swid, sub wiki id
 179   * @param string $title
 180   * @return object
 181   */
 182  function wiki_get_page_by_title($swid, $title) {
 183      global $DB;
 184      return $DB->get_record('wiki_pages', array('subwikiid' => $swid, 'title' => $title));
 185  }
 186  
 187  /**
 188   * Get a version record by record id
 189   * @param int $versionid, the version id
 190   * @return object
 191   */
 192  function wiki_get_version($versionid) {
 193      global $DB;
 194      return $DB->get_record('wiki_versions', array('id' => $versionid));
 195  }
 196  
 197  /**
 198   * Get first page of wiki instace
 199   * @param int $subwikiid
 200   * @param int $module, wiki instance object
 201   */
 202  function wiki_get_first_page($subwikid, $module = null) {
 203      global $DB, $USER;
 204  
 205      $sql = "SELECT p.*
 206              FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p
 207              WHERE s.id = ? AND
 208              s.wikiid = w.id AND
 209              w.firstpagetitle = p.title AND
 210              p.subwikiid = s.id";
 211      return $DB->get_record_sql($sql, array($subwikid));
 212  }
 213  
 214  function wiki_save_section($wikipage, $sectiontitle, $sectioncontent, $userid) {
 215  
 216      $wiki = wiki_get_wiki_from_pageid($wikipage->id);
 217      $cm = get_coursemodule_from_instance('wiki', $wiki->id);
 218      $context = context_module::instance($cm->id);
 219  
 220      if (has_capability('mod/wiki:editpage', $context)) {
 221          $version = wiki_get_current_version($wikipage->id);
 222          $content = wiki_parser_proxy::get_section($version->content, $version->contentformat, $sectiontitle, true);
 223  
 224          $newcontent = $content[0] . $sectioncontent . $content[2];
 225  
 226          return wiki_save_page($wikipage, $newcontent, $userid);
 227      } else {
 228          return false;
 229      }
 230  }
 231  
 232  /**
 233   * Save page content
 234   * @param object $wikipage
 235   * @param string $newcontent
 236   * @param int $userid
 237   */
 238  function wiki_save_page($wikipage, $newcontent, $userid) {
 239      global $DB;
 240  
 241      $wiki = wiki_get_wiki_from_pageid($wikipage->id);
 242      $cm = get_coursemodule_from_instance('wiki', $wiki->id);
 243      $context = context_module::instance($cm->id);
 244  
 245      if (has_capability('mod/wiki:editpage', $context)) {
 246          $version = wiki_get_current_version($wikipage->id);
 247  
 248          $version->content = $newcontent;
 249          $version->userid = $userid;
 250          $version->version++;
 251          $version->timecreated = time();
 252          $version->id = $DB->insert_record('wiki_versions', $version);
 253  
 254          $wikipage->timemodified = $version->timecreated;
 255          $wikipage->userid = $userid;
 256          $return = wiki_refresh_cachedcontent($wikipage, $newcontent);
 257          $event = \mod_wiki\event\page_updated::create(
 258                  array(
 259                      'context' => $context,
 260                      'objectid' => $wikipage->id,
 261                      'relateduserid' => $userid,
 262                      'other' => array(
 263                          'newcontent' => $newcontent
 264                          )
 265                      ));
 266          $event->add_record_snapshot('wiki', $wiki);
 267          $event->add_record_snapshot('wiki_pages', $wikipage);
 268          $event->add_record_snapshot('wiki_versions', $version);
 269          $event->trigger();
 270          return $return;
 271      } else {
 272          return false;
 273      }
 274  }
 275  
 276  function wiki_refresh_cachedcontent($page, $newcontent = null) {
 277      global $DB;
 278  
 279      $version = wiki_get_current_version($page->id);
 280      if (empty($version)) {
 281          return null;
 282      }
 283      if (!isset($newcontent)) {
 284          $newcontent = $version->content;
 285      }
 286  
 287      $options = array('swid' => $page->subwikiid, 'pageid' => $page->id);
 288      $parseroutput = wiki_parse_content($version->contentformat, $newcontent, $options);
 289      $page->cachedcontent = $parseroutput['toc'] . $parseroutput['parsed_text'];
 290      $page->timerendered = time();
 291      $DB->update_record('wiki_pages', $page);
 292  
 293      wiki_refresh_page_links($page, $parseroutput['link_count']);
 294  
 295      return array('page' => $page, 'sections' => $parseroutput['repeated_sections'], 'version' => $version->version);
 296  }
 297  
 298  /**
 299   * Restore a page with specified version.
 300   *
 301   * @param stdClass $wikipage wiki page record
 302   * @param stdClass $version wiki page version to restore
 303   * @param context_module $context context of wiki module
 304   * @return stdClass restored page
 305   */
 306  function wiki_restore_page($wikipage, $version, $context) {
 307      $return = wiki_save_page($wikipage, $version->content, $version->userid);
 308      $event = \mod_wiki\event\page_version_restored::create(
 309              array(
 310                  'context' => $context,
 311                  'objectid' => $version->id,
 312                  'other' => array(
 313                      'pageid' => $wikipage->id
 314                      )
 315                  ));
 316      $event->add_record_snapshot('wiki_versions', $version);
 317      $event->trigger();
 318      return $return['page'];
 319  }
 320  
 321  function wiki_refresh_page_links($page, $links) {
 322      global $DB;
 323  
 324      $DB->delete_records('wiki_links', array('frompageid' => $page->id));
 325      foreach ($links as $linkname => $linkinfo) {
 326  
 327          $newlink = new stdClass();
 328          $newlink->subwikiid = $page->subwikiid;
 329          $newlink->frompageid = $page->id;
 330  
 331          if ($linkinfo['new']) {
 332              $newlink->tomissingpage = $linkname;
 333          } else {
 334              $newlink->topageid = $linkinfo['pageid'];
 335          }
 336  
 337          try {
 338              $DB->insert_record('wiki_links', $newlink);
 339          } catch (dml_exception $e) {
 340              debugging($e->getMessage());
 341          }
 342  
 343      }
 344  }
 345  
 346  /**
 347   * Create a new wiki page, if the page exists, return existing pageid
 348   * @param int $swid
 349   * @param string $title
 350   * @param string $format
 351   * @param int $userid
 352   */
 353  function wiki_create_page($swid, $title, $format, $userid) {
 354      global $DB;
 355      $subwiki = wiki_get_subwiki($swid);
 356      $cm = get_coursemodule_from_instance('wiki', $subwiki->wikiid);
 357      $context = context_module::instance($cm->id);
 358      require_capability('mod/wiki:editpage', $context);
 359      // if page exists
 360      if ($page = wiki_get_page_by_title($swid, $title)) {
 361          return $page->id;
 362      }
 363  
 364      // Creating a new empty version
 365      $version = new stdClass();
 366      $version->content = '';
 367      $version->contentformat = $format;
 368      $version->version = 0;
 369      $version->timecreated = time();
 370      $version->userid = $userid;
 371  
 372      $versionid = null;
 373      $versionid = $DB->insert_record('wiki_versions', $version);
 374  
 375      // Createing a new empty page
 376      $page = new stdClass();
 377      $page->subwikiid = $swid;
 378      $page->title = $title;
 379      $page->cachedcontent = '';
 380      $page->timecreated = $version->timecreated;
 381      $page->timemodified = $version->timecreated;
 382      $page->timerendered = $version->timecreated;
 383      $page->userid = $userid;
 384      $page->pageviews = 0;
 385      $page->readonly = 0;
 386  
 387      $pageid = $DB->insert_record('wiki_pages', $page);
 388  
 389      // Setting the pageid
 390      $version->id = $versionid;
 391      $version->pageid = $pageid;
 392      $DB->update_record('wiki_versions', $version);
 393  
 394      $event = \mod_wiki\event\page_created::create(
 395              array(
 396                  'context' => $context,
 397                  'objectid' => $pageid
 398                  )
 399              );
 400      $event->trigger();
 401  
 402      wiki_make_cache_expire($page->title);
 403      return $pageid;
 404  }
 405  
 406  function wiki_make_cache_expire($pagename) {
 407      global $DB;
 408  
 409      $sql = "UPDATE {wiki_pages}
 410              SET timerendered = 0
 411              WHERE id IN ( SELECT l.frompageid
 412                  FROM {wiki_links} l
 413                  WHERE l.tomissingpage = ?
 414              )";
 415      $DB->execute ($sql, array($pagename));
 416  }
 417  
 418  /**
 419   * Get a specific version of page
 420   * @param int $pageid
 421   * @param int $version
 422   */
 423  function wiki_get_wiki_page_version($pageid, $version) {
 424      global $DB;
 425      return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'version' => $version));
 426  }
 427  
 428  /**
 429   * Get version list
 430   * @param int $pageid
 431   * @param int $limitfrom
 432   * @param int $limitnum
 433   */
 434  function wiki_get_wiki_page_versions($pageid, $limitfrom, $limitnum) {
 435      global $DB;
 436      return $DB->get_records('wiki_versions', array('pageid' => $pageid), 'version DESC', '*', $limitfrom, $limitnum);
 437  }
 438  
 439  /**
 440   * Count the number of page version
 441   * @param int $pageid
 442   */
 443  function wiki_count_wiki_page_versions($pageid) {
 444      global $DB;
 445      return $DB->count_records('wiki_versions', array('pageid' => $pageid));
 446  }
 447  
 448  /**
 449   * Get linked from page
 450   * @param int $pageid
 451   */
 452  function wiki_get_linked_to_pages($pageid) {
 453      global $DB;
 454      return $DB->get_records('wiki_links', array('frompageid' => $pageid));
 455  }
 456  
 457  /**
 458   * Get linked from page
 459   * @param int $pageid
 460   */
 461  function wiki_get_linked_from_pages($pageid) {
 462      global $DB;
 463      return $DB->get_records('wiki_links', array('topageid' => $pageid));
 464  }
 465  
 466  /**
 467   * Get pages which user have been edited
 468   * @param int $swid
 469   * @param int $userid
 470   */
 471  function wiki_get_contributions($swid, $userid) {
 472      global $DB;
 473  
 474      $sql = "SELECT v.*
 475              FROM {wiki_versions} v, {wiki_pages} p
 476              WHERE p.subwikiid = ? AND
 477              v.pageid = p.id AND
 478              v.userid = ?";
 479  
 480      return $DB->get_records_sql($sql, array($swid, $userid));
 481  }
 482  
 483  /**
 484   * Get missing or empty pages in wiki
 485   * @param int $swid sub wiki id
 486   */
 487  function wiki_get_missing_or_empty_pages($swid) {
 488      global $DB;
 489  
 490      $sql = "SELECT DISTINCT p.title, p.id, p.subwikiid
 491              FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p
 492              WHERE s.wikiid = w.id and
 493              s.id = ? and
 494              w.firstpagetitle != p.title and
 495              p.subwikiid = ? and
 496              1 =  (SELECT count(*)
 497                  FROM {wiki_versions} v
 498                  WHERE v.pageid = p.id)
 499              UNION
 500              SELECT DISTINCT l.tomissingpage as title, 0 as id, l.subwikiid
 501              FROM {wiki_links} l
 502              WHERE l.subwikiid = ? and
 503              l.topageid = 0";
 504  
 505      return $DB->get_records_sql($sql, array($swid, $swid, $swid));
 506  }
 507  
 508  /**
 509   * Get pages list in wiki
 510   * @param int $swid sub wiki id
 511   * @param string $sort How to sort the pages. By default, title ASC.
 512   * @return stdClass[]
 513   */
 514  function wiki_get_page_list($swid, $sort = 'title ASC') {
 515      global $DB;
 516      $records = $DB->get_records('wiki_pages', array('subwikiid' => $swid), $sort);
 517      return $records;
 518  }
 519  
 520  /**
 521   * Return a list of orphaned wikis for one specific subwiki
 522   * @global object
 523   * @param int $swid sub wiki id
 524   */
 525  function wiki_get_orphaned_pages($swid) {
 526      global $DB;
 527  
 528      $sql = "SELECT p.id, p.title
 529              FROM {wiki_pages} p, {wiki} w , {wiki_subwikis} s
 530              WHERE p.subwikiid = ?
 531              AND s.id = ?
 532              AND w.id = s.wikiid
 533              AND p.title != w.firstpagetitle
 534              AND p.id NOT IN (SELECT topageid FROM {wiki_links} WHERE subwikiid = ?)";
 535  
 536      return $DB->get_records_sql($sql, array($swid, $swid, $swid));
 537  }
 538  
 539  /**
 540   * Search wiki title
 541   * @param int $swid sub wiki id
 542   * @param string $search
 543   */
 544  function wiki_search_title($swid, $search) {
 545      global $DB;
 546  
 547      return $DB->get_records_select('wiki_pages', "subwikiid = ? AND title LIKE ?", array($swid, '%'.$search.'%'));
 548  }
 549  
 550  /**
 551   * Search wiki content
 552   * @param int $swid sub wiki id
 553   * @param string $search
 554   */
 555  function wiki_search_content($swid, $search) {
 556      global $DB;
 557  
 558      return $DB->get_records_select('wiki_pages', "subwikiid = ? AND cachedcontent LIKE ?", array($swid, '%'.$search.'%'));
 559  }
 560  
 561  /**
 562   * Search wiki title and content
 563   * @param int $swid sub wiki id
 564   * @param string $search
 565   */
 566  function wiki_search_all($swid, $search) {
 567      global $DB;
 568  
 569      return $DB->get_records_select('wiki_pages', "subwikiid = ? AND (cachedcontent LIKE ? OR title LIKE ?)", array($swid, '%'.$search.'%', '%'.$search.'%'));
 570  }
 571  
 572  /**
 573   * Get user data
 574   */
 575  function wiki_get_user_info($userid) {
 576      global $DB;
 577      return $DB->get_record('user', array('id' => $userid));
 578  }
 579  
 580  /**
 581   * Increase page view nubmer
 582   * @param int $page, database record
 583   */
 584  function wiki_increment_pageviews($page) {
 585      global $DB;
 586  
 587      $page->pageviews++;
 588      $DB->update_record('wiki_pages', $page);
 589  }
 590  
 591  //----------------------------------------------------------
 592  //----------------------------------------------------------
 593  
 594  /**
 595   * Text format supported by wiki module
 596   */
 597  function wiki_get_formats() {
 598      return array('html', 'creole', 'nwiki');
 599  }
 600  
 601  /**
 602   * Parses a string with the wiki markup language in $markup.
 603   *
 604   * @return Array or false when something wrong has happened.
 605   *
 606   * Returned array contains the following fields:
 607   *     'parsed_text' => String. Contains the parsed wiki content.
 608   *     'unparsed_text' => String. Constains the original wiki content.
 609   *     'link_count' => Array of array('destination' => ..., 'new' => "is new?"). Contains the internal wiki links found in the wiki content.
 610   *      'deleted_sections' => the list of deleted sections.
 611   *              '' =>
 612   *
 613   * @author Josep Arús Pous
 614   **/
 615  function wiki_parse_content($markup, $pagecontent, $options = array()) {
 616      global $PAGE;
 617  
 618      $subwiki = wiki_get_subwiki($options['swid']);
 619      $cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid);
 620      $context = context_module::instance($cm->id);
 621  
 622      $parser_options = array(
 623          'link_callback' => '/mod/wiki/locallib.php:wiki_parser_link',
 624          'link_callback_args' => array('swid' => $options['swid']),
 625          'table_callback' => '/mod/wiki/locallib.php:wiki_parser_table',
 626          'real_path_callback' => '/mod/wiki/locallib.php:wiki_parser_real_path',
 627          'real_path_callback_args' => array(
 628              'context' => $context,
 629              'component' => 'mod_wiki',
 630              'filearea' => 'attachments',
 631              'subwikiid'=> $subwiki->id,
 632              'pageid' => $options['pageid']
 633          ),
 634          'pageid' => $options['pageid'],
 635          'pretty_print' => (isset($options['pretty_print']) && $options['pretty_print']),
 636          'printable' => (isset($options['printable']) && $options['printable'])
 637      );
 638  
 639      return wiki_parser_proxy::parse($pagecontent, $markup, $parser_options);
 640  }
 641  
 642  /**
 643   * This function is the parser callback to parse wiki links.
 644   *
 645   * It returns the necesary information to print a link.
 646   *
 647   * NOTE: Empty pages and non-existent pages must be print in red color.
 648   *
 649   * !!!!!! IMPORTANT !!!!!!
 650   * It is critical that you call format_string on the content before it is used.
 651   *
 652   * @param string|stdClass $link name of a page or page object.
 653   * @param array $options
 654   * @return array Array('content' => string, 'url' => string, 'new' => bool, 'link_info' => array)
 655   *
 656   * @TODO Doc return and options
 657   */
 658  function wiki_parser_link($link, $options = null) {
 659      global $CFG;
 660  
 661      if (is_object($link)) {
 662          $parsedlink = array('content' => $link->title, 'url' => $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $link->id, 'new' => false, 'link_info' => array('link' => $link->title, 'pageid' => $link->id, 'new' => false));
 663  
 664          $version = wiki_get_current_version($link->id);
 665          if ($version->version == 0) {
 666              $parsedlink['new'] = true;
 667          }
 668          return $parsedlink;
 669      } else {
 670          $swid = $options['swid'];
 671  
 672          if ($page = wiki_get_page_by_title($swid, $link)) {
 673              $parsedlink = array('content' => $link, 'url' => $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $page->id, 'new' => false, 'link_info' => array('link' => $link, 'pageid' => $page->id, 'new' => false));
 674  
 675              $version = wiki_get_current_version($page->id);
 676              if ($version->version == 0) {
 677                  $parsedlink['new'] = true;
 678              }
 679  
 680              return $parsedlink;
 681  
 682          } else {
 683              return array('content' => $link, 'url' => $CFG->wwwroot . '/mod/wiki/create.php?swid=' . $swid . '&amp;title=' . urlencode($link) . '&amp;action=new', 'new' => true, 'link_info' => array('link' => $link, 'new' => true, 'pageid' => 0));
 684          }
 685      }
 686  }
 687  
 688  /**
 689   * Returns the table fully parsed (HTML)
 690   *
 691   * @return HTML for the table $table
 692   * @author Josep Arús Pous
 693   *
 694   **/
 695  function wiki_parser_table($table) {
 696      global $OUTPUT;
 697  
 698      $htmltable = new html_table();
 699  
 700      $headers = $table[0];
 701      $htmltable->head = array();
 702      foreach ($headers as $h) {
 703          $htmltable->head[] = $h[1];
 704      }
 705  
 706      array_shift($table);
 707      $htmltable->data = array();
 708      foreach ($table as $row) {
 709          $row_data = array();
 710          foreach ($row as $r) {
 711              $row_data[] = $r[1];
 712          }
 713          $htmltable->data[] = $row_data;
 714      }
 715  
 716      return html_writer::table($htmltable);
 717  }
 718  
 719  /**
 720   * Returns an absolute path link, unless there is no such link.
 721   *
 722   * @param string $url Link's URL or filename
 723   * @param stdClass $context filearea params
 724   * @param string $component The component the file is associated with
 725   * @param string $filearea The filearea the file is stored in
 726   * @param int $swid Sub wiki id
 727   *
 728   * @return string URL for files full path
 729   */
 730  
 731  function wiki_parser_real_path($url, $context, $component, $filearea, $swid) {
 732      global $CFG;
 733  
 734      if (preg_match("/^(?:http|ftp)s?\:\/\//", $url)) {
 735          return $url;
 736      } else {
 737  
 738          $file = 'pluginfile.php';
 739          if (!$CFG->slasharguments) {
 740              $file = $file . '?file=';
 741          }
 742          $baseurl = "$CFG->wwwroot/$file/{$context->id}/$component/$filearea/$swid/";
 743          // it is a file in current file area
 744          return $baseurl . $url;
 745      }
 746  }
 747  
 748  /**
 749   * Returns the token used by a wiki language to represent a given tag or "object" (bold -> **)
 750   *
 751   * @return A string when it has only one token at the beginning (f. ex. lists). An array composed by 2 strings when it has 2 tokens, one at the beginning and one at the end (f. ex. italics). Returns false otherwise.
 752   * @author Josep Arús Pous
 753   **/
 754  function wiki_parser_get_token($markup, $name) {
 755  
 756      return wiki_parser_proxy::get_token($name, $markup);
 757  }
 758  
 759  /**
 760   * Checks if current user can view a subwiki
 761   *
 762   * @param stdClass $subwiki usually record from {wiki_subwikis}. Must contain fields 'wikiid', 'groupid', 'userid'.
 763   *     If it also contains fields 'course' and 'groupmode' from table {wiki} it will save extra DB query.
 764   * @param stdClass $wiki optional wiki object if known
 765   * @return bool
 766   */
 767  function wiki_user_can_view($subwiki, $wiki = null) {
 768      global $USER;
 769  
 770      if (empty($wiki) || $wiki->id != $subwiki->wikiid) {
 771          $wiki = wiki_get_wiki($subwiki->wikiid);
 772      }
 773      $modinfo = get_fast_modinfo($wiki->course);
 774      if (!isset($modinfo->instances['wiki'][$subwiki->wikiid])) {
 775          // Module does not exist.
 776          return false;
 777      }
 778      $cm = $modinfo->instances['wiki'][$subwiki->wikiid];
 779      if (!$cm->uservisible) {
 780          // The whole module is not visible to the current user.
 781          return false;
 782      }
 783      $context = context_module::instance($cm->id);
 784  
 785      // Working depending on activity groupmode
 786      switch (groups_get_activity_groupmode($cm)) {
 787      case NOGROUPS:
 788  
 789          if ($wiki->wikimode == 'collaborative') {
 790              // Collaborative Mode:
 791              // There is one wiki for all the class.
 792              //
 793              // Only view capbility needed
 794              return has_capability('mod/wiki:viewpage', $context);
 795          } else if ($wiki->wikimode == 'individual') {
 796              // Individual Mode:
 797              // Each person owns a wiki.
 798              if ($subwiki->userid == $USER->id) {
 799                  // Only the owner of the wiki can view it
 800                  return has_capability('mod/wiki:viewpage', $context);
 801              } else { // User has special capabilities
 802                  // User must have:
 803                  //      mod/wiki:viewpage capability
 804                  // and
 805                  //      mod/wiki:managewiki capability
 806                  $view = has_capability('mod/wiki:viewpage', $context);
 807                  $manage = has_capability('mod/wiki:managewiki', $context);
 808  
 809                  return $view && $manage;
 810              }
 811          } else {
 812              //Error
 813              return false;
 814          }
 815      case SEPARATEGROUPS:
 816          // Collaborative and Individual Mode
 817          //
 818          // Collaborative Mode:
 819          //      There is one wiki per group.
 820          // Individual Mode:
 821          //      Each person owns a wiki.
 822          if ($wiki->wikimode == 'collaborative' || $wiki->wikimode == 'individual') {
 823              // Only members of subwiki group could view that wiki
 824              if (in_array($subwiki->groupid, $modinfo->get_groups($cm->groupingid))) {
 825                  // Only view capability needed
 826                  return has_capability('mod/wiki:viewpage', $context);
 827  
 828              } else { // User is not part of that group
 829                  // User must have:
 830                  //      mod/wiki:managewiki capability
 831                  // or
 832                  //      moodle/site:accessallgroups capability
 833                  // and
 834                  //      mod/wiki:viewpage capability
 835                  $view = has_capability('mod/wiki:viewpage', $context);
 836                  $manage = has_capability('mod/wiki:managewiki', $context);
 837                  $access = has_capability('moodle/site:accessallgroups', $context);
 838                  return ($manage || $access) && $view;
 839              }
 840          } else {
 841              //Error
 842              return false;
 843          }
 844      case VISIBLEGROUPS:
 845          // Collaborative and Individual Mode
 846          //
 847          // Collaborative Mode:
 848          //      There is one wiki per group.
 849          // Individual Mode:
 850          //      Each person owns a wiki.
 851          if ($wiki->wikimode == 'collaborative' || $wiki->wikimode == 'individual') {
 852              // Everybody can read all wikis
 853              //
 854              // Only view capability needed
 855              return has_capability('mod/wiki:viewpage', $context);
 856          } else {
 857              //Error
 858              return false;
 859          }
 860      default: // Error
 861          return false;
 862      }
 863  }
 864  
 865  /**
 866   * Checks if current user can edit a subwiki
 867   *
 868   * @param $subwiki
 869   */
 870  function wiki_user_can_edit($subwiki) {
 871      global $USER;
 872  
 873      $wiki = wiki_get_wiki($subwiki->wikiid);
 874      $cm = get_coursemodule_from_instance('wiki', $wiki->id);
 875      $context = context_module::instance($cm->id);
 876  
 877      // Working depending on activity groupmode
 878      switch (groups_get_activity_groupmode($cm)) {
 879      case NOGROUPS:
 880  
 881          if ($wiki->wikimode == 'collaborative') {
 882              // Collaborative Mode:
 883              // There is a wiki for all the class.
 884              //
 885              // Only edit capbility needed
 886              return has_capability('mod/wiki:editpage', $context);
 887          } else if ($wiki->wikimode == 'individual') {
 888              // Individual Mode
 889              // There is a wiki per user
 890  
 891              // Only the owner of that wiki can edit it
 892              if ($subwiki->userid == $USER->id) {
 893                  return has_capability('mod/wiki:editpage', $context);
 894              } else { // Current user is not the owner of that wiki.
 895  
 896                  // User must have:
 897                  //      mod/wiki:editpage capability
 898                  // and
 899                  //      mod/wiki:managewiki capability
 900                  $edit = has_capability('mod/wiki:editpage', $context);
 901                  $manage = has_capability('mod/wiki:managewiki', $context);
 902  
 903                  return $edit && $manage;
 904              }
 905          } else {
 906              //Error
 907              return false;
 908          }
 909      case SEPARATEGROUPS:
 910          if ($wiki->wikimode == 'collaborative') {
 911              // Collaborative Mode:
 912              // There is one wiki per group.
 913              //
 914              // Only members of subwiki group could edit that wiki
 915              if (groups_is_member($subwiki->groupid)) {
 916                  // Only edit capability needed
 917                  return has_capability('mod/wiki:editpage', $context);
 918              } else { // User is not part of that group
 919                  // User must have:
 920                  //      mod/wiki:managewiki capability
 921                  // and
 922                  //      moodle/site:accessallgroups capability
 923                  // and
 924                  //      mod/wiki:editpage capability
 925                  $manage = has_capability('mod/wiki:managewiki', $context);
 926                  $access = has_capability('moodle/site:accessallgroups', $context);
 927                  $edit = has_capability('mod/wiki:editpage', $context);
 928                  return $manage && $access && $edit;
 929              }
 930          } else if ($wiki->wikimode == 'individual') {
 931              // Individual Mode:
 932              // Each person owns a wiki.
 933              //
 934              // Only the owner of that wiki can edit it
 935              if ($subwiki->userid == $USER->id) {
 936                  return has_capability('mod/wiki:editpage', $context);
 937              } else { // Current user is not the owner of that wiki.
 938                  // User must have:
 939                  //      mod/wiki:managewiki capability
 940                  // and
 941                  //      moodle/site:accessallgroups capability
 942                  // and
 943                  //      mod/wiki:editpage capability
 944                  $manage = has_capability('mod/wiki:managewiki', $context);
 945                  $access = has_capability('moodle/site:accessallgroups', $context);
 946                  $edit = has_capability('mod/wiki:editpage', $context);
 947                  return $manage && $access && $edit;
 948              }
 949          } else {
 950              //Error
 951              return false;
 952          }
 953      case VISIBLEGROUPS:
 954          if ($wiki->wikimode == 'collaborative') {
 955              // Collaborative Mode:
 956              // There is one wiki per group.
 957              //
 958              // Only members of subwiki group could edit that wiki
 959              if (groups_is_member($subwiki->groupid)) {
 960                  // Only edit capability needed
 961                  return has_capability('mod/wiki:editpage', $context);
 962              } else { // User is not part of that group
 963                  // User must have:
 964                  //      mod/wiki:managewiki capability
 965                  // and
 966                  //      mod/wiki:editpage capability
 967                  $manage = has_capability('mod/wiki:managewiki', $context);
 968                  $edit = has_capability('mod/wiki:editpage', $context);
 969                  return $manage && $edit;
 970              }
 971          } else if ($wiki->wikimode == 'individual') {
 972              // Individual Mode:
 973              // Each person owns a wiki.
 974              //
 975              // Only the owner of that wiki can edit it
 976              if ($subwiki->userid == $USER->id) {
 977                  return has_capability('mod/wiki:editpage', $context);
 978              } else { // Current user is not the owner of that wiki.
 979                  // User must have:
 980                  //      mod/wiki:managewiki capability
 981                  // and
 982                  //      mod/wiki:editpage capability
 983                  $manage = has_capability('mod/wiki:managewiki', $context);
 984                  $edit = has_capability('mod/wiki:editpage', $context);
 985                  return $manage && $edit;
 986              }
 987          } else {
 988              //Error
 989              return false;
 990          }
 991      default: // Error
 992          return false;
 993      }
 994  }
 995  
 996  //----------------
 997  // Locks
 998  //----------------
 999  
1000  /**
1001   * Checks if a page-section is locked.
1002   *
1003   * @return true if the combination of section and page is locked, FALSE otherwise.
1004   */
1005  function wiki_is_page_section_locked($pageid, $userid, $section = null) {
1006      global $DB;
1007  
1008      $sql = "pageid = ? AND lockedat > ? AND userid != ?";
1009      $params = array($pageid, time(), $userid);
1010  
1011      if (!empty($section)) {
1012          $sql .= " AND (sectionname = ? OR sectionname IS null)";
1013          $params[] = $section;
1014      }
1015  
1016      return $DB->record_exists_select('wiki_locks', $sql, $params);
1017  }
1018  
1019  /**
1020   * Inserts or updates a wiki_locks record.
1021   */
1022  function wiki_set_lock($pageid, $userid, $section = null, $insert = false) {
1023      global $DB;
1024  
1025      if (wiki_is_page_section_locked($pageid, $userid, $section)) {
1026          return false;
1027      }
1028  
1029      $params = array('pageid' => $pageid, 'userid' => $userid, 'sectionname' => $section);
1030  
1031      $lock = $DB->get_record('wiki_locks', $params);
1032  
1033      if (!empty($lock)) {
1034          $DB->update_record('wiki_locks', array('id' => $lock->id, 'lockedat' => time() + LOCK_TIMEOUT));
1035      } else if ($insert) {
1036          $DB->insert_record('wiki_locks',
1037              array('pageid' => $pageid, 'sectionname' => $section, 'userid' => $userid, 'lockedat' => time() + LOCK_TIMEOUT));
1038      }
1039  
1040      return true;
1041  }
1042  
1043  /**
1044   * Deletes wiki_locks that are not in use. (F.Ex. after submitting the changes). If no userid is present, it deletes ALL the wiki_locks of a specific page.
1045   *
1046   * @param int $pageid page id.
1047   * @param int $userid id of user for which lock is deleted.
1048   * @param string $section section to be deleted.
1049   * @param bool $delete_from_db deleted from db.
1050   * @param bool $delete_section_and_page delete section and page version.
1051   */
1052  function wiki_delete_locks($pageid, $userid = null, $section = null, $delete_from_db = true, $delete_section_and_page = false) {
1053      global $DB;
1054  
1055      $wiki = wiki_get_wiki_from_pageid($pageid);
1056      $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1057      $context = context_module::instance($cm->id);
1058  
1059      $params = array('pageid' => $pageid);
1060  
1061      if (!empty($userid)) {
1062          $params['userid'] = $userid;
1063      }
1064  
1065      if (!empty($section)) {
1066          $params['sectionname'] = $section;
1067      }
1068  
1069      if ($delete_from_db) {
1070          $DB->delete_records('wiki_locks', $params);
1071          if ($delete_section_and_page && !empty($section)) {
1072              $params['sectionname'] = null;
1073              $DB->delete_records('wiki_locks', $params);
1074          }
1075          $event = \mod_wiki\event\page_locks_deleted::create(
1076          array(
1077              'context' => $context,
1078              'objectid' => $pageid,
1079              'relateduserid' => $userid,
1080              'other' => array(
1081                  'section' => $section
1082                  )
1083              ));
1084          // No need to add snapshot, as important data is section, userid and pageid, which is part of event.
1085          $event->trigger();
1086      } else {
1087          $DB->set_field('wiki_locks', 'lockedat', time(), $params);
1088      }
1089  }
1090  
1091  /**
1092   * Deletes wiki_locks that expired 1 hour ago.
1093   */
1094  function wiki_delete_old_locks() {
1095      global $DB;
1096  
1097      $DB->delete_records_select('wiki_locks', "lockedat < ?", array(time() - 3600));
1098  }
1099  
1100  /**
1101   * Deletes wiki_links. It can be sepecific link or links attached in subwiki
1102   *
1103   * @global mixed $DB database object
1104   * @param int $linkid id of the link to be deleted
1105   * @param int $topageid links to the specific page
1106   * @param int $frompageid links from specific page
1107   * @param int $subwikiid links to subwiki
1108   */
1109  function wiki_delete_links($linkid = null, $topageid = null, $frompageid = null, $subwikiid = null) {
1110      global $DB;
1111      $params = array();
1112  
1113      // if link id is givien then don't check for anything else
1114      if (!empty($linkid)) {
1115          $params['id'] = $linkid;
1116      } else {
1117          if (!empty($topageid)) {
1118              $params['topageid'] = $topageid;
1119          }
1120          if (!empty($frompageid)) {
1121              $params['frompageid'] = $frompageid;
1122          }
1123          if (!empty($subwikiid)) {
1124              $params['subwikiid'] = $subwikiid;
1125          }
1126      }
1127  
1128      //Delete links if any params are passed, else nothing to delete.
1129      if (!empty($params)) {
1130          $DB->delete_records('wiki_links', $params);
1131      }
1132  }
1133  
1134  /**
1135   * Delete wiki synonyms related to subwikiid or page
1136   *
1137   * @param int $subwikiid id of sunbwiki
1138   * @param int $pageid id of page
1139   */
1140  function wiki_delete_synonym($subwikiid, $pageid = null) {
1141      global $DB;
1142  
1143      $params = array('subwikiid' => $subwikiid);
1144      if (!is_null($pageid)) {
1145          $params['pageid'] = $pageid;
1146      }
1147      $DB->delete_records('wiki_synonyms', $params, IGNORE_MISSING);
1148  }
1149  
1150  /**
1151   * Delete pages and all related data
1152   *
1153   * @param mixed $context context in which page needs to be deleted.
1154   * @param mixed $pageids id's of pages to be deleted
1155   * @param int $subwikiid id of the subwiki for which all pages should be deleted
1156   */
1157  function wiki_delete_pages($context, $pageids = null, $subwikiid = null) {
1158      global $DB, $CFG;
1159  
1160      if (!empty($pageids) && is_int($pageids)) {
1161         $pageids = array($pageids);
1162      } else if (!empty($subwikiid)) {
1163          $pageids = wiki_get_page_list($subwikiid);
1164      }
1165  
1166      //If there is no pageid then return as we can't delete anything.
1167      if (empty($pageids)) {
1168          return;
1169      }
1170  
1171      /// Delete page and all it's relevent data
1172      foreach ($pageids as $pageid) {
1173          if (is_object($pageid)) {
1174              $pageid = $pageid->id;
1175          }
1176  
1177          //Delete page comments
1178          $comments = wiki_get_comments($context->id, $pageid);
1179          foreach ($comments as $commentid => $commentvalue) {
1180              wiki_delete_comment($commentid, $context, $pageid);
1181          }
1182  
1183          //Delete page tags
1184          core_tag_tag::remove_all_item_tags('mod_wiki', 'wiki_pages', $pageid);
1185  
1186          //Delete Synonym
1187          wiki_delete_synonym($subwikiid, $pageid);
1188  
1189          //Delete all page versions
1190          wiki_delete_page_versions(array($pageid=>array(0)), $context);
1191  
1192          //Delete all page locks
1193          wiki_delete_locks($pageid);
1194  
1195          //Delete all page links
1196          wiki_delete_links(null, $pageid);
1197  
1198          $params = array('id' => $pageid);
1199  
1200          // Get page before deleting.
1201          $page = $DB->get_record('wiki_pages', $params);
1202  
1203          //Delete page
1204          $DB->delete_records('wiki_pages', $params);
1205  
1206          // Trigger page_deleted event.
1207          $event = \mod_wiki\event\page_deleted::create(
1208                  array(
1209                      'context' => $context,
1210                      'objectid' => $pageid,
1211                      'other' => array('subwikiid' => $subwikiid)
1212                      ));
1213          $event->add_record_snapshot('wiki_pages', $page);
1214          $event->trigger();
1215      }
1216  }
1217  
1218  /**
1219   * Delete specificed versions of a page or versions created by users
1220   * if version is 0 then it will remove all versions of the page
1221   *
1222   * @param array $deleteversions delete versions for a page
1223   * @param context_module $context module context
1224   */
1225  function wiki_delete_page_versions($deleteversions, $context = null) {
1226      global $DB;
1227  
1228      /// delete page-versions
1229      foreach ($deleteversions as $id => $versions) {
1230          $params = array('pageid' => $id);
1231          if (is_null($context)) {
1232              $wiki = wiki_get_wiki_from_pageid($id);
1233              $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1234              $context = context_module::instance($cm->id);
1235          }
1236          // Delete all versions, if version specified is 0.
1237          if (in_array(0, $versions)) {
1238              $oldversions = $DB->get_records('wiki_versions', $params);
1239              $DB->delete_records('wiki_versions', $params, IGNORE_MISSING);
1240          } else {
1241              list($insql, $param) = $DB->get_in_or_equal($versions);
1242              $insql .= ' AND pageid = ?';
1243              array_push($param, $params['pageid']);
1244              $oldversions = $DB->get_records_select('wiki_versions', 'version ' . $insql, $param);
1245              $DB->delete_records_select('wiki_versions', 'version ' . $insql, $param);
1246          }
1247          foreach ($oldversions as $version) {
1248              // Trigger page version deleted event.
1249              $event = \mod_wiki\event\page_version_deleted::create(
1250                      array(
1251                          'context' => $context,
1252                          'objectid' => $version->id,
1253                          'other' => array(
1254                              'pageid' => $id
1255                          )
1256                      ));
1257              $event->add_record_snapshot('wiki_versions', $version);
1258              $event->trigger();
1259          }
1260      }
1261  }
1262  
1263  function wiki_get_comment($commentid){
1264      global $DB;
1265      return $DB->get_record('comments', array('id' => $commentid));
1266  }
1267  
1268  /**
1269   * Returns all comments by context and pageid
1270   *
1271   * @param int $contextid Current context id
1272   * @param int $pageid Current pageid
1273   **/
1274  function wiki_get_comments($contextid, $pageid) {
1275      global $DB;
1276  
1277      return $DB->get_records('comments', array('contextid' => $contextid, 'itemid' => $pageid, 'commentarea' => 'wiki_page'), 'timecreated ASC');
1278  }
1279  
1280  /**
1281   * Add comments ro database
1282   *
1283   * @param object $context. Current context
1284   * @param int $pageid. Current pageid
1285   * @param string $content. Content of the comment
1286   * @param string editor. Version of editor we are using.
1287   **/
1288  function wiki_add_comment($context, $pageid, $content, $editor) {
1289      global $CFG;
1290      require_once($CFG->dirroot . '/comment/lib.php');
1291  
1292      list($context, $course, $cm) = get_context_info_array($context->id);
1293      $cmt = new stdclass();
1294      $cmt->context = $context;
1295      $cmt->itemid = $pageid;
1296      $cmt->area = 'wiki_page';
1297      $cmt->course = $course;
1298      $cmt->component = 'mod_wiki';
1299  
1300      $manager = new comment($cmt);
1301  
1302      if ($editor == 'creole') {
1303          $manager->add($content, FORMAT_CREOLE);
1304      } else if ($editor == 'html') {
1305          $manager->add($content, FORMAT_HTML);
1306      } else if ($editor == 'nwiki') {
1307          $manager->add($content, FORMAT_NWIKI);
1308      }
1309  
1310  }
1311  
1312  /**
1313   * Delete comments from database
1314   *
1315   * @param $idcomment. Id of comment which will be deleted
1316   * @param $context. Current context
1317   * @param $pageid. Current pageid
1318   **/
1319  function wiki_delete_comment($idcomment, $context, $pageid) {
1320      global $CFG;
1321      require_once($CFG->dirroot . '/comment/lib.php');
1322  
1323      list($context, $course, $cm) = get_context_info_array($context->id);
1324      $cmt = new stdClass();
1325      $cmt->context = $context;
1326      $cmt->itemid = $pageid;
1327      $cmt->area = 'wiki_page';
1328      $cmt->course = $course;
1329      $cmt->component = 'mod_wiki';
1330  
1331      $manager = new comment($cmt);
1332      $manager->delete($idcomment);
1333  
1334  }
1335  
1336  /**
1337   * Delete al comments from wiki
1338   *
1339   **/
1340  function wiki_delete_comments_wiki() {
1341      global $PAGE, $DB;
1342  
1343      $cm = $PAGE->cm;
1344      $context = context_module::instance($cm->id);
1345  
1346      $table = 'comments';
1347      $select = 'contextid = ?';
1348  
1349      $DB->delete_records_select($table, $select, array($context->id));
1350  
1351  }
1352  
1353  function wiki_add_progress($pageid, $oldversionid, $versionid, $progress) {
1354      global $DB;
1355      for ($v = $oldversionid + 1; $v <= $versionid; $v++) {
1356          $user = wiki_get_wiki_page_id($pageid, $v);
1357  
1358          $DB->insert_record('wiki_progress', array('userid' => $user->userid, 'pageid' => $pageid, 'versionid' => $v, 'progress' => $progress));
1359      }
1360  }
1361  
1362  function wiki_get_wiki_page_id($pageid, $id) {
1363      global $DB;
1364      return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'id' => $id));
1365  }
1366  
1367  function wiki_print_page_content($page, $context, $subwikiid) {
1368      global $OUTPUT, $CFG;
1369  
1370      if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) {
1371          $content = wiki_refresh_cachedcontent($page);
1372          $page = $content['page'];
1373      }
1374  
1375      if (isset($content)) {
1376          $box = '';
1377          foreach ($content['sections'] as $s) {
1378              $box .= '<p>' . get_string('repeatedsection', 'wiki', $s) . '</p>';
1379          }
1380  
1381          if (!empty($box)) {
1382              echo $OUTPUT->box($box);
1383          }
1384      }
1385      $html = file_rewrite_pluginfile_urls($page->cachedcontent, 'pluginfile.php', $context->id, 'mod_wiki', 'attachments', $subwikiid);
1386      $html = format_text($html, FORMAT_HTML, array('overflowdiv' => true, 'allowid' => true));
1387      echo $OUTPUT->box($html);
1388  
1389      echo $OUTPUT->tag_list(core_tag_tag::get_item_tags('mod_wiki', 'wiki_pages', $page->id),
1390              null, 'wiki-tags');
1391  
1392      wiki_increment_pageviews($page);
1393  }
1394  
1395  /**
1396   * This function trims any given text and returns it with some dots at the end
1397   *
1398   * @param string $text
1399   * @param string $limit
1400   *
1401   * @return string
1402   */
1403  function wiki_trim_string($text, $limit = 25) {
1404  
1405      if (core_text::strlen($text) > $limit) {
1406          $text = core_text::substr($text, 0, $limit) . '...';
1407      }
1408  
1409      return $text;
1410  }
1411  
1412  /**
1413   * Prints default edit form fields and buttons
1414   *
1415   * @param string $format Edit form format (html, creole...)
1416   * @param integer $version Version number. A negative number means no versioning.
1417   */
1418  
1419  function wiki_print_edit_form_default_fields($format, $pageid, $version = -1, $upload = false, $deleteuploads = array()) {
1420      global $CFG, $PAGE, $OUTPUT;
1421  
1422      echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
1423  
1424      if ($version >= 0) {
1425          echo '<input type="hidden" name="version" value="' . $version . '" />';
1426      }
1427  
1428      echo '<input type="hidden" name="format" value="' . $format . '"/>';
1429  
1430      //attachments
1431      require_once($CFG->dirroot . '/lib/form/filemanager.php');
1432  
1433      $filemanager = new MoodleQuickForm_filemanager('attachments', get_string('wikiattachments', 'wiki'), array('id' => 'attachments'), array('subdirs' => false, 'maxfiles' => 99, 'maxbytes' => $CFG->maxbytes));
1434  
1435      $value = file_get_submitted_draft_itemid('attachments');
1436      if (!empty($value) && !$upload) {
1437          $filemanager->setValue($value);
1438      }
1439  
1440      echo "<fieldset class=\"wiki-upload-section clearfix\"><legend class=\"ftoggler\">" . get_string("uploadtitle", 'wiki') . "</legend>";
1441  
1442      echo $OUTPUT->container_start('container');
1443      print $filemanager->toHtml();
1444      echo $OUTPUT->container_end();
1445  
1446      $cm = $PAGE->cm;
1447      $context = context_module::instance($cm->id);
1448  
1449      echo $OUTPUT->container_start('container wiki-upload-table');
1450      wiki_print_upload_table($context, 'wiki_upload', $pageid, $deleteuploads);
1451      echo $OUTPUT->container_end();
1452  
1453      echo "</fieldset>";
1454  
1455      echo '<input class="wiki_button btn btn-secondary" type="submit" name="editoption" value="'
1456          . get_string('save', 'wiki') . '" />';
1457      echo '<input class="wiki_button btn btn-secondary" type="submit" name="editoption" value="'
1458          . get_string('upload', 'wiki') . '" />';
1459      echo '<input class="wiki_button btn btn-secondary" type="submit" name="editoption" value="' . get_string('preview') . '" />';
1460      echo '<input class="wiki_button btn btn-secondary" type="submit" name="editoption" value="' . get_string('cancel') . '" />';
1461  }
1462  
1463  /**
1464   * Prints a table with the files attached to a wiki page
1465   * @param object $context
1466   * @param string $filearea
1467   * @param int $fileitemid
1468   * @param array deleteuploads
1469   */
1470  function wiki_print_upload_table($context, $filearea, $fileitemid, $deleteuploads = array()) {
1471      global $CFG, $OUTPUT;
1472  
1473      $htmltable = new html_table();
1474  
1475      $htmltable->head = array(get_string('deleteupload', 'wiki'), get_string('uploadname', 'wiki'), get_string('uploadactions', 'wiki'));
1476  
1477      $fs = get_file_storage();
1478      $files = $fs->get_area_files($context->id, 'mod_wiki', $filearea, $fileitemid); //TODO: this is weird (skodak)
1479  
1480      foreach ($files as $file) {
1481          if (!$file->is_directory()) {
1482              $checkbox = '<input type="checkbox" name="deleteupload[]", value="' . $file->get_pathnamehash() . '"';
1483  
1484              if (in_array($file->get_pathnamehash(), $deleteuploads)) {
1485                  $checkbox .= ' checked="checked"';
1486              }
1487  
1488              $checkbox .= " />";
1489  
1490              $htmltable->data[] = array($checkbox, '<a href="' . file_encode_url($CFG->wwwroot . '/pluginfile.php', '/' . $context->id . '/wiki_upload/' . $fileitemid . '/' . $file->get_filename()) . '">' . $file->get_filename() . '</a>', "");
1491          }
1492      }
1493  
1494      print '<h3 class="upload-table-title">' . get_string('uploadfiletitle', 'wiki') . "</h3>";
1495      print html_writer::table($htmltable);
1496  }
1497  
1498  /**
1499   * Generate wiki's page tree
1500   *
1501   * @param page_wiki $page. A wiki page object
1502   * @param navigation_node $node. Starting navigation_node
1503   * @param array $keys. An array to store keys
1504   * @return an array with all tree nodes
1505   */
1506  function wiki_build_tree($page, $node, &$keys) {
1507      $content = array();
1508      static $icon = null;
1509      if ($icon === null) {
1510          // Substitute the default navigation icon with empty image.
1511          $icon = new pix_icon('spacer', '');
1512      }
1513      $pages = wiki_get_linked_pages($page->id);
1514      foreach ($pages as $p) {
1515          $key = $page->id . ':' . $p->id;
1516          if (in_array($key, $keys)) {
1517              break;
1518          }
1519          array_push($keys, $key);
1520          $l = wiki_parser_link($p);
1521          $link = new moodle_url('/mod/wiki/view.php', array('pageid' => $p->id));
1522          // navigation_node::get_content will format the title for us
1523          $nodeaux = $node->add($p->title, $link, null, null, null, $icon);
1524          if ($l['new']) {
1525              $nodeaux->add_class('wiki_newentry');
1526          }
1527          wiki_build_tree($p, $nodeaux, $keys);
1528      }
1529      $content[] = $node;
1530      return $content;
1531  }
1532  
1533  /**
1534   * Get linked pages from page
1535   * @param int $pageid
1536   */
1537  function wiki_get_linked_pages($pageid) {
1538      global $DB;
1539  
1540      $sql = "SELECT p.id, p.title
1541              FROM {wiki_pages} p
1542              JOIN {wiki_links} l ON l.topageid = p.id
1543              WHERE l.frompageid = ?
1544              ORDER BY p.title ASC";
1545      return $DB->get_records_sql($sql, array($pageid));
1546  }
1547  
1548  /**
1549   * Get updated pages from wiki
1550   * @param int $pageid
1551   */
1552  function wiki_get_updated_pages_by_subwiki($swid) {
1553      global $DB, $USER;
1554  
1555      $sql = "SELECT *
1556              FROM {wiki_pages}
1557              WHERE subwikiid = ? AND timemodified > ?
1558              ORDER BY timemodified DESC";
1559      return $DB->get_records_sql($sql, array($swid, $USER->lastlogin));
1560  }
1561  
1562  /**
1563   * Check if the user can create pages in a certain wiki.
1564   * @param context $context Wiki's context.
1565   * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
1566   * @return bool True if user can create pages, false otherwise.
1567   * @since Moodle 3.1
1568   */
1569  function wiki_can_create_pages($context, $user = null) {
1570      return has_capability('mod/wiki:createpage', $context, $user);
1571  }
1572  
1573  /**
1574   * Get a sub wiki instance by wiki id, group id and user id.
1575   * If the wiki doesn't exist in DB it will return an isntance with id -1.
1576   *
1577   * @param int $wikiid  Wiki ID.
1578   * @param int $groupid Group ID.
1579   * @param int $userid  User ID.
1580   * @return object      Subwiki instance.
1581   * @since Moodle 3.1
1582   */
1583  function wiki_get_possible_subwiki_by_group($wikiid, $groupid, $userid = 0) {
1584      if (!$subwiki = wiki_get_subwiki_by_group($wikiid, $groupid, $userid)) {
1585          $subwiki = new stdClass();
1586          $subwiki->id = -1;
1587          $subwiki->wikiid = $wikiid;
1588          $subwiki->groupid = $groupid;
1589          $subwiki->userid = $userid;
1590      }
1591      return $subwiki;
1592  }
1593  
1594  /**
1595   * Get all the possible subwikis visible to the user in a wiki.
1596   * It will return all the subwikis that can be created in a wiki, even if they don't exist in DB yet.
1597   *
1598   * @param  stdClass $wiki          Wiki to get the subwikis from.
1599   * @param  cm_info|stdClass $cm    Optional. The course module object.
1600   * @param  context_module $context Optional. Context of wiki module.
1601   * @return array                   List of subwikis.
1602   * @since Moodle 3.1
1603   */
1604  function wiki_get_visible_subwikis($wiki, $cm = null, $context = null) {
1605      global $USER;
1606  
1607      $subwikis = array();
1608  
1609      if (empty($wiki) or !is_object($wiki)) {
1610          // Wiki not valid.
1611          return $subwikis;
1612      }
1613  
1614      if (empty($cm)) {
1615          $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1616      }
1617      if (empty($context)) {
1618          $context = context_module::instance($cm->id);
1619      }
1620  
1621      if (!has_capability('mod/wiki:viewpage', $context)) {
1622          return $subwikis;
1623      }
1624  
1625      $manage = has_capability('mod/wiki:managewiki', $context);
1626  
1627      if (!$groupmode = groups_get_activity_groupmode($cm)) {
1628          // No groups.
1629          if ($wiki->wikimode == 'collaborative') {
1630              // Only 1 subwiki.
1631              $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, 0);
1632          } else if ($wiki->wikimode == 'individual') {
1633              // There's 1 subwiki per user.
1634              if ($manage) {
1635                  // User can view all subwikis.
1636                  $users = get_enrolled_users($context);
1637                  foreach ($users as $user) {
1638                      $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $user->id);
1639                  }
1640              } else {
1641                  // User can only see his subwiki.
1642                  $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $USER->id);
1643              }
1644          }
1645      } else {
1646          if ($wiki->wikimode == 'collaborative') {
1647              // 1 subwiki per group.
1648              $aag = has_capability('moodle/site:accessallgroups', $context);
1649              if ($aag || $groupmode == VISIBLEGROUPS) {
1650                  // User can see all groups.
1651                  $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
1652                  $allparticipants = new stdClass();
1653                  $allparticipants->id = 0;
1654                  array_unshift($allowedgroups, $allparticipants); // Add all participants.
1655              } else {
1656                  // User can only see the groups he belongs to.
1657                  $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
1658              }
1659  
1660              foreach ($allowedgroups as $group) {
1661                  $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, 0);
1662              }
1663          } else if ($wiki->wikimode == 'individual') {
1664              // 1 subwiki per user and group.
1665  
1666              if ($manage || $groupmode == VISIBLEGROUPS) {
1667                  // User can view all subwikis.
1668                  $users = get_enrolled_users($context);
1669                  foreach ($users as $user) {
1670                      // Get all the groups this user belongs to.
1671                      $groups = groups_get_all_groups($cm->course, $user->id);
1672                      if (!empty($groups)) {
1673                          foreach ($groups as $group) {
1674                              $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, $user->id);
1675                          }
1676                      } else {
1677                          // User doesn't belong to any group, add it to group 0.
1678                          $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $user->id);
1679                      }
1680                  }
1681              } else {
1682                  // The user can only see the subwikis of the groups he belongs.
1683                  $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
1684                  foreach ($allowedgroups as $group) {
1685                      $users = groups_get_members($group->id);
1686                      foreach ($users as $user) {
1687                          $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, $user->id);
1688                      }
1689                  }
1690              }
1691          }
1692      }
1693  
1694      return $subwikis;
1695  }
1696  
1697  /**
1698   * Utility function for getting a subwiki by group and user, validating that the user can view it.
1699   * If the subwiki doesn't exists in DB yet it'll have id -1.
1700   *
1701   * @param stdClass $wiki The wiki.
1702   * @param int $groupid Group ID. 0 means the subwiki doesn't use groups.
1703   * @param int $userid User ID. 0 means the subwiki doesn't use users.
1704   * @return stdClass Subwiki. If it doesn't exists in DB yet it'll have id -1. If the user can't view the
1705   *                  subwiki this function will return false.
1706   * @since  Moodle 3.1
1707   * @throws moodle_exception
1708   */
1709  function wiki_get_subwiki_by_group_and_user_with_validation($wiki, $groupid, $userid) {
1710      global $USER, $DB;
1711  
1712      // Get subwiki based on group and user.
1713      if (!$subwiki = wiki_get_subwiki_by_group($wiki->id, $groupid, $userid)) {
1714  
1715          // The subwiki doesn't exist.
1716          // Validate if user is valid.
1717          if ($userid != 0) {
1718              $user = core_user::get_user($userid, '*', MUST_EXIST);
1719              core_user::require_active_user($user);
1720          }
1721  
1722          // Validate that groupid is valid.
1723          if ($groupid != 0 && !groups_group_exists($groupid)) {
1724              throw new moodle_exception('cannotfindgroup', 'error');
1725          }
1726  
1727          // Valid data but subwiki not found. We'll simulate a subwiki object to check if the user would be able to see it
1728          // if it existed. If he's able to see it then we'll return an empty array because the subwiki has no pages.
1729          $subwiki = new stdClass();
1730          $subwiki->id = -1;
1731          $subwiki->wikiid = $wiki->id;
1732          $subwiki->userid = $userid;
1733          $subwiki->groupid = $groupid;
1734      }
1735  
1736      // Check that the user can view the subwiki. This function checks capabilities.
1737      if (!wiki_user_can_view($subwiki, $wiki)) {
1738          return false;
1739      }
1740  
1741      return $subwiki;
1742  }
1743  
1744  /**
1745   * Returns wiki pages tagged with a specified tag.
1746   *
1747   * This is a callback used by the tag area mod_wiki/wiki_pages to search for wiki pages
1748   * tagged with a specific tag.
1749   *
1750   * @param core_tag_tag $tag
1751   * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1752   *             are displayed on the page and the per-page limit may be bigger
1753   * @param int $fromctx context id where the link was displayed, may be used by callbacks
1754   *            to display items in the same context first
1755   * @param int $ctx context id where to search for records
1756   * @param bool $rec search in subcontexts as well
1757   * @param int $page 0-based number of page being displayed
1758   * @return \core_tag\output\tagindex
1759   */
1760  function mod_wiki_get_tagged_pages($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1761      global $OUTPUT;
1762      $perpage = $exclusivemode ? 20 : 5;
1763  
1764      // Build the SQL query.
1765      $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1766      $query = "SELECT wp.id, wp.title, ws.userid, ws.wikiid, ws.id AS subwikiid, ws.groupid, w.wikimode,
1767                      cm.id AS cmid, c.id AS courseid, c.shortname, c.fullname, $ctxselect
1768                  FROM {wiki_pages} wp
1769                  JOIN {wiki_subwikis} ws ON wp.subwikiid = ws.id
1770                  JOIN {wiki} w ON w.id = ws.wikiid
1771                  JOIN {modules} m ON m.name='wiki'
1772                  JOIN {course_modules} cm ON cm.module = m.id AND cm.instance = w.id
1773                  JOIN {tag_instance} tt ON wp.id = tt.itemid
1774                  JOIN {course} c ON cm.course = c.id
1775                  JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
1776                 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
1777                   AND cm.deletioninprogress = 0
1778                   AND wp.id %ITEMFILTER% AND c.id %COURSEFILTER%";
1779  
1780      $params = array('itemtype' => 'wiki_pages', 'tagid' => $tag->id, 'component' => 'mod_wiki',
1781          'coursemodulecontextlevel' => CONTEXT_MODULE);
1782  
1783      if ($ctx) {
1784          $context = $ctx ? context::instance_by_id($ctx) : context_system::instance();
1785          $query .= $rec ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
1786          $params['contextid'] = $context->id;
1787          $params['path'] = $context->path.'/%';
1788      }
1789  
1790      $query .= " ORDER BY ";
1791      if ($fromctx) {
1792          // In order-clause specify that modules from inside "fromctx" context should be returned first.
1793          $fromcontext = context::instance_by_id($fromctx);
1794          $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
1795          $params['fromcontextid'] = $fromcontext->id;
1796          $params['frompath'] = $fromcontext->path.'/%';
1797      }
1798      $query .= ' c.sortorder, cm.id, wp.id';
1799  
1800      $totalpages = $page + 1;
1801  
1802      // Use core_tag_index_builder to build and filter the list of items.
1803      $builder = new core_tag_index_builder('mod_wiki', 'wiki_pages', $query, $params, $page * $perpage, $perpage + 1);
1804      while ($item = $builder->has_item_that_needs_access_check()) {
1805          context_helper::preload_from_record($item);
1806          $courseid = $item->courseid;
1807          if (!$builder->can_access_course($courseid)) {
1808              $builder->set_accessible($item, false);
1809              continue;
1810          }
1811          $modinfo = get_fast_modinfo($builder->get_course($courseid));
1812          // Set accessibility of this item and all other items in the same course.
1813          $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
1814              if ($taggeditem->courseid == $courseid) {
1815                  $accessible = false;
1816                  if (($cm = $modinfo->get_cm($taggeditem->cmid)) && $cm->uservisible) {
1817                      $subwiki = (object)array('id' => $taggeditem->subwikiid, 'groupid' => $taggeditem->groupid,
1818                          'userid' => $taggeditem->userid, 'wikiid' => $taggeditem->wikiid);
1819                      $wiki = (object)array('id' => $taggeditem->wikiid, 'wikimode' => $taggeditem->wikimode,
1820                          'course' => $cm->course);
1821                      $accessible = wiki_user_can_view($subwiki, $wiki);
1822                  }
1823                  $builder->set_accessible($taggeditem, $accessible);
1824              }
1825          });
1826      }
1827  
1828      $items = $builder->get_items();
1829      if (count($items) > $perpage) {
1830          $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
1831          array_pop($items);
1832      }
1833  
1834      // Build the display contents.
1835      if ($items) {
1836          $tagfeed = new core_tag\output\tagfeed();
1837          foreach ($items as $item) {
1838              context_helper::preload_from_record($item);
1839              $modinfo = get_fast_modinfo($item->courseid);
1840              $cm = $modinfo->get_cm($item->cmid);
1841              $pageurl = new moodle_url('/mod/wiki/view.php', array('pageid' => $item->id));
1842              $pagename = format_string($item->title, true, array('context' => context_module::instance($item->cmid)));
1843              $pagename = html_writer::link($pageurl, $pagename);
1844              $courseurl = course_get_url($item->courseid, $cm->sectionnum);
1845              $cmname = html_writer::link($cm->url, $cm->get_formatted_name());
1846              $coursename = format_string($item->fullname, true, array('context' => context_course::instance($item->courseid)));
1847              $coursename = html_writer::link($courseurl, $coursename);
1848              $icon = html_writer::link($pageurl, html_writer::empty_tag('img', array('src' => $cm->get_icon_url())));
1849              $tagfeed->add($icon, $pagename, $cmname.'<br>'.$coursename);
1850          }
1851  
1852          $content = $OUTPUT->render_from_template('core_tag/tagfeed',
1853                  $tagfeed->export_for_template($OUTPUT));
1854  
1855          return new core_tag\output\tagindex($tag, 'mod_wiki', 'wiki_pages', $content,
1856                  $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1857      }
1858  }