MDL-52993 wiki: Fix wiki_user_can_edit for collab and separate groups
[moodle.git] / mod / wiki / locallib.php
blob7e8411ae4d0c901970d05876ca076672422c2604
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 require_once($CFG->dirroot . '/mod/wiki/lib.php');
36 require_once($CFG->dirroot . '/mod/wiki/parser/parser.php');
37 require_once($CFG->libdir . '/filelib.php');
39 define('WIKI_REFRESH_CACHE_TIME', 30); // @TODO: To be deleted.
40 define('FORMAT_CREOLE', '37');
41 define('FORMAT_NWIKI', '38');
42 define('NO_VALID_RATE', '-999');
43 define('IMPROVEMENT', '+');
44 define('EQUAL', '=');
45 define('WORST', '-');
47 define('LOCK_TIMEOUT', 30);
49 /**
50 * Get a wiki instance
51 * @param int $wikiid the instance id of wiki
53 function wiki_get_wiki($wikiid) {
54 global $DB;
56 return $DB->get_record('wiki', array('id' => $wikiid));
59 /**
60 * Get sub wiki instances with same wiki id
61 * @param int $wikiid
63 function wiki_get_subwikis($wikiid) {
64 global $DB;
65 return $DB->get_records('wiki_subwikis', array('wikiid' => $wikiid));
68 /**
69 * Get a sub wiki instance by wiki id and group id
70 * @param int $wikiid
71 * @param int $groupid
72 * @return object
74 function wiki_get_subwiki_by_group($wikiid, $groupid, $userid = 0) {
75 global $DB;
76 return $DB->get_record('wiki_subwikis', array('wikiid' => $wikiid, 'groupid' => $groupid, 'userid' => $userid));
79 /**
80 * Get a sub wiki instace by instance id
81 * @param int $subwikiid
82 * @return object
84 function wiki_get_subwiki($subwikiid) {
85 global $DB;
86 return $DB->get_record('wiki_subwikis', array('id' => $subwikiid));
90 /**
91 * Add a new sub wiki instance
92 * @param int $wikiid
93 * @param int $groupid
94 * @return int $insertid
96 function wiki_add_subwiki($wikiid, $groupid, $userid = 0) {
97 global $DB;
99 $record = new StdClass();
100 $record->wikiid = $wikiid;
101 $record->groupid = $groupid;
102 $record->userid = $userid;
104 $insertid = $DB->insert_record('wiki_subwikis', $record);
105 return $insertid;
109 * Get a wiki instance by pageid
110 * @param int $pageid
111 * @return object
113 function wiki_get_wiki_from_pageid($pageid) {
114 global $DB;
116 $sql = "SELECT w.*
117 FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p
118 WHERE p.id = ? AND
119 p.subwikiid = s.id AND
120 s.wikiid = w.id";
122 return $DB->get_record_sql($sql, array($pageid));
126 * Get a wiki page by pageid
127 * @param int $pageid
128 * @return object
130 function wiki_get_page($pageid) {
131 global $DB;
132 return $DB->get_record('wiki_pages', array('id' => $pageid));
136 * Get latest version of wiki page
137 * @param int $pageid
138 * @return object
140 function wiki_get_current_version($pageid) {
141 global $DB;
143 // @TODO: Fix this query
144 $sql = "SELECT *
145 FROM {wiki_versions}
146 WHERE pageid = ?
147 ORDER BY version DESC";
148 $records = $DB->get_records_sql($sql, array($pageid), 0, 1);
149 return array_pop($records);
154 * Alias of wiki_get_current_version
155 * @TODO, does the exactly same thing as wiki_get_current_version, should be removed
156 * @param int $pageid
157 * @return object
159 function wiki_get_last_version($pageid) {
160 return wiki_get_current_version($pageid);
164 * Get page section
165 * @param int $pageid
166 * @param string $section
168 function wiki_get_section_page($page, $section) {
170 $version = wiki_get_current_version($page->id);
171 return wiki_parser_proxy::get_section($version->content, $version->contentformat, $section);
175 * Get a wiki page by page title
176 * @param int $swid, sub wiki id
177 * @param string $title
178 * @return object
180 function wiki_get_page_by_title($swid, $title) {
181 global $DB;
182 return $DB->get_record('wiki_pages', array('subwikiid' => $swid, 'title' => $title));
186 * Get a version record by record id
187 * @param int $versionid, the version id
188 * @return object
190 function wiki_get_version($versionid) {
191 global $DB;
192 return $DB->get_record('wiki_versions', array('id' => $versionid));
196 * Get first page of wiki instace
197 * @param int $subwikiid
198 * @param int $module, wiki instance object
200 function wiki_get_first_page($subwikid, $module = null) {
201 global $DB, $USER;
203 $sql = "SELECT p.*
204 FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p
205 WHERE s.id = ? AND
206 s.wikiid = w.id AND
207 w.firstpagetitle = p.title AND
208 p.subwikiid = s.id";
209 return $DB->get_record_sql($sql, array($subwikid));
212 function wiki_save_section($wikipage, $sectiontitle, $sectioncontent, $userid) {
214 $wiki = wiki_get_wiki_from_pageid($wikipage->id);
215 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
216 $context = context_module::instance($cm->id);
218 if (has_capability('mod/wiki:editpage', $context)) {
219 $version = wiki_get_current_version($wikipage->id);
220 $content = wiki_parser_proxy::get_section($version->content, $version->contentformat, $sectiontitle, true);
222 $newcontent = $content[0] . $sectioncontent . $content[2];
224 return wiki_save_page($wikipage, $newcontent, $userid);
225 } else {
226 return false;
231 * Save page content
232 * @param object $wikipage
233 * @param string $newcontent
234 * @param int $userid
236 function wiki_save_page($wikipage, $newcontent, $userid) {
237 global $DB;
239 $wiki = wiki_get_wiki_from_pageid($wikipage->id);
240 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
241 $context = context_module::instance($cm->id);
243 if (has_capability('mod/wiki:editpage', $context)) {
244 $version = wiki_get_current_version($wikipage->id);
246 $version->content = $newcontent;
247 $version->userid = $userid;
248 $version->version++;
249 $version->timecreated = time();
250 $version->id = $DB->insert_record('wiki_versions', $version);
252 $wikipage->timemodified = $version->timecreated;
253 $wikipage->userid = $userid;
254 $return = wiki_refresh_cachedcontent($wikipage, $newcontent);
255 $event = \mod_wiki\event\page_updated::create(
256 array(
257 'context' => $context,
258 'objectid' => $wikipage->id,
259 'relateduserid' => $userid,
260 'other' => array(
261 'newcontent' => $newcontent
264 $event->add_record_snapshot('wiki', $wiki);
265 $event->add_record_snapshot('wiki_pages', $wikipage);
266 $event->add_record_snapshot('wiki_versions', $version);
267 $event->trigger();
268 return $return;
269 } else {
270 return false;
274 function wiki_refresh_cachedcontent($page, $newcontent = null) {
275 global $DB;
277 $version = wiki_get_current_version($page->id);
278 if (empty($version)) {
279 return null;
281 if (!isset($newcontent)) {
282 $newcontent = $version->content;
285 $options = array('swid' => $page->subwikiid, 'pageid' => $page->id);
286 $parseroutput = wiki_parse_content($version->contentformat, $newcontent, $options);
287 $page->cachedcontent = $parseroutput['toc'] . $parseroutput['parsed_text'];
288 $page->timerendered = time();
289 $DB->update_record('wiki_pages', $page);
291 wiki_refresh_page_links($page, $parseroutput['link_count']);
293 return array('page' => $page, 'sections' => $parseroutput['repeated_sections'], 'version' => $version->version);
297 * Restore a page with specified version.
299 * @param stdClass $wikipage wiki page record
300 * @param stdClass $version wiki page version to restore
301 * @param context_module $context context of wiki module
302 * @return stdClass restored page
304 function wiki_restore_page($wikipage, $version, $context) {
305 $return = wiki_save_page($wikipage, $version->content, $version->userid);
306 $event = \mod_wiki\event\page_version_restored::create(
307 array(
308 'context' => $context,
309 'objectid' => $version->id,
310 'other' => array(
311 'pageid' => $wikipage->id
314 $event->add_record_snapshot('wiki_versions', $version);
315 $event->trigger();
316 return $return['page'];
319 function wiki_refresh_page_links($page, $links) {
320 global $DB;
322 $DB->delete_records('wiki_links', array('frompageid' => $page->id));
323 foreach ($links as $linkname => $linkinfo) {
325 $newlink = new stdClass();
326 $newlink->subwikiid = $page->subwikiid;
327 $newlink->frompageid = $page->id;
329 if ($linkinfo['new']) {
330 $newlink->tomissingpage = $linkname;
331 } else {
332 $newlink->topageid = $linkinfo['pageid'];
335 try {
336 $DB->insert_record('wiki_links', $newlink);
337 } catch (dml_exception $e) {
338 debugging($e->getMessage());
345 * Create a new wiki page, if the page exists, return existing pageid
346 * @param int $swid
347 * @param string $title
348 * @param string $format
349 * @param int $userid
351 function wiki_create_page($swid, $title, $format, $userid) {
352 global $DB;
353 $subwiki = wiki_get_subwiki($swid);
354 $cm = get_coursemodule_from_instance('wiki', $subwiki->wikiid);
355 $context = context_module::instance($cm->id);
356 require_capability('mod/wiki:editpage', $context);
357 // if page exists
358 if ($page = wiki_get_page_by_title($swid, $title)) {
359 return $page->id;
362 // Creating a new empty version
363 $version = new stdClass();
364 $version->content = '';
365 $version->contentformat = $format;
366 $version->version = 0;
367 $version->timecreated = time();
368 $version->userid = $userid;
370 $versionid = null;
371 $versionid = $DB->insert_record('wiki_versions', $version);
373 // Createing a new empty page
374 $page = new stdClass();
375 $page->subwikiid = $swid;
376 $page->title = $title;
377 $page->cachedcontent = '';
378 $page->timecreated = $version->timecreated;
379 $page->timemodified = $version->timecreated;
380 $page->timerendered = $version->timecreated;
381 $page->userid = $userid;
382 $page->pageviews = 0;
383 $page->readonly = 0;
385 $pageid = $DB->insert_record('wiki_pages', $page);
387 // Setting the pageid
388 $version->id = $versionid;
389 $version->pageid = $pageid;
390 $DB->update_record('wiki_versions', $version);
392 $event = \mod_wiki\event\page_created::create(
393 array(
394 'context' => $context,
395 'objectid' => $pageid
398 $event->trigger();
400 wiki_make_cache_expire($page->title);
401 return $pageid;
404 function wiki_make_cache_expire($pagename) {
405 global $DB;
407 $sql = "UPDATE {wiki_pages}
408 SET timerendered = 0
409 WHERE id IN ( SELECT l.frompageid
410 FROM {wiki_links} l
411 WHERE l.tomissingpage = ?
413 $DB->execute ($sql, array($pagename));
417 * Get a specific version of page
418 * @param int $pageid
419 * @param int $version
421 function wiki_get_wiki_page_version($pageid, $version) {
422 global $DB;
423 return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'version' => $version));
427 * Get version list
428 * @param int $pageid
429 * @param int $limitfrom
430 * @param int $limitnum
432 function wiki_get_wiki_page_versions($pageid, $limitfrom, $limitnum) {
433 global $DB;
434 return $DB->get_records('wiki_versions', array('pageid' => $pageid), 'version DESC', '*', $limitfrom, $limitnum);
438 * Count the number of page version
439 * @param int $pageid
441 function wiki_count_wiki_page_versions($pageid) {
442 global $DB;
443 return $DB->count_records('wiki_versions', array('pageid' => $pageid));
447 * Get linked from page
448 * @param int $pageid
450 function wiki_get_linked_to_pages($pageid) {
451 global $DB;
452 return $DB->get_records('wiki_links', array('frompageid' => $pageid));
456 * Get linked from page
457 * @param int $pageid
459 function wiki_get_linked_from_pages($pageid) {
460 global $DB;
461 return $DB->get_records('wiki_links', array('topageid' => $pageid));
465 * Get pages which user have been edited
466 * @param int $swid
467 * @param int $userid
469 function wiki_get_contributions($swid, $userid) {
470 global $DB;
472 $sql = "SELECT v.*
473 FROM {wiki_versions} v, {wiki_pages} p
474 WHERE p.subwikiid = ? AND
475 v.pageid = p.id AND
476 v.userid = ?";
478 return $DB->get_records_sql($sql, array($swid, $userid));
482 * Get missing or empty pages in wiki
483 * @param int $swid sub wiki id
485 function wiki_get_missing_or_empty_pages($swid) {
486 global $DB;
488 $sql = "SELECT DISTINCT p.title, p.id, p.subwikiid
489 FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p
490 WHERE s.wikiid = w.id and
491 s.id = ? and
492 w.firstpagetitle != p.title and
493 p.subwikiid = ? and
494 1 = (SELECT count(*)
495 FROM {wiki_versions} v
496 WHERE v.pageid = p.id)
497 UNION
498 SELECT DISTINCT l.tomissingpage as title, 0 as id, l.subwikiid
499 FROM {wiki_links} l
500 WHERE l.subwikiid = ? and
501 l.topageid = 0";
503 return $DB->get_records_sql($sql, array($swid, $swid, $swid));
507 * Get pages list in wiki
508 * @param int $swid sub wiki id
510 function wiki_get_page_list($swid) {
511 global $DB;
512 $records = $DB->get_records('wiki_pages', array('subwikiid' => $swid), 'title ASC');
513 return $records;
517 * Return a list of orphaned wikis for one specific subwiki
518 * @global object
519 * @param int $swid sub wiki id
521 function wiki_get_orphaned_pages($swid) {
522 global $DB;
524 $sql = "SELECT p.id, p.title
525 FROM {wiki_pages} p, {wiki} w , {wiki_subwikis} s
526 WHERE p.subwikiid = ?
527 AND s.id = ?
528 AND w.id = s.wikiid
529 AND p.title != w.firstpagetitle
530 AND p.id NOT IN (SELECT topageid FROM {wiki_links} WHERE subwikiid = ?)";
532 return $DB->get_records_sql($sql, array($swid, $swid, $swid));
536 * Search wiki title
537 * @param int $swid sub wiki id
538 * @param string $search
540 function wiki_search_title($swid, $search) {
541 global $DB;
543 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND title LIKE ?", array($swid, '%'.$search.'%'));
547 * Search wiki content
548 * @param int $swid sub wiki id
549 * @param string $search
551 function wiki_search_content($swid, $search) {
552 global $DB;
554 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND cachedcontent LIKE ?", array($swid, '%'.$search.'%'));
558 * Search wiki title and content
559 * @param int $swid sub wiki id
560 * @param string $search
562 function wiki_search_all($swid, $search) {
563 global $DB;
565 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND (cachedcontent LIKE ? OR title LIKE ?)", array($swid, '%'.$search.'%', '%'.$search.'%'));
569 * Get user data
571 function wiki_get_user_info($userid) {
572 global $DB;
573 return $DB->get_record('user', array('id' => $userid));
577 * Increase page view nubmer
578 * @param int $page, database record
580 function wiki_increment_pageviews($page) {
581 global $DB;
583 $page->pageviews++;
584 $DB->update_record('wiki_pages', $page);
587 //----------------------------------------------------------
588 //----------------------------------------------------------
591 * Text format supported by wiki module
593 function wiki_get_formats() {
594 return array('html', 'creole', 'nwiki');
598 * Parses a string with the wiki markup language in $markup.
600 * @return Array or false when something wrong has happened.
602 * Returned array contains the following fields:
603 * 'parsed_text' => String. Contains the parsed wiki content.
604 * 'unparsed_text' => String. Constains the original wiki content.
605 * 'link_count' => Array of array('destination' => ..., 'new' => "is new?"). Contains the internal wiki links found in the wiki content.
606 * 'deleted_sections' => the list of deleted sections.
607 * '' =>
609 * @author Josep Arús Pous
611 function wiki_parse_content($markup, $pagecontent, $options = array()) {
612 global $PAGE;
614 $subwiki = wiki_get_subwiki($options['swid']);
615 $cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid);
616 $context = context_module::instance($cm->id);
618 $parser_options = array(
619 'link_callback' => '/mod/wiki/locallib.php:wiki_parser_link',
620 'link_callback_args' => array('swid' => $options['swid']),
621 'table_callback' => '/mod/wiki/locallib.php:wiki_parser_table',
622 'real_path_callback' => '/mod/wiki/locallib.php:wiki_parser_real_path',
623 'real_path_callback_args' => array(
624 'context' => $context,
625 'component' => 'mod_wiki',
626 'filearea' => 'attachments',
627 'subwikiid'=> $subwiki->id,
628 'pageid' => $options['pageid']
630 'pageid' => $options['pageid'],
631 'pretty_print' => (isset($options['pretty_print']) && $options['pretty_print']),
632 'printable' => (isset($options['printable']) && $options['printable'])
635 return wiki_parser_proxy::parse($pagecontent, $markup, $parser_options);
639 * This function is the parser callback to parse wiki links.
641 * It returns the necesary information to print a link.
643 * NOTE: Empty pages and non-existent pages must be print in red color.
645 * !!!!!! IMPORTANT !!!!!!
646 * It is critical that you call format_string on the content before it is used.
648 * @param string|page_wiki $link name of a page
649 * @param array $options
650 * @return array Array('content' => string, 'url' => string, 'new' => bool, 'link_info' => array)
652 * @TODO Doc return and options
654 function wiki_parser_link($link, $options = null) {
655 global $CFG;
657 if (is_object($link)) {
658 $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));
660 $version = wiki_get_current_version($link->id);
661 if ($version->version == 0) {
662 $parsedlink['new'] = true;
664 return $parsedlink;
665 } else {
666 $swid = $options['swid'];
668 if ($page = wiki_get_page_by_title($swid, $link)) {
669 $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));
671 $version = wiki_get_current_version($page->id);
672 if ($version->version == 0) {
673 $parsedlink['new'] = true;
676 return $parsedlink;
678 } else {
679 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));
685 * Returns the table fully parsed (HTML)
687 * @return HTML for the table $table
688 * @author Josep Arús Pous
691 function wiki_parser_table($table) {
692 global $OUTPUT;
694 $htmltable = new html_table();
696 $headers = $table[0];
697 $htmltable->head = array();
698 foreach ($headers as $h) {
699 $htmltable->head[] = $h[1];
702 array_shift($table);
703 $htmltable->data = array();
704 foreach ($table as $row) {
705 $row_data = array();
706 foreach ($row as $r) {
707 $row_data[] = $r[1];
709 $htmltable->data[] = $row_data;
712 return html_writer::table($htmltable);
716 * Returns an absolute path link, unless there is no such link.
718 * @param string $url Link's URL or filename
719 * @param stdClass $context filearea params
720 * @param string $component The component the file is associated with
721 * @param string $filearea The filearea the file is stored in
722 * @param int $swid Sub wiki id
724 * @return string URL for files full path
727 function wiki_parser_real_path($url, $context, $component, $filearea, $swid) {
728 global $CFG;
730 if (preg_match("/^(?:http|ftp)s?\:\/\//", $url)) {
731 return $url;
732 } else {
734 $file = 'pluginfile.php';
735 if (!$CFG->slasharguments) {
736 $file = $file . '?file=';
738 $baseurl = "$CFG->wwwroot/$file/{$context->id}/$component/$filearea/$swid/";
739 // it is a file in current file area
740 return $baseurl . $url;
745 * Returns the token used by a wiki language to represent a given tag or "object" (bold -> **)
747 * @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.
748 * @author Josep Arús Pous
750 function wiki_parser_get_token($markup, $name) {
752 return wiki_parser_proxy::get_token($name, $markup);
756 * Checks if current user can view a subwiki
758 * @param stdClass $subwiki usually record from {wiki_subwikis}. Must contain fields 'wikiid', 'groupid', 'userid'.
759 * If it also contains fields 'course' and 'groupmode' from table {wiki} it will save extra DB query.
760 * @param stdClass $wiki optional wiki object if known
761 * @return bool
763 function wiki_user_can_view($subwiki, $wiki = null) {
764 global $USER;
766 if (empty($wiki) || $wiki->id != $subwiki->wikiid) {
767 $wiki = wiki_get_wiki($subwiki->wikiid);
769 $modinfo = get_fast_modinfo($wiki->course);
770 if (!isset($modinfo->instances['wiki'][$subwiki->wikiid])) {
771 // Module does not exist.
772 return false;
774 $cm = $modinfo->instances['wiki'][$subwiki->wikiid];
775 if (!$cm->uservisible) {
776 // The whole module is not visible to the current user.
777 return false;
779 $context = context_module::instance($cm->id);
781 // Working depending on activity groupmode
782 switch (groups_get_activity_groupmode($cm)) {
783 case NOGROUPS:
785 if ($wiki->wikimode == 'collaborative') {
786 // Collaborative Mode:
787 // There is one wiki for all the class.
789 // Only view capbility needed
790 return has_capability('mod/wiki:viewpage', $context);
791 } else if ($wiki->wikimode == 'individual') {
792 // Individual Mode:
793 // Each person owns a wiki.
794 if ($subwiki->userid == $USER->id) {
795 // Only the owner of the wiki can view it
796 return has_capability('mod/wiki:viewpage', $context);
797 } else { // User has special capabilities
798 // User must have:
799 // mod/wiki:viewpage capability
800 // and
801 // mod/wiki:managewiki capability
802 $view = has_capability('mod/wiki:viewpage', $context);
803 $manage = has_capability('mod/wiki:managewiki', $context);
805 return $view && $manage;
807 } else {
808 //Error
809 return false;
811 case SEPARATEGROUPS:
812 // Collaborative and Individual Mode
814 // Collaborative Mode:
815 // There is one wiki per group.
816 // Individual Mode:
817 // Each person owns a wiki.
818 if ($wiki->wikimode == 'collaborative' || $wiki->wikimode == 'individual') {
819 // Only members of subwiki group could view that wiki
820 if (in_array($subwiki->groupid, $modinfo->get_groups($cm->groupingid))) {
821 // Only view capability needed
822 return has_capability('mod/wiki:viewpage', $context);
824 } else { // User is not part of that group
825 // User must have:
826 // mod/wiki:managewiki capability
827 // or
828 // moodle/site:accessallgroups capability
829 // and
830 // mod/wiki:viewpage capability
831 $view = has_capability('mod/wiki:viewpage', $context);
832 $manage = has_capability('mod/wiki:managewiki', $context);
833 $access = has_capability('moodle/site:accessallgroups', $context);
834 return ($manage || $access) && $view;
836 } else {
837 //Error
838 return false;
840 case VISIBLEGROUPS:
841 // Collaborative and Individual Mode
843 // Collaborative Mode:
844 // There is one wiki per group.
845 // Individual Mode:
846 // Each person owns a wiki.
847 if ($wiki->wikimode == 'collaborative' || $wiki->wikimode == 'individual') {
848 // Everybody can read all wikis
850 // Only view capability needed
851 return has_capability('mod/wiki:viewpage', $context);
852 } else {
853 //Error
854 return false;
856 default: // Error
857 return false;
862 * Checks if current user can edit a subwiki
864 * @param $subwiki
866 function wiki_user_can_edit($subwiki) {
867 global $USER;
869 $wiki = wiki_get_wiki($subwiki->wikiid);
870 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
871 $context = context_module::instance($cm->id);
873 // Working depending on activity groupmode
874 switch (groups_get_activity_groupmode($cm)) {
875 case NOGROUPS:
877 if ($wiki->wikimode == 'collaborative') {
878 // Collaborative Mode:
879 // There is a wiki for all the class.
881 // Only edit capbility needed
882 return has_capability('mod/wiki:editpage', $context);
883 } else if ($wiki->wikimode == 'individual') {
884 // Individual Mode
885 // There is a wiki per user
887 // Only the owner of that wiki can edit it
888 if ($subwiki->userid == $USER->id) {
889 return has_capability('mod/wiki:editpage', $context);
890 } else { // Current user is not the owner of that wiki.
892 // User must have:
893 // mod/wiki:editpage capability
894 // and
895 // mod/wiki:managewiki capability
896 $edit = has_capability('mod/wiki:editpage', $context);
897 $manage = has_capability('mod/wiki:managewiki', $context);
899 return $edit && $manage;
901 } else {
902 //Error
903 return false;
905 case SEPARATEGROUPS:
906 if ($wiki->wikimode == 'collaborative') {
907 // Collaborative Mode:
908 // There is one wiki per group.
910 // Only members of subwiki group could edit that wiki
911 if (groups_is_member($subwiki->groupid)) {
912 // Only edit capability needed
913 return has_capability('mod/wiki:editpage', $context);
914 } else { // User is not part of that group
915 // User must have:
916 // mod/wiki:managewiki capability
917 // and
918 // moodle/site:accessallgroups capability
919 // and
920 // mod/wiki:editpage capability
921 $manage = has_capability('mod/wiki:managewiki', $context);
922 $access = has_capability('moodle/site:accessallgroups', $context);
923 $edit = has_capability('mod/wiki:editpage', $context);
924 return $manage && $access && $edit;
926 } else if ($wiki->wikimode == 'individual') {
927 // Individual Mode:
928 // Each person owns a wiki.
930 // Only the owner of that wiki can edit it
931 if ($subwiki->userid == $USER->id) {
932 return has_capability('mod/wiki:editpage', $context);
933 } else { // Current user is not the owner of that wiki.
934 // User must have:
935 // mod/wiki:managewiki capability
936 // and
937 // moodle/site:accessallgroups capability
938 // and
939 // mod/wiki:editpage capability
940 $manage = has_capability('mod/wiki:managewiki', $context);
941 $access = has_capability('moodle/site:accessallgroups', $context);
942 $edit = has_capability('mod/wiki:editpage', $context);
943 return $manage && $access && $edit;
945 } else {
946 //Error
947 return false;
949 case VISIBLEGROUPS:
950 if ($wiki->wikimode == 'collaborative') {
951 // Collaborative Mode:
952 // There is one wiki per group.
954 // Only members of subwiki group could edit that wiki
955 if (groups_is_member($subwiki->groupid)) {
956 // Only edit capability needed
957 return has_capability('mod/wiki:editpage', $context);
958 } else { // User is not part of that group
959 // User must have:
960 // mod/wiki:managewiki capability
961 // and
962 // mod/wiki:editpage capability
963 $manage = has_capability('mod/wiki:managewiki', $context);
964 $edit = has_capability('mod/wiki:editpage', $context);
965 return $manage && $edit;
967 } else if ($wiki->wikimode == 'individual') {
968 // Individual Mode:
969 // Each person owns a wiki.
971 // Only the owner of that wiki can edit it
972 if ($subwiki->userid == $USER->id) {
973 return has_capability('mod/wiki:editpage', $context);
974 } else { // Current user is not the owner of that wiki.
975 // User must have:
976 // mod/wiki:managewiki capability
977 // and
978 // mod/wiki:editpage capability
979 $manage = has_capability('mod/wiki:managewiki', $context);
980 $edit = has_capability('mod/wiki:editpage', $context);
981 return $manage && $edit;
983 } else {
984 //Error
985 return false;
987 default: // Error
988 return false;
992 //----------------
993 // Locks
994 //----------------
997 * Checks if a page-section is locked.
999 * @return true if the combination of section and page is locked, FALSE otherwise.
1001 function wiki_is_page_section_locked($pageid, $userid, $section = null) {
1002 global $DB;
1004 $sql = "pageid = ? AND lockedat > ? AND userid != ?";
1005 $params = array($pageid, time(), $userid);
1007 if (!empty($section)) {
1008 $sql .= " AND (sectionname = ? OR sectionname IS null)";
1009 $params[] = $section;
1012 return $DB->record_exists_select('wiki_locks', $sql, $params);
1016 * Inserts or updates a wiki_locks record.
1018 function wiki_set_lock($pageid, $userid, $section = null, $insert = false) {
1019 global $DB;
1021 if (wiki_is_page_section_locked($pageid, $userid, $section)) {
1022 return false;
1025 $params = array('pageid' => $pageid, 'userid' => $userid, 'sectionname' => $section);
1027 $lock = $DB->get_record('wiki_locks', $params);
1029 if (!empty($lock)) {
1030 $DB->update_record('wiki_locks', array('id' => $lock->id, 'lockedat' => time() + LOCK_TIMEOUT));
1031 } else if ($insert) {
1032 $DB->insert_record('wiki_locks', array('pageid' => $pageid, 'sectionname' => $section, 'userid' => $userid, 'lockedat' => time() + 30));
1035 return true;
1039 * 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.
1041 * @param int $pageid page id.
1042 * @param int $userid id of user for which lock is deleted.
1043 * @param string $section section to be deleted.
1044 * @param bool $delete_from_db deleted from db.
1045 * @param bool $delete_section_and_page delete section and page version.
1047 function wiki_delete_locks($pageid, $userid = null, $section = null, $delete_from_db = true, $delete_section_and_page = false) {
1048 global $DB;
1050 $wiki = wiki_get_wiki_from_pageid($pageid);
1051 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1052 $context = context_module::instance($cm->id);
1054 $params = array('pageid' => $pageid);
1056 if (!empty($userid)) {
1057 $params['userid'] = $userid;
1060 if (!empty($section)) {
1061 $params['sectionname'] = $section;
1064 if ($delete_from_db) {
1065 $DB->delete_records('wiki_locks', $params);
1066 if ($delete_section_and_page && !empty($section)) {
1067 $params['sectionname'] = null;
1068 $DB->delete_records('wiki_locks', $params);
1070 $event = \mod_wiki\event\page_locks_deleted::create(
1071 array(
1072 'context' => $context,
1073 'objectid' => $pageid,
1074 'relateduserid' => $userid,
1075 'other' => array(
1076 'section' => $section
1079 // No need to add snapshot, as important data is section, userid and pageid, which is part of event.
1080 $event->trigger();
1081 } else {
1082 $DB->set_field('wiki_locks', 'lockedat', time(), $params);
1087 * Deletes wiki_locks that expired 1 hour ago.
1089 function wiki_delete_old_locks() {
1090 global $DB;
1092 $DB->delete_records_select('wiki_locks', "lockedat < ?", array(time() - 3600));
1096 * Deletes wiki_links. It can be sepecific link or links attached in subwiki
1098 * @global mixed $DB database object
1099 * @param int $linkid id of the link to be deleted
1100 * @param int $topageid links to the specific page
1101 * @param int $frompageid links from specific page
1102 * @param int $subwikiid links to subwiki
1104 function wiki_delete_links($linkid = null, $topageid = null, $frompageid = null, $subwikiid = null) {
1105 global $DB;
1106 $params = array();
1108 // if link id is givien then don't check for anything else
1109 if (!empty($linkid)) {
1110 $params['id'] = $linkid;
1111 } else {
1112 if (!empty($topageid)) {
1113 $params['topageid'] = $topageid;
1115 if (!empty($frompageid)) {
1116 $params['frompageid'] = $frompageid;
1118 if (!empty($subwikiid)) {
1119 $params['subwikiid'] = $subwikiid;
1123 //Delete links if any params are passed, else nothing to delete.
1124 if (!empty($params)) {
1125 $DB->delete_records('wiki_links', $params);
1130 * Delete wiki synonyms related to subwikiid or page
1132 * @param int $subwikiid id of sunbwiki
1133 * @param int $pageid id of page
1135 function wiki_delete_synonym($subwikiid, $pageid = null) {
1136 global $DB;
1138 $params = array('subwikiid' => $subwikiid);
1139 if (!is_null($pageid)) {
1140 $params['pageid'] = $pageid;
1142 $DB->delete_records('wiki_synonyms', $params, IGNORE_MISSING);
1146 * Delete pages and all related data
1148 * @param mixed $context context in which page needs to be deleted.
1149 * @param mixed $pageids id's of pages to be deleted
1150 * @param int $subwikiid id of the subwiki for which all pages should be deleted
1152 function wiki_delete_pages($context, $pageids = null, $subwikiid = null) {
1153 global $DB, $CFG;
1155 if (!empty($pageids) && is_int($pageids)) {
1156 $pageids = array($pageids);
1157 } else if (!empty($subwikiid)) {
1158 $pageids = wiki_get_page_list($subwikiid);
1161 //If there is no pageid then return as we can't delete anything.
1162 if (empty($pageids)) {
1163 return;
1166 require_once($CFG->dirroot . '/tag/lib.php');
1168 /// Delete page and all it's relevent data
1169 foreach ($pageids as $pageid) {
1170 if (is_object($pageid)) {
1171 $pageid = $pageid->id;
1174 //Delete page comments
1175 $comments = wiki_get_comments($context->id, $pageid);
1176 foreach ($comments as $commentid => $commentvalue) {
1177 wiki_delete_comment($commentid, $context, $pageid);
1180 //Delete page tags
1181 $tags = tag_get_tags_array('wiki_pages', $pageid);
1182 foreach ($tags as $tagid => $tagvalue) {
1183 tag_delete_instance('wiki_pages', $pageid, $tagid);
1186 //Delete Synonym
1187 wiki_delete_synonym($subwikiid, $pageid);
1189 //Delete all page versions
1190 wiki_delete_page_versions(array($pageid=>array(0)), $context);
1192 //Delete all page locks
1193 wiki_delete_locks($pageid);
1195 //Delete all page links
1196 wiki_delete_links(null, $pageid);
1198 $params = array('id' => $pageid);
1200 // Get page before deleting.
1201 $page = $DB->get_record('wiki_pages', $params);
1203 //Delete page
1204 $DB->delete_records('wiki_pages', $params);
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)
1213 $event->add_record_snapshot('wiki_pages', $page);
1214 $event->trigger();
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
1222 * @param array $deleteversions delete versions for a page
1223 * @param context_module $context module context
1225 function wiki_delete_page_versions($deleteversions, $context = null) {
1226 global $DB;
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);
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_recordset_select('wiki_versions', 'version ' . $insql, $param);
1245 $DB->delete_records_select('wiki_versions', 'version ' . $insql, $param);
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
1257 $event->add_record_snapshot('wiki_versions', $version);
1258 $event->trigger();
1263 function wiki_get_comment($commentid){
1264 global $DB;
1265 return $DB->get_record('comments', array('id' => $commentid));
1269 * Returns all comments by context and pageid
1271 * @param int $contextid Current context id
1272 * @param int $pageid Current pageid
1274 function wiki_get_comments($contextid, $pageid) {
1275 global $DB;
1277 return $DB->get_records('comments', array('contextid' => $contextid, 'itemid' => $pageid, 'commentarea' => 'wiki_page'), 'timecreated ASC');
1281 * Add comments ro database
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.
1288 function wiki_add_comment($context, $pageid, $content, $editor) {
1289 global $CFG;
1290 require_once($CFG->dirroot . '/comment/lib.php');
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';
1300 $manager = new comment($cmt);
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);
1313 * Delete comments from database
1315 * @param $idcomment. Id of comment which will be deleted
1316 * @param $context. Current context
1317 * @param $pageid. Current pageid
1319 function wiki_delete_comment($idcomment, $context, $pageid) {
1320 global $CFG;
1321 require_once($CFG->dirroot . '/comment/lib.php');
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';
1331 $manager = new comment($cmt);
1332 $manager->delete($idcomment);
1337 * Delete al comments from wiki
1340 function wiki_delete_comments_wiki() {
1341 global $PAGE, $DB;
1343 $cm = $PAGE->cm;
1344 $context = context_module::instance($cm->id);
1346 $table = 'comments';
1347 $select = 'contextid = ?';
1349 $DB->delete_records_select($table, $select, array($context->id));
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);
1358 $DB->insert_record('wiki_progress', array('userid' => $user->userid, 'pageid' => $pageid, 'versionid' => $v, 'progress' => $progress));
1362 function wiki_get_wiki_page_id($pageid, $id) {
1363 global $DB;
1364 return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'id' => $id));
1367 function wiki_print_page_content($page, $context, $subwikiid) {
1368 global $OUTPUT, $CFG;
1370 if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) {
1371 $content = wiki_refresh_cachedcontent($page);
1372 $page = $content['page'];
1375 if (isset($content)) {
1376 $box = '';
1377 foreach ($content['sections'] as $s) {
1378 $box .= '<p>' . get_string('repeatedsection', 'wiki', $s) . '</p>';
1381 if (!empty($box)) {
1382 echo $OUTPUT->box($box);
1385 $html = file_rewrite_pluginfile_urls($page->cachedcontent, 'pluginfile.php', $context->id, 'mod_wiki', 'attachments', $subwikiid);
1386 $html = format_text($html, FORMAT_MOODLE, array('overflowdiv'=>true, 'allowid'=>true));
1387 echo $OUTPUT->box($html);
1389 if (!empty($CFG->usetags)) {
1390 $tags = tag_get_tags_array('wiki_pages', $page->id);
1391 echo $OUTPUT->container_start('wiki-tags');
1392 echo '<span class="wiki-tags-title">'.get_string('tags').': </span>';
1393 $links = array();
1394 foreach ($tags as $tagid=>$tag) {
1395 $url = new moodle_url('/tag/index.php', array('tag'=>$tag));
1396 $links[] = html_writer::link($url, $tag, array('title'=>get_string('tagtitle', 'wiki', $tag)));
1398 echo join($links, ", ");
1399 echo $OUTPUT->container_end();
1402 wiki_increment_pageviews($page);
1406 * This function trims any given text and returns it with some dots at the end
1408 * @param string $text
1409 * @param string $limit
1411 * @return string
1413 function wiki_trim_string($text, $limit = 25) {
1415 if (core_text::strlen($text) > $limit) {
1416 $text = core_text::substr($text, 0, $limit) . '...';
1419 return $text;
1423 * Prints default edit form fields and buttons
1425 * @param string $format Edit form format (html, creole...)
1426 * @param integer $version Version number. A negative number means no versioning.
1429 function wiki_print_edit_form_default_fields($format, $pageid, $version = -1, $upload = false, $deleteuploads = array()) {
1430 global $CFG, $PAGE, $OUTPUT;
1432 echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
1434 if ($version >= 0) {
1435 echo '<input type="hidden" name="version" value="' . $version . '" />';
1438 echo '<input type="hidden" name="format" value="' . $format . '"/>';
1440 //attachments
1441 require_once($CFG->dirroot . '/lib/form/filemanager.php');
1443 $filemanager = new MoodleQuickForm_filemanager('attachments', get_string('wikiattachments', 'wiki'), array('id' => 'attachments'), array('subdirs' => false, 'maxfiles' => 99, 'maxbytes' => $CFG->maxbytes));
1445 $value = file_get_submitted_draft_itemid('attachments');
1446 if (!empty($value) && !$upload) {
1447 $filemanager->setValue($value);
1450 echo "<fieldset class=\"wiki-upload-section clearfix\"><legend class=\"ftoggler\">" . get_string("uploadtitle", 'wiki') . "</legend>";
1452 echo $OUTPUT->container_start('mdl-align wiki-form-center aaaaa');
1453 print $filemanager->toHtml();
1454 echo $OUTPUT->container_end();
1456 $cm = $PAGE->cm;
1457 $context = context_module::instance($cm->id);
1459 echo $OUTPUT->container_start('mdl-align wiki-form-center wiki-upload-table');
1460 wiki_print_upload_table($context, 'wiki_upload', $pageid, $deleteuploads);
1461 echo $OUTPUT->container_end();
1463 echo "</fieldset>";
1465 echo '<input class="wiki_button" type="submit" name="editoption" value="' . get_string('save', 'wiki') . '"/>';
1466 echo '<input class="wiki_button" type="submit" name="editoption" value="' . get_string('upload', 'wiki') . '"/>';
1467 echo '<input class="wiki_button" type="submit" name="editoption" value="' . get_string('preview') . '"/>';
1468 echo '<input class="wiki_button" type="submit" name="editoption" value="' . get_string('cancel') . '" />';
1472 * Prints a table with the files attached to a wiki page
1473 * @param object $context
1474 * @param string $filearea
1475 * @param int $fileitemid
1476 * @param array deleteuploads
1478 function wiki_print_upload_table($context, $filearea, $fileitemid, $deleteuploads = array()) {
1479 global $CFG, $OUTPUT;
1481 $htmltable = new html_table();
1483 $htmltable->head = array(get_string('deleteupload', 'wiki'), get_string('uploadname', 'wiki'), get_string('uploadactions', 'wiki'));
1485 $fs = get_file_storage();
1486 $files = $fs->get_area_files($context->id, 'mod_wiki', $filearea, $fileitemid); //TODO: this is weird (skodak)
1488 foreach ($files as $file) {
1489 if (!$file->is_directory()) {
1490 $checkbox = '<input type="checkbox" name="deleteupload[]", value="' . $file->get_pathnamehash() . '"';
1492 if (in_array($file->get_pathnamehash(), $deleteuploads)) {
1493 $checkbox .= ' checked="checked"';
1496 $checkbox .= " />";
1498 $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>', "");
1502 print '<h3 class="upload-table-title">' . get_string('uploadfiletitle', 'wiki') . "</h3>";
1503 print html_writer::table($htmltable);
1507 * Generate wiki's page tree
1509 * @param page_wiki $page. A wiki page object
1510 * @param navigation_node $node. Starting navigation_node
1511 * @param array $keys. An array to store keys
1512 * @return an array with all tree nodes
1514 function wiki_build_tree($page, $node, &$keys) {
1515 $content = array();
1516 static $icon = null;
1517 if ($icon === null) {
1518 // Substitute the default navigation icon with empty image.
1519 $icon = new pix_icon('spacer', '');
1521 $pages = wiki_get_linked_pages($page->id);
1522 foreach ($pages as $p) {
1523 $key = $page->id . ':' . $p->id;
1524 if (in_array($key, $keys)) {
1525 break;
1527 array_push($keys, $key);
1528 $l = wiki_parser_link($p);
1529 $link = new moodle_url('/mod/wiki/view.php', array('pageid' => $p->id));
1530 // navigation_node::get_content will format the title for us
1531 $nodeaux = $node->add($p->title, $link, null, null, null, $icon);
1532 if ($l['new']) {
1533 $nodeaux->add_class('wiki_newentry');
1535 wiki_build_tree($p, $nodeaux, $keys);
1537 $content[] = $node;
1538 return $content;
1542 * Get linked pages from page
1543 * @param int $pageid
1545 function wiki_get_linked_pages($pageid) {
1546 global $DB;
1548 $sql = "SELECT p.id, p.title
1549 FROM {wiki_pages} p
1550 JOIN {wiki_links} l ON l.topageid = p.id
1551 WHERE l.frompageid = ?
1552 ORDER BY p.title ASC";
1553 return $DB->get_records_sql($sql, array($pageid));
1557 * Get updated pages from wiki
1558 * @param int $pageid
1560 function wiki_get_updated_pages_by_subwiki($swid) {
1561 global $DB, $USER;
1563 $sql = "SELECT *
1564 FROM {wiki_pages}
1565 WHERE subwikiid = ? AND timemodified > ?
1566 ORDER BY timemodified DESC";
1567 return $DB->get_records_sql($sql, array($swid, $USER->lastlogin));