MDL-62977 mod_wiki: style buttons appropriately
[moodle.git] / mod / wiki / locallib.php
CommitLineData
00710f4c
DC
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * This contains functions and classes that will be used by scripts in wiki module
20 *
593b8385 21 * @package mod_wiki
7db38cd5
SH
22 * @copyright 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu
23 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
00710f4c
DC
24 *
25 * @author Jordi Piguillem
26 * @author Marc Alier
27 * @author David Jimenez
28 * @author Josep Arus
29 * @author Daniel Serrano
30 * @author Kenneth Riba
31 *
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 */
34
6ffb8fa2
SB
35defined('MOODLE_INTERNAL') || die();
36
00710f4c
DC
37require_once($CFG->dirroot . '/mod/wiki/lib.php');
38require_once($CFG->dirroot . '/mod/wiki/parser/parser.php');
99d19c13 39require_once($CFG->libdir . '/filelib.php');
00710f4c
DC
40
41define('WIKI_REFRESH_CACHE_TIME', 30); // @TODO: To be deleted.
42define('FORMAT_CREOLE', '37');
43define('FORMAT_NWIKI', '38');
44define('NO_VALID_RATE', '-999');
45define('IMPROVEMENT', '+');
46define('EQUAL', '=');
47define('WORST', '-');
48
49define('LOCK_TIMEOUT', 30);
50
51/**
52 * Get a wiki instance
53 * @param int $wikiid the instance id of wiki
54 */
55function wiki_get_wiki($wikiid) {
56 global $DB;
57
58 return $DB->get_record('wiki', array('id' => $wikiid));
59}
60
61/**
62 * Get sub wiki instances with same wiki id
63 * @param int $wikiid
64 */
65function wiki_get_subwikis($wikiid) {
66 global $DB;
67 return $DB->get_records('wiki_subwikis', array('wikiid' => $wikiid));
68}
69
70/**
71 * Get a sub wiki instance by wiki id and group id
72 * @param int $wikiid
73 * @param int $groupid
74 * @return object
75 */
76function wiki_get_subwiki_by_group($wikiid, $groupid, $userid = 0) {
77 global $DB;
78 return $DB->get_record('wiki_subwikis', array('wikiid' => $wikiid, 'groupid' => $groupid, 'userid' => $userid));
79}
80
81/**
82 * Get a sub wiki instace by instance id
83 * @param int $subwikiid
84 * @return object
85 */
86function wiki_get_subwiki($subwikiid) {
87 global $DB;
88 return $DB->get_record('wiki_subwikis', array('id' => $subwikiid));
89
90}
91
92/**
93 * Add a new sub wiki instance
94 * @param int $wikiid
95 * @param int $groupid
96 * @return int $insertid
97 */
98function wiki_add_subwiki($wikiid, $groupid, $userid = 0) {
99 global $DB;
100
101 $record = new StdClass();
102 $record->wikiid = $wikiid;
103 $record->groupid = $groupid;
104 $record->userid = $userid;
105
106 $insertid = $DB->insert_record('wiki_subwikis', $record);
107 return $insertid;
108}
109
110/**
111 * Get a wiki instance by pageid
112 * @param int $pageid
113 * @return object
114 */
115function wiki_get_wiki_from_pageid($pageid) {
116 global $DB;
117
9730c555
JP
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";
00710f4c
DC
123
124 return $DB->get_record_sql($sql, array($pageid));
125}
126
127/**
128 * Get a wiki page by pageid
129 * @param int $pageid
130 * @return object
131 */
132function wiki_get_page($pageid) {
133 global $DB;
134 return $DB->get_record('wiki_pages', array('id' => $pageid));
135}
136
137/**
138 * Get latest version of wiki page
139 * @param int $pageid
140 * @return object
141 */
142function wiki_get_current_version($pageid) {
143 global $DB;
144
9730c555
JP
145 // @TODO: Fix this query
146 $sql = "SELECT *
147 FROM {wiki_versions}
148 WHERE pageid = ?
70b082fa 149 ORDER BY version DESC";
54352ac9
PS
150 $records = $DB->get_records_sql($sql, array($pageid), 0, 1);
151 return array_pop($records);
00710f4c
DC
152
153}
154
155/**
156 * Alias of wiki_get_current_version
157 * @TODO, does the exactly same thing as wiki_get_current_version, should be removed
158 * @param int $pageid
159 * @return object
160 */
161function wiki_get_last_version($pageid) {
162 return wiki_get_current_version($pageid);
163}
164
165/**
166 * Get page section
167 * @param int $pageid
168 * @param string $section
169 */
170function wiki_get_section_page($page, $section) {
171
172 $version = wiki_get_current_version($page->id);
173 return wiki_parser_proxy::get_section($version->content, $version->contentformat, $section);
174}
175
176/**
177 * Get a wiki page by page title
178 * @param int $swid, sub wiki id
179 * @param string $title
180 * @return object
181 */
182function wiki_get_page_by_title($swid, $title) {
183 global $DB;
184 return $DB->get_record('wiki_pages', array('subwikiid' => $swid, 'title' => $title));
185}
186
187/**
188 * Get a version record by record id
189 * @param int $versionid, the version id
190 * @return object
191 */
192function wiki_get_version($versionid) {
193 global $DB;
194 return $DB->get_record('wiki_versions', array('id' => $versionid));
195}
196
197/**
198 * Get first page of wiki instace
199 * @param int $subwikiid
200 * @param int $module, wiki instance object
201 */
37dcd4b6 202function wiki_get_first_page($subwikid, $module = null) {
00710f4c 203 global $DB, $USER;
00710f4c 204
9730c555
JP
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";
00710f4c
DC
211 return $DB->get_record_sql($sql, array($subwikid));
212}
213
214function wiki_save_section($wikipage, $sectiontitle, $sectioncontent, $userid) {
215
216 $wiki = wiki_get_wiki_from_pageid($wikipage->id);
217 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1df23626 218 $context = context_module::instance($cm->id);
00710f4c
DC
219
220 if (has_capability('mod/wiki:editpage', $context)) {
221 $version = wiki_get_current_version($wikipage->id);
222 $content = wiki_parser_proxy::get_section($version->content, $version->contentformat, $sectiontitle, true);
223
224 $newcontent = $content[0] . $sectioncontent . $content[2];
225
226 return wiki_save_page($wikipage, $newcontent, $userid);
227 } else {
228 return false;
229 }
230}
231
232/**
233 * Save page content
234 * @param object $wikipage
235 * @param string $newcontent
236 * @param int $userid
237 */
238function wiki_save_page($wikipage, $newcontent, $userid) {
239 global $DB;
240
241 $wiki = wiki_get_wiki_from_pageid($wikipage->id);
242 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1df23626 243 $context = context_module::instance($cm->id);
00710f4c
DC
244
245 if (has_capability('mod/wiki:editpage', $context)) {
246 $version = wiki_get_current_version($wikipage->id);
247
248 $version->content = $newcontent;
249 $version->userid = $userid;
250 $version->version++;
251 $version->timecreated = time();
fb92417b 252 $version->id = $DB->insert_record('wiki_versions', $version);
00710f4c
DC
253
254 $wikipage->timemodified = $version->timecreated;
255 $wikipage->userid = $userid;
256 $return = wiki_refresh_cachedcontent($wikipage, $newcontent);
fb92417b
RT
257 $event = \mod_wiki\event\page_updated::create(
258 array(
259 'context' => $context,
260 'objectid' => $wikipage->id,
261 'relateduserid' => $userid,
262 'other' => array(
263 'newcontent' => $newcontent
264 )
265 ));
266 $event->add_record_snapshot('wiki', $wiki);
267 $event->add_record_snapshot('wiki_pages', $wikipage);
268 $event->add_record_snapshot('wiki_versions', $version);
269 $event->trigger();
00710f4c
DC
270 return $return;
271 } else {
272 return false;
273 }
274}
275
276function wiki_refresh_cachedcontent($page, $newcontent = null) {
277 global $DB;
278
279 $version = wiki_get_current_version($page->id);
79f0bac6
DC
280 if (empty($version)) {
281 return null;
282 }
00710f4c
DC
283 if (!isset($newcontent)) {
284 $newcontent = $version->content;
285 }
286
287 $options = array('swid' => $page->subwikiid, 'pageid' => $page->id);
288 $parseroutput = wiki_parse_content($version->contentformat, $newcontent, $options);
289 $page->cachedcontent = $parseroutput['toc'] . $parseroutput['parsed_text'];
290 $page->timerendered = time();
291 $DB->update_record('wiki_pages', $page);
292
293 wiki_refresh_page_links($page, $parseroutput['link_count']);
294
295 return array('page' => $page, 'sections' => $parseroutput['repeated_sections'], 'version' => $version->version);
296}
0e729875 297
00710f4c 298/**
0e729875
RT
299 * Restore a page with specified version.
300 *
301 * @param stdClass $wikipage wiki page record
302 * @param stdClass $version wiki page version to restore
303 * @param context_module $context context of wiki module
304 * @return stdClass restored page
00710f4c 305 */
0e729875
RT
306function wiki_restore_page($wikipage, $version, $context) {
307 $return = wiki_save_page($wikipage, $version->content, $version->userid);
308 $event = \mod_wiki\event\page_version_restored::create(
309 array(
310 'context' => $context,
311 'objectid' => $version->id,
312 'other' => array(
313 'pageid' => $wikipage->id
314 )
315 ));
316 $event->add_record_snapshot('wiki_versions', $version);
317 $event->trigger();
00710f4c
DC
318 return $return['page'];
319}
320
321function wiki_refresh_page_links($page, $links) {
322 global $DB;
323
324 $DB->delete_records('wiki_links', array('frompageid' => $page->id));
325 foreach ($links as $linkname => $linkinfo) {
326
327 $newlink = new stdClass();
328 $newlink->subwikiid = $page->subwikiid;
329 $newlink->frompageid = $page->id;
330
331 if ($linkinfo['new']) {
332 $newlink->tomissingpage = $linkname;
333 } else {
334 $newlink->topageid = $linkinfo['pageid'];
335 }
336
79f0bac6
DC
337 try {
338 $DB->insert_record('wiki_links', $newlink);
339 } catch (dml_exception $e) {
340 debugging($e->getMessage());
341 }
00710f4c
DC
342
343 }
344}
345
346/**
347 * Create a new wiki page, if the page exists, return existing pageid
348 * @param int $swid
349 * @param string $title
350 * @param string $format
351 * @param int $userid
352 */
353function wiki_create_page($swid, $title, $format, $userid) {
4c4e6591 354 global $DB;
7bc03dd5
JP
355 $subwiki = wiki_get_subwiki($swid);
356 $cm = get_coursemodule_from_instance('wiki', $subwiki->wikiid);
1df23626 357 $context = context_module::instance($cm->id);
7bc03dd5 358 require_capability('mod/wiki:editpage', $context);
00710f4c
DC
359 // if page exists
360 if ($page = wiki_get_page_by_title($swid, $title)) {
361 return $page->id;
362 }
363
364 // Creating a new empty version
365 $version = new stdClass();
366 $version->content = '';
367 $version->contentformat = $format;
368 $version->version = 0;
369 $version->timecreated = time();
370 $version->userid = $userid;
371
372 $versionid = null;
a9637e7d 373 $versionid = $DB->insert_record('wiki_versions', $version);
00710f4c
DC
374
375 // Createing a new empty page
376 $page = new stdClass();
377 $page->subwikiid = $swid;
378 $page->title = $title;
379 $page->cachedcontent = '';
380 $page->timecreated = $version->timecreated;
381 $page->timemodified = $version->timecreated;
382 $page->timerendered = $version->timecreated;
383 $page->userid = $userid;
384 $page->pageviews = 0;
385 $page->readonly = 0;
386
387 $pageid = $DB->insert_record('wiki_pages', $page);
388
389 // Setting the pageid
390 $version->id = $versionid;
391 $version->pageid = $pageid;
392 $DB->update_record('wiki_versions', $version);
393
a8481a66
RT
394 $event = \mod_wiki\event\page_created::create(
395 array(
396 'context' => $context,
397 'objectid' => $pageid
398 )
399 );
400 $event->trigger();
401
00710f4c
DC
402 wiki_make_cache_expire($page->title);
403 return $pageid;
404}
405
406function wiki_make_cache_expire($pagename) {
407 global $DB;
408
9730c555
JP
409 $sql = "UPDATE {wiki_pages}
410 SET timerendered = 0
411 WHERE id IN ( SELECT l.frompageid
412 FROM {wiki_links} l
413 WHERE l.tomissingpage = ?
414 )";
00710f4c
DC
415 $DB->execute ($sql, array($pagename));
416}
417
418/**
419 * Get a specific version of page
420 * @param int $pageid
421 * @param int $version
422 */
423function wiki_get_wiki_page_version($pageid, $version) {
424 global $DB;
425 return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'version' => $version));
426}
427
428/**
429 * Get version list
430 * @param int $pageid
431 * @param int $limitfrom
432 * @param int $limitnum
433 */
434function wiki_get_wiki_page_versions($pageid, $limitfrom, $limitnum) {
435 global $DB;
436 return $DB->get_records('wiki_versions', array('pageid' => $pageid), 'version DESC', '*', $limitfrom, $limitnum);
437}
438
439/**
440 * Count the number of page version
441 * @param int $pageid
442 */
443function wiki_count_wiki_page_versions($pageid) {
444 global $DB;
445 return $DB->count_records('wiki_versions', array('pageid' => $pageid));
446}
447
448/**
449 * Get linked from page
450 * @param int $pageid
451 */
452function wiki_get_linked_to_pages($pageid) {
453 global $DB;
454 return $DB->get_records('wiki_links', array('frompageid' => $pageid));
455}
456
457/**
458 * Get linked from page
459 * @param int $pageid
460 */
461function wiki_get_linked_from_pages($pageid) {
462 global $DB;
463 return $DB->get_records('wiki_links', array('topageid' => $pageid));
464}
465
466/**
467 * Get pages which user have been edited
468 * @param int $swid
469 * @param int $userid
470 */
471function wiki_get_contributions($swid, $userid) {
472 global $DB;
473
9730c555
JP
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 = ?";
00710f4c
DC
479
480 return $DB->get_records_sql($sql, array($swid, $userid));
481}
482
483/**
484 * Get missing or empty pages in wiki
485 * @param int $swid sub wiki id
486 */
487function wiki_get_missing_or_empty_pages($swid) {
488 global $DB;
489
9730c555
JP
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";
00710f4c
DC
504
505 return $DB->get_records_sql($sql, array($swid, $swid, $swid));
506}
507
508/**
509 * Get pages list in wiki
510 * @param int $swid sub wiki id
96abf9af 511 * @param string $sort How to sort the pages. By default, title ASC.
00710f4c 512 */
96abf9af 513function wiki_get_page_list($swid, $sort = 'title ASC') {
00710f4c 514 global $DB;
96abf9af 515 $records = $DB->get_records('wiki_pages', array('subwikiid' => $swid), $sort);
00710f4c
DC
516 return $records;
517}
518
519/**
520 * Return a list of orphaned wikis for one specific subwiki
521 * @global object
522 * @param int $swid sub wiki id
523 */
524function wiki_get_orphaned_pages($swid) {
525 global $DB;
526
9730c555
JP
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
92b145dc 533 AND p.id NOT IN (SELECT topageid FROM {wiki_links} WHERE subwikiid = ?)";
00710f4c 534
9730c555 535 return $DB->get_records_sql($sql, array($swid, $swid, $swid));
00710f4c
DC
536}
537
538/**
539 * Search wiki title
540 * @param int $swid sub wiki id
541 * @param string $search
542 */
543function wiki_search_title($swid, $search) {
544 global $DB;
75b986e7
JP
545
546 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND title LIKE ?", array($swid, '%'.$search.'%'));
00710f4c
DC
547}
548
549/**
550 * Search wiki content
551 * @param int $swid sub wiki id
552 * @param string $search
553 */
554function wiki_search_content($swid, $search) {
555 global $DB;
75b986e7
JP
556
557 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND cachedcontent LIKE ?", array($swid, '%'.$search.'%'));
00710f4c
DC
558}
559
560/**
561 * Search wiki title and content
562 * @param int $swid sub wiki id
563 * @param string $search
564 */
565function wiki_search_all($swid, $search) {
566 global $DB;
75b986e7
JP
567
568 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND (cachedcontent LIKE ? OR title LIKE ?)", array($swid, '%'.$search.'%', '%'.$search.'%'));
00710f4c
DC
569}
570
571/**
9ffd2726 572 * Get user data
00710f4c
DC
573 */
574function wiki_get_user_info($userid) {
9ffd2726
JP
575 global $DB;
576 return $DB->get_record('user', array('id' => $userid));
00710f4c
DC
577}
578
579/**
580 * Increase page view nubmer
581 * @param int $page, database record
582 */
583function wiki_increment_pageviews($page) {
584 global $DB;
585
586 $page->pageviews++;
587 $DB->update_record('wiki_pages', $page);
588}
589
590//----------------------------------------------------------
591//----------------------------------------------------------
592
593/**
594 * Text format supported by wiki module
595 */
596function wiki_get_formats() {
44c0751b 597 return array('html', 'creole', 'nwiki');
00710f4c
DC
598}
599
600/**
601 * Parses a string with the wiki markup language in $markup.
602 *
603 * @return Array or false when something wrong has happened.
604 *
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 * '' =>
611 *
612 * @author Josep Arús Pous
613 **/
614function wiki_parse_content($markup, $pagecontent, $options = array()) {
615 global $PAGE;
616
617 $subwiki = wiki_get_subwiki($options['swid']);
618 $cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid);
1df23626 619 $context = context_module::instance($cm->id);
00710f4c 620
c464a238
SH
621 $parser_options = array(
622 'link_callback' => '/mod/wiki/locallib.php:wiki_parser_link',
12c9bbbd
DC
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']
632 ),
633 'pageid' => $options['pageid'],
634 'pretty_print' => (isset($options['pretty_print']) && $options['pretty_print']),
635 'printable' => (isset($options['printable']) && $options['printable'])
636 );
00710f4c
DC
637
638 return wiki_parser_proxy::parse($pagecontent, $markup, $parser_options);
639}
640
641/**
642 * This function is the parser callback to parse wiki links.
643 *
644 * It returns the necesary information to print a link.
645 *
646 * NOTE: Empty pages and non-existent pages must be print in red color.
647 *
4c4e6591
SH
648 * !!!!!! IMPORTANT !!!!!!
649 * It is critical that you call format_string on the content before it is used.
00710f4c 650 *
4c4e6591
SH
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)
00710f4c
DC
654 *
655 * @TODO Doc return and options
656 */
657function wiki_parser_link($link, $options = null) {
658 global $CFG;
659
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));
662
663 $version = wiki_get_current_version($link->id);
664 if ($version->version == 0) {
665 $parsedlink['new'] = true;
666 }
667 return $parsedlink;
668 } else {
669 $swid = $options['swid'];
670
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));
673
674 $version = wiki_get_current_version($page->id);
675 if ($version->version == 0) {
676 $parsedlink['new'] = true;
677 }
678
679 return $parsedlink;
680
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));
683 }
684 }
685}
686
687/**
688 * Returns the table fully parsed (HTML)
689 *
690 * @return HTML for the table $table
691 * @author Josep Arús Pous
692 *
693 **/
694function wiki_parser_table($table) {
695 global $OUTPUT;
696
697 $htmltable = new html_table();
698
699 $headers = $table[0];
700 $htmltable->head = array();
701 foreach ($headers as $h) {
702 $htmltable->head[] = $h[1];
703 }
704
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];
711 }
712 $htmltable->data[] = $row_data;
713 }
714
715 return html_writer::table($htmltable);
716}
717
718/**
719 * Returns an absolute path link, unless there is no such link.
720 *
c464a238
SH
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
00710f4c 726 *
c464a238 727 * @return string URL for files full path
00710f4c
DC
728 */
729
12c9bbbd 730function wiki_parser_real_path($url, $context, $component, $filearea, $swid) {
00710f4c
DC
731 global $CFG;
732
733 if (preg_match("/^(?:http|ftp)s?\:\/\//", $url)) {
734 return $url;
735 } else {
12c9bbbd
DC
736
737 $file = 'pluginfile.php';
738 if (!$CFG->slasharguments) {
739 $file = $file . '?file=';
740 }
741 $baseurl = "$CFG->wwwroot/$file/{$context->id}/$component/$filearea/$swid/";
742 // it is a file in current file area
743 return $baseurl . $url;
00710f4c
DC
744 }
745}
746
747/**
748 * Returns the token used by a wiki language to represent a given tag or "object" (bold -> **)
749 *
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
752 **/
753function wiki_parser_get_token($markup, $name) {
754
755 return wiki_parser_proxy::get_token($name, $markup);
756}
757
758/**
759 * Checks if current user can view a subwiki
760 *
3a7b9b76
MG
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
00710f4c 765 */
3a7b9b76 766function wiki_user_can_view($subwiki, $wiki = null) {
00710f4c
DC
767 global $USER;
768
3a7b9b76
MG
769 if (empty($wiki) || $wiki->id != $subwiki->wikiid) {
770 $wiki = wiki_get_wiki($subwiki->wikiid);
771 }
772 $modinfo = get_fast_modinfo($wiki->course);
773 if (!isset($modinfo->instances['wiki'][$subwiki->wikiid])) {
774 // Module does not exist.
775 return false;
776 }
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;
781 }
1df23626 782 $context = context_module::instance($cm->id);
00710f4c
DC
783
784 // Working depending on activity groupmode
785 switch (groups_get_activity_groupmode($cm)) {
786 case NOGROUPS:
787
788 if ($wiki->wikimode == 'collaborative') {
789 // Collaborative Mode:
790 // There is one wiki for all the class.
791 //
792 // Only view capbility needed
cece1791 793 return has_capability('mod/wiki:viewpage', $context);
00710f4c
DC
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
cece1791 799 return has_capability('mod/wiki:viewpage', $context);
00710f4c
DC
800 } else { // User has special capabilities
801 // User must have:
802 // mod/wiki:viewpage capability
803 // and
804 // mod/wiki:managewiki capability
cece1791
DC
805 $view = has_capability('mod/wiki:viewpage', $context);
806 $manage = has_capability('mod/wiki:managewiki', $context);
00710f4c
DC
807
808 return $view && $manage;
809 }
810 } else {
811 //Error
812 return false;
813 }
814 case SEPARATEGROUPS:
815 // Collaborative and Individual Mode
816 //
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
3a7b9b76 823 if (in_array($subwiki->groupid, $modinfo->get_groups($cm->groupingid))) {
00710f4c 824 // Only view capability needed
cece1791 825 return has_capability('mod/wiki:viewpage', $context);
00710f4c
DC
826
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
cece1791
DC
834 $view = has_capability('mod/wiki:viewpage', $context);
835 $manage = has_capability('mod/wiki:managewiki', $context);
836 $access = has_capability('moodle/site:accessallgroups', $context);
00710f4c 837 return ($manage || $access) && $view;
37dcd4b6 838 }
00710f4c
DC
839 } else {
840 //Error
841 return false;
842 }
843 case VISIBLEGROUPS:
844 // Collaborative and Individual Mode
845 //
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
852 //
853 // Only view capability needed
cece1791 854 return has_capability('mod/wiki:viewpage', $context);
00710f4c
DC
855 } else {
856 //Error
857 return false;
858 }
859 default: // Error
860 return false;
861 }
862}
863
864/**
865 * Checks if current user can edit a subwiki
866 *
867 * @param $subwiki
868 */
869function wiki_user_can_edit($subwiki) {
870 global $USER;
871
872 $wiki = wiki_get_wiki($subwiki->wikiid);
873 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1df23626 874 $context = context_module::instance($cm->id);
00710f4c
DC
875
876 // Working depending on activity groupmode
877 switch (groups_get_activity_groupmode($cm)) {
878 case NOGROUPS:
879
880 if ($wiki->wikimode == 'collaborative') {
881 // Collaborative Mode:
882 // There is a wiki for all the class.
883 //
884 // Only edit capbility needed
cece1791 885 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
886 } else if ($wiki->wikimode == 'individual') {
887 // Individual Mode
888 // There is a wiki per user
889
890 // Only the owner of that wiki can edit it
891 if ($subwiki->userid == $USER->id) {
cece1791 892 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
893 } else { // Current user is not the owner of that wiki.
894
895 // User must have:
896 // mod/wiki:editpage capability
897 // and
898 // mod/wiki:managewiki capability
cece1791
DC
899 $edit = has_capability('mod/wiki:editpage', $context);
900 $manage = has_capability('mod/wiki:managewiki', $context);
00710f4c
DC
901
902 return $edit && $manage;
903 }
904 } else {
905 //Error
906 return false;
907 }
908 case SEPARATEGROUPS:
909 if ($wiki->wikimode == 'collaborative') {
910 // Collaborative Mode:
911 // There is one wiki per group.
912 //
913 // Only members of subwiki group could edit that wiki
bb05505e 914 if (groups_is_member($subwiki->groupid)) {
00710f4c 915 // Only edit capability needed
cece1791 916 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
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
cece1791
DC
924 $manage = has_capability('mod/wiki:managewiki', $context);
925 $access = has_capability('moodle/site:accessallgroups', $context);
926 $edit = has_capability('mod/wiki:editpage', $context);
00710f4c
DC
927 return $manage && $access && $edit;
928 }
929 } else if ($wiki->wikimode == 'individual') {
930 // Individual Mode:
931 // Each person owns a wiki.
932 //
933 // Only the owner of that wiki can edit it
934 if ($subwiki->userid == $USER->id) {
cece1791 935 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
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
cece1791
DC
943 $manage = has_capability('mod/wiki:managewiki', $context);
944 $access = has_capability('moodle/site:accessallgroups', $context);
945 $edit = has_capability('mod/wiki:editpage', $context);
00710f4c
DC
946 return $manage && $access && $edit;
947 }
948 } else {
949 //Error
950 return false;
951 }
952 case VISIBLEGROUPS:
953 if ($wiki->wikimode == 'collaborative') {
954 // Collaborative Mode:
955 // There is one wiki per group.
956 //
957 // Only members of subwiki group could edit that wiki
dc0cabb4 958 if (groups_is_member($subwiki->groupid)) {
00710f4c 959 // Only edit capability needed
cece1791 960 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
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
cece1791
DC
966 $manage = has_capability('mod/wiki:managewiki', $context);
967 $edit = has_capability('mod/wiki:editpage', $context);
00710f4c
DC
968 return $manage && $edit;
969 }
970 } else if ($wiki->wikimode == 'individual') {
971 // Individual Mode:
972 // Each person owns a wiki.
973 //
974 // Only the owner of that wiki can edit it
975 if ($subwiki->userid == $USER->id) {
cece1791 976 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
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
cece1791
DC
982 $manage = has_capability('mod/wiki:managewiki', $context);
983 $edit = has_capability('mod/wiki:editpage', $context);
00710f4c
DC
984 return $manage && $edit;
985 }
986 } else {
987 //Error
988 return false;
989 }
990 default: // Error
991 return false;
992 }
993}
994
995//----------------
996// Locks
997//----------------
998
999/**
1000 * Checks if a page-section is locked.
1001 *
1002 * @return true if the combination of section and page is locked, FALSE otherwise.
1003 */
1004function wiki_is_page_section_locked($pageid, $userid, $section = null) {
1005 global $DB;
1006
1007 $sql = "pageid = ? AND lockedat > ? AND userid != ?";
1008 $params = array($pageid, time(), $userid);
1009
1010 if (!empty($section)) {
1011 $sql .= " AND (sectionname = ? OR sectionname IS null)";
1012 $params[] = $section;
1013 }
1014
1015 return $DB->record_exists_select('wiki_locks', $sql, $params);
1016}
1017
1018/**
1019 * Inserts or updates a wiki_locks record.
1020 */
1021function wiki_set_lock($pageid, $userid, $section = null, $insert = false) {
1022 global $DB;
1023
1024 if (wiki_is_page_section_locked($pageid, $userid, $section)) {
1025 return false;
1026 }
1027
1028 $params = array('pageid' => $pageid, 'userid' => $userid, 'sectionname' => $section);
1029
1030 $lock = $DB->get_record('wiki_locks', $params);
1031
1032 if (!empty($lock)) {
1033 $DB->update_record('wiki_locks', array('id' => $lock->id, 'lockedat' => time() + LOCK_TIMEOUT));
1034 } else if ($insert) {
c13c21b9
PFO
1035 $DB->insert_record('wiki_locks',
1036 array('pageid' => $pageid, 'sectionname' => $section, 'userid' => $userid, 'lockedat' => time() + LOCK_TIMEOUT));
00710f4c
DC
1037 }
1038
1039 return true;
1040}
1041
1042/**
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.
b3dd79d1
RT
1044 *
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.
00710f4c
DC
1050 */
1051function wiki_delete_locks($pageid, $userid = null, $section = null, $delete_from_db = true, $delete_section_and_page = false) {
1052 global $DB;
1053
b3dd79d1
RT
1054 $wiki = wiki_get_wiki_from_pageid($pageid);
1055 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1056 $context = context_module::instance($cm->id);
1057
00710f4c
DC
1058 $params = array('pageid' => $pageid);
1059
1060 if (!empty($userid)) {
1061 $params['userid'] = $userid;
1062 }
1063
1064 if (!empty($section)) {
1065 $params['sectionname'] = $section;
1066 }
1067
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);
1073 }
b3dd79d1
RT
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
1081 )
1082 ));
1083 // No need to add snapshot, as important data is section, userid and pageid, which is part of event.
1084 $event->trigger();
00710f4c
DC
1085 } else {
1086 $DB->set_field('wiki_locks', 'lockedat', time(), $params);
1087 }
1088}
1089
1090/**
1091 * Deletes wiki_locks that expired 1 hour ago.
1092 */
1093function wiki_delete_old_locks() {
1094 global $DB;
1095
1096 $DB->delete_records_select('wiki_locks', "lockedat < ?", array(time() - 3600));
1097}
1098
ac0a82cf
RT
1099/**
1100 * Deletes wiki_links. It can be sepecific link or links attached in subwiki
1101 *
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
1107 */
1108function wiki_delete_links($linkid = null, $topageid = null, $frompageid = null, $subwikiid = null) {
1109 global $DB;
1110 $params = array();
1111
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;
1118 }
1119 if (!empty($frompageid)) {
1120 $params['frompageid'] = $frompageid;
1121 }
1122 if (!empty($subwikiid)) {
1123 $params['subwikiid'] = $subwikiid;
1124 }
1125 }
1126
1127 //Delete links if any params are passed, else nothing to delete.
1128 if (!empty($params)) {
1129 $DB->delete_records('wiki_links', $params);
1130 }
1131}
1132
1133/**
1134 * Delete wiki synonyms related to subwikiid or page
1135 *
1136 * @param int $subwikiid id of sunbwiki
1137 * @param int $pageid id of page
1138 */
1139function wiki_delete_synonym($subwikiid, $pageid = null) {
1140 global $DB;
1141
1142 $params = array('subwikiid' => $subwikiid);
1143 if (!is_null($pageid)) {
1144 $params['pageid'] = $pageid;
1145 }
1146 $DB->delete_records('wiki_synonyms', $params, IGNORE_MISSING);
1147}
1148
1149/**
1150 * Delete pages and all related data
1151 *
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
1155 */
1156function wiki_delete_pages($context, $pageids = null, $subwikiid = null) {
d6a54be3 1157 global $DB, $CFG;
ac0a82cf
RT
1158
1159 if (!empty($pageids) && is_int($pageids)) {
1160 $pageids = array($pageids);
1161 } else if (!empty($subwikiid)) {
1162 $pageids = wiki_get_page_list($subwikiid);
1163 }
1164
1165 //If there is no pageid then return as we can't delete anything.
1166 if (empty($pageids)) {
1167 return;
1168 }
1169
1170 /// Delete page and all it's relevent data
1171 foreach ($pageids as $pageid) {
1172 if (is_object($pageid)) {
1173 $pageid = $pageid->id;
1174 }
1175
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);
1180 }
1181
1182 //Delete page tags
b0b2c93d 1183 core_tag_tag::remove_all_item_tags('mod_wiki', 'wiki_pages', $pageid);
ac0a82cf
RT
1184
1185 //Delete Synonym
1186 wiki_delete_synonym($subwikiid, $pageid);
1187
1188 //Delete all page versions
d6a54be3 1189 wiki_delete_page_versions(array($pageid=>array(0)), $context);
ac0a82cf
RT
1190
1191 //Delete all page locks
1192 wiki_delete_locks($pageid);
1193
1194 //Delete all page links
1195 wiki_delete_links(null, $pageid);
1196
ac0a82cf 1197 $params = array('id' => $pageid);
d6a54be3
RT
1198
1199 // Get page before deleting.
1200 $page = $DB->get_record('wiki_pages', $params);
1201
1202 //Delete page
ac0a82cf 1203 $DB->delete_records('wiki_pages', $params);
d6a54be3
RT
1204
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)
1211 ));
1212 $event->add_record_snapshot('wiki_pages', $page);
1213 $event->trigger();
ac0a82cf
RT
1214 }
1215}
1216
1217/**
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
1220 *
1221 * @param array $deleteversions delete versions for a page
d6a54be3 1222 * @param context_module $context module context
ac0a82cf 1223 */
d6a54be3 1224function wiki_delete_page_versions($deleteversions, $context = null) {
ac0a82cf
RT
1225 global $DB;
1226
1227 /// delete page-versions
1228 foreach ($deleteversions as $id => $versions) {
d6a54be3
RT
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);
1234 }
1235 // Delete all versions, if version specified is 0.
1236 if (in_array(0, $versions)) {
1237 $oldversions = $DB->get_records('wiki_versions', $params);
ac0a82cf 1238 $DB->delete_records('wiki_versions', $params, IGNORE_MISSING);
d6a54be3
RT
1239 } else {
1240 list($insql, $param) = $DB->get_in_or_equal($versions);
1241 $insql .= ' AND pageid = ?';
1242 array_push($param, $params['pageid']);
a938e409 1243 $oldversions = $DB->get_records_select('wiki_versions', 'version ' . $insql, $param);
d6a54be3
RT
1244 $DB->delete_records_select('wiki_versions', 'version ' . $insql, $param);
1245 }
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
1254 )
1255 ));
1256 $event->add_record_snapshot('wiki_versions', $version);
1257 $event->trigger();
ac0a82cf
RT
1258 }
1259 }
1260}
1261
9bf1b716
JP
1262function wiki_get_comment($commentid){
1263 global $DB;
becf81c7 1264 return $DB->get_record('comments', array('id' => $commentid));
9bf1b716
JP
1265}
1266
00710f4c
DC
1267/**
1268 * Returns all comments by context and pageid
1269 *
e94f6c65
RT
1270 * @param int $contextid Current context id
1271 * @param int $pageid Current pageid
00710f4c 1272 **/
9ffd2726 1273function wiki_get_comments($contextid, $pageid) {
00710f4c
DC
1274 global $DB;
1275
cde6172d 1276 return $DB->get_records('comments', array('contextid' => $contextid, 'itemid' => $pageid, 'commentarea' => 'wiki_page'), 'timecreated ASC');
00710f4c
DC
1277}
1278
1279/**
1280 * Add comments ro database
1281 *
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.
1286 **/
1287function wiki_add_comment($context, $pageid, $content, $editor) {
1288 global $CFG;
1289 require_once($CFG->dirroot . '/comment/lib.php');
1290
1291 list($context, $course, $cm) = get_context_info_array($context->id);
1292 $cmt = new stdclass();
1293 $cmt->context = $context;
1294 $cmt->itemid = $pageid;
ab422920 1295 $cmt->area = 'wiki_page';
00710f4c 1296 $cmt->course = $course;
d846488e 1297 $cmt->component = 'mod_wiki';
00710f4c
DC
1298
1299 $manager = new comment($cmt);
1300
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);
1307 }
1308
1309}
1310
1311/**
1312 * Delete comments from database
1313 *
1314 * @param $idcomment. Id of comment which will be deleted
1315 * @param $context. Current context
1316 * @param $pageid. Current pageid
1317 **/
1318function wiki_delete_comment($idcomment, $context, $pageid) {
1319 global $CFG;
1320 require_once($CFG->dirroot . '/comment/lib.php');
1321
1322 list($context, $course, $cm) = get_context_info_array($context->id);
6bdfef5d 1323 $cmt = new stdClass();
00710f4c
DC
1324 $cmt->context = $context;
1325 $cmt->itemid = $pageid;
ab422920 1326 $cmt->area = 'wiki_page';
00710f4c 1327 $cmt->course = $course;
d846488e 1328 $cmt->component = 'mod_wiki';
00710f4c
DC
1329
1330 $manager = new comment($cmt);
1331 $manager->delete($idcomment);
1332
1333}
1334
1335/**
1336 * Delete al comments from wiki
1337 *
1338 **/
1339function wiki_delete_comments_wiki() {
1340 global $PAGE, $DB;
1341
1342 $cm = $PAGE->cm;
1df23626 1343 $context = context_module::instance($cm->id);
00710f4c
DC
1344
1345 $table = 'comments';
1346 $select = 'contextid = ?';
1347
1348 $DB->delete_records_select($table, $select, array($context->id));
1349
1350}
1351
1352function 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);
1356
1357 $DB->insert_record('wiki_progress', array('userid' => $user->userid, 'pageid' => $pageid, 'versionid' => $v, 'progress' => $progress));
1358 }
1359}
1360
1361function wiki_get_wiki_page_id($pageid, $id) {
1362 global $DB;
1363 return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'id' => $id));
1364}
1365
1366function wiki_print_page_content($page, $context, $subwikiid) {
1367 global $OUTPUT, $CFG;
1368
1369 if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) {
1370 $content = wiki_refresh_cachedcontent($page);
1371 $page = $content['page'];
1372 }
1373
1374 if (isset($content)) {
1375 $box = '';
1376 foreach ($content['sections'] as $s) {
1377 $box .= '<p>' . get_string('repeatedsection', 'wiki', $s) . '</p>';
1378 }
1379
1380 if (!empty($box)) {
1381 echo $OUTPUT->box($box);
1382 }
1383 }
64f93798 1384 $html = file_rewrite_pluginfile_urls($page->cachedcontent, 'pluginfile.php', $context->id, 'mod_wiki', 'attachments', $subwikiid);
5058a4d1 1385 $html = format_text($html, FORMAT_HTML, array('overflowdiv' => true, 'allowid' => true));
00710f4c
DC
1386 echo $OUTPUT->box($html);
1387
b0b2c93d
MG
1388 echo $OUTPUT->tag_list(core_tag_tag::get_item_tags('mod_wiki', 'wiki_pages', $page->id),
1389 null, 'wiki-tags');
00710f4c
DC
1390
1391 wiki_increment_pageviews($page);
1392}
1393
1394/**
1395 * This function trims any given text and returns it with some dots at the end
1396 *
1397 * @param string $text
1398 * @param string $limit
1399 *
1400 * @return string
1401 */
1402function wiki_trim_string($text, $limit = 25) {
1403
2f1e464a
PS
1404 if (core_text::strlen($text) > $limit) {
1405 $text = core_text::substr($text, 0, $limit) . '...';
00710f4c
DC
1406 }
1407
1408 return $text;
1409}
1410
1411/**
1412 * Prints default edit form fields and buttons
1413 *
1414 * @param string $format Edit form format (html, creole...)
1415 * @param integer $version Version number. A negative number means no versioning.
1416 */
1417
1418function wiki_print_edit_form_default_fields($format, $pageid, $version = -1, $upload = false, $deleteuploads = array()) {
1419 global $CFG, $PAGE, $OUTPUT;
1420
1421 echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
1422
1423 if ($version >= 0) {
1424 echo '<input type="hidden" name="version" value="' . $version . '" />';
1425 }
1426
1427 echo '<input type="hidden" name="format" value="' . $format . '"/>';
1428
1429 //attachments
1430 require_once($CFG->dirroot . '/lib/form/filemanager.php');
1431
1432 $filemanager = new MoodleQuickForm_filemanager('attachments', get_string('wikiattachments', 'wiki'), array('id' => 'attachments'), array('subdirs' => false, 'maxfiles' => 99, 'maxbytes' => $CFG->maxbytes));
1433
1434 $value = file_get_submitted_draft_itemid('attachments');
1435 if (!empty($value) && !$upload) {
1436 $filemanager->setValue($value);
1437 }
1438
1439 echo "<fieldset class=\"wiki-upload-section clearfix\"><legend class=\"ftoggler\">" . get_string("uploadtitle", 'wiki') . "</legend>";
1440
28f24584 1441 echo $OUTPUT->container_start('container');
00710f4c
DC
1442 print $filemanager->toHtml();
1443 echo $OUTPUT->container_end();
1444
1445 $cm = $PAGE->cm;
1df23626 1446 $context = context_module::instance($cm->id);
00710f4c 1447
28f24584 1448 echo $OUTPUT->container_start('container wiki-upload-table');
00710f4c
DC
1449 wiki_print_upload_table($context, 'wiki_upload', $pageid, $deleteuploads);
1450 echo $OUTPUT->container_end();
1451
1452 echo "</fieldset>";
1453
1b722e3c
MN
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') . '" />';
00710f4c
DC
1460}
1461
1462/**
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
1468 */
1469function wiki_print_upload_table($context, $filearea, $fileitemid, $deleteuploads = array()) {
1470 global $CFG, $OUTPUT;
1471
1472 $htmltable = new html_table();
1473
1474 $htmltable->head = array(get_string('deleteupload', 'wiki'), get_string('uploadname', 'wiki'), get_string('uploadactions', 'wiki'));
1475
1476 $fs = get_file_storage();
64f93798 1477 $files = $fs->get_area_files($context->id, 'mod_wiki', $filearea, $fileitemid); //TODO: this is weird (skodak)
00710f4c
DC
1478
1479 foreach ($files as $file) {
1480 if (!$file->is_directory()) {
1481 $checkbox = '<input type="checkbox" name="deleteupload[]", value="' . $file->get_pathnamehash() . '"';
1482
1483 if (in_array($file->get_pathnamehash(), $deleteuploads)) {
1484 $checkbox .= ' checked="checked"';
1485 }
1486
1487 $checkbox .= " />";
1488
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>', "");
1490 }
1491 }
1492
1493 print '<h3 class="upload-table-title">' . get_string('uploadfiletitle', 'wiki') . "</h3>";
1494 print html_writer::table($htmltable);
1495}
1496
1497/**
1498 * Generate wiki's page tree
1499 *
4c4e6591
SH
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
00710f4c
DC
1503 * @return an array with all tree nodes
1504 */
1505function wiki_build_tree($page, $node, &$keys) {
1506 $content = array();
c3625f5b
MG
1507 static $icon = null;
1508 if ($icon === null) {
317e98ba
MG
1509 // Substitute the default navigation icon with empty image.
1510 $icon = new pix_icon('spacer', '');
c3625f5b 1511 }
00710f4c
DC
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;
1517 }
1518 array_push($keys, $key);
1519 $l = wiki_parser_link($p);
1520 $link = new moodle_url('/mod/wiki/view.php', array('pageid' => $p->id));
4c4e6591 1521 // navigation_node::get_content will format the title for us
00710f4c
DC
1522 $nodeaux = $node->add($p->title, $link, null, null, null, $icon);
1523 if ($l['new']) {
1524 $nodeaux->add_class('wiki_newentry');
1525 }
1526 wiki_build_tree($p, $nodeaux, $keys);
1527 }
1528 $content[] = $node;
1529 return $content;
1530}
1531
1532/**
1533 * Get linked pages from page
1534 * @param int $pageid
1535 */
1536function wiki_get_linked_pages($pageid) {
1537 global $DB;
1538
9730c555 1539 $sql = "SELECT p.id, p.title
e22465c7
PS
1540 FROM {wiki_pages} p
1541 JOIN {wiki_links} l ON l.topageid = p.id
9730c555
JP
1542 WHERE l.frompageid = ?
1543 ORDER BY p.title ASC";
37dcd4b6
JP
1544 return $DB->get_records_sql($sql, array($pageid));
1545}
1546
1547/**
1548 * Get updated pages from wiki
1549 * @param int $pageid
1550 */
1551function wiki_get_updated_pages_by_subwiki($swid) {
1552 global $DB, $USER;
1553
9730c555
JP
1554 $sql = "SELECT *
1555 FROM {wiki_pages}
1556 WHERE subwikiid = ? AND timemodified > ?
1557 ORDER BY timemodified DESC";
37dcd4b6 1558 return $DB->get_records_sql($sql, array($swid, $USER->lastlogin));
00710f4c 1559}
23cbaefb
DP
1560
1561/**
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
1567 */
1568function wiki_can_create_pages($context, $user = null) {
1569 return has_capability('mod/wiki:createpage', $context, $user);
1570}
44f1b701
DP
1571
1572/**
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.
1575 *
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
1581 */
1582function 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;
1589 }
1590 return $subwiki;
1591}
1592
1593/**
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.
1596 *
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
1602 */
1603function wiki_get_visible_subwikis($wiki, $cm = null, $context = null) {
1604 global $USER;
1605
1606 $subwikis = array();
1607
1608 if (empty($wiki) or !is_object($wiki)) {
1609 // Wiki not valid.
1610 return $subwikis;
1611 }
1612
1613 if (empty($cm)) {
1614 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1615 }
1616 if (empty($context)) {
1617 $context = context_module::instance($cm->id);
1618 }
1619
1620 if (!has_capability('mod/wiki:viewpage', $context)) {
1621 return $subwikis;
1622 }
1623
1624 $manage = has_capability('mod/wiki:managewiki', $context);
1625
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);
1638 }
1639 } else {
1640 // User can only see his subwiki.
1641 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $USER->id);
1642 }
1643 }
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);
1657 }
1658
1659 foreach ($allowedgroups as $group) {
1660 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, 0);
1661 }
1662 } else if ($wiki->wikimode == 'individual') {
1663 // 1 subwiki per user and group.
1664
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);
1674 }
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);
1678 }
1679 }
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);
1687 }
1688 }
1689 }
1690 }
1691 }
1692
1693 return $subwikis;
1694}
62e20cfe
DP
1695
1696/**
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.
1699 *
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
1707 */
1708function wiki_get_subwiki_by_group_and_user_with_validation($wiki, $groupid, $userid) {
1709 global $USER, $DB;
1710
1711 // Get subwiki based on group and user.
1712 if (!$subwiki = wiki_get_subwiki_by_group($wiki->id, $groupid, $userid)) {
1713
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);
1719 }
1720
1721 // Validate that groupid is valid.
1722 if ($groupid != 0 && !groups_group_exists($groupid)) {
1723 throw new moodle_exception('cannotfindgroup', 'error');
1724 }
1725
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;
1733 }
1734
1735 // Check that the user can view the subwiki. This function checks capabilities.
1736 if (!wiki_user_can_view($subwiki, $wiki)) {
1737 return false;
1738 }
1739
1740 return $subwiki;
1741}
92c90b96
MG
1742
1743/**
1744 * Returns wiki pages tagged with a specified tag.
1745 *
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.
1748 *
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
1758 */
1759function mod_wiki_get_tagged_pages($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
1760 global $OUTPUT;
1761 $perpage = $exclusivemode ? 20 : 5;
1762
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
5e5ce443 1776 AND cm.deletioninprogress = 0
92c90b96
MG
1777 AND wp.id %ITEMFILTER% AND c.id %COURSEFILTER%";
1778
1779 $params = array('itemtype' => 'wiki_pages', 'tagid' => $tag->id, 'component' => 'mod_wiki',
1780 'coursemodulecontextlevel' => CONTEXT_MODULE);
1781
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.'/%';
1787 }
1788
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.'/%';
1796 }
1797 $query .= ' c.sortorder, cm.id, wp.id';
1798
1799 $totalpages = $page + 1;
1800
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;
1809 }
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,
d5722b44 1817 'userid' => $taggeditem->userid, 'wikiid' => $taggeditem->wikiid);
92c90b96
MG
1818 $wiki = (object)array('id' => $taggeditem->wikiid, 'wikimode' => $taggeditem->wikimode,
1819 'course' => $cm->course);
1820 $accessible = wiki_user_can_view($subwiki, $wiki);
1821 }
1822 $builder->set_accessible($taggeditem, $accessible);
1823 }
1824 });
1825 }
1826
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);
1831 }
1832
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);
1849 }
1850
1851 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
1852 $tagfeed->export_for_template($OUTPUT));
1853
1854 return new core_tag\output\tagindex($tag, 'mod_wiki', 'wiki_pages', $content,
1855 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1856 }
1857}