MDL-52809 wiki: New WS mod_wiki_get_subwikis
[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
35require_once($CFG->dirroot . '/mod/wiki/lib.php');
36require_once($CFG->dirroot . '/mod/wiki/parser/parser.php');
99d19c13 37require_once($CFG->libdir . '/filelib.php');
00710f4c
DC
38
39define('WIKI_REFRESH_CACHE_TIME', 30); // @TODO: To be deleted.
40define('FORMAT_CREOLE', '37');
41define('FORMAT_NWIKI', '38');
42define('NO_VALID_RATE', '-999');
43define('IMPROVEMENT', '+');
44define('EQUAL', '=');
45define('WORST', '-');
46
47define('LOCK_TIMEOUT', 30);
48
49/**
50 * Get a wiki instance
51 * @param int $wikiid the instance id of wiki
52 */
53function wiki_get_wiki($wikiid) {
54 global $DB;
55
56 return $DB->get_record('wiki', array('id' => $wikiid));
57}
58
59/**
60 * Get sub wiki instances with same wiki id
61 * @param int $wikiid
62 */
63function wiki_get_subwikis($wikiid) {
64 global $DB;
65 return $DB->get_records('wiki_subwikis', array('wikiid' => $wikiid));
66}
67
68/**
69 * Get a sub wiki instance by wiki id and group id
70 * @param int $wikiid
71 * @param int $groupid
72 * @return object
73 */
74function 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));
77}
78
79/**
80 * Get a sub wiki instace by instance id
81 * @param int $subwikiid
82 * @return object
83 */
84function wiki_get_subwiki($subwikiid) {
85 global $DB;
86 return $DB->get_record('wiki_subwikis', array('id' => $subwikiid));
87
88}
89
90/**
91 * Add a new sub wiki instance
92 * @param int $wikiid
93 * @param int $groupid
94 * @return int $insertid
95 */
96function wiki_add_subwiki($wikiid, $groupid, $userid = 0) {
97 global $DB;
98
99 $record = new StdClass();
100 $record->wikiid = $wikiid;
101 $record->groupid = $groupid;
102 $record->userid = $userid;
103
104 $insertid = $DB->insert_record('wiki_subwikis', $record);
105 return $insertid;
106}
107
108/**
109 * Get a wiki instance by pageid
110 * @param int $pageid
111 * @return object
112 */
113function wiki_get_wiki_from_pageid($pageid) {
114 global $DB;
115
9730c555
JP
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";
00710f4c
DC
121
122 return $DB->get_record_sql($sql, array($pageid));
123}
124
125/**
126 * Get a wiki page by pageid
127 * @param int $pageid
128 * @return object
129 */
130function wiki_get_page($pageid) {
131 global $DB;
132 return $DB->get_record('wiki_pages', array('id' => $pageid));
133}
134
135/**
136 * Get latest version of wiki page
137 * @param int $pageid
138 * @return object
139 */
140function wiki_get_current_version($pageid) {
141 global $DB;
142
9730c555
JP
143 // @TODO: Fix this query
144 $sql = "SELECT *
145 FROM {wiki_versions}
146 WHERE pageid = ?
70b082fa 147 ORDER BY version DESC";
54352ac9
PS
148 $records = $DB->get_records_sql($sql, array($pageid), 0, 1);
149 return array_pop($records);
00710f4c
DC
150
151}
152
153/**
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
158 */
159function wiki_get_last_version($pageid) {
160 return wiki_get_current_version($pageid);
161}
162
163/**
164 * Get page section
165 * @param int $pageid
166 * @param string $section
167 */
168function wiki_get_section_page($page, $section) {
169
170 $version = wiki_get_current_version($page->id);
171 return wiki_parser_proxy::get_section($version->content, $version->contentformat, $section);
172}
173
174/**
175 * Get a wiki page by page title
176 * @param int $swid, sub wiki id
177 * @param string $title
178 * @return object
179 */
180function wiki_get_page_by_title($swid, $title) {
181 global $DB;
182 return $DB->get_record('wiki_pages', array('subwikiid' => $swid, 'title' => $title));
183}
184
185/**
186 * Get a version record by record id
187 * @param int $versionid, the version id
188 * @return object
189 */
190function wiki_get_version($versionid) {
191 global $DB;
192 return $DB->get_record('wiki_versions', array('id' => $versionid));
193}
194
195/**
196 * Get first page of wiki instace
197 * @param int $subwikiid
198 * @param int $module, wiki instance object
199 */
37dcd4b6 200function wiki_get_first_page($subwikid, $module = null) {
00710f4c 201 global $DB, $USER;
00710f4c 202
9730c555
JP
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";
00710f4c
DC
209 return $DB->get_record_sql($sql, array($subwikid));
210}
211
212function wiki_save_section($wikipage, $sectiontitle, $sectioncontent, $userid) {
213
214 $wiki = wiki_get_wiki_from_pageid($wikipage->id);
215 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1df23626 216 $context = context_module::instance($cm->id);
00710f4c
DC
217
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);
221
222 $newcontent = $content[0] . $sectioncontent . $content[2];
223
224 return wiki_save_page($wikipage, $newcontent, $userid);
225 } else {
226 return false;
227 }
228}
229
230/**
231 * Save page content
232 * @param object $wikipage
233 * @param string $newcontent
234 * @param int $userid
235 */
236function wiki_save_page($wikipage, $newcontent, $userid) {
237 global $DB;
238
239 $wiki = wiki_get_wiki_from_pageid($wikipage->id);
240 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1df23626 241 $context = context_module::instance($cm->id);
00710f4c
DC
242
243 if (has_capability('mod/wiki:editpage', $context)) {
244 $version = wiki_get_current_version($wikipage->id);
245
246 $version->content = $newcontent;
247 $version->userid = $userid;
248 $version->version++;
249 $version->timecreated = time();
fb92417b 250 $version->id = $DB->insert_record('wiki_versions', $version);
00710f4c
DC
251
252 $wikipage->timemodified = $version->timecreated;
253 $wikipage->userid = $userid;
254 $return = wiki_refresh_cachedcontent($wikipage, $newcontent);
fb92417b
RT
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
262 )
263 ));
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();
00710f4c
DC
268 return $return;
269 } else {
270 return false;
271 }
272}
273
274function wiki_refresh_cachedcontent($page, $newcontent = null) {
275 global $DB;
276
277 $version = wiki_get_current_version($page->id);
79f0bac6
DC
278 if (empty($version)) {
279 return null;
280 }
00710f4c
DC
281 if (!isset($newcontent)) {
282 $newcontent = $version->content;
283 }
284
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);
290
291 wiki_refresh_page_links($page, $parseroutput['link_count']);
292
293 return array('page' => $page, 'sections' => $parseroutput['repeated_sections'], 'version' => $version->version);
294}
0e729875 295
00710f4c 296/**
0e729875
RT
297 * Restore a page with specified version.
298 *
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
00710f4c 303 */
0e729875
RT
304function 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
312 )
313 ));
314 $event->add_record_snapshot('wiki_versions', $version);
315 $event->trigger();
00710f4c
DC
316 return $return['page'];
317}
318
319function wiki_refresh_page_links($page, $links) {
320 global $DB;
321
322 $DB->delete_records('wiki_links', array('frompageid' => $page->id));
323 foreach ($links as $linkname => $linkinfo) {
324
325 $newlink = new stdClass();
326 $newlink->subwikiid = $page->subwikiid;
327 $newlink->frompageid = $page->id;
328
329 if ($linkinfo['new']) {
330 $newlink->tomissingpage = $linkname;
331 } else {
332 $newlink->topageid = $linkinfo['pageid'];
333 }
334
79f0bac6
DC
335 try {
336 $DB->insert_record('wiki_links', $newlink);
337 } catch (dml_exception $e) {
338 debugging($e->getMessage());
339 }
00710f4c
DC
340
341 }
342}
343
344/**
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
350 */
351function wiki_create_page($swid, $title, $format, $userid) {
4c4e6591 352 global $DB;
7bc03dd5
JP
353 $subwiki = wiki_get_subwiki($swid);
354 $cm = get_coursemodule_from_instance('wiki', $subwiki->wikiid);
1df23626 355 $context = context_module::instance($cm->id);
7bc03dd5 356 require_capability('mod/wiki:editpage', $context);
00710f4c
DC
357 // if page exists
358 if ($page = wiki_get_page_by_title($swid, $title)) {
359 return $page->id;
360 }
361
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;
369
370 $versionid = null;
a9637e7d 371 $versionid = $DB->insert_record('wiki_versions', $version);
00710f4c
DC
372
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;
384
385 $pageid = $DB->insert_record('wiki_pages', $page);
386
387 // Setting the pageid
388 $version->id = $versionid;
389 $version->pageid = $pageid;
390 $DB->update_record('wiki_versions', $version);
391
a8481a66
RT
392 $event = \mod_wiki\event\page_created::create(
393 array(
394 'context' => $context,
395 'objectid' => $pageid
396 )
397 );
398 $event->trigger();
399
00710f4c
DC
400 wiki_make_cache_expire($page->title);
401 return $pageid;
402}
403
404function wiki_make_cache_expire($pagename) {
405 global $DB;
406
9730c555
JP
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 = ?
412 )";
00710f4c
DC
413 $DB->execute ($sql, array($pagename));
414}
415
416/**
417 * Get a specific version of page
418 * @param int $pageid
419 * @param int $version
420 */
421function wiki_get_wiki_page_version($pageid, $version) {
422 global $DB;
423 return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'version' => $version));
424}
425
426/**
427 * Get version list
428 * @param int $pageid
429 * @param int $limitfrom
430 * @param int $limitnum
431 */
432function 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);
435}
436
437/**
438 * Count the number of page version
439 * @param int $pageid
440 */
441function wiki_count_wiki_page_versions($pageid) {
442 global $DB;
443 return $DB->count_records('wiki_versions', array('pageid' => $pageid));
444}
445
446/**
447 * Get linked from page
448 * @param int $pageid
449 */
450function wiki_get_linked_to_pages($pageid) {
451 global $DB;
452 return $DB->get_records('wiki_links', array('frompageid' => $pageid));
453}
454
455/**
456 * Get linked from page
457 * @param int $pageid
458 */
459function wiki_get_linked_from_pages($pageid) {
460 global $DB;
461 return $DB->get_records('wiki_links', array('topageid' => $pageid));
462}
463
464/**
465 * Get pages which user have been edited
466 * @param int $swid
467 * @param int $userid
468 */
469function wiki_get_contributions($swid, $userid) {
470 global $DB;
471
9730c555
JP
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 = ?";
00710f4c
DC
477
478 return $DB->get_records_sql($sql, array($swid, $userid));
479}
480
481/**
482 * Get missing or empty pages in wiki
483 * @param int $swid sub wiki id
484 */
485function wiki_get_missing_or_empty_pages($swid) {
486 global $DB;
487
9730c555
JP
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";
00710f4c
DC
502
503 return $DB->get_records_sql($sql, array($swid, $swid, $swid));
504}
505
506/**
507 * Get pages list in wiki
508 * @param int $swid sub wiki id
509 */
510function wiki_get_page_list($swid) {
511 global $DB;
512 $records = $DB->get_records('wiki_pages', array('subwikiid' => $swid), 'title ASC');
513 return $records;
514}
515
516/**
517 * Return a list of orphaned wikis for one specific subwiki
518 * @global object
519 * @param int $swid sub wiki id
520 */
521function wiki_get_orphaned_pages($swid) {
522 global $DB;
523
9730c555
JP
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
92b145dc 530 AND p.id NOT IN (SELECT topageid FROM {wiki_links} WHERE subwikiid = ?)";
00710f4c 531
9730c555 532 return $DB->get_records_sql($sql, array($swid, $swid, $swid));
00710f4c
DC
533}
534
535/**
536 * Search wiki title
537 * @param int $swid sub wiki id
538 * @param string $search
539 */
540function wiki_search_title($swid, $search) {
541 global $DB;
75b986e7
JP
542
543 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND title LIKE ?", array($swid, '%'.$search.'%'));
00710f4c
DC
544}
545
546/**
547 * Search wiki content
548 * @param int $swid sub wiki id
549 * @param string $search
550 */
551function wiki_search_content($swid, $search) {
552 global $DB;
75b986e7
JP
553
554 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND cachedcontent LIKE ?", array($swid, '%'.$search.'%'));
00710f4c
DC
555}
556
557/**
558 * Search wiki title and content
559 * @param int $swid sub wiki id
560 * @param string $search
561 */
562function wiki_search_all($swid, $search) {
563 global $DB;
75b986e7
JP
564
565 return $DB->get_records_select('wiki_pages', "subwikiid = ? AND (cachedcontent LIKE ? OR title LIKE ?)", array($swid, '%'.$search.'%', '%'.$search.'%'));
00710f4c
DC
566}
567
568/**
9ffd2726 569 * Get user data
00710f4c
DC
570 */
571function wiki_get_user_info($userid) {
9ffd2726
JP
572 global $DB;
573 return $DB->get_record('user', array('id' => $userid));
00710f4c
DC
574}
575
576/**
577 * Increase page view nubmer
578 * @param int $page, database record
579 */
580function wiki_increment_pageviews($page) {
581 global $DB;
582
583 $page->pageviews++;
584 $DB->update_record('wiki_pages', $page);
585}
586
587//----------------------------------------------------------
588//----------------------------------------------------------
589
590/**
591 * Text format supported by wiki module
592 */
593function wiki_get_formats() {
44c0751b 594 return array('html', 'creole', 'nwiki');
00710f4c
DC
595}
596
597/**
598 * Parses a string with the wiki markup language in $markup.
599 *
600 * @return Array or false when something wrong has happened.
601 *
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 * '' =>
608 *
609 * @author Josep Arús Pous
610 **/
611function wiki_parse_content($markup, $pagecontent, $options = array()) {
612 global $PAGE;
613
614 $subwiki = wiki_get_subwiki($options['swid']);
615 $cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid);
1df23626 616 $context = context_module::instance($cm->id);
00710f4c 617
c464a238
SH
618 $parser_options = array(
619 'link_callback' => '/mod/wiki/locallib.php:wiki_parser_link',
12c9bbbd
DC
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']
629 ),
630 'pageid' => $options['pageid'],
631 'pretty_print' => (isset($options['pretty_print']) && $options['pretty_print']),
632 'printable' => (isset($options['printable']) && $options['printable'])
633 );
00710f4c
DC
634
635 return wiki_parser_proxy::parse($pagecontent, $markup, $parser_options);
636}
637
638/**
639 * This function is the parser callback to parse wiki links.
640 *
641 * It returns the necesary information to print a link.
642 *
643 * NOTE: Empty pages and non-existent pages must be print in red color.
644 *
4c4e6591
SH
645 * !!!!!! IMPORTANT !!!!!!
646 * It is critical that you call format_string on the content before it is used.
00710f4c 647 *
4c4e6591
SH
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)
00710f4c
DC
651 *
652 * @TODO Doc return and options
653 */
654function wiki_parser_link($link, $options = null) {
655 global $CFG;
656
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));
659
660 $version = wiki_get_current_version($link->id);
661 if ($version->version == 0) {
662 $parsedlink['new'] = true;
663 }
664 return $parsedlink;
665 } else {
666 $swid = $options['swid'];
667
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));
670
671 $version = wiki_get_current_version($page->id);
672 if ($version->version == 0) {
673 $parsedlink['new'] = true;
674 }
675
676 return $parsedlink;
677
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));
680 }
681 }
682}
683
684/**
685 * Returns the table fully parsed (HTML)
686 *
687 * @return HTML for the table $table
688 * @author Josep Arús Pous
689 *
690 **/
691function wiki_parser_table($table) {
692 global $OUTPUT;
693
694 $htmltable = new html_table();
695
696 $headers = $table[0];
697 $htmltable->head = array();
698 foreach ($headers as $h) {
699 $htmltable->head[] = $h[1];
700 }
701
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];
708 }
709 $htmltable->data[] = $row_data;
710 }
711
712 return html_writer::table($htmltable);
713}
714
715/**
716 * Returns an absolute path link, unless there is no such link.
717 *
c464a238
SH
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
00710f4c 723 *
c464a238 724 * @return string URL for files full path
00710f4c
DC
725 */
726
12c9bbbd 727function wiki_parser_real_path($url, $context, $component, $filearea, $swid) {
00710f4c
DC
728 global $CFG;
729
730 if (preg_match("/^(?:http|ftp)s?\:\/\//", $url)) {
731 return $url;
732 } else {
12c9bbbd
DC
733
734 $file = 'pluginfile.php';
735 if (!$CFG->slasharguments) {
736 $file = $file . '?file=';
737 }
738 $baseurl = "$CFG->wwwroot/$file/{$context->id}/$component/$filearea/$swid/";
739 // it is a file in current file area
740 return $baseurl . $url;
00710f4c
DC
741 }
742}
743
744/**
745 * Returns the token used by a wiki language to represent a given tag or "object" (bold -> **)
746 *
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
749 **/
750function wiki_parser_get_token($markup, $name) {
751
752 return wiki_parser_proxy::get_token($name, $markup);
753}
754
755/**
756 * Checks if current user can view a subwiki
757 *
3a7b9b76
MG
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
00710f4c 762 */
3a7b9b76 763function wiki_user_can_view($subwiki, $wiki = null) {
00710f4c
DC
764 global $USER;
765
3a7b9b76
MG
766 if (empty($wiki) || $wiki->id != $subwiki->wikiid) {
767 $wiki = wiki_get_wiki($subwiki->wikiid);
768 }
769 $modinfo = get_fast_modinfo($wiki->course);
770 if (!isset($modinfo->instances['wiki'][$subwiki->wikiid])) {
771 // Module does not exist.
772 return false;
773 }
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;
778 }
1df23626 779 $context = context_module::instance($cm->id);
00710f4c
DC
780
781 // Working depending on activity groupmode
782 switch (groups_get_activity_groupmode($cm)) {
783 case NOGROUPS:
784
785 if ($wiki->wikimode == 'collaborative') {
786 // Collaborative Mode:
787 // There is one wiki for all the class.
788 //
789 // Only view capbility needed
cece1791 790 return has_capability('mod/wiki:viewpage', $context);
00710f4c
DC
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
cece1791 796 return has_capability('mod/wiki:viewpage', $context);
00710f4c
DC
797 } else { // User has special capabilities
798 // User must have:
799 // mod/wiki:viewpage capability
800 // and
801 // mod/wiki:managewiki capability
cece1791
DC
802 $view = has_capability('mod/wiki:viewpage', $context);
803 $manage = has_capability('mod/wiki:managewiki', $context);
00710f4c
DC
804
805 return $view && $manage;
806 }
807 } else {
808 //Error
809 return false;
810 }
811 case SEPARATEGROUPS:
812 // Collaborative and Individual Mode
813 //
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
3a7b9b76 820 if (in_array($subwiki->groupid, $modinfo->get_groups($cm->groupingid))) {
00710f4c 821 // Only view capability needed
cece1791 822 return has_capability('mod/wiki:viewpage', $context);
00710f4c
DC
823
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
cece1791
DC
831 $view = has_capability('mod/wiki:viewpage', $context);
832 $manage = has_capability('mod/wiki:managewiki', $context);
833 $access = has_capability('moodle/site:accessallgroups', $context);
00710f4c 834 return ($manage || $access) && $view;
37dcd4b6 835 }
00710f4c
DC
836 } else {
837 //Error
838 return false;
839 }
840 case VISIBLEGROUPS:
841 // Collaborative and Individual Mode
842 //
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
849 //
850 // Only view capability needed
cece1791 851 return has_capability('mod/wiki:viewpage', $context);
00710f4c
DC
852 } else {
853 //Error
854 return false;
855 }
856 default: // Error
857 return false;
858 }
859}
860
861/**
862 * Checks if current user can edit a subwiki
863 *
864 * @param $subwiki
865 */
866function wiki_user_can_edit($subwiki) {
867 global $USER;
868
869 $wiki = wiki_get_wiki($subwiki->wikiid);
870 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1df23626 871 $context = context_module::instance($cm->id);
00710f4c
DC
872
873 // Working depending on activity groupmode
874 switch (groups_get_activity_groupmode($cm)) {
875 case NOGROUPS:
876
877 if ($wiki->wikimode == 'collaborative') {
878 // Collaborative Mode:
879 // There is a wiki for all the class.
880 //
881 // Only edit capbility needed
cece1791 882 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
883 } else if ($wiki->wikimode == 'individual') {
884 // Individual Mode
885 // There is a wiki per user
886
887 // Only the owner of that wiki can edit it
888 if ($subwiki->userid == $USER->id) {
cece1791 889 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
890 } else { // Current user is not the owner of that wiki.
891
892 // User must have:
893 // mod/wiki:editpage capability
894 // and
895 // mod/wiki:managewiki capability
cece1791
DC
896 $edit = has_capability('mod/wiki:editpage', $context);
897 $manage = has_capability('mod/wiki:managewiki', $context);
00710f4c
DC
898
899 return $edit && $manage;
900 }
901 } else {
902 //Error
903 return false;
904 }
905 case SEPARATEGROUPS:
906 if ($wiki->wikimode == 'collaborative') {
907 // Collaborative Mode:
908 // There is one wiki per group.
909 //
910 // Only members of subwiki group could edit that wiki
bb05505e 911 if (groups_is_member($subwiki->groupid)) {
00710f4c 912 // Only edit capability needed
cece1791 913 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
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
cece1791
DC
921 $manage = has_capability('mod/wiki:managewiki', $context);
922 $access = has_capability('moodle/site:accessallgroups', $context);
923 $edit = has_capability('mod/wiki:editpage', $context);
00710f4c
DC
924 return $manage && $access && $edit;
925 }
926 } else if ($wiki->wikimode == 'individual') {
927 // Individual Mode:
928 // Each person owns a wiki.
929 //
930 // Only the owner of that wiki can edit it
931 if ($subwiki->userid == $USER->id) {
cece1791 932 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
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
cece1791
DC
940 $manage = has_capability('mod/wiki:managewiki', $context);
941 $access = has_capability('moodle/site:accessallgroups', $context);
942 $edit = has_capability('mod/wiki:editpage', $context);
00710f4c
DC
943 return $manage && $access && $edit;
944 }
945 } else {
946 //Error
947 return false;
948 }
949 case VISIBLEGROUPS:
950 if ($wiki->wikimode == 'collaborative') {
951 // Collaborative Mode:
952 // There is one wiki per group.
953 //
954 // Only members of subwiki group could edit that wiki
dc0cabb4 955 if (groups_is_member($subwiki->groupid)) {
00710f4c 956 // Only edit capability needed
cece1791 957 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
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
cece1791
DC
963 $manage = has_capability('mod/wiki:managewiki', $context);
964 $edit = has_capability('mod/wiki:editpage', $context);
00710f4c
DC
965 return $manage && $edit;
966 }
967 } else if ($wiki->wikimode == 'individual') {
968 // Individual Mode:
969 // Each person owns a wiki.
970 //
971 // Only the owner of that wiki can edit it
972 if ($subwiki->userid == $USER->id) {
cece1791 973 return has_capability('mod/wiki:editpage', $context);
00710f4c
DC
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
cece1791
DC
979 $manage = has_capability('mod/wiki:managewiki', $context);
980 $edit = has_capability('mod/wiki:editpage', $context);
00710f4c
DC
981 return $manage && $edit;
982 }
983 } else {
984 //Error
985 return false;
986 }
987 default: // Error
988 return false;
989 }
990}
991
992//----------------
993// Locks
994//----------------
995
996/**
997 * Checks if a page-section is locked.
998 *
999 * @return true if the combination of section and page is locked, FALSE otherwise.
1000 */
1001function wiki_is_page_section_locked($pageid, $userid, $section = null) {
1002 global $DB;
1003
1004 $sql = "pageid = ? AND lockedat > ? AND userid != ?";
1005 $params = array($pageid, time(), $userid);
1006
1007 if (!empty($section)) {
1008 $sql .= " AND (sectionname = ? OR sectionname IS null)";
1009 $params[] = $section;
1010 }
1011
1012 return $DB->record_exists_select('wiki_locks', $sql, $params);
1013}
1014
1015/**
1016 * Inserts or updates a wiki_locks record.
1017 */
1018function wiki_set_lock($pageid, $userid, $section = null, $insert = false) {
1019 global $DB;
1020
1021 if (wiki_is_page_section_locked($pageid, $userid, $section)) {
1022 return false;
1023 }
1024
1025 $params = array('pageid' => $pageid, 'userid' => $userid, 'sectionname' => $section);
1026
1027 $lock = $DB->get_record('wiki_locks', $params);
1028
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));
1033 }
1034
1035 return true;
1036}
1037
1038/**
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.
b3dd79d1
RT
1040 *
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.
00710f4c
DC
1046 */
1047function wiki_delete_locks($pageid, $userid = null, $section = null, $delete_from_db = true, $delete_section_and_page = false) {
1048 global $DB;
1049
b3dd79d1
RT
1050 $wiki = wiki_get_wiki_from_pageid($pageid);
1051 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1052 $context = context_module::instance($cm->id);
1053
00710f4c
DC
1054 $params = array('pageid' => $pageid);
1055
1056 if (!empty($userid)) {
1057 $params['userid'] = $userid;
1058 }
1059
1060 if (!empty($section)) {
1061 $params['sectionname'] = $section;
1062 }
1063
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);
1069 }
b3dd79d1
RT
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
1077 )
1078 ));
1079 // No need to add snapshot, as important data is section, userid and pageid, which is part of event.
1080 $event->trigger();
00710f4c
DC
1081 } else {
1082 $DB->set_field('wiki_locks', 'lockedat', time(), $params);
1083 }
1084}
1085
1086/**
1087 * Deletes wiki_locks that expired 1 hour ago.
1088 */
1089function wiki_delete_old_locks() {
1090 global $DB;
1091
1092 $DB->delete_records_select('wiki_locks', "lockedat < ?", array(time() - 3600));
1093}
1094
ac0a82cf
RT
1095/**
1096 * Deletes wiki_links. It can be sepecific link or links attached in subwiki
1097 *
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
1103 */
1104function wiki_delete_links($linkid = null, $topageid = null, $frompageid = null, $subwikiid = null) {
1105 global $DB;
1106 $params = array();
1107
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;
1114 }
1115 if (!empty($frompageid)) {
1116 $params['frompageid'] = $frompageid;
1117 }
1118 if (!empty($subwikiid)) {
1119 $params['subwikiid'] = $subwikiid;
1120 }
1121 }
1122
1123 //Delete links if any params are passed, else nothing to delete.
1124 if (!empty($params)) {
1125 $DB->delete_records('wiki_links', $params);
1126 }
1127}
1128
1129/**
1130 * Delete wiki synonyms related to subwikiid or page
1131 *
1132 * @param int $subwikiid id of sunbwiki
1133 * @param int $pageid id of page
1134 */
1135function wiki_delete_synonym($subwikiid, $pageid = null) {
1136 global $DB;
1137
1138 $params = array('subwikiid' => $subwikiid);
1139 if (!is_null($pageid)) {
1140 $params['pageid'] = $pageid;
1141 }
1142 $DB->delete_records('wiki_synonyms', $params, IGNORE_MISSING);
1143}
1144
1145/**
1146 * Delete pages and all related data
1147 *
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
1151 */
1152function wiki_delete_pages($context, $pageids = null, $subwikiid = null) {
d6a54be3 1153 global $DB, $CFG;
ac0a82cf
RT
1154
1155 if (!empty($pageids) && is_int($pageids)) {
1156 $pageids = array($pageids);
1157 } else if (!empty($subwikiid)) {
1158 $pageids = wiki_get_page_list($subwikiid);
1159 }
1160
1161 //If there is no pageid then return as we can't delete anything.
1162 if (empty($pageids)) {
1163 return;
1164 }
1165
1166 /// Delete page and all it's relevent data
1167 foreach ($pageids as $pageid) {
1168 if (is_object($pageid)) {
1169 $pageid = $pageid->id;
1170 }
1171
1172 //Delete page comments
1173 $comments = wiki_get_comments($context->id, $pageid);
1174 foreach ($comments as $commentid => $commentvalue) {
1175 wiki_delete_comment($commentid, $context, $pageid);
1176 }
1177
1178 //Delete page tags
b0b2c93d 1179 core_tag_tag::remove_all_item_tags('mod_wiki', 'wiki_pages', $pageid);
ac0a82cf
RT
1180
1181 //Delete Synonym
1182 wiki_delete_synonym($subwikiid, $pageid);
1183
1184 //Delete all page versions
d6a54be3 1185 wiki_delete_page_versions(array($pageid=>array(0)), $context);
ac0a82cf
RT
1186
1187 //Delete all page locks
1188 wiki_delete_locks($pageid);
1189
1190 //Delete all page links
1191 wiki_delete_links(null, $pageid);
1192
ac0a82cf 1193 $params = array('id' => $pageid);
d6a54be3
RT
1194
1195 // Get page before deleting.
1196 $page = $DB->get_record('wiki_pages', $params);
1197
1198 //Delete page
ac0a82cf 1199 $DB->delete_records('wiki_pages', $params);
d6a54be3
RT
1200
1201 // Trigger page_deleted event.
1202 $event = \mod_wiki\event\page_deleted::create(
1203 array(
1204 'context' => $context,
1205 'objectid' => $pageid,
1206 'other' => array('subwikiid' => $subwikiid)
1207 ));
1208 $event->add_record_snapshot('wiki_pages', $page);
1209 $event->trigger();
ac0a82cf
RT
1210 }
1211}
1212
1213/**
1214 * Delete specificed versions of a page or versions created by users
1215 * if version is 0 then it will remove all versions of the page
1216 *
1217 * @param array $deleteversions delete versions for a page
d6a54be3 1218 * @param context_module $context module context
ac0a82cf 1219 */
d6a54be3 1220function wiki_delete_page_versions($deleteversions, $context = null) {
ac0a82cf
RT
1221 global $DB;
1222
1223 /// delete page-versions
1224 foreach ($deleteversions as $id => $versions) {
d6a54be3
RT
1225 $params = array('pageid' => $id);
1226 if (is_null($context)) {
1227 $wiki = wiki_get_wiki_from_pageid($id);
1228 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1229 $context = context_module::instance($cm->id);
1230 }
1231 // Delete all versions, if version specified is 0.
1232 if (in_array(0, $versions)) {
1233 $oldversions = $DB->get_records('wiki_versions', $params);
ac0a82cf 1234 $DB->delete_records('wiki_versions', $params, IGNORE_MISSING);
d6a54be3
RT
1235 } else {
1236 list($insql, $param) = $DB->get_in_or_equal($versions);
1237 $insql .= ' AND pageid = ?';
1238 array_push($param, $params['pageid']);
1239 $oldversions = $DB->get_recordset_select('wiki_versions', 'version ' . $insql, $param);
1240 $DB->delete_records_select('wiki_versions', 'version ' . $insql, $param);
1241 }
1242 foreach ($oldversions as $version) {
1243 // Trigger page version deleted event.
1244 $event = \mod_wiki\event\page_version_deleted::create(
1245 array(
1246 'context' => $context,
1247 'objectid' => $version->id,
1248 'other' => array(
1249 'pageid' => $id
1250 )
1251 ));
1252 $event->add_record_snapshot('wiki_versions', $version);
1253 $event->trigger();
ac0a82cf
RT
1254 }
1255 }
1256}
1257
9bf1b716
JP
1258function wiki_get_comment($commentid){
1259 global $DB;
becf81c7 1260 return $DB->get_record('comments', array('id' => $commentid));
9bf1b716
JP
1261}
1262
00710f4c
DC
1263/**
1264 * Returns all comments by context and pageid
1265 *
e94f6c65
RT
1266 * @param int $contextid Current context id
1267 * @param int $pageid Current pageid
00710f4c 1268 **/
9ffd2726 1269function wiki_get_comments($contextid, $pageid) {
00710f4c
DC
1270 global $DB;
1271
cde6172d 1272 return $DB->get_records('comments', array('contextid' => $contextid, 'itemid' => $pageid, 'commentarea' => 'wiki_page'), 'timecreated ASC');
00710f4c
DC
1273}
1274
1275/**
1276 * Add comments ro database
1277 *
1278 * @param object $context. Current context
1279 * @param int $pageid. Current pageid
1280 * @param string $content. Content of the comment
1281 * @param string editor. Version of editor we are using.
1282 **/
1283function wiki_add_comment($context, $pageid, $content, $editor) {
1284 global $CFG;
1285 require_once($CFG->dirroot . '/comment/lib.php');
1286
1287 list($context, $course, $cm) = get_context_info_array($context->id);
1288 $cmt = new stdclass();
1289 $cmt->context = $context;
1290 $cmt->itemid = $pageid;
ab422920 1291 $cmt->area = 'wiki_page';
00710f4c 1292 $cmt->course = $course;
d846488e 1293 $cmt->component = 'mod_wiki';
00710f4c
DC
1294
1295 $manager = new comment($cmt);
1296
1297 if ($editor == 'creole') {
1298 $manager->add($content, FORMAT_CREOLE);
1299 } else if ($editor == 'html') {
1300 $manager->add($content, FORMAT_HTML);
1301 } else if ($editor == 'nwiki') {
1302 $manager->add($content, FORMAT_NWIKI);
1303 }
1304
1305}
1306
1307/**
1308 * Delete comments from database
1309 *
1310 * @param $idcomment. Id of comment which will be deleted
1311 * @param $context. Current context
1312 * @param $pageid. Current pageid
1313 **/
1314function wiki_delete_comment($idcomment, $context, $pageid) {
1315 global $CFG;
1316 require_once($CFG->dirroot . '/comment/lib.php');
1317
1318 list($context, $course, $cm) = get_context_info_array($context->id);
6bdfef5d 1319 $cmt = new stdClass();
00710f4c
DC
1320 $cmt->context = $context;
1321 $cmt->itemid = $pageid;
ab422920 1322 $cmt->area = 'wiki_page';
00710f4c 1323 $cmt->course = $course;
d846488e 1324 $cmt->component = 'mod_wiki';
00710f4c
DC
1325
1326 $manager = new comment($cmt);
1327 $manager->delete($idcomment);
1328
1329}
1330
1331/**
1332 * Delete al comments from wiki
1333 *
1334 **/
1335function wiki_delete_comments_wiki() {
1336 global $PAGE, $DB;
1337
1338 $cm = $PAGE->cm;
1df23626 1339 $context = context_module::instance($cm->id);
00710f4c
DC
1340
1341 $table = 'comments';
1342 $select = 'contextid = ?';
1343
1344 $DB->delete_records_select($table, $select, array($context->id));
1345
1346}
1347
1348function wiki_add_progress($pageid, $oldversionid, $versionid, $progress) {
1349 global $DB;
1350 for ($v = $oldversionid + 1; $v <= $versionid; $v++) {
1351 $user = wiki_get_wiki_page_id($pageid, $v);
1352
1353 $DB->insert_record('wiki_progress', array('userid' => $user->userid, 'pageid' => $pageid, 'versionid' => $v, 'progress' => $progress));
1354 }
1355}
1356
1357function wiki_get_wiki_page_id($pageid, $id) {
1358 global $DB;
1359 return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'id' => $id));
1360}
1361
1362function wiki_print_page_content($page, $context, $subwikiid) {
1363 global $OUTPUT, $CFG;
1364
1365 if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) {
1366 $content = wiki_refresh_cachedcontent($page);
1367 $page = $content['page'];
1368 }
1369
1370 if (isset($content)) {
1371 $box = '';
1372 foreach ($content['sections'] as $s) {
1373 $box .= '<p>' . get_string('repeatedsection', 'wiki', $s) . '</p>';
1374 }
1375
1376 if (!empty($box)) {
1377 echo $OUTPUT->box($box);
1378 }
1379 }
64f93798 1380 $html = file_rewrite_pluginfile_urls($page->cachedcontent, 'pluginfile.php', $context->id, 'mod_wiki', 'attachments', $subwikiid);
2f8b49d5 1381 $html = format_text($html, FORMAT_MOODLE, array('overflowdiv'=>true, 'allowid'=>true));
00710f4c
DC
1382 echo $OUTPUT->box($html);
1383
b0b2c93d
MG
1384 echo $OUTPUT->tag_list(core_tag_tag::get_item_tags('mod_wiki', 'wiki_pages', $page->id),
1385 null, 'wiki-tags');
00710f4c
DC
1386
1387 wiki_increment_pageviews($page);
1388}
1389
1390/**
1391 * This function trims any given text and returns it with some dots at the end
1392 *
1393 * @param string $text
1394 * @param string $limit
1395 *
1396 * @return string
1397 */
1398function wiki_trim_string($text, $limit = 25) {
1399
2f1e464a
PS
1400 if (core_text::strlen($text) > $limit) {
1401 $text = core_text::substr($text, 0, $limit) . '...';
00710f4c
DC
1402 }
1403
1404 return $text;
1405}
1406
1407/**
1408 * Prints default edit form fields and buttons
1409 *
1410 * @param string $format Edit form format (html, creole...)
1411 * @param integer $version Version number. A negative number means no versioning.
1412 */
1413
1414function wiki_print_edit_form_default_fields($format, $pageid, $version = -1, $upload = false, $deleteuploads = array()) {
1415 global $CFG, $PAGE, $OUTPUT;
1416
1417 echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
1418
1419 if ($version >= 0) {
1420 echo '<input type="hidden" name="version" value="' . $version . '" />';
1421 }
1422
1423 echo '<input type="hidden" name="format" value="' . $format . '"/>';
1424
1425 //attachments
1426 require_once($CFG->dirroot . '/lib/form/filemanager.php');
1427
1428 $filemanager = new MoodleQuickForm_filemanager('attachments', get_string('wikiattachments', 'wiki'), array('id' => 'attachments'), array('subdirs' => false, 'maxfiles' => 99, 'maxbytes' => $CFG->maxbytes));
1429
1430 $value = file_get_submitted_draft_itemid('attachments');
1431 if (!empty($value) && !$upload) {
1432 $filemanager->setValue($value);
1433 }
1434
1435 echo "<fieldset class=\"wiki-upload-section clearfix\"><legend class=\"ftoggler\">" . get_string("uploadtitle", 'wiki') . "</legend>";
1436
1437 echo $OUTPUT->container_start('mdl-align wiki-form-center aaaaa');
1438 print $filemanager->toHtml();
1439 echo $OUTPUT->container_end();
1440
1441 $cm = $PAGE->cm;
1df23626 1442 $context = context_module::instance($cm->id);
00710f4c
DC
1443
1444 echo $OUTPUT->container_start('mdl-align wiki-form-center wiki-upload-table');
1445 wiki_print_upload_table($context, 'wiki_upload', $pageid, $deleteuploads);
1446 echo $OUTPUT->container_end();
1447
1448 echo "</fieldset>";
1449
1450 echo '<input class="wiki_button" type="submit" name="editoption" value="' . get_string('save', 'wiki') . '"/>';
1451 echo '<input class="wiki_button" type="submit" name="editoption" value="' . get_string('upload', 'wiki') . '"/>';
1452 echo '<input class="wiki_button" type="submit" name="editoption" value="' . get_string('preview') . '"/>';
1453 echo '<input class="wiki_button" type="submit" name="editoption" value="' . get_string('cancel') . '" />';
1454}
1455
1456/**
1457 * Prints a table with the files attached to a wiki page
1458 * @param object $context
1459 * @param string $filearea
1460 * @param int $fileitemid
1461 * @param array deleteuploads
1462 */
1463function wiki_print_upload_table($context, $filearea, $fileitemid, $deleteuploads = array()) {
1464 global $CFG, $OUTPUT;
1465
1466 $htmltable = new html_table();
1467
1468 $htmltable->head = array(get_string('deleteupload', 'wiki'), get_string('uploadname', 'wiki'), get_string('uploadactions', 'wiki'));
1469
1470 $fs = get_file_storage();
64f93798 1471 $files = $fs->get_area_files($context->id, 'mod_wiki', $filearea, $fileitemid); //TODO: this is weird (skodak)
00710f4c
DC
1472
1473 foreach ($files as $file) {
1474 if (!$file->is_directory()) {
1475 $checkbox = '<input type="checkbox" name="deleteupload[]", value="' . $file->get_pathnamehash() . '"';
1476
1477 if (in_array($file->get_pathnamehash(), $deleteuploads)) {
1478 $checkbox .= ' checked="checked"';
1479 }
1480
1481 $checkbox .= " />";
1482
1483 $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>', "");
1484 }
1485 }
1486
1487 print '<h3 class="upload-table-title">' . get_string('uploadfiletitle', 'wiki') . "</h3>";
1488 print html_writer::table($htmltable);
1489}
1490
1491/**
1492 * Generate wiki's page tree
1493 *
4c4e6591
SH
1494 * @param page_wiki $page. A wiki page object
1495 * @param navigation_node $node. Starting navigation_node
1496 * @param array $keys. An array to store keys
00710f4c
DC
1497 * @return an array with all tree nodes
1498 */
1499function wiki_build_tree($page, $node, &$keys) {
1500 $content = array();
c3625f5b
MG
1501 static $icon = null;
1502 if ($icon === null) {
317e98ba
MG
1503 // Substitute the default navigation icon with empty image.
1504 $icon = new pix_icon('spacer', '');
c3625f5b 1505 }
00710f4c
DC
1506 $pages = wiki_get_linked_pages($page->id);
1507 foreach ($pages as $p) {
1508 $key = $page->id . ':' . $p->id;
1509 if (in_array($key, $keys)) {
1510 break;
1511 }
1512 array_push($keys, $key);
1513 $l = wiki_parser_link($p);
1514 $link = new moodle_url('/mod/wiki/view.php', array('pageid' => $p->id));
4c4e6591 1515 // navigation_node::get_content will format the title for us
00710f4c
DC
1516 $nodeaux = $node->add($p->title, $link, null, null, null, $icon);
1517 if ($l['new']) {
1518 $nodeaux->add_class('wiki_newentry');
1519 }
1520 wiki_build_tree($p, $nodeaux, $keys);
1521 }
1522 $content[] = $node;
1523 return $content;
1524}
1525
1526/**
1527 * Get linked pages from page
1528 * @param int $pageid
1529 */
1530function wiki_get_linked_pages($pageid) {
1531 global $DB;
1532
9730c555 1533 $sql = "SELECT p.id, p.title
e22465c7
PS
1534 FROM {wiki_pages} p
1535 JOIN {wiki_links} l ON l.topageid = p.id
9730c555
JP
1536 WHERE l.frompageid = ?
1537 ORDER BY p.title ASC";
37dcd4b6
JP
1538 return $DB->get_records_sql($sql, array($pageid));
1539}
1540
1541/**
1542 * Get updated pages from wiki
1543 * @param int $pageid
1544 */
1545function wiki_get_updated_pages_by_subwiki($swid) {
1546 global $DB, $USER;
1547
9730c555
JP
1548 $sql = "SELECT *
1549 FROM {wiki_pages}
1550 WHERE subwikiid = ? AND timemodified > ?
1551 ORDER BY timemodified DESC";
37dcd4b6 1552 return $DB->get_records_sql($sql, array($swid, $USER->lastlogin));
00710f4c 1553}
23cbaefb
DP
1554
1555/**
1556 * Check if the user can create pages in a certain wiki.
1557 * @param context $context Wiki's context.
1558 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
1559 * @return bool True if user can create pages, false otherwise.
1560 * @since Moodle 3.1
1561 */
1562function wiki_can_create_pages($context, $user = null) {
1563 return has_capability('mod/wiki:createpage', $context, $user);
1564}
44f1b701
DP
1565
1566/**
1567 * Get a sub wiki instance by wiki id, group id and user id.
1568 * If the wiki doesn't exist in DB it will return an isntance with id -1.
1569 *
1570 * @param int $wikiid Wiki ID.
1571 * @param int $groupid Group ID.
1572 * @param int $userid User ID.
1573 * @return object Subwiki instance.
1574 * @since Moodle 3.1
1575 */
1576function wiki_get_possible_subwiki_by_group($wikiid, $groupid, $userid = 0) {
1577 if (!$subwiki = wiki_get_subwiki_by_group($wikiid, $groupid, $userid)) {
1578 $subwiki = new stdClass();
1579 $subwiki->id = -1;
1580 $subwiki->wikiid = $wikiid;
1581 $subwiki->groupid = $groupid;
1582 $subwiki->userid = $userid;
1583 }
1584 return $subwiki;
1585}
1586
1587/**
1588 * Get all the possible subwikis visible to the user in a wiki.
1589 * It will return all the subwikis that can be created in a wiki, even if they don't exist in DB yet.
1590 *
1591 * @param stdClass $wiki Wiki to get the subwikis from.
1592 * @param cm_info|stdClass $cm Optional. The course module object.
1593 * @param context_module $context Optional. Context of wiki module.
1594 * @return array List of subwikis.
1595 * @since Moodle 3.1
1596 */
1597function wiki_get_visible_subwikis($wiki, $cm = null, $context = null) {
1598 global $USER;
1599
1600 $subwikis = array();
1601
1602 if (empty($wiki) or !is_object($wiki)) {
1603 // Wiki not valid.
1604 return $subwikis;
1605 }
1606
1607 if (empty($cm)) {
1608 $cm = get_coursemodule_from_instance('wiki', $wiki->id);
1609 }
1610 if (empty($context)) {
1611 $context = context_module::instance($cm->id);
1612 }
1613
1614 if (!has_capability('mod/wiki:viewpage', $context)) {
1615 return $subwikis;
1616 }
1617
1618 $manage = has_capability('mod/wiki:managewiki', $context);
1619
1620 if (!$groupmode = groups_get_activity_groupmode($cm)) {
1621 // No groups.
1622 if ($wiki->wikimode == 'collaborative') {
1623 // Only 1 subwiki.
1624 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, 0);
1625 } else if ($wiki->wikimode == 'individual') {
1626 // There's 1 subwiki per user.
1627 if ($manage) {
1628 // User can view all subwikis.
1629 $users = get_enrolled_users($context);
1630 foreach ($users as $user) {
1631 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $user->id);
1632 }
1633 } else {
1634 // User can only see his subwiki.
1635 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $USER->id);
1636 }
1637 }
1638 } else {
1639 if ($wiki->wikimode == 'collaborative') {
1640 // 1 subwiki per group.
1641 $aag = has_capability('moodle/site:accessallgroups', $context);
1642 if ($aag || $groupmode == VISIBLEGROUPS) {
1643 // User can see all groups.
1644 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
1645 $allparticipants = new stdClass();
1646 $allparticipants->id = 0;
1647 array_unshift($allowedgroups, $allparticipants); // Add all participants.
1648 } else {
1649 // User can only see the groups he belongs to.
1650 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
1651 }
1652
1653 foreach ($allowedgroups as $group) {
1654 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, 0);
1655 }
1656 } else if ($wiki->wikimode == 'individual') {
1657 // 1 subwiki per user and group.
1658
1659 if ($manage || $groupmode == VISIBLEGROUPS) {
1660 // User can view all subwikis.
1661 $users = get_enrolled_users($context);
1662 foreach ($users as $user) {
1663 // Get all the groups this user belongs to.
1664 $groups = groups_get_all_groups($cm->course, $user->id);
1665 if (!empty($groups)) {
1666 foreach ($groups as $group) {
1667 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, $user->id);
1668 }
1669 } else {
1670 // User doesn't belong to any group, add it to group 0.
1671 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, 0, $user->id);
1672 }
1673 }
1674 } else {
1675 // The user can only see the subwikis of the groups he belongs.
1676 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
1677 foreach ($allowedgroups as $group) {
1678 $users = groups_get_members($group->id);
1679 foreach ($users as $user) {
1680 $subwikis[] = wiki_get_possible_subwiki_by_group($wiki->id, $group->id, $user->id);
1681 }
1682 }
1683 }
1684 }
1685 }
1686
1687 return $subwikis;
1688}