forked from moodleou/moodle-mod_ouwiki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locallib.php
4076 lines (3608 loc) · 150 KB
/
locallib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Local library file for ouwiki. These are non-standard functions that are used
* only by ouwiki.
*
* @package mod
* @subpackage ouwiki
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
**/
/* Make sure this isn't being directly accessed */
defined('MOODLE_INTERNAL') || die();
/* Include the files that are required by this module */
require_once($CFG->dirroot . '/mod/ouwiki/lib.php');
require_once($CFG->dirroot . '/mod/ouwiki/difflib.php');
require_once($CFG->libdir . '/portfolio/caller.php');
// subwikis
define('OUWIKI_SUBWIKIS_SINGLE', 0);
define('OUWIKI_SUBWIKIS_GROUPS', 1);
define('OUWIKI_SUBWIKIS_INDIVIDUAL', 2);
// locks
define('OUWIKI_LOCK_PERSISTENCE', 120);
define('OUWIKI_LOCK_RECONFIRM', 60);
define('OUWIKI_LOCK_NOJS', 15*60);
define('OUWIKI_LOCK_TIMEOUT', 30*60);
define('OUWIKI_SESSION_LOCKS', 'ouwikilocks'); // Session variable used to store wiki locks
// format params
define('OUWIKI_PARAMS_LINK', 0);
define('OUWIKI_PARAMS_FORM', 1);
define('OUWIKI_PARAMS_URL', 2);
define('OUWIKI_PARAMS_ARRAY', 3);
define('OUWIKI_FORMAT_HTML', 'html');
define('OUWIKI_FORMAT_RTF', 'rtf');
define('OUWIKI_FORMAT_TEMPLATE', 'template');
// pages
define('OUWIKI_GETPAGE_REQUIREVERSION', 0);
define('OUWIKI_GETPAGE_ACCEPTNOVERSION', 1);
define('OUWIKI_GETPAGE_CREATE', 2);
define('OUWIKI_PAGESIZE', 50);
define('OUWIKI_MAXRESULTS', 50);
define('OUWIKI_RESULTSPERPAGE', 10);
// general
define('OUWIKI_LINKS_SQUAREBRACKETS', '/\[\[(.*?)\]\]/');
define('OUWIKI_SYSTEMUSER', -1);
define('OUWIKI_TIMEOUT_EXTRA', 60);
define('OUWIKI_FEEDSIZE', 50);
// participation
define('OUWIKI_NO_PARTICIPATION', 0);
define('OUWIKI_MY_PARTICIPATION', 1);
define('OUWIKI_USER_PARTICIPATION', 2);
define('OUWIKI_PARTICIPATION_PERPAGE', 100);
// User preference
define('OUWIKI_PREF_HIDEANNOTATIONS', 'ouwiki_hide_annotations');
function ouwiki_dberror($error, $source = null) {
if (!$source) {
$backtrace = debug_backtrace();
$source = preg_replace('@^.*/(.*)(\.php)?$@', '\1',
$backtrace[0]['file']).'/'.$backtrace[0]['line'];
}
throw new moodle_exception('Database problem: ' . $error . ' (code OUWIKI-' . $source . ')');
}
function ouwiki_error($text, $source = null) {
if (!$source) {
$backtrace = debug_backtrace();
$source = preg_replace('^.*/(.*)(\.php)?$^', '$1',
$backtrace[0]['file']).'/'.$backtrace[0]['line'];
}
throw new moodle_exception("Wiki error: $text (code OUWIKI-$source)");
}
/**
* Gets cm, ouwiki and subwiki based on selected activity id and subwiki id
* Populates vars sent, overriding initial values
* @param int $selectedact cm id
* @param int $selectedsubwiki subwiki id
* @param null $selectedouwiki empty
* @param object $course
* @param bool $ignorechecks Set to true to ignore activity + subwiki access checks
*/
function ouwiki_get_wikiinfo(&$selectedact, &$selectedsubwiki, &$selectedouwiki, $course,
$ignorechecks = false) {
global $DB;
$modinfo = get_fast_modinfo($course);
$selectedact = $modinfo->get_cm($selectedact);
$selectedcontext = context_module::instance($selectedact->id);
// Basic checks that it is OK to continue using activity.
if (!$ignorechecks && (!$selectedact->uservisible ||
!has_capability('mod/ouwiki:view', $selectedcontext))) {
ouwiki_error('You are not able to access the selected wiki.');
}
// Get sub wiki selected - joining to wiki activity and cm to verify all correct.
$sql = 'SELECT ouwiki.*, sw.userid, sw.groupid FROM {ouwiki_subwikis} sw
JOIN {ouwiki} ouwiki on ouwiki.id = sw.wikiid
JOIN {course_modules} cm on cm.instance = ouwiki.id
and cm.module = (SELECT id FROM {modules} where name = ?)
WHERE sw.id = ?';
$selectedouwiki = $DB->get_record_sql($sql, array('ouwiki', $selectedsubwiki), MUST_EXIST);
// Get our subwiki using locallib function to check access.
if (!$ignorechecks) {
$selectedsubwiki = ouwiki_get_subwiki($course, $selectedouwiki, $selectedact, $selectedcontext,
$selectedouwiki->groupid, $selectedouwiki->userid, false);
} else {
$selectedsubwiki = $DB->get_record('ouwiki_subwikis', array('id' => $selectedsubwiki));
}
}
/**
* Obtains the appropriate subwiki object for a request. If one cannot
* be obtained, either creates one or calls error() and stops.
*
* @param object $ouwiki Wiki object
* @param object $cm Course-module object
* @param object $context Context to use for checking permissions
* @param int $groupid Group ID or 0 to use any appropriate group
* @param int $userid User ID or 0 to use current user
* @param bool $create If true, creates a wiki if it doesn't exist
* @return mixed Object with the data from the subwiki table. Also has extra 'canedit' field
* set to true if that's allowed.
*/
function ouwiki_get_subwiki($course, $ouwiki, $cm, $context, $groupid, $userid, $create = null) {
global $USER, $DB;
switch($ouwiki->subwikis) {
case OUWIKI_SUBWIKIS_SINGLE:
$subwiki = $DB->get_record_select('ouwiki_subwikis', 'wikiid = ? AND groupid IS NULL
AND userid IS NULL', array($ouwiki->id));
if ($subwiki) {
ouwiki_set_extra_subwiki_fields($subwiki, $ouwiki, $context);
return $subwiki;
}
if ($create) {
$subwiki = ouwiki_create_subwiki($ouwiki, $cm, $course);
ouwiki_set_extra_subwiki_fields($subwiki, $ouwiki, $context);
ouwiki_init_pages($course, $cm, $ouwiki, $subwiki);
return $subwiki;
}
ouwiki_error('Wiki does not exist. View wikis before attempting other actions.');
break;
case OUWIKI_SUBWIKIS_GROUPS:
if (empty($groupid)) {
$groupid = groups_get_activity_group($cm, true);
}
if (!$groupid) {
// Active group not known - get first group available.
$groups = groups_get_activity_allowed_groups($cm);
if (!$groups) {
if (!groups_get_all_groups($cm->course, 0, $cm->groupingid)) {
ouwiki_error('This wiki cannot be displayed because it is a group wiki,
but no groups have been set up for the course (or grouping, if selected).');
} else {
ouwiki_error('You do not have access to any of the groups in this wiki.');
}
}
$groupid = reset($groups)->id;
}
$othergroup = !groups_is_member($groupid);
// Place get subwiki here to facilitate checking agaimst magic number below.
$subwiki = $DB->get_record_select('ouwiki_subwikis', 'wikiid = ? AND groupid = ?
AND userid IS NULL', array($ouwiki->id, $groupid));
if ($othergroup && $cm->groupmode == SEPARATEGROUPS) {
// Ignore if in feed,
// get magic has optional_param check against subwiki->magic - to deal with separate groups problem.
$magic = optional_param('magic', 0, PARAM_RAW);
if (!$subwiki || $magic != $subwiki->magic) {
if (!has_capability('moodle/site:accessallgroups', $context) &&
!has_capability('mod/ouwiki:editothers', $context)) {
ouwiki_error(get_string('error_nopermission', 'ouwiki'));
}
}
}
if ($subwiki) {
ouwiki_set_extra_subwiki_fields($subwiki, $ouwiki, $context, $othergroup);
return $subwiki;
}
if ($create) {
$subwiki = ouwiki_create_subwiki($ouwiki, $cm, $course, null, $groupid);
ouwiki_set_extra_subwiki_fields($subwiki, $ouwiki, $context, $othergroup);
ouwiki_init_pages($course, $cm, $ouwiki, $subwiki);
return $subwiki;
}
ouwiki_error('Wiki does not exist. View wikis before attempting other actions.');
break;
case OUWIKI_SUBWIKIS_INDIVIDUAL:
if ($userid == 0) {
$userid = $USER->id;
}
$otheruser = false;
if ($userid != $USER->id) {
$otheruser = true;
// Is user allowed to view everybody?
if (!has_capability('mod/ouwiki:viewallindividuals', $context)) {
// Nope. Are they allowed to view people in same group?
if (!has_capability('mod/ouwiki:viewgroupindividuals', $context)) {
ouwiki_error('You do not have access to view somebody else\'s wiki.');
}
// Check user is in same group. Note this isn't now restricted to the
// module grouping
$ourgroups = groups_get_all_groups($cm->course, $USER->id);
$theirgroups = groups_get_all_groups($cm->course, $userid);
$found = false;
foreach ($ourgroups as $ourgroup) {
foreach ($theirgroups as $theirgroup) {
if ($ourgroup->id == $theirgroup->id) {
$found = true;
break;
}
}
if ($found) {
break;
}
}
if (!$found) {
ouwiki_error('You do not have access to view this user\'s wiki.');
}
}
}
// OK now find wiki
$subwiki = $DB->get_record_select('ouwiki_subwikis', 'wikiid = ? AND groupid IS NULL
AND userid = ?', array($ouwiki->id, $userid));
if ($subwiki) {
ouwiki_set_extra_subwiki_fields($subwiki, $ouwiki, $context, $otheruser, !$otheruser);
return $subwiki;
}
// Create one
if ($create) {
$subwiki = ouwiki_create_subwiki($ouwiki, $cm, $course, $userid);
ouwiki_set_extra_subwiki_fields($subwiki, $ouwiki, $context, $otheruser, !$otheruser);
ouwiki_init_pages($course, $cm, $ouwiki, $subwiki);
return $subwiki;
}
ouwiki_error('Wiki does not exist. View wikis before attempting other actions.');
break;
default:
ouwiki_error("Unexpected subwikis value: {$ouwiki->subwikis}");
}
}
// Create a new subwiki instance
function ouwiki_create_subwiki($ouwiki, $cm, $course, $userid = null, $groupid = null) {
global $DB;
$subwiki = new StdClass;
$subwiki->wikiid = $ouwiki->id;
$subwiki->userid = $userid;
$subwiki->groupid = $groupid;
$subwiki->magic = ouwiki_generate_magic_number();
try {
$subwiki->id = $DB->insert_record('ouwiki_subwikis', $subwiki);
} catch (Exception $e) {
ouwiki_dberror($e);
}
return $subwiki;
}
/**
* Initialises wiki pages. Does nothing unless there's a template.
*
* @param object $cm Course-module object
* @param object $subwiki Subwiki object
* @param object $ouwiki OU wiki object
*/
function ouwiki_init_pages($course, $cm, $ouwiki, $subwiki) {
global $CFG;
if (is_null($ouwiki->template)) {
return;
}
$fs = get_file_storage();
$zip = get_file_packer();
$context = context_module::instance($cm->id);
$filepath = '/'.$context->id.'/mod_ouwiki/template/'.$ouwiki->id.$ouwiki->template;
if ($file = $fs->get_file_by_hash(sha1($filepath)) AND !$file->is_directory()) {
if (strpos($ouwiki->template, '.xml') !== false) {
// XML template expected.
$xmlfile = $file;
} else {
// Zip format expected.
$xmlfilename = strtolower(get_string('template', 'mod_ouwiki')) . '.xml';
if (!$xmlfile = $fs->get_file($context->id, 'mod_ouwiki', 'template', $ouwiki->id, '/',
$xmlfilename)) {
// XML (and other files) not extracted yet. Do once only.
$zip->extract_to_storage($file, $context->id, 'mod_ouwiki', 'template', $ouwiki->id, '/');
$xmlfile = $fs->get_file($context->id, 'mod_ouwiki', 'template', $ouwiki->id, '/',
$xmlfilename);
}
}
$content = $xmlfile->get_content();
$xml = new DOMDocument();
$xml->loadXML($content);
if (!$xml) {
ouwiki_error('Failed to load wiki template - not valid XML.
Check file in XML viewer and correct.');
}
if ($xml->documentElement->tagName != 'wiki') {
ouwiki_error('Failed to load wiki template - must begin with <wiki> tag.');
}
for ($page = $xml->documentElement->firstChild; $page; $page = $page->nextSibling) {
if ($page->nodeType != XML_ELEMENT_NODE) {
continue;
}
if ($page->tagName != 'page') {
ouwiki_error('Failed to load wiki template - expected <page>.');
}
$title = null;
$xhtml = null;
$oldcontextid = null;
$oldpagever = null;
$oldversionid = null;
$attachments = array();
for ($child = $page->firstChild; $child; $child = $child->nextSibling) {
if ($child->nodeType != XML_ELEMENT_NODE) {
continue;
}
if (!$child->firstChild) {
$text = '';
} else {
if ($child->firstChild->nodeType != XML_TEXT_NODE &&
$child->firstChild->nodeType != XML_CDATA_SECTION_NODE) {
ouwiki_error('Failed to load wiki template - expected text node.');
}
if ($child->firstChild->nextSibling) {
ouwiki_error('Failed to load wiki template - expected single text node.');
}
$text = $child->firstChild->nodeValue;
}
switch ($child->tagName) {
case 'title':
// Replace non-breaking spaces with normal spaces in title
$title = str_replace(html_entity_decode(' ', ENT_QUOTES, 'UTF-8'), ' ', $text);
break;
case 'xhtml':
$xhtml = $text;
break;
case 'versionid':
$oldversionid = (int) $text;
break;
case 'attachments':
$attachments = explode('|', $text);
break;
default:
ouwiki_error('Failed to load wiki template - unexpected element <'.
$child->tagName.'>.');
}
}
if ($xhtml === null) {
ouwiki_error('Failed to load wiki template - required <xhtml>.');
}
$newverid = ouwiki_save_new_version($course, $cm, $ouwiki, $subwiki, $title, $xhtml,
-1, -1, -1, true);
// Copy any images or attachments associated with old version id.
if ($oldfiles = $fs->get_directory_files($context->id, 'mod_ouwiki', 'template',
$ouwiki->id, "/$oldversionid/")) {
foreach ($oldfiles as $oldfile) {
if (in_array($oldfile->get_filename(), $attachments)) {
// Copy this file to the version attachment record.
$fs->create_file_from_storedfile(array(
'contextid' => $context->id,
'filearea' => 'attachment',
'itemid' => $newverid,
'filepath' => '/'), $oldfile);
}
if (mimeinfo('string', $oldfile->get_filename()) == 'image') {
// Copy this image file to the version record.
$fs->create_file_from_storedfile(array(
'contextid' => $context->id,
'filearea' => 'content',
'itemid' => $newverid,
'filepath' => '/'), $oldfile);
}
}
}
}
// lock start page if setting enabled
if ($ouwiki->lockstartpages) {
// get start page
$startpage = ouwiki_get_current_page($subwiki, null);
ouwiki_lock_editing($startpage->pageid, true);
}
} else {
ouwiki_error('Failed to load wiki template - file missing.');
}
}
/**
* Checks whether a user can edit a wiki, assuming that they can view it. This
* adds $subwiki->canedit, set to either true or false.
*
* @param object &$subwiki The subwiki object to which we are going to add a canedit variable
* @param object $ouwiki Wiki object
* @param object $context Context for permissions
* @param bool $othergroup If true, user is attempting to access a group that's not theirs
* @param bool $defaultwiki If true, user is accessing the wiki that they see by default
*/
function ouwiki_set_extra_subwiki_fields(&$subwiki, $ouwiki, $context, $othergroup = null,
$defaultwiki = null) {
// They must have the edit capability
$subwiki->canedit = has_capability('mod/ouwiki:edit', $context);
$subwiki->canannotate = has_capability('mod/ouwiki:annotate', $context);
$subwiki->annotation = $ouwiki->annotation;
// If wiki is not one of theirs, they need edit/annotate others or (historical) accesallgroups.
if ($othergroup) {
$subwiki->canedit = $subwiki->canedit &&
(has_capability('moodle/site:accessallgroups', $context) ||
has_capability('mod/ouwiki:editothers', $context));
$subwiki->canannotate = $subwiki->canannotate &&
(has_capability('moodle/site:accessallgroups', $context) ||
has_capability('mod/ouwiki:annotateothers', $context));
}
// Editing might be turned off for the wiki at the moment
$subwiki->canedit = $subwiki->canedit &&
(is_null($ouwiki->editbegin) || time() >= $ouwiki->editbegin);
$subwiki->canedit = $subwiki->canedit &&
(is_null($ouwiki->editend) || time() < $ouwiki->editend);
$subwiki->defaultwiki = $defaultwiki;
}
/**
* Checks whether the wiki is locked due to specific dates being set. (This is only used for
* informational display as the dates are already taken into account in the general checking
* for edit permission.)
*
* @param object $subwiki The subwiki object
* @param object $ouwiki Wiki object
* @param object $context Context for permissions
* @return False if not locked or a string of information if locked
*/
function ouwiki_timelocked($subwiki, $ouwiki, $context) {
// If they don't have edit permission anyhow then they won't be able to edit later
// so don't show this
if (!has_capability('mod/ouwiki:edit', $context)) {
return false;
}
if (!empty($ouwiki->editbegin) && time() < $ouwiki->editbegin) {
return get_string('timelocked_before', 'ouwiki',
userdate($ouwiki->editbegin, get_string('strftimedate')));
}
if (!empty($ouwiki->editend) && time() >= $ouwiki->editend) {
return get_string('timelocked_after', 'ouwiki');
}
return false;
}
/**
* Return the shared params needed to create a moodle_url
*
* @param string $page Name of page (null for startpage)
* @param object $subwiki Current subwiki object
* @param object $cm Course-module object
* @return Array
*/
function ouwiki_shared_url_params($pagename, $subwiki, $cm) {
$params = array('id' => $cm->id);
if (!$subwiki->defaultwiki) {
if ($subwiki->groupid) {
$params['group'] = $subwiki->groupid;
}
}
if ($subwiki->userid) {
$params['user'] = $subwiki->userid;
}
if (strtolower(trim($pagename)) !== strtolower(get_string('startpage', 'ouwiki')) &&
$pagename !== '') {
$params['page'] = $pagename;
}
return $params;
}
/**
* Prints the parameters that identify a particular wiki and could be used in view.php etc.
*
* @param string $page Name of page (empty string for startpage)
* @param object $subwiki Current subwiki object
* @param object $cm Course-module object
* @param int $type OUWIKI_PARAMS_xx constant
* @return mixed Either array or string depending on type
*/
function ouwiki_display_wiki_parameters($page, $subwiki, $cm, $type = OUWIKI_PARAMS_LINK) {
if ($type == OUWIKI_PARAMS_ARRAY) {
$output = array();
$output['id'] = $cm->id;
} else {
$output = ouwiki_get_parameter('id', $cm->id, $type);
}
if (!$subwiki->defaultwiki) {
if ($subwiki->groupid) {
if ($type == OUWIKI_PARAMS_ARRAY) {
$output['group'] = $subwiki->groupid;
} else {
$output .= ouwiki_get_parameter('group', $subwiki->groupid, $type);
}
}
}
if ($subwiki->userid) {
if ($type == OUWIKI_PARAMS_ARRAY) {
$output['user'] = $subwiki->userid;
} else {
$output .= ouwiki_get_parameter('user', $subwiki->userid, $type);
}
}
if ($page !== '') {
if ($type == OUWIKI_PARAMS_ARRAY) {
$output['page'] = $page;
} else {
$output .= ouwiki_get_parameter('page', $page, $type);
}
}
return $output;
}
// Internal function used by the above
function ouwiki_get_parameter($name, $value, $type) {
switch ($type) {
case OUWIKI_PARAMS_FORM:
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
$output = "<input type='hidden' name='$name' value='$value' />";
break;
case OUWIKI_PARAMS_LINK:
$value = htmlspecialchars(urlencode($value), ENT_QUOTES, 'UTF-8');
$output = '';
if ($name != 'id') {
$output .= '&';
}
$output .= "$name=$value";
break;
case OUWIKI_PARAMS_URL:
$value = urlencode($value);
$output = '';
if ($name != 'id') {
$output .= '&';
}
$output .= "$name=$value";
break;
}
return $output;
}
/**
* Prints the subwiki selector if user has access to more than one subwiki.
* Also displays the currently-viewing subwiki.
*
* @param object $subwiki Current subwiki object
* @param object $ouwiki Wiki object
* @param object $cm Course-module object
* @param object $context Context for permissions
* @param object $course Course object
* @param string $actionurl
* @param string $querytext for use when changing groups against search criteria
*/
function ouwiki_display_subwiki_selector($subwiki, $ouwiki, $cm, $context, $course, $actionurl = 'view.php', $querytext = '') {
global $USER, $DB, $OUTPUT;
if ($ouwiki->subwikis == OUWIKI_SUBWIKIS_SINGLE) {
return '';
}
$choicefield = '';
switch($ouwiki->subwikis) {
case OUWIKI_SUBWIKIS_GROUPS:
$groups = groups_get_activity_allowed_groups($cm);
uasort($groups, function($a, $b) { return strcasecmp($a->name, $b->name); });
$wikifor = htmlspecialchars($groups[$subwiki->groupid]->name);
// Do they have more than one?
if (count($groups) > 1) {
$choicefield = 'group';
$choices = $groups;
}
break;
case OUWIKI_SUBWIKIS_INDIVIDUAL:
$user = $DB->get_record('user', array('id' => $subwiki->userid),
'username, ' . implode(',', \core_user\fields::get_picture_fields()));
$wikifor = ouwiki_display_user($user, $cm->course);
$userfieldsapi = \core_user\fields::for_userpic();
$usernamefields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
if (has_capability('mod/ouwiki:viewallindividuals', $context)) {
// Get list of everybody...
$choicefield = 'user';
try {
$choices = $DB->get_records_sql('SELECT ' . $usernamefields .
' FROM {ouwiki_subwikis} sw
INNER JOIN {user} u ON sw.userid = u.id
WHERE sw.wikiid = ?
ORDER BY u.lastname, u.firstname', array($ouwiki->id));
} catch (Exception $e) {
ouwiki_dberror($e);
}
foreach ($choices as $choice) {
$choice->name = fullname($choice);
}
} else if (has_capability('mod/ouwiki:viewgroupindividuals', $context)) {
$choicefield = 'user';
$choices = array();
// User allowed to view people in same group
$theirgroups = groups_get_all_groups($cm->course, $USER->id,
$course->defaultgroupingid);
if (!$theirgroups) {
$theirgroups = array();
}
foreach ($theirgroups as $group) {
$members = groups_get_members($group->id, 'u.id, ' . $usernamefields);
foreach ($members as $member) {
$member->name = fullname($member);
$choices[$member->id] = $member;
}
}
}
break;
default:
ouwiki_error("Unexpected subwikis value: {$ouwiki->subwikis}");
}
$out = '<div class="ouw_subwiki">';
if ($choicefield && count($choices) > 1) {
$actionquery = '';
if (!empty($querytext)) {
$actionquery = '&query=' . rawurlencode($querytext);
}
$actionurl = '/mod/ouwiki/'. $actionurl .'?id=' . $cm->id . $actionquery;
$urlroot = new moodle_url($actionurl);
if ($choicefield == 'user') {
// Individuals.
$individualsmenu = array();
foreach ($choices as $choice) {
$individualsmenu[$choice->id] = $choice->name;
}
$select = new single_select($urlroot, 'user', $individualsmenu, $subwiki->userid, null, 'selectuser');
$select->label = get_string('wikifor', 'ouwiki');
$output = $OUTPUT->render($select);
$out .= '<div class="individualselector">'.$output.'</div>';
} else if ($choicefield == 'group') {
// Group mode.
$out .= groups_print_activity_menu($cm, $urlroot, true, true);
}
} else {
$out .= get_string('wikifor', 'ouwiki') . $wikifor;
}
$out .= '</div>';
return $out;
}
/**
* Returns an object containing the details from 'pages' and 'versions'
* tables for the current version of the specified (named) page, or false
* if page does not exist. Note that if the page exists but there are no
* versions, then the version fields will not be set.
*
* @param object $subwiki Current subwiki object
* @param string $pagename Name of desired page or null for start
* @param int $option OUWIKI_GETPAGE_xx value. Can use _ACCEPTNOVERSION
* if it's OK when a version doesn't exist, or _CREATE which creates
* pages when they don't exist.
* @return object Page-version object
*/
function ouwiki_get_current_page($subwiki, $pagename, $option = OUWIKI_GETPAGE_REQUIREVERSION) {
global $DB;
$params = array($subwiki->id);
$pagename_s = 'UPPER(p.title) = ?';
$params[] = core_text::strtoupper($pagename);
$jointype = $option == OUWIKI_GETPAGE_REQUIREVERSION ? 'JOIN' : 'LEFT JOIN';
$userfieldsapi = \core_user\fields::for_userpic();
$userfields = $userfieldsapi->get_sql('u', false, '', 'userid1', false)->selects;
$sql = "SELECT p.id AS pageid, p.subwikiid, p.title, p.currentversionid, p.firstversionid,
p.locked, v.id AS versionid, v.xhtml, v.timecreated, v.userid, v.xhtmlformat,
v.wordcount, v.previousversionid, $userfields
FROM {ouwiki_pages} p
$jointype {ouwiki_versions} v ON p.currentversionid = v.id
LEFT JOIN {user} u ON v.userid = u.id
WHERE p.subwikiid = ? AND $pagename_s";
$pageversion = $DB->get_record_sql($sql, $params);
if (!$pageversion) {
if ($option != OUWIKI_GETPAGE_CREATE) {
return false;
}
// Create page
$pageversion = new StdClass;
$pageversion->subwikiid = $subwiki->id;
$pageversion->title = $pagename ? $pagename : '';
$pageversion->locked = 0;
$pageversion->firstversionid = null; // new page
$pageversion->timemodified = time();
try {
$pageversion->pageid = $DB->insert_record('ouwiki_pages', $pageversion);
} catch (Exception $e) {
ouwiki_dberror($e);
}
// Update any missing link records that might exist
$uppertitle = core_text::strtoupper($pagename);
try {
$DB->execute("UPDATE {ouwiki_links}
SET tomissingpage = NULL, topageid = ?
WHERE tomissingpage = ?
AND ? = (
SELECT p.subwikiid
FROM {ouwiki_versions} v
INNER JOIN {ouwiki_pages} p ON v.pageid = p.id
WHERE v.id = fromversionid)",
array($pageversion->pageid, $uppertitle, $subwiki->id));
} catch (Exception $e) {
ouwiki_dberror($e);
}
$pageversion->currentversionid = null;
$pageversion->versionid = null;
$pageversion->xhtml = null;
$pageversion->xhtmlformat = null;
$pageversion->timecreated = null;
$pageversion->userid = null;
$pageversion->previousversionid = null; // first version for page
return $pageversion;
}
// Ensure valid value for comparing time created
$timecreated = empty($pageversion->timecreated) ? 0 : $pageversion->timecreated;
$sql = "SELECT v.id, v.timecreated, v.userid, $userfields
FROM {ouwiki_versions} v
LEFT JOIN {user} u ON v.userid = u.id
WHERE v.pageid = ?
AND v.timecreated <= ?
AND v.deletedat IS NULL
ORDER BY v.id DESC";
$pageversion->recentversions = $DB->get_records_sql($sql,
array($pageversion->pageid, $timecreated), 0, 3);
return $pageversion;
}
/**
* Obtains all the pages from a subwiki as pageversion objects. As a special
* bonus feature, this query also returns the firstname and lastname of current
* author (person in userid field of version).
* @return array Array of pageversion objects (note: the 'recentversions'
* member is not available, but otherwise these are the same as from
* ouwiki_get_current_page) in same order as index page
*/
function ouwiki_get_subwiki_allpages($subwiki) {
global $DB;
$userfieldsapi = \core_user\fields::for_userpic();
$userfields = $userfieldsapi->get_sql('u', false, '', 'userid1', false)->selects;
$sql = "SELECT p.id AS pageid, p.subwikiid, p.title, p.currentversionid, p.firstversionid,
p.locked, v.id AS versionid, v.xhtml, v.timecreated, v.userid, v.xhtmlformat,
v.wordcount, v.previousversionid, $userfields
FROM {ouwiki_pages} p
JOIN {ouwiki_versions} v ON p.currentversionid = v.id
LEFT JOIN {user} u ON u.id = v.userid
WHERE p.subwikiid = ? AND v.deletedat IS NULL
ORDER BY CASE WHEN p.title IS NULL THEN '' ELSE UPPER(p.title) END";
return $DB->get_records_sql($sql, array($subwiki->id));
}
/**
* Returns an object containing the details from 'pages' and 'versions'
* tables for the specified version of the specified (named) page, or false
* if page/version does not exist.
*
* @param object $subwiki Current subwiki object
* @param string $pagename Name of desired page or null for start
* @return object $pageversion Version object
*/
function ouwiki_get_page_version($subwiki, $pagename, $versionid) {
global $DB;
$userfieldsapi = \core_user\fields::for_userpic();
$userfields = $userfieldsapi->get_sql('u', false, '', 'userid1', false)->selects;
$sql = "SELECT p.id AS pageid, p.subwikiid, p.title, p.currentversionid,
v.id AS versionid, v.xhtml, v.timecreated, v.userid, v.xhtmlformat,
v.deletedat, $userfields,
v.wordcount
FROM {ouwiki_pages} p, {ouwiki_versions} v
LEFT JOIN {user} u ON v.userid = u.id
WHERE p.subwikiid = ? AND v.id = ? AND UPPER(p.title) = ?";
$pagename = core_text::strtoupper($pagename);
$pageversion = $DB->get_record_sql($sql, array($subwiki->id, $versionid, $pagename));
$pageversion->recentversions = false;
return $pageversion;
}
/**
* Obtains details (versionid,timecreated plus user id,username,firstname,lastname)
* for the previous and next version after the specified one.
*
* @param object $pageversion Page/version object
* @return object Object with ->prev and ->next fields, either of which may be false
* to indicate (respectively) that this is the first or last version. If not false,
* these objects contain the fields mentioned above.
*/
function ouwiki_get_prevnext_version_details($pageversion) {
global $DB;
$userfieldsapi = \core_user\fields::for_userpic();
$userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
$prevnext = new StdClass;
$prevsql = "SELECT v.id AS versionid, v.timecreated, $userfields
FROM {ouwiki_versions} v
LEFT JOIN {user} u ON u.id = v.userid
WHERE v.pageid = ?
AND v.timecreated < ?
AND v.deletedat IS NULL
ORDER BY v.id DESC";
$prev = $DB->get_records_sql($prevsql,
array($pageversion->pageid, $pageversion->timecreated), 0, 1);
$prevnext->prev = $prev ? current($prev) : false;
$nextsql = "SELECT v.id AS versionid, v.timecreated, $userfields
FROM {ouwiki_versions} v
LEFT JOIN {user} u ON u.id = v.userid
WHERE v.pageid = ?
AND v.timecreated > ?
AND v.deletedat IS NULL
ORDER BY v.id";
$next = $DB->get_records_sql($nextsql,
array($pageversion->pageid, $pageversion->timecreated), 0, 1);
$prevnext->next = $next ? current($next) : false;
return $prevnext;
}
/**
* Returns an HTML span with appropriate class to indicate how recent something
* is by colour.
*/
function ouwiki_recent_span($time) {
$now = time();
if ($now-$time < 5*60) {
$category = 'ouw_recenter';
} else if ($now - $time < 4*60*60) {
$category = 'ouw_recent';
} else {
$category = 'ouw_recentnot';
}
return '<span class="'.$category.'">';
}
function ouwiki_internal_re_heading($matches) {
global $PAGE;
$ouwikioutput = $PAGE->get_renderer('mod_ouwiki');
return $ouwikioutput->ouwiki_internal_re_heading_bits($matches);
}
function ouwiki_internal_re_plain_heading_bits($matches) {
return '<div class="ouw_heading"><h'.$matches[1].' id="ouw_s'.$matches[2].'">'.$matches[3].
'</h'.$matches[1].'></div>';
}
function ouwiki_internal_re_internallinks($matches) {
// Used to replace links when displaying wiki all one one page
global $ouwiki_internallinks;
$details = ouwiki_get_wiki_link_details($matches[1]);
// See if it matches a known page
foreach ($ouwiki_internallinks as $indexpage) {
if (($details->page === '' && $indexpage->title === '') ||
(isset($indexpage->title) && strtoupper($indexpage->title) === strtoupper($details->page)) ) {
// Page matches, return link
return '<a class="ouw_wikilink" href="#' . $indexpage->pageid .
'">' . $details->title . '</a>';
}
}
// Page did not match, return title in brackets
return '(' . $details->title . ')';
}
function ouwiki_internal_re_wikilinks($matches) {
global $ouwiki_wikilinks;
$details = ouwiki_get_wiki_link_details($matches[1]);
return '<a class="ouw_wikilink" href="view.php?' .
ouwiki_display_wiki_parameters('', $ouwiki_wikilinks->subwiki,
$ouwiki_wikilinks->cm) .
($details->page !== ''
? '&page=' . htmlspecialchars(urlencode($details->page)) : '') .
'">' . $details->title . '</a>';
}
function ouwiki_convert_content($content, $subwiki, $cm, $internallinks = null,
$xhtmlformat = FORMAT_HTML) {
// Detect links. Note that changes to this code ought to be reflected
// in the code in ouwiki_save_new_version which analyses to search for
// links.
// When displayed on one page
global $ouwiki_internallinks, $ouwiki_wikilinks;
// Ordinary [[links]]
if ($internallinks) {
$ouwiki_internallinks = $internallinks;
$function = 'ouwiki_internal_re_internallinks';
} else {
$ouwiki_wikilinks = (object) array('subwiki' => $subwiki, 'cm' => $cm);
$function = 'ouwiki_internal_re_wikilinks';
}
$content = preg_replace_callback(OUWIKI_LINKS_SQUAREBRACKETS, $function, $content);
// We do not use FORMAT_MOODLE (which adds linebreaks etc) because that was
// already handled manually.
$options = ouwiki_format_text_options();
$options->para = false;
$addwrapperdivs = true;
if (strpos($content, '<div class="ouwiki_content">') !== false) {
// Stop adding text wrapper divs when already in data.
$addwrapperdivs = false;
}
$toreturn = format_text($content, $xhtmlformat, $options);
if ($addwrapperdivs) {
$toreturn = html_writer::tag('div', $toreturn, array('class' => 'ouwiki_content'));
}
return $toreturn;
}
/**
* Return default common options for {@link format_text()} when preparing
* a content to be displayed on an ouwiki page
*
* We set the option in format_text to allow ids through because otherwise
* annotations break. (This requires Moodle 2.0.3.)
*
* @return stdClass
*/
function ouwiki_format_text_options() {
$options = new stdClass();
$options->trusted = true;
$options->allowid = true;
return $options;
}
/**
* Displays a user's name and link to profile etc.
* @param object $user User object (must have at least id, firstname and lastname)
* @param int $courseid ID of course
* @param bool $link If true, makes it a link