MDL-63660 tool_dataprivacy: Increase expected export file size
[moodle.git] / mod / wiki / locallib.php
blobb4e123067fa564c7764dfbe2ded0edd5df6aef33
1 <?php
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.
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/>.
18 /**
19 * This contains functions and classes that will be used by scripts in wiki module
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
25 * @author Jordi Piguillem
26 * @author Marc Alier
27 * @author David Jimenez
28 * @author Josep Arus
29 * @author Daniel Serrano
30 * @author Kenneth Riba
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') || die();
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');
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', '-');
49 define('LOCK_TIMEOUT', 30);
51 /**
52 * Get a wiki instance
53 * @param int $wikiid the instance id of wiki
55 function wiki_get_wiki($wikiid) {
56 global $DB;
58 return $DB->get_record('wiki', array('id' => $wikiid));
61 /**
62 * Get sub wiki instances with same wiki id
63 * @param int $wikiid
65 function wiki_get_subwikis($wikiid) {
66 global $DB;
67 return $DB->get_records('wiki_subwikis', array('wikiid' => $wikiid));
70 /**
71 * Get a sub wiki instance by wiki id and group id
72 * @param int $wikiid
73 * @param int $groupid
74 * @return object
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));
81 /**
82 * Get a sub wiki instace by instance id
83 * @param int $subwikiid
84 * @return object
86 function wiki_get_subwiki($subwikiid) {
87 global $DB;
88 return $DB->get_record('wiki_subwikis', array('id' => $subwikiid));
92 /**
93 * Add a new sub wiki instance
94 * @param int $wikiid
95 * @param int $groupid
96 * @return int $insertid
98 function wiki_add_subwiki($wikiid, $groupid, $userid = 0) {
99 global $DB;
101 $record = new StdClass();
102 $record->wikiid = $wikiid;
103 $record->groupid = $groupid;
104 $record->userid = $userid;
106 $insertid = $DB->insert_record('wiki_subwikis', $record);
107 return $insertid;
111 * Get a wiki instance by pageid
112 * @param int $pageid
113 * @return object
115 function wiki_get_wiki_from_pageid($pageid) {
116 global $DB;
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";
124 return $DB->get_record_sql($sql, array($pageid));
128 * Get a wiki page by pageid
129 * @param int $pageid
130 * @return object
132 function wiki_get_page($pageid) {
133 global $DB;
134 return $DB->get_record('wiki_pages', array('id' => $pageid));
138 * Get latest version of wiki page
139 * @param int $pageid
140 * @return object
142 function wiki_get_current_version($pageid) {
143 global $DB;
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);
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
161 function wiki_get_last_version($pageid) {
162 return wiki_get_current_version($pageid);
166 * Get page section
167 * @param int $pageid
168 * @param string $section
170 function wiki_get_section_page($page, $section) {
172 $version = wiki_get_current_version($page->id);
173 return wiki_parser_proxy::get_section($version->content, $version->contentformat, $section);
177 * Get a wiki page by page title
178 * @param int $swid, sub wiki id
179 * @param string $title
180 * @return object
182 function wiki_get_page_by_title($swid, $title) {
183 global $DB;
184 return $DB->get_record('wiki_pages', array('subwikiid' => $swid, 'title' => $title));
188 * Get a version record by record id
189 * @param int $versionid, the version id
190 * @return object
192 function wiki_get_version($versionid) {
193 global $DB;
194 return $DB->get_record('wiki_versions', array('id' => $versionid));
198 * Get first page of wiki instace
199 * @param int $subwikiid
200 * @param int $module, wiki instance object
202 function wiki_get_first_page($subwikid, $module = null) {
203 global $DB, $USER;
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));
214 function wiki_save_section($wikipage, $sectiontitle, $sectioncontent, $userid) {
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);
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);
224 $newcontent = $content[0] . $sectioncontent . $content[2];
226 return wiki_save_page($wikipage, $newcontent, $userid);
227 } else {
228 return false;
233 * Save page content
234 * @param object $wikipage
235 * @param string $newcontent
236 * @param int $userid
238 function wiki_save_page($wikipage, $newcontent, $userid) {
239 global $DB;
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);
245 if (has_capability('mod/wiki:editpage', $context)) {
246 $version = wiki_get_current_version($wikipage->id);
248 $version->content = $newcontent;
249 $version->userid = $userid;
250 $version->version++;
251 $version->timecreated = time();
252 $version->id = $DB->insert_record('wiki_versions', $version);
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
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;
276 function wiki_refresh_cachedcontent($page, $newcontent = null) {
277 global $DB;
279 $version = wiki_get_current_version($page->id);
280 if (empty($version)) {
281 return null;
283 if (!isset($newcontent)) {
284 $newcontent = $version->content;
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);
293 wiki_refresh_page_links($page, $parseroutput['link_count']);
295 return array('page' => $page, 'sections' => $parseroutput['repeated_sections'], 'version' => $version->version);
299 * Restore a page with specified version.
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
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
316 $event->add_record_snapshot('wiki_versions', $version);
317 $event->trigger();
318 return $return['page'];
321 function wiki_refresh_page_links($page, $links) {
322 global $DB;
324 $DB->delete_records('wiki_links', array('frompageid' => $page->id));
325 foreach ($links as $linkname => $linkinfo) {
327 $newlink = new stdClass();
328 $newlink->subwikiid = $page->subwikiid;
329 $newlink->frompageid = $page->id;
331 if ($linkinfo['new']) {
332 $newlink->tomissingpage = $linkname;
333 } else {
334 $newlink->topageid = $linkinfo['pageid'];
337 try {
338 $DB->insert_record('wiki_links', $newlink);
339 } catch (dml_exception $e) {
340 debugging($e->getMessage());
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
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;
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;
372 $versionid = null;
373 $versionid = $DB->insert_record('wiki_versions', $version);
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;
387 $pageid = $DB->insert_record('wiki_pages', $page);
389 // Setting the pageid
390 $version->id = $versionid;
391 $version->pageid = $pageid;
392 $DB->update_record('wiki_versions', $version);
394 $event = \mod_wiki\event\page_created::create(
395 array(
396 'context' => $context,
397 'objectid' => $pageid
400 $event->trigger();
402 wiki_make_cache_expire($page->title);
403 return $pageid;
406 function wiki_make_cache_expire($pagename) {
407 global $DB;
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 = ?
415 $DB->execute ($sql, array($pagename));
419 * Get a specific version of page
420 * @param int $pageid
421 * @param int $version
423 function wiki_get_wiki_page_version($pageid, $version) {
424 global $DB;
425 return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'version' => $version));
429 * Get version list
430 * @param int $pageid
431 * @param int $limitfrom
432 * @param int $limitnum
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);
440 * Count the number of page version
441 * @param int $pageid
443 function wiki_count_wiki_page_versions($pageid) {
444 global $DB;
445 return $DB->count_records('wiki_versions', array('pageid' => $pageid));
449 * Get linked from page
450 * @param int $pageid
452 function wiki_get_linked_to_pages($pageid) {
453 global $DB;
454 return $DB->get_records('wiki_links', array('frompageid' => $pageid));
458 * Get linked from page
459 * @param int $pageid
461 function wiki_get_linked_from_pages($pageid) {
462 global $DB;
463 return $DB->get_records('wiki_links', array('topageid' => $pageid));
467 * Get pages which user have been edited
468 * @param int $swid
469 * @param int $userid
471 function wiki_get_contributions($swid, $userid) {
472 global $DB;
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 = ?";
480 return $DB->get_records_sql($sql, array($swid, $userid));
484 * Get missing or empty pages in wiki
485 * @param int $swid sub wiki id
487 function wiki_get_missing_or_empty_pages($swid) {
488 global $DB;
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";
505 return $DB->get_records_sql($sql, array($swid, $swid, $swid));
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.
513 function wiki_get_page_list($swid, $sort = 'title ASC') {
514 global $DB;
515 $records = $DB->get_records('wiki_pages', array('subwikiid' => $swid), $sort);
516 return $records;
520 * Return a list of orphaned wikis for one specific subwiki
521 * @global object
522 * @param int $swid sub wiki id
524 function wiki_get_orphaned_pages($swid) {
525 global $DB;
527 $sql = "SELECT p.id, p.title
528 FROM {wiki_pages} p, {wiki} w , {wiki_subwikis} s
529 WHERE p.subwikiid = ?
530 AND s.id = ?
531 AND w.id = s.wikiid
532 AND p.title != w.firstpagetitle
533 AND p.id NOT IN (SELECT topageid FROM {wiki_links} WHERE subwikiid = ?)";
535 return $DB->get_records_sql($sql, array($swid, $swid, $swid));
539 * Search wiki title
540 * @param int $swid sub wiki id
541 * @param string $search
543 function wiki_search_title($swid, $search) {
544 global $DB;
546 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND title LIKE ?", array($swid, '%'.$search.'%'));
550 * Search wiki content
551 * @param int $swid sub wiki id
552 * @param string $search
554 function wiki_search_content($swid, $search) {
555 global $DB;
557 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND cachedcontent LIKE ?", array($swid, '%'.$search.'%'));
561 * Search wiki title and content
562 * @param int $swid sub wiki id
563 * @param string $search
565 function wiki_search_all($swid, $search) {
566 global $DB;
568 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND (cachedcontent LIKE ? OR title LIKE ?)", array($swid, '%'.$search.'%', '%'.$search.'%'));
572 * Get user data
574 function wiki_get_user_info($userid) {
575 global $DB;
576 return $DB->get_record('user', array('id' => $userid));
580 * Increase page view nubmer
581 * @param int $page, database record
583 function wiki_increment_pageviews($page) {
584 global $DB;
586 $page->pageviews++;
587 $DB->update_record('wiki_pages', $page);
590 //----------------------------------------------------------
591 //----------------------------------------------------------
594 * Text format supported by wiki module
596 function wiki_get_formats() {
597 return array('html', 'creole', 'nwiki');
601 * Parses a string with the wiki markup language in $markup.
603 * @return Array or false when something wrong has happened.
605 * Returned array contains the following fields:
606 * 'parsed_text' => String. Contains the parsed wiki content.
607 * 'unparsed_text' => String. Constains the original wiki content.
608 * 'link_count' => Array of array('destination' => ..., 'new' => "is new?"). Contains the internal wiki links found in the wiki content.
609 * 'deleted_sections' => the list of deleted sections.
610 * '' =>
612 * @author Josep Arús Pous
614 function wiki_parse_content($markup, $pagecontent, $options = array()) {
615 global $PAGE;
617 $subwiki = wiki_get_subwiki($options['swid']);
618 $cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid);
619 $context = context_module::instance($cm->id);
621 $parser_options = array(
622 'link_callback' => '/mod/wiki/locallib.php:wiki_parser_link',
623 'link_callback_args' => array('swid' => $options['swid']),
624 'table_callback' => '/mod/wiki/locallib.php:wiki_parser_table',
625 'real_path_callback' => '/mod/wiki/locallib.php:wiki_parser_real_path',
626 'real_path_callback_args' => array(
627 'context' => $context,
628 'component' => 'mod_wiki',
629 'filearea' => 'attachments',
630 'subwikiid'=> $subwiki->id,
631 'pageid' => $options['pageid']
633 'pageid' => $options['pageid'],
634 'pretty_print' => (isset($options['pretty_print']) && $options['pretty_print']),
635 'printable' => (isset($options['printable']) && $options['printable'])
638 return wiki_parser_proxy::parse($pagecontent, $markup, $parser_options);
642 * This function is the parser callback to parse wiki links.
644 * It returns the necesary information to print a link.
646 * NOTE: Empty pages and non-existent pages must be print in red color.
648 * !!!!!! IMPORTANT !!!!!!
649 * It is critical that you call format_string on the content before it is used.
651 * @param string|page_wiki $link name of a page
652 * @param array $options
653 * @return array Array('content' => string, 'url' => string, 'new' => bool, 'link_info' => array)
655 * @TODO Doc return and options
657 function wiki_parser_link($link, $options = null) {
658 global $CFG;
660 if (is_object($link)) {
661 $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 $version = wiki_get_current_version($link->id);
664 if ($version->version == 0) {
665 $parsedlink['new'] = true;
667 return $parsedlink;
668 } else {
669 $swid = $options['swid'];
671 if ($page = wiki_get_page_by_title($swid, $link)) {
672 $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 $version = wiki_get_current_version($page->id);
675 if ($version->version == 0) {
676 $parsedlink['new'] = true;
679 return $parsedlink;
681 } else {
682 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));
688 * Returns the table fully parsed (HTML)
690 * @return HTML for the table $table
691 * @author Josep Arús Pous
694 function wiki_parser_table($table) {
695 global $OUTPUT;
697 $htmltable = new html_table();
699 $headers = $table[0];
700 $htmltable->head = array();
701 foreach ($headers as $h) {
702 $htmltable->head[] = $h[1];
705 array_shift($table);
706 $htmltable->data = array();
707 foreach ($table as $row) {
708 $row_data = array();
709 foreach ($row as $r) {
710 $row_data[] = $r[1];
712 $htmltable->data[] = $row_data;
715 return html_writer::table($htmltable);
719 * Returns an absolute path link, unless there is no such link.
721 * @param string $url Link's URL or filename
722 * @param stdClass $context filearea params
723 * @param string $component The component the file is associated with
724 * @param string $filearea The filearea the file is stored in
725 * @param int $swid Sub wiki id
727 * @return string URL for files full path
730 function wiki_parser_real_path($url, $context, $component, $filearea, $swid) {
731 global $CFG;
733 if (preg_match("/^(?:http|ftp)s?\:\/\//", $url)) {
734 return $url;
735 } else {
737 $file = 'pluginfile.php';
738 if (!$CFG->slasharguments) {
739 $file = $file . '?file=';
741 $baseurl = "$CFG->wwwroot/$file/{$context->id}/$component/$filearea/$swid/";
742 // it is a file in current file area
743 return $baseurl . $url;
748 * Returns the token used by a wiki language to represent a given tag or "object" (bold -> **)
750 * @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.
751 * @author Josep Arús Pous
753 function wiki_parser_get_token($markup, $name) {
755 return wiki_parser_proxy::get_token($name, $markup);
759 * Checks if current user can view a subwiki
761 * @param stdClass $subwiki usually record from {wiki_subwikis}. Must contain fields 'wikiid', 'groupid', 'userid'.
762 * If it also contains fields 'course' and 'groupmode' from table {wiki} it will save extra DB query.
763 * @param stdClass $wiki optional wiki object if known
764 * @return bool
766 function wiki_user_can_view($subwiki, $wiki = null) {
767 global $USER;
769 if (empty($wiki) || $wiki->id != $subwiki->wikiid) {
770 $wiki = wiki_get_wiki($subwiki->wikiid);
772 $modinfo = get_fast_modinfo($wiki->course);
773 if (!isset($modinfo->instances['wiki'][$subwiki->wikiid])) {
774 // Module does not exist.
775 return false;
777 $cm = $modinfo->instances['wiki'][$subwiki->wikiid];
778 if (!$cm->uservisible) {
779 // The whole module is not visible to the current user.
780 return false;
782 $context = context_module::instance($cm->id);
784 // Working depending on activity groupmode
785 switch (groups_get_activity_groupmode($cm)) {
786 case NOGROUPS:
788 if ($wiki->wikimode == 'collaborative') {
789 // Collaborative Mode:
790 // There is one wiki for all the class.
792 // Only view capbility needed
793 return has_capability('mod/wiki:viewpage', $context);
794 } else if ($wiki->wikimode == 'individual') {
795 // Individual Mode:
796 // Each person owns a wiki.
797 if ($subwiki->userid == $USER->id) {
798 // Only the owner of the wiki can view it
799 return has_capability('mod/wiki:viewpage', $context);
800 } else { // User has special capabilities
801 // User must have:
802 // mod/wiki:viewpage capability
803 // and
804 // mod/wiki:managewiki capability
805 $view = has_capability('mod/wiki:viewpage', $context);
806 $manage = has_capability('mod/wiki:managewiki', $context);
808 return $view && $manage;
810 } else {
811 //Error
812 return false;
814 case SEPARATEGROUPS:
815 // Collaborative and Individual Mode
817 // Collaborative Mode:
818 // There is one wiki per group.
819 // Individual Mode:
820 // Each person owns a wiki.
821 if ($wiki->wikimode == 'collaborative' || $wiki->wikimode == 'individual') {
822 // Only members of subwiki group could view that wiki
823 if (in_array($subwiki->groupid, $modinfo->get_groups($cm->groupingid))) {
824 // Only view capability needed
825 return has_capability('mod/wiki:viewpage', $context);
827 } else { // User is not part of that group
828 // User must have:
829 // mod/wiki:managewiki capability
830 // or
831 // moodle/site:accessallgroups capability
832 // and
833 // mod/wiki:viewpage capability
834 $view = has_capability('mod/wiki:viewpage', $context);
835 $manage = has_capability('mod/wiki:managewiki', $context);
836 $access = has_capability('moodle/site:accessallgroups', $context);
837 return ($manage || $access) && $view;
839 } else {
840 //Error
841 return false;
843 case VISIBLEGROUPS:
844 // Collaborative and Individual Mode
846 // Collaborative Mode:
847 // There is one wiki per group.
848 // Individual Mode:
849 // Each person owns a wiki.
850 if ($wiki->wikimode == 'collaborative' || $wiki->wikimode == 'individual') {
851 // Everybody can read all wikis
853 // Only view capability needed
854 return has_capability('mod/wiki:viewpage', $context);
855 } else {
856 //Error
857 return false;
859 default: // Error
860 return false;
865 * Checks if current user can edit a subwiki
867 * @param $subwiki
869 function wiki_user_can_edit($subwiki) {
870 global $USER;
872 $wiki = wiki_get_wiki($subwiki->wikiid);
873 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
874 $context = context_module::instance($cm->id);
876 // Working depending on activity groupmode
877 switch (groups_get_activity_groupmode($cm)) {
878 case NOGROUPS:
880 if ($wiki->wikimode == 'collaborative') {
881 // Collaborative Mode:
882 // There is a wiki for all the class.
884 // Only edit capbility needed
885 return has_capability('mod/wiki:editpage', $context);
886 } else if ($wiki->wikimode == 'individual') {
887 // Individual Mode
888 // There is a wiki per user
890 // Only the owner of that wiki can edit it
891 if ($subwiki->userid == $USER->id) {
892 return has_capability('mod/wiki:editpage', $context);
893 } else { // Current user is not the owner of that wiki.
895 // User must have:
896 // mod/wiki:editpage capability
897 // and
898 // mod/wiki:managewiki capability
899 $edit = has_capability('mod/wiki:editpage', $context);
900 $manage = has_capability('mod/wiki:managewiki', $context);
902 return $edit && $manage;
904 } else {
905 //Error
906 return false;
908 case SEPARATEGROUPS:
909 if ($wiki->wikimode == 'collaborative') {
910 // Collaborative Mode:
911 // There is one wiki per group.
913 // Only members of subwiki group could edit that wiki
914 if (groups_is_member($subwiki->groupid)) {
915 // Only edit capability needed
916 return has_capability('mod/wiki:editpage', $context);
917 } else { // User is not part of that group
918 // User must have:
919 // mod/wiki:managewiki capability
920 // and
921 // moodle/site:accessallgroups capability
922 // and
923 // mod/wiki:editpage capability
924 $manage = has_capability('mod/wiki:managewiki', $context);
925 $access = has_capability('moodle/site:accessallgroups', $context);
926 $edit = has_capability('mod/wiki:editpage', $context);
927 return $manage && $access && $edit;
929 } else if ($wiki->wikimode == 'individual') {
930 // Individual Mode:
931 // Each person owns a wiki.
933 // Only the owner of that wiki can edit it
934 if ($subwiki->userid == $USER->id) {
935 return has_capability('mod/wiki:editpage', $context);
936 } else { // Current user is not the owner of that wiki.
937 // User must have:
938 // mod/wiki:managewiki capability
939 // and
940 // moodle/site:accessallgroups capability
941 // and
942 // mod/wiki:editpage capability
943 $manage = has_capability('mod/wiki:managewiki', $context);
944 $access = has_capability('moodle/site:accessallgroups', $context);
945 $edit = has_capability('mod/wiki:editpage', $context);
946 return $manage && $access && $edit;
948 } else {
949 //Error
950 return false;
952 case VISIBLEGROUPS:
953 if ($wiki->wikimode == 'collaborative') {
954 // Collaborative Mode:
955 // There is one wiki per group.
957 // Only members of subwiki group could edit that wiki
958 if (groups_is_member($subwiki->groupid)) {
959 // Only edit capability needed
960 return has_capability('mod/wiki:editpage', $context);
961 } else { // User is not part of that group
962 // User must have:
963 // mod/wiki:managewiki capability
964 // and
965 // mod/wiki:editpage capability
966 $manage = has_capability('mod/wiki:managewiki', $context);
967 $edit = has_capability('mod/wiki:editpage', $context);
968 return $manage && $edit;
970 } else if ($wiki->wikimode == 'individual') {
971 // Individual Mode:
972 // Each person owns a wiki.
974 // Only the owner of that wiki can edit it
975 if ($subwiki->userid == $USER->id) {
976 return has_capability('mod/wiki:editpage', $context);
977 } else { // Current user is not the owner of that wiki.
978 // User must have:
979 // mod/wiki:managewiki capability
980 // and
981 // mod/wiki:editpage capability
982 $manage = has_capability('mod/wiki:managewiki', $context);
983 $edit = has_capability('mod/wiki:editpage', $context);
984 return $manage && $edit;
986 } else {
987 //Error
988 return false;
990 default: // Error
991 return false;
995 //----------------
996 // Locks
997 //----------------
1000 * Checks if a page-section is locked.
1002 * @return true if the combination of section and page is locked, FALSE otherwise.
1004 function wiki_is_page_section_locked($pageid, $userid, $section = null) {
1005 global $DB;
1007 $sql = "pageid = ? AND lockedat > ? AND userid != ?";
1008 $params = array($pageid, time(), $userid);
1010 if (!empty($section)) {
1011 $sql .= " AND (sectionname = ? OR sectionname IS null)";
1012 $params[] = $section;
1015 return $DB->record_exists_select('wiki_locks', $sql, $params);
1019 * Inserts or updates a wiki_locks record.
1021 function wiki_set_lock($pageid, $userid, $section = null, $insert = false) {
1022 global $DB;
1024 if (wiki_is_page_section_locked($pageid, $userid, $section)) {
1025 return false;
1028 $params = array('pageid' => $pageid, 'userid' => $userid, 'sectionname' => $section);
1030 $lock = $DB->get_record('wiki_locks', $params);
1032 if (!empty($lock)) {
1033 $DB->update_record('wiki_locks', array('id' => $lock->id, 'lockedat' => time() + LOCK_TIMEOUT));
1034 } else if ($insert) {
1035 $DB->insert_record('wiki_locks',
1036 array('pageid' => $pageid, 'sectionname' => $section, 'userid' => $userid, 'lockedat' => time() + LOCK_TIMEOUT));
1039 return true;
1043 * 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 * @param int $pageid page id.
1046 * @param int $userid id of user for which lock is deleted.
1047 * @param string $section section to be deleted.
1048 * @param bool $delete_from_db deleted from db.
1049 * @param bool $delete_section_and_page delete section and page version.
1051 function wiki_delete_locks($pageid, $userid = null, $section = null, $delete_from_db = true, $delete_section_and_page = false) {
1052 global $DB;
1054 $wiki = wiki_get_wiki_from_pageid($pageid);
1055 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1056 $context = context_module::instance($cm->id);
1058 $params = array('pageid' => $pageid);
1060 if (!empty($userid)) {
1061 $params['userid'] = $userid;
1064 if (!empty($section)) {
1065 $params['sectionname'] = $section;
1068 if ($delete_from_db) {
1069 $DB->delete_records('wiki_locks', $params);
1070 if ($delete_section_and_page && !empty($section)) {
1071 $params['sectionname'] = null;
1072 $DB->delete_records('wiki_locks', $params);
1074 $event = \mod_wiki\event\page_locks_deleted::create(
1075 array(
1076 'context' => $context,
1077 'objectid' => $pageid,
1078 'relateduserid' => $userid,
1079 'other' => array(
1080 'section' => $section
1083 // No need to add snapshot, as important data is section, userid and pageid, which is part of event.
1084 $event->trigger();
1085 } else {
1086 $DB->set_field('wiki_locks', 'lockedat', time(), $params);
1091 * Deletes wiki_locks that expired 1 hour ago.
1093 function wiki_delete_old_locks() {
1094 global $DB;
1096 $DB->delete_records_select('wiki_locks', "lockedat < ?", array(time() - 3600));
1100 * Deletes wiki_links. It can be sepecific link or links attached in subwiki
1102 * @global mixed $DB database object
1103 * @param int $linkid id of the link to be deleted
1104 * @param int $topageid links to the specific page
1105 * @param int $frompageid links from specific page
1106 * @param int $subwikiid links to subwiki
1108 function wiki_delete_links($linkid = null, $topageid = null, $frompageid = null, $subwikiid = null) {
1109 global $DB;
1110 $params = array();
1112 // if link id is givien then don't check for anything else
1113 if (!empty($linkid)) {
1114 $params['id'] = $linkid;
1115 } else {
1116 if (!empty($topageid)) {
1117 $params['topageid'] = $topageid;
1119 if (!empty($frompageid)) {
1120 $params['frompageid'] = $frompageid;
1122 if (!empty($subwikiid)) {
1123 $params['subwikiid'] = $subwikiid;
1127 //Delete links if any params are passed, else nothing to delete.
1128 if (!empty($params)) {
1129 $DB->delete_records('wiki_links', $params);
1134 * Delete wiki synonyms related to subwikiid or page
1136 * @param int $subwikiid id of sunbwiki
1137 * @param int $pageid id of page
1139 function wiki_delete_synonym($subwikiid, $pageid = null) {
1140 global $DB;
1142 $params = array('subwikiid' => $subwikiid);
1143 if (!is_null($pageid)) {
1144 $params['pageid'] = $pageid;
1146 $DB->delete_records('wiki_synonyms', $params, IGNORE_MISSING);
1150 * Delete pages and all related data
1152 * @param mixed $context context in which page needs to be deleted.
1153 * @param mixed $pageids id's of pages to be deleted
1154 * @param int $subwikiid id of the subwiki for which all pages should be deleted
1156 function wiki_delete_pages($context, $pageids = null, $subwikiid = null) {
1157 global $DB, $CFG;
1159 if (!empty($pageids) && is_int($pageids)) {
1160 $pageids = array($pageids);
1161 } else if (!empty($subwikiid)) {
1162 $pageids = wiki_get_page_list($subwikiid);
1165 //If there is no pageid then return as we can't delete anything.
1166 if (empty($pageids)) {
1167 return;
1170 /// Delete page and all it's relevent data
1171 foreach ($pageids as $pageid) {
1172 if (is_object($pageid)) {
1173 $pageid = $pageid->id;
1176 //Delete page comments
1177 $comments = wiki_get_comments($context->id, $pageid);
1178 foreach ($comments as $commentid => $commentvalue) {
1179 wiki_delete_comment($commentid, $context, $pageid);
1182 //Delete page tags
1183 core_tag_tag::remove_all_item_tags('mod_wiki', 'wiki_pages', $pageid);
1185 //Delete Synonym
1186 wiki_delete_synonym($subwikiid, $pageid);
1188 //Delete all page versions
1189 wiki_delete_page_versions(array($pageid=>array(0)), $context);
1191 //Delete all page locks
1192 wiki_delete_locks($pageid);
1194 //Delete all page links
1195 wiki_delete_links(null, $pageid);
1197 $params = array('id' => $pageid);
1199 // Get page before deleting.
1200 $page = $DB->get_record('wiki_pages', $params);
1202 //Delete page
1203 $DB->delete_records('wiki_pages', $params);
1205 // Trigger page_deleted event.
1206 $event = \mod_wiki\event\page_deleted::create(
1207 array(
1208 'context' => $context,
1209 'objectid' => $pageid,
1210 'other' => array('subwikiid' => $subwikiid)
1212 $event->add_record_snapshot('wiki_pages', $page);
1213 $event->trigger();
1218 * Delete specificed versions of a page or versions created by users
1219 * if version is 0 then it will remove all versions of the page
1221 * @param array $deleteversions delete versions for a page
1222 * @param context_module $context module context
1224 function wiki_delete_page_versions($deleteversions, $context = null) {
1225 global $DB;
1227 /// delete page-versions
1228 foreach ($deleteversions as $id => $versions) {
1229 $params = array('pageid' => $id);
1230 if (is_null($context)) {
1231 $wiki = wiki_get_wiki_from_pageid($id);
1232 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1233 $context = context_module::instance($cm->id);
1235 // Delete all versions, if version specified is 0.
1236 if (in_array(0, $versions)) {
1237 $oldversions = $DB->get_records('wiki_versions', $params);
1238 $DB->delete_records('wiki_versions', $params, IGNORE_MISSING);
1239 } else {
1240 list($insql, $param) = $DB->get_in_or_equal($versions);
1241 $insql .= ' AND pageid = ?';
1242 array_push($param, $params['pageid']);
1243 $oldversions = $DB->get_records_select('wiki_versions', 'version ' . $insql, $param);
1244 $DB->delete_records_select('wiki_versions', 'version ' . $insql, $param);
1246 foreach ($oldversions as $version) {
1247 // Trigger page version deleted event.
1248 $event = \mod_wiki\event\page_version_deleted::create(
1249 array(
1250 'context' => $context,
1251 'objectid' => $version->id,
1252 'other' => array(
1253 'pageid' => $id
1256 $event->add_record_snapshot('wiki_versions', $version);
1257 $event->trigger();
1262 function wiki_get_comment($commentid){
1263 global $DB;
1264 return $DB->get_record('comments', array('id' => $commentid));
1268 * Returns all comments by context and pageid
1270 * @param int $contextid Current context id
1271 * @param int $pageid Current pageid
1273 function wiki_get_comments($contextid, $pageid) {
1274 global $DB;
1276 return $DB->get_records('comments', array('contextid' => $contextid, 'itemid' => $pageid, 'commentarea' => 'wiki_page'), 'timecreated ASC');
1280 * Add comments ro database
1282 * @param object $context. Current context
1283 * @param int $pageid. Current pageid
1284 * @param string $content. Content of the comment
1285 * @param string editor. Version of editor we are using.
1287 function wiki_add_comment($context, $pageid, $content, $editor) {
1288 global $CFG;
1289 require_once($CFG->dirroot . '/comment/lib.php');
1291 list($context, $course, $cm) = get_context_info_array($context->id);
1292 $cmt = new stdclass();
1293 $cmt->context = $context;
1294 $cmt->itemid = $pageid;
1295 $cmt->area = 'wiki_page';
1296 $cmt->course = $course;
1297 $cmt->component = 'mod_wiki';
1299 $manager = new comment($cmt);
1301 if ($editor == 'creole') {
1302 $manager->add($content, FORMAT_CREOLE);
1303 } else if ($editor == 'html') {
1304 $manager->add($content, FORMAT_HTML);
1305 } else if ($editor == 'nwiki') {
1306 $manager->add($content, FORMAT_NWIKI);
1312 * Delete comments from database
1314 * @param $idcomment. Id of comment which will be deleted
1315 * @param $context. Current context
1316 * @param $pageid. Current pageid
1318 function wiki_delete_comment($idcomment, $context, $pageid) {
1319 global $CFG;
1320 require_once($CFG->dirroot . '/comment/lib.php');
1322 list($context, $course, $cm) = get_context_info_array($context->id);
1323 $cmt = new stdClass();
1324 $cmt->context = $context;
1325 $cmt->itemid = $pageid;
1326 $cmt->area = 'wiki_page';
1327 $cmt->course = $course;
1328 $cmt->component = 'mod_wiki';
1330 $manager = new comment($cmt);
1331 $manager->delete($idcomment);
1336 * Delete al comments from wiki
1339 function wiki_delete_comments_wiki() {
1340 global $PAGE, $DB;
1342 $cm = $PAGE->cm;
1343 $context = context_module::instance($cm->id);
1345 $table = 'comments';
1346 $select = 'contextid = ?';
1348 $DB->delete_records_select($table, $select, array($context->id));
1352 function wiki_add_progress($pageid, $oldversionid, $versionid, $progress) {
1353 global $DB;
1354 for ($v = $oldversionid + 1; $v <= $versionid; $v++) {
1355 $user = wiki_get_wiki_page_id($pageid, $v);
1357 $DB->insert_record('wiki_progress', array('userid' => $user->userid, 'pageid' => $pageid, 'versionid' => $v, 'progress' => $progress));
1361 function wiki_get_wiki_page_id($pageid, $id) {
1362 global $DB;
1363 return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'id' => $id));
1366 function wiki_print_page_content($page, $context, $subwikiid) {
1367 global $OUTPUT, $CFG;
1369 if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) {
1370 $content = wiki_refresh_cachedcontent($page);
1371 $page = $content['page'];
1374 if (isset($content)) {
1375 $box = '';
1376 foreach ($content['sections'] as $s) {
1377 $box .= '<p>' . get_string('repeatedsection', 'wiki', $s) . '</p>';
1380 if (!empty($box)) {
1381 echo $OUTPUT->box($box);
1384 $html = file_rewrite_pluginfile_urls($page->cachedcontent, 'pluginfile.php', $context->id, 'mod_wiki', 'attachments', $subwikiid);
1385 $html = format_text($html, FORMAT_HTML, array('overflowdiv' => true, 'allowid' => true));
1386 echo $OUTPUT->box($html);
1388 echo $OUTPUT->tag_list(core_tag_tag::get_item_tags('mod_wiki', 'wiki_pages', $page->id),
1389 null, 'wiki-tags');
1391 wiki_increment_pageviews($page);
1395 * This function trims any given text and returns it with some dots at the end
1397 * @param string $text
1398 * @param string $limit
1400 * @return string
1402 function wiki_trim_string($text, $limit = 25) {
1404 if (core_text::strlen($text) > $limit) {
1405 $text = core_text::substr($text, 0, $limit) . '...';
1408 return $text;
1412 * Prints default edit form fields and buttons
1414 * @param string $format Edit form format (html, creole...)
1415 * @param integer $version Version number. A negative number means no versioning.
1418 function wiki_print_edit_form_default_fields($format, $pageid, $version = -1, $upload = false, $deleteuploads = array()) {
1419 global $CFG, $PAGE, $OUTPUT;
1421 echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
1423 if ($version >= 0) {
1424 echo '<input type="hidden" name="version" value="' . $version . '" />';
1427 echo '<input type="hidden" name="format" value="' . $format . '"/>';
1429 //attachments
1430 require_once($CFG->dirroot . '/lib/form/filemanager.php');
1432 $filemanager = new MoodleQuickForm_filemanager('attachments', get_string('wikiattachments', 'wiki'), array('id' => 'attachments'), array('subdirs' => false, 'maxfiles' => 99, 'maxbytes' => $CFG->maxbytes));
1434 $value = file_get_submitted_draft_itemid('attachments');
1435 if (!empty($value) && !$upload) {
1436 $filemanager->setValue($value);
1439 echo "<fieldset class=\"wiki-upload-section clearfix\"><legend class=\"ftoggler\">" . get_string("uploadtitle", 'wiki') . "</legend>";
1441 echo $OUTPUT->container_start('container');
1442 print $filemanager->toHtml();
1443 echo $OUTPUT->container_end();
1445 $cm = $PAGE->cm;
1446 $context = context_module::instance($cm->id);
1448 echo $OUTPUT->container_start('container wiki-upload-table');
1449 wiki_print_upload_table($context, 'wiki_upload', $pageid, $deleteuploads);
1450 echo $OUTPUT->container_end();
1452 echo "</fieldset>";
1454 echo '<input class="wiki_button btn btn-secondary" type="submit" name="editoption" value="'
1455 . get_string('save', 'wiki') . '" />';
1456 echo '<input class="wiki_button btn btn-secondary" type="submit" name="editoption" value="'
1457 . get_string('upload', 'wiki') . '" />';
1458 echo '<input class="wiki_button btn btn-secondary" type="submit" name="editoption" value="' . get_string('preview') . '" />';
1459 echo '<input class="wiki_button btn btn-secondary" type="submit" name="editoption" value="' . get_string('cancel') . '" />';
1463 * Prints a table with the files attached to a wiki page
1464 * @param object $context
1465 * @param string $filearea
1466 * @param int $fileitemid
1467 * @param array deleteuploads
1469 function wiki_print_upload_table($context, $filearea, $fileitemid, $deleteuploads = array()) {
1470 global $CFG, $OUTPUT;
1472 $htmltable = new html_table();
1474 $htmltable->head = array(get_string('deleteupload', 'wiki'), get_string('uploadname', 'wiki'), get_string('uploadactions', 'wiki'));
1476 $fs = get_file_storage();
1477 $files = $fs->get_area_files($context->id, 'mod_wiki', $filearea, $fileitemid); //TODO: this is weird (skodak)
1479 foreach ($files as $file) {
1480 if (!$file->is_directory()) {
1481 $checkbox = '<input type="checkbox" name="deleteupload[]", value="' . $file->get_pathnamehash() . '"';
1483 if (in_array($file->get_pathnamehash(), $deleteuploads)) {
1484 $checkbox .= ' checked="checked"';
1487 $checkbox .= " />";
1489 $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>', "");
1493 print '<h3 class="upload-table-title">' . get_string('uploadfiletitle', 'wiki') . "</h3>";
1494 print html_writer::table($htmltable);
1498 * Generate wiki's page tree
1500 * @param page_wiki $page. A wiki page object
1501 * @param navigation_node $node. Starting navigation_node
1502 * @param array $keys. An array to store keys
1503 * @return an array with all tree nodes
1505 function wiki_build_tree($page, $node, &$keys) {
1506 $content = array();
1507 static $icon = null;
1508 if ($icon === null) {
1509 // Substitute the default navigation icon with empty image.
1510 $icon = new pix_icon('spacer', '');
1512 $pages = wiki_get_linked_pages($page->id);
1513 foreach ($pages as $p) {
1514 $key = $page->id . ':' . $p->id;
1515 if (in_array($key, $keys)) {
1516 break;
1518 array_push($keys, $key);
1519 $l = wiki_parser_link($p);
1520 $link = new moodle_url('/mod/wiki/view.php', array('pageid' => $p->id));
1521 // navigation_node::get_content will format the title for us
1522 $nodeaux = $node->add($p->title, $link, null, null, null, $icon);
1523 if ($l['new']) {
1524 $nodeaux->add_class('wiki_newentry');
1526 wiki_build_tree($p, $nodeaux, $keys);
1528 $content[] = $node;
1529 return $content;
1533 * Get linked pages from page
1534 * @param int $pageid
1536 function wiki_get_linked_pages($pageid) {
1537 global $DB;
1539 $sql = "SELECT p.id, p.title
1540 FROM {wiki_pages} p
1541 JOIN {wiki_links} l ON l.topageid = p.id
1542 WHERE l.frompageid = ?
1543 ORDER BY p.title ASC";
1544 return $DB->get_records_sql($sql, array($pageid));
1548 * Get updated pages from wiki
1549 * @param int $pageid
1551 function wiki_get_updated_pages_by_subwiki($swid) {
1552 global $DB, $USER;
1554 $sql = "SELECT *
1555 FROM {wiki_pages}
1556 WHERE subwikiid = ? AND timemodified > ?
1557 ORDER BY timemodified DESC";
1558 return $DB->get_records_sql($sql, array($swid, $USER->lastlogin));
1562 * Check if the user can create pages in a certain wiki.
1563 * @param context $context Wiki's context.
1564 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
1565 * @return bool True if user can create pages, false otherwise.
1566 * @since Moodle 3.1
1568 function wiki_can_create_pages($context, $user = null) {
1569 return has_capability('mod/wiki:createpage', $context, $user);
1573 * Get a sub wiki instance by wiki id, group id and user id.
1574 * If the wiki doesn't exist in DB it will return an isntance with id -1.
1576 * @param int $wikiid Wiki ID.
1577 * @param int $groupid Group ID.
1578 * @param int $userid User ID.
1579 * @return object Subwiki instance.
1580 * @since Moodle 3.1
1582 function wiki_get_possible_subwiki_by_group($wikiid, $groupid, $userid = 0) {
1583 if (!$subwiki = wiki_get_subwiki_by_group($wikiid, $groupid, $userid)) {
1584 $subwiki = new stdClass();
1585 $subwiki->id = -1;
1586 $subwiki->wikiid = $wikiid;
1587 $subwiki->groupid = $groupid;
1588 $subwiki->userid = $userid;
1590 return $subwiki;
1594 * Get all the possible subwikis visible to the user in a wiki.
1595 * It will return all the subwikis that can be created in a wiki, even if they don't exist in DB yet.
1597 * @param stdClass $wiki Wiki to get the subwikis from.
1598 * @param cm_info|stdClass $cm Optional. The course module object.
1599 * @param context_module $context Optional. Context of wiki module.
1600 * @return array List of subwikis.
1601 * @since Moodle 3.1
1603 function wiki_get_visible_subwikis($wiki, $cm = null, $context = null) {
1604 global $USER;
1606 $subwikis = array();
1608 if (empty($wiki) or !is_object($wiki)) {
1609 // Wiki not valid.
1610 return $subwikis;
1613 if (empty($cm)) {
1614 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1616 if (empty($context)) {
1617 $context = context_module::instance($cm->id);
1620 if (!has_capability('mod/wiki:viewpage', $context)) {
1621 return $subwikis;
1624 $manage = has_capability('mod/wiki:managewiki', $context);
1626 if (!$groupmode = groups_get_activity_groupmode($cm)) {
1627 // No groups.
1628 if ($wiki->wikimode == 'collaborative') {
1629 // Only 1 subwiki.
1630 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, 0);
1631 } else if ($wiki->wikimode == 'individual') {
1632 // There's 1 subwiki per user.
1633 if ($manage) {
1634 // User can view all subwikis.
1635 $users = get_enrolled_users($context);
1636 foreach ($users as $user) {
1637 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $user->id);
1639 } else {
1640 // User can only see his subwiki.
1641 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $USER->id);
1644 } else {
1645 if ($wiki->wikimode == 'collaborative') {
1646 // 1 subwiki per group.
1647 $aag = has_capability('moodle/site:accessallgroups', $context);
1648 if ($aag || $groupmode == VISIBLEGROUPS) {
1649 // User can see all groups.
1650 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
1651 $allparticipants = new stdClass();
1652 $allparticipants->id = 0;
1653 array_unshift($allowedgroups, $allparticipants); // Add all participants.
1654 } else {
1655 // User can only see the groups he belongs to.
1656 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
1659 foreach ($allowedgroups as $group) {
1660 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, 0);
1662 } else if ($wiki->wikimode == 'individual') {
1663 // 1 subwiki per user and group.
1665 if ($manage || $groupmode == VISIBLEGROUPS) {
1666 // User can view all subwikis.
1667 $users = get_enrolled_users($context);
1668 foreach ($users as $user) {
1669 // Get all the groups this user belongs to.
1670 $groups = groups_get_all_groups($cm->course, $user->id);
1671 if (!empty($groups)) {
1672 foreach ($groups as $group) {
1673 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, $user->id);
1675 } else {
1676 // User doesn't belong to any group, add it to group 0.
1677 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $user->id);
1680 } else {
1681 // The user can only see the subwikis of the groups he belongs.
1682 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
1683 foreach ($allowedgroups as $group) {
1684 $users = groups_get_members($group->id);
1685 foreach ($users as $user) {
1686 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, $user->id);
1693 return $subwikis;
1697 * Utility function for getting a subwiki by group and user, validating that the user can view it.
1698 * If the subwiki doesn't exists in DB yet it'll have id -1.
1700 * @param stdClass $wiki The wiki.
1701 * @param int $groupid Group ID. 0 means the subwiki doesn't use groups.
1702 * @param int $userid User ID. 0 means the subwiki doesn't use users.
1703 * @return stdClass Subwiki. If it doesn't exists in DB yet it'll have id -1. If the user can't view the
1704 * subwiki this function will return false.
1705 * @since Moodle 3.1
1706 * @throws moodle_exception
1708 function wiki_get_subwiki_by_group_and_user_with_validation($wiki, $groupid, $userid) {
1709 global $USER, $DB;
1711 // Get subwiki based on group and user.
1712 if (!$subwiki = wiki_get_subwiki_by_group($wiki->id, $groupid, $userid)) {
1714 // The subwiki doesn't exist.
1715 // Validate if user is valid.
1716 if ($userid != 0) {
1717 $user = core_user::get_user($userid, '*', MUST_EXIST);
1718 core_user::require_active_user($user);
1721 // Validate that groupid is valid.
1722 if ($groupid != 0 && !groups_group_exists($groupid)) {
1723 throw new moodle_exception('cannotfindgroup', 'error');
1726 // Valid data but subwiki not found. We'll simulate a subwiki object to check if the user would be able to see it
1727 // if it existed. If he's able to see it then we'll return an empty array because the subwiki has no pages.
1728 $subwiki = new stdClass();
1729 $subwiki->id = -1;
1730 $subwiki->wikiid = $wiki->id;
1731 $subwiki->userid = $userid;
1732 $subwiki->groupid = $groupid;
1735 // Check that the user can view the subwiki. This function checks capabilities.
1736 if (!wiki_user_can_view($subwiki, $wiki)) {
1737 return false;
1740 return $subwiki;
1744 * Returns wiki pages tagged with a specified tag.
1746 * This is a callback used by the tag area mod_wiki/wiki_pages to search for wiki pages
1747 * tagged with a specific tag.
1749 * @param core_tag_tag $tag
1750 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1751 * are displayed on the page and the per-page limit may be bigger
1752 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1753 * to display items in the same context first
1754 * @param int $ctx context id where to search for records
1755 * @param bool $rec search in subcontexts as well
1756 * @param int $page 0-based number of page being displayed
1757 * @return \core_tag\output\tagindex
1759 function mod_wiki_get_tagged_pages($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1760 global $OUTPUT;
1761 $perpage = $exclusivemode ? 20 : 5;
1763 // Build the SQL query.
1764 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1765 $query = "SELECT wp.id, wp.title, ws.userid, ws.wikiid, ws.id AS subwikiid, ws.groupid, w.wikimode,
1766 cm.id AS cmid, c.id AS courseid, c.shortname, c.fullname, $ctxselect
1767 FROM {wiki_pages} wp
1768 JOIN {wiki_subwikis} ws ON wp.subwikiid = ws.id
1769 JOIN {wiki} w ON w.id = ws.wikiid
1770 JOIN {modules} m ON m.name='wiki'
1771 JOIN {course_modules} cm ON cm.module = m.id AND cm.instance = w.id
1772 JOIN {tag_instance} tt ON wp.id = tt.itemid
1773 JOIN {course} c ON cm.course = c.id
1774 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
1775 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
1776 AND cm.deletioninprogress = 0
1777 AND wp.id %ITEMFILTER% AND c.id %COURSEFILTER%";
1779 $params = array('itemtype' => 'wiki_pages', 'tagid' => $tag->id, 'component' => 'mod_wiki',
1780 'coursemodulecontextlevel' => CONTEXT_MODULE);
1782 if ($ctx) {
1783 $context = $ctx ? context::instance_by_id($ctx) : context_system::instance();
1784 $query .= $rec ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
1785 $params['contextid'] = $context->id;
1786 $params['path'] = $context->path.'/%';
1789 $query .= " ORDER BY ";
1790 if ($fromctx) {
1791 // In order-clause specify that modules from inside "fromctx" context should be returned first.
1792 $fromcontext = context::instance_by_id($fromctx);
1793 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
1794 $params['fromcontextid'] = $fromcontext->id;
1795 $params['frompath'] = $fromcontext->path.'/%';
1797 $query .= ' c.sortorder, cm.id, wp.id';
1799 $totalpages = $page + 1;
1801 // Use core_tag_index_builder to build and filter the list of items.
1802 $builder = new core_tag_index_builder('mod_wiki', 'wiki_pages', $query, $params, $page * $perpage, $perpage + 1);
1803 while ($item = $builder->has_item_that_needs_access_check()) {
1804 context_helper::preload_from_record($item);
1805 $courseid = $item->courseid;
1806 if (!$builder->can_access_course($courseid)) {
1807 $builder->set_accessible($item, false);
1808 continue;
1810 $modinfo = get_fast_modinfo($builder->get_course($courseid));
1811 // Set accessibility of this item and all other items in the same course.
1812 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
1813 if ($taggeditem->courseid == $courseid) {
1814 $accessible = false;
1815 if (($cm = $modinfo->get_cm($taggeditem->cmid)) && $cm->uservisible) {
1816 $subwiki = (object)array('id' => $taggeditem->subwikiid, 'groupid' => $taggeditem->groupid,
1817 'userid' => $taggeditem->userid, 'wikiid' => $taggeditem->wikiid);
1818 $wiki = (object)array('id' => $taggeditem->wikiid, 'wikimode' => $taggeditem->wikimode,
1819 'course' => $cm->course);
1820 $accessible = wiki_user_can_view($subwiki, $wiki);
1822 $builder->set_accessible($taggeditem, $accessible);
1827 $items = $builder->get_items();
1828 if (count($items) > $perpage) {
1829 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
1830 array_pop($items);
1833 // Build the display contents.
1834 if ($items) {
1835 $tagfeed = new core_tag\output\tagfeed();
1836 foreach ($items as $item) {
1837 context_helper::preload_from_record($item);
1838 $modinfo = get_fast_modinfo($item->courseid);
1839 $cm = $modinfo->get_cm($item->cmid);
1840 $pageurl = new moodle_url('/mod/wiki/view.php', array('pageid' => $item->id));
1841 $pagename = format_string($item->title, true, array('context' => context_module::instance($item->cmid)));
1842 $pagename = html_writer::link($pageurl, $pagename);
1843 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
1844 $cmname = html_writer::link($cm->url, $cm->get_formatted_name());
1845 $coursename = format_string($item->fullname, true, array('context' => context_course::instance($item->courseid)));
1846 $coursename = html_writer::link($courseurl, $coursename);
1847 $icon = html_writer::link($pageurl, html_writer::empty_tag('img', array('src' => $cm->get_icon_url())));
1848 $tagfeed->add($icon, $pagename, $cmname.'<br>'.$coursename);
1851 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
1852 $tagfeed->export_for_template($OUTPUT));
1854 return new core_tag\output\tagindex($tag, 'mod_wiki', 'wiki_pages', $content,
1855 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);