Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / mod / wiki / lib.php
blob923a599406c843067ec89a81d255074a57c669c1
1 <?php // $Id$
3 /// Library of functions and constants for module wiki
4 /// (replace wiki with the name of your module and delete this line)
7 $wiki_CONSTANT = 7; /// for example
8 $site = get_site();
9 $WIKI_TYPES = array ('teacher' => get_string('defaultcourseteacher'),
10 'group' => get_string('groups',"wiki"),
11 'student' => get_string('defaultcoursestudent') );
12 define("EWIKI_ESCAPE_AT", 0); # For the algebraic filter
14 // How long locks stay around without being confirmed (seconds)
15 define("WIKI_LOCK_PERSISTENCE",120);
17 // How often to confirm that you still want a lock
18 define("WIKI_LOCK_RECONFIRM",60);
20 // Session variable used to store wiki locks
21 define('SESSION_WIKI_LOCKS','wikilocks');
23 /*** Moodle 1.7 compatibility functions *****
25 ********************************************/
26 function wiki_context($wiki) {
27 //TODO: add some $cm caching if needed
28 if (is_object($wiki)) {
29 $wiki = $wiki->id;
31 if (! $cm = get_coursemodule_from_instance('wiki', $wiki)) {
32 error('Course Module ID was incorrect');
35 return get_context_instance(CONTEXT_MODULE, $cm->id);
38 function wiki_is_teacher($wiki, $userid=NULL) {
39 return has_capability('mod/wiki:manage', wiki_context($wiki), $userid);
42 function wiki_is_teacheredit($wiki, $userid=NULL) {
43 return has_capability('mod/wiki:manage', wiki_context($wiki), $userid)
44 and has_capability('moodle/site:accessallgroups', wiki_context($wiki), $userid);
47 function wiki_is_student($wiki, $userid=NULL) {
48 return has_capability('mod/wiki:participate', wiki_context($wiki), $userid);
51 function wiki_get_students($wiki, $groups='', $sort='u.lastaccess', $fields='u.*') {
52 return $users = get_users_by_capability(wiki_context($wiki), 'mod/wiki:participate', $fields, $sort, '', '', $groups);
55 /* end of compatibility functions */
58 function wiki_add_instance($wiki) {
59 /// Given an object containing all the necessary data,
60 /// (defined by the form in mod.html) this function
61 /// will create a new instance and return the id number
62 /// of the new instance.
64 $wiki->timemodified = time();
66 # May have to add extra stuff in here #
68 /// Determine the pagename for this wiki and save.
69 $wiki->pagename = wiki_page_name($wiki);
71 return insert_record("wiki", $wiki);
75 function wiki_update_instance($wiki) {
76 /// Given an object containing all the necessary data,
77 /// (defined by the form in mod.html) this function
78 /// will update an existing instance with new data.
80 /// Determine the pagename for this wiki.
81 $wiki->pagename = wiki_page_name($wiki);
83 $wiki->timemodified = time();
84 $wiki->id = $wiki->instance;
85 return update_record("wiki", $wiki);
88 /// Delete all Directories recursively
89 function wiki_rmdir($basedir) {
90 $handle = @opendir($basedir);
91 if($handle) {
92 while (false!==($folder = readdir($handle))) {
93 if($folder != "." && $folder != ".." && $folder != "CVS") {
94 wiki_rmdir("$basedir/$folder"); // recursive
97 closedir($handle);
99 @rmdir($basedir);
102 function wiki_delete_instance($id) {
103 /// Given an ID of an instance of this module,
104 /// this function will permanently delete the instance
105 /// and any data that depends on it.
106 global $CFG;
108 if (! $wiki = get_record("wiki", "id", $id)) {
109 return false;
112 $result = true;
114 #Delete Files
115 ### Should probably check regardless of this setting in case its been changed...
116 if($wiki->ewikiacceptbinary) {
117 if ($basedir = $CFG->dataroot."/".$wiki->course."/".$CFG->moddata."/wiki/$id") {
118 if ($files = get_directory_list($basedir)) {
119 foreach ($files as $file) {
120 #if ($file != $exception) {
121 unlink("$basedir/$file");
122 notify("Existing file '$file' has been deleted!");
126 #if (!$exception) { // Delete directory as well, if empty
127 wiki_rmdir("$basedir");
132 # Delete any dependent records here #
133 if(!delete_records("wiki_locks","wikiid",$wiki->id)) {
134 $result = false;
137 if (! delete_records("wiki", "id", $wiki->id)) {
138 $result = false;
141 /// Delete all wiki_entries and wiki_pages.
142 if (($wiki_entries = wiki_get_entries($wiki)) !== false) {
143 foreach ($wiki_entries as $wiki_entry) {
144 if (! delete_records("wiki_pages", "wiki", "$wiki_entry->id")) {
145 $result = false;
147 if (! delete_records("wiki_entries", "id", "$wiki_entry->id")) {
148 $result = false;
153 return $result;
156 function wiki_user_outline($course, $user, $mod, $wiki) {
157 /// Return a small object with summary information about what a
158 /// user has done with a given particular instance of this module
159 /// Used for user activity reports.
160 /// $return->time = the time they did it
161 /// $return->info = a short text description
163 $return = NULL;
164 return $return;
167 function wiki_user_complete($course, $user, $mod, $wiki) {
168 /// Print a detailed representation of what a user has done with
169 /// a given particular instance of this module, for user activity reports.
171 return true;
174 function wiki_print_recent_activity($course, $isteacher, $timestart) {
175 /// Given a course and a time, this module should find recent activity
176 /// that has occurred in wiki activities and print it out.
177 /// Return true if there was output, or false is there was none.
179 global $CFG;
181 $sql = "SELECT l.*, cm.instance FROM {$CFG->prefix}log l
182 INNER JOIN {$CFG->prefix}course_modules cm ON l.cmid = cm.id
183 WHERE l.time > '$timestart' AND l.course = {$course->id}
184 AND l.module = 'wiki' AND action LIKE 'edit%'
185 ORDER BY l.time ASC";
187 if (!$logs = get_records_sql($sql)){
188 return false;
191 $modinfo = get_fast_modinfo($course);
192 $wikis = array();
194 foreach ($logs as $log) {
195 $cm = $modinfo->instances['wiki'][$log->instance];
196 if (!$cm->uservisible) {
197 continue;
200 $wikis[$log->info] = wiki_log_info($log);
201 $wikis[$log->info]->pagename = $log->info;
202 $wikis[$log->info]->time = $log->time;
203 $wikis[$log->info]->url = str_replace('&', '&amp;', $log->url);
206 if (!$wikis) {
207 return false;
209 print_headline(get_string('updatedwikipages', 'wiki').':', 3);
210 foreach ($wikis as $wiki) {
211 print_recent_activity_note($wiki->time, $wiki, $wiki->pagename,
212 $CFG->wwwroot.'/mod/wiki/'.$wiki->url);
215 return false;
218 function wiki_log_info($log) {
219 global $CFG;
220 return get_record_sql("SELECT u.firstname, u.lastname
221 FROM {$CFG->prefix}user u
222 WHERE u.id = '$log->userid'");
225 function wiki_cron () {
226 /// Function to be run periodically according to the moodle cron
227 /// This function searches for things that need to be done, such
228 /// as sending out mail, toggling flags etc ...
230 // Delete expired locks
231 $result=delete_records_select('wiki_locks','lockedseen < '.(time()-WIKI_LOCK_PERSISTENCE));
233 return $result;
236 function wiki_grades($wikiid) {
237 /// Must return an array of grades for a given instance of this module,
238 /// indexed by user. It also returns a maximum allowed grade.
240 return NULL;
243 function wiki_get_participants($wikiid) {
244 //Returns the users with data in one wiki
245 //(users with records in wiki_pages and wiki_entries)
247 global $CFG;
249 //Get users from wiki_pages
250 $st_pages = get_records_sql("SELECT DISTINCT u.id, u.id
251 FROM {$CFG->prefix}user u,
252 {$CFG->prefix}wiki_entries e,
253 {$CFG->prefix}wiki_pages p
254 WHERE e.wikiid = '$wikiid' and
255 p.wiki = e.id and
256 u.id = p.userid");
258 //Get users from wiki_entries
259 $st_entries = get_records_sql("SELECT DISTINCT u.id, u.id
260 FROM {$CFG->prefix}user u,
261 {$CFG->prefix}wiki_entries e
262 WHERE e.wikiid = '$wikiid' and
263 u.id = e.userid");
265 //Add entries to pages
266 if ($st_entries) {
267 foreach ($st_entries as $st_entry) {
268 $st_pages[$st_entry->id] = $st_entry;
272 return $st_pages;
276 //////////////////////////////////////////////////////////////////////////////////////
277 /// Any other wiki functions go here. Each of them must have a name that
278 /// starts with wiki_
280 function wiki_wiki_name($wikiname) {
281 /// Return the passed in string in Wiki name format.
282 /// Remove any leading and trailing whitespace, capitalize all the words
283 /// and then remove any internal whitespace.
285 if (wiki_is_wiki_name($wikiname)) {
286 return $wikiname;
288 else {
289 /// Create uppercase words and remove whitespace.
290 $wikiname = preg_replace("/(\w+)\s/", "$1", ucwords(trim($wikiname)));
292 /// Check again - there may only be one word.
293 if (wiki_is_wiki_name($wikiname)) {
294 return $wikiname;
296 /// If there is only one word, append default wiki name to it.
297 else {
298 return $wikiname.get_string('wikidefaultpagename', 'wiki');
303 function wiki_is_wiki_name($wikiname) {
304 /// Check for correct wikiname syntax and return true or false.
306 /// If there are spaces between the words, incorrect format.
307 if (preg_match_all('/\w+/', $wikiname, $out) > 1) {
308 return false;
310 /// If there isn't more than one group of uppercase letters separated by
311 /// lowercase letters or '_', incorrect format.
312 else if (preg_match_all('/[A-Z]+[a-z_]+/', $wikiname, $out) > 1) {
313 return true;
315 else {
316 return false;
320 function wiki_page_name(&$wiki) {
321 /// Determines the wiki's page name and returns it.
322 if (!empty($wiki->initialcontent)) {
323 $ppos = strrpos($wiki->initialcontent, '/');
324 if ($ppos === false) {
325 $pagename = $wiki->initialcontent;
327 else {
328 $pagename = substr($wiki->initialcontent, $ppos+1);
331 else if (!empty($wiki->pagename)) {
332 $pagename = $wiki->pagename;
334 else {
335 $pagename = $wiki->name;
337 return $pagename;
340 function wiki_content_dir(&$wiki) {
341 /// Determines the wiki's default content directory (if there is one).
342 global $CFG;
344 if (!empty($wiki->initialcontent)) {
345 $ppos = strrpos($wiki->initialcontent, '/');
346 if ($ppos === false) {
347 $subdir = '';
349 else {
350 $subdir = substr($wiki->initialcontent, 0, $ppos+1);
352 $contentdir = $CFG->dataroot.'/'.$wiki->course.'/'.$subdir;
354 else {
355 $contentdir = false;
357 return $contentdir;
360 function wiki_get_course_wikis($courseid, $wtype='*') {
361 /// Returns all wikis for the specified course and optionally of the specified type.
363 $select = 'course = '.$courseid;
364 if ($wtype != '*') {
365 $select .= ' AND wtype = \''.$wtype.'\'';
367 return get_records_select('wiki', $select, 'id');
370 function wiki_has_entries(&$wiki) {
371 /// Returns true if wiki already has wiki entries; otherwise false.
373 return record_exists('wiki_entries', 'wikiid', $wiki->id);
376 function wiki_get_entries(&$wiki, $byindex=NULL) {
377 /// Returns an array with all wiki entries indexed by entry id; false if there are none.
378 /// If the optional $byindex is specified, returns the entries indexed by that field.
379 /// Valid values for $byindex are 'student', 'group'.
380 global $CFG;
382 if ($byindex == 'student') {
383 return get_records('wiki_entries', 'wikiid', $wiki->id, '',
384 'userid,id,wikiid,course,groupid,pagename,timemodified');
386 else if ($byindex == 'group') {
387 return get_records('wiki_entries', 'wikiid', $wiki->id, '',
388 'groupid,id,wikiid,course,userid,pagename,timemodified');
390 else {
391 return get_records('wiki_entries', 'wikiid', $wiki->id);
395 function wiki_get_default_entry(&$wiki, &$course, $userid=0, $groupid=0) {
396 /// Returns the wiki entry according to the wiki type.
397 /// Optionally, will return wiki entry for $userid student wiki, or
398 /// $groupid group or teacher wiki.
399 /// Creates one if it needs to and it can.
400 global $USER;
401 /// If there is a groupmode, get the user's group id.
402 $groupmode = groups_get_activity_groupmode($wiki);
403 // if groups mode is in use and no group supplied, use the first one found
404 if ($groupmode && !$groupid) {
405 if(($mygroupids=mygroupid($course->id)) && count($mygroupids)>0) {
406 // Use first group. They ought to be able to change later
407 $groupid=$mygroupids[0];
408 } else {
409 // Whatever groups are in the course, pick one
410 $coursegroups = groups_get_all_groups($course->id);
411 if(!$coursegroups || count($coursegroups)==0) {
412 error("Can't access wiki in group mode when no groups are configured for the course");
414 $unkeyed=array_values($coursegroups); // Make sure first item is index 0
415 $groupid=$unkeyed[0]->id;
419 /// If the wiki entry doesn't exist, can this user create it?
420 if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false) {
421 if (wiki_can_add_entry($wiki, $USER, $course, $userid, $groupid)) {
422 wiki_add_entry($wiki, $course, $userid, $groupid);
423 if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false) {
424 error("Could not add wiki entry.");
428 //print_object($wiki_entry);
429 return $wiki_entry;
432 function wiki_get_entry(&$wiki, &$course, $userid=0, $groupid=0) {
433 /// Returns the wiki entry according to the wiki type.
434 /// Optionally, will return wiki entry for $userid student wiki, or
435 /// $groupid group or teacher wiki.
436 global $USER;
438 switch ($wiki->wtype) {
439 case 'student':
440 /// If a specific user was requested, return it, if allowed.
441 if ($userid and wiki_user_can_access_student_wiki($wiki, $userid, $course)) {
442 $wentry = wiki_get_student_entry($wiki, $userid);
445 /// If there is no entry for this user, check if this user is a teacher.
446 else if (!$wentry = wiki_get_student_entry($wiki, $USER->id)) {
447 /* if (wiki_is_teacher($wiki, $USER->id)) {
448 /// If this user is a teacher, return the first entry.
449 if ($wentries = wiki_get_entries($wiki)) {
450 $wentry = current($wentries);
454 break;
456 case 'group':
457 /// If there is a groupmode, get the user's group id.
458 $groupmode = groups_get_activity_groupmode($wiki);
459 if($groupmode) {
460 if(!$groupid) {
461 if(($mygroupids=mygroupid($course->id)) && count($mygroupids)>0) {
462 // Use first group. They ought to be able to change later
463 $groupid=$mygroupids[0];
464 } else {
465 // Whatever groups are in the course, pick one
466 $coursegroups = groups_get_all_groups($course->id);
467 if(!$coursegroups || count($coursegroups)==0) {
468 error("Can't access wiki in group mode when no groups are configured for the course");
470 $unkeyed=array_values($coursegroups); // Make sure first item is index 0
471 $groupid=$unkeyed[0]->id;
475 //echo "groupid is in wiki_get_entry ".$groupid."<br />";
476 /// If a specific group was requested, return it, if allowed.
477 if ($groupid and wiki_user_can_access_group_wiki($wiki, $groupid, $course)) {
478 $wentry = wiki_get_group_entry($wiki, $groupid);
479 } else {
480 error("Cannot access any groups for this wiki");
483 /// If mode is 'nogroups', then groupid is zero.
484 else {
485 $wentry = wiki_get_group_entry($wiki, 0);
487 break;
489 case 'teacher':
490 /// If there is a groupmode, get the user's group id.
491 if (groupmode($course, $wiki)) {
492 $mygroupids = mygroupid($course->id);//same here, default to the first one
493 $groupid = $groupid ? $groupid : $mygroupids[0]/*mygroupid($course->id)*/;
496 /// If a specific group was requested, return it, if allowed.
497 if (wiki_user_can_access_teacher_wiki($wiki, $groupid, $course)) {
498 $wentry = wiki_get_teacher_entry($wiki, $groupid);
500 break;
502 return $wentry;
505 function wiki_get_teacher_entry(&$wiki, $groupid=0) {
506 /// Returns the wiki entry for the wiki teacher type.
507 return get_record('wiki_entries', 'wikiid', $wiki->id, 'course', $wiki->course, 'groupid', $groupid);
510 function wiki_get_group_entry(&$wiki, $groupid=null) {
511 /// Returns the wiki entry for the given group.
512 return get_record('wiki_entries', 'wikiid', $wiki->id, 'groupid', $groupid);
515 function wiki_get_student_entry(&$wiki, $userid=null) {
516 /// Returns the wiki entry for the given student.
517 global $USER;
519 if (is_null($userid)) {
520 $userid = $USER->id;
522 return get_record('wiki_entries', 'wikiid', $wiki->id, 'userid', $userid);
525 function wiki_get_other_wikis(&$wiki, &$user, &$course, $currentid=0) {
526 /// Returns a list of other wikis to display, depending on the type, group and user.
527 /// Returns the key containing the currently selected entry as well.
529 global $CFG, $id;
531 $wikis = false;
533 $groupmode = groups_get_activity_groupmode($wiki);
534 $mygroupid = mygroupid($course->id);
535 $isteacher = wiki_is_teacher($wiki, $user->id);
536 $isteacheredit = wiki_is_teacheredit($wiki, $user->id);
538 $groupingid = null;
539 $cm = new stdClass;
540 $cm->id = $wiki->cmid;
541 $cm->groupmode = $wiki->groupmode;
542 $cm->groupingid = $wiki->groupingid;
543 $cm->groupmembersonly = $wiki->groupmembersonly;
544 if (!empty($CFG->enablegroupings) && !empty($cm->groupingid)) {
545 $groupingid = $wiki->groupingid;
549 switch ($wiki->wtype) {
551 case 'student':
552 /// Get all the existing entries for this wiki.
553 $wiki_entries = wiki_get_entries($wiki, 'student');
555 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
556 $sql = "SELECT gm.userid FROM {$CFG->prefix}groups_members gm " .
557 "INNER JOIN {$CFG->prefix}groupings_groups gg ON gm.groupid = gg.groupid " .
558 "WHERE gg.groupingid = $wiki->groupingid ";
560 $groupingmembers = get_records_sql($sql);
563 if ($isteacher and (SITEID != $course->id)) {
565 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all student
566 /// wikis, regardless of creation.
567 if ((SITEID != $course->id) and ($isteacheredit or ($groupmode == NOGROUPS))) {
569 if ($students = get_course_students($course->id)) {
570 /// Default pagename is dependent on the wiki settings.
571 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
573 foreach ($students as $student) {
574 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid) && empty($groupingmembers[$student->id])) {
575 continue;
577 /// If this student already has an entry, use its pagename.
578 if ($wiki_entries[$student->id]) {
579 $pagename = $wiki_entries[$student->id]->pagename;
581 else {
582 $pagename = $defpagename;
585 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
586 $wikis[$key] = fullname($student).':'.$pagename;
590 else if ($groupmode == SEPARATEGROUPS) {
592 if ($students = wiki_get_students($wiki, $mygroupid)) {
593 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
594 foreach ($students as $student) {
595 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid) && empty($groupingmembers[$student->id])) {
596 continue;
598 /// If this student already has an entry, use its pagename.
599 if ($wiki_entries[$student->id]) {
600 $pagename = $wiki_entries[$student->id]->pagename;
602 else {
603 $pagename = $defpagename;
606 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
607 $wikis[$key] = fullname($student).':'.$pagename;
611 else if ($groupmode == VISIBLEGROUPS) {
612 /// Get all students in your group.
613 if ($students = wiki_get_students($wiki, $mygroupid)) {
614 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
615 foreach ($students as $student) {
616 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid) && empty($groupingmembers[$student->id])) {
617 continue;
619 /// If this student already has an entry, use its pagename.
620 if ($wiki_entries[$student->id]) {
621 $pagename = $wiki_entries[$student->id]->pagename;
623 else {
624 $pagename = $defpagename;
626 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
627 $wikis[$key] = fullname($student).':'.$pagename;
630 /// Get all student wikis created, regardless of group.
631 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
632 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
633 .' FROM '.$CFG->prefix.'wiki_entries w '
634 .' INNER JOIN '.$CFG->prefix.'user u ON w.userid = u.id '
635 .' INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = u.id '
636 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON gm.groupid = gg.groupid '
637 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
638 .' ORDER BY w.id';
639 } else {
640 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
641 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'user u '
642 .' WHERE w.wikiid = '.$wiki->id.' AND u.id = w.userid '
643 .' ORDER BY w.id';
645 $wiki_entries = get_records_sql($sql);
646 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
647 foreach ($wiki_entries as $wiki_entry) {
648 $key = 'view.php?id='.$id.'&userid='.$wiki_entry->userid.'&page='.$wiki_entry->pagename;
649 $wikis[$key] = fullname($wiki_entry).':'.$wiki_entry->pagename;
650 if ($currentid == $wiki_entry->id) {
651 $wikis['selected'] = $key;
656 else {
657 /// A user can see other student wikis if they are a member of the same
658 /// group (for separate groups) or there are visible groups, or if this is
659 /// a site-level wiki, and they are an administrator.
660 if (($groupmode == VISIBLEGROUPS) or wiki_is_teacheredit($wiki)) {
661 $viewall = true;
663 else if ($groupmode == SEPARATEGROUPS) {
664 $viewall = mygroupid($course->id);
666 else {
667 $viewall = false;
670 if ($viewall !== false) {
671 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
672 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
673 .' FROM '.$CFG->prefix.'wiki_entries w '
674 .' INNER JOIN '.$CFG->prefix.'user u ON w.userid = u.id '
675 .' INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = u.id '
676 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON gm.groupid = gg.groupid '
677 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
678 .' ORDER BY w.id';
679 } else {
680 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
681 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'user u '
682 .' WHERE w.wikiid = '.$wiki->id.' AND u.id = w.userid '
683 .' ORDER BY w.id';
685 $wiki_entries = get_records_sql($sql);
686 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
687 foreach ($wiki_entries as $wiki_entry) {
688 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid) && empty($groupingmembers[$wiki_entry->userid])) {
689 continue;
692 if (($viewall === true) or groups_is_member($viewall, $wiki_entry->userid)) {
693 $key = 'view.php?id='.$id.'&userid='.$wiki_entry->userid.'&page='.$wiki_entry->pagename;
694 $wikis[$key] = fullname($wiki_entry).':'.$wiki_entry->pagename;
695 if ($currentid == $wiki_entry->id) {
696 $wikis['selected'] = $key;
702 break;
704 case 'group':
705 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all group
706 /// wikis, regardless of creation.
708 /// If user is a member of multiple groups, need to show current group etc?
710 /// Get all the existing entries for this wiki.
711 $wiki_entries = wiki_get_entries($wiki, 'group');
713 if ($groupmode and ($isteacheredit or ($isteacher and !$mygroupid))) {
714 if ($groups = groups_get_all_groups($course->id, null, $groupingid)) {
715 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
716 foreach ($groups as $group) {
718 /// If this group already has an entry, use its pagename.
719 if (isset($wiki_entries[$group->id])) {
720 $pagename = $wiki_entries[$group->id]->pagename;
722 else {
723 $pagename = $defpagename;
726 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
727 $wikis[$key] = $group->name.':'.$pagename;
731 //if a studnet with multiple groups in SPG
732 else if ($groupmode == SEPARATEGROUPS){
733 if ($groups = groups_get_all_groups($course->id, $user->id, $groupingid)){
735 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
736 foreach ($groups as $group) {
737 /// If this group already has an entry, use its pagename.
738 if (isset($wiki_entries[$group->id])) {
739 $pagename = $wiki_entries[$group->id]->pagename;
741 else {
742 $pagename = $defpagename;
744 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
745 $wikis[$key] = $group->name.':'.$pagename;
751 /// A user can see other group wikis if there are visible groups.
752 else if ($groupmode == VISIBLEGROUPS) {
753 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
754 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
755 .' FROM '.$CFG->prefix.'wiki_entries w '
756 .' INNER JOIN '.$CFG->prefix.'groups g ON g.id = w.groupid '
757 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON g.id = gg.groupid '
758 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
759 .' ORDER BY w.groupid';
760 } else {
761 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
762 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
763 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
764 .' ORDER BY w.groupid';
766 $wiki_entries = get_records_sql($sql);
767 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
768 foreach ($wiki_entries as $wiki_entry) {
769 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
770 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
771 if ($currentid == $wiki_entry->id) {
772 $wikis['selected'] = $key;
776 break;
778 case 'teacher':
779 if ($isteacher) {
780 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all
781 /// teacher wikis, regardless of creation.
782 if ($groupmode and ($isteacheredit or ($isteacher and !$mygroupid))) {
783 if ($groups = groups_get_all_groups($course->id, null, $groupingid)) {
784 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
785 foreach ($groups as $group) {
786 /// If this group already has an entry, use its pagename.
787 if ($wiki_entries[$group->id]) {
788 $pagename = $wiki_entries[$group->id]->pagename;
790 else {
791 $pagename = $defpagename;
794 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
795 $wikis[$key] = $group->name.':'.$pagename;
799 /// A teacher can see all other group teacher wikis.
800 else if ($groupmode) {
801 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
802 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
803 .' FROM '.$CFG->prefix.'wiki_entries w '
804 .' INNER JOIN '.$CFG->prefix.'groups g ON g.id = w.groupid '
805 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON g.id = gg.groupid '
806 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
807 .' ORDER BY w.groupid';
808 } else {
809 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
810 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
811 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
812 .' ORDER BY w.groupid';
814 $wiki_entries = get_records_sql($sql);
815 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
816 foreach ($wiki_entries as $wiki_entry) {
817 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
818 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
819 if ($currentid == $wiki_entry->id) {
820 $wikis['selected'] = $key;
825 else {
826 /// A user can see other teacher wikis if they are a teacher, a member of the same
827 /// group (for separate groups) or there are visible groups.
828 if ($groupmode == VISIBLEGROUPS) {
829 $viewall = true;
831 else if ($groupmode == SEPARATEGROUPS) {
832 $viewall = $mygroupid;
834 else {
835 $viewall = false;
837 if ($viewall !== false) {
838 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
839 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
840 .' FROM '.$CFG->prefix.'wiki_entries w '
841 .' INNER JOIN '.$CFG->prefix.'groups g ON g.id = w.groupid '
842 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON g.id = gg.groupid '
843 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
844 .' ORDER BY w.groupid';
845 } else {
846 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
847 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
848 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
849 .' ORDER BY w.groupid';
851 $wiki_entries = get_records_sql($sql);
852 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
855 foreach ($wiki_entries as $wiki_entry) {
856 if (($viewall === true) or @in_array($wiki_entry->groupid, $viewall)/*$viewall == $wiki_entry->groupid*/) {
857 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
858 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
859 if ($currentid == $wiki_entry->id) {
860 $wikis['selected'] = $key;
866 break;
869 return $wikis;
872 function wiki_add_entry(&$wiki, &$course, $userid=0, $groupid=0) {
873 /// Adds a new wiki entry of the specified type, unless already entered.
874 /// No checking is done here. It is assumed that the caller has the correct
875 /// privileges to add this entry.
877 global $USER;
879 /// If this wiki already has a wiki_type entry, return false.
880 if (wiki_get_entry($wiki, $course, $userid, $groupid) !== false) {
881 return false;
884 $wiki_entry = new Object();
886 switch ($wiki->wtype) {
888 case 'student':
889 $wiki_entry->wikiid = $wiki->id;
890 $wiki_entry->userid = $userid ? $userid : $USER->id;
891 $wiki_entry->pagename = wiki_page_name($wiki);
892 $wiki_entry->timemodified = time();
893 break;
895 case 'group':
896 /// Get the groupmode. It's been added to the wiki object.
897 $groupmode = groups_get_activity_groupmode($wiki);
899 ///give the first groupid by default and try
900 $mygroups = mygroupid($course->id);
902 /// If there is a groupmode, get the group id.
903 if ($groupmode) {
904 $groupid = $groupid ? $groupid : $mygroups[0]/*mygroupid($course->id)*/;
906 /// If mode is 'nogroups', then groupid is zero.
907 else {
908 $groupid = 0;
910 $wiki_entry->wikiid = $wiki->id;
911 $wiki_entry->groupid = $groupid;
912 $wiki_entry->pagename = wiki_page_name($wiki);
913 $wiki_entry->timemodified = time();
915 break;
917 case 'teacher':
918 /// Get the groupmode. It's been added to the wiki object.
919 $groupmode = groups_get_activity_groupmode($wiki);
921 /// If there is a groupmode, get the user's group id.
922 if ($groupmode and $groupid == 0) {
923 $mygroupid = mygroupid($course->id);
924 $groupid = $mygroupid[0]/*mygroupid($course->id)*/;
927 $wiki_entry->wikiid = $wiki->id;
928 $wiki_entry->course = $wiki->course;
929 $wiki_entry->groupid = $groupid;
930 $wiki_entry->pagename = wiki_page_name($wiki);
931 $wiki_entry->timemodified = time();
932 break;
934 $wiki_entry->pagename = addslashes($wiki_entry->pagename);
936 return insert_record("wiki_entries", $wiki_entry, true);
939 function wiki_can_add_entry(&$wiki, &$user, &$course, $userid=0, $groupid=0) {
940 /// Returns true or false if the user can add a wiki entry for this wiki.
942 /// Get the groupmode. It's been added to the wiki object.
943 $groupmode = groups_get_activity_groupmode($wiki);
944 $mygroupid = mygroupid($course->id);
946 switch ($wiki->wtype) {
948 case 'student':
949 /// A student can create their own wiki, if they are a member of that course.
950 /// A user can create their own wiki at the site level.
951 if ($userid == 0) {
952 return (wiki_is_student($wiki, $user->id) or wiki_is_student($wiki, $user->id));
954 /// An editing teacher can create any student wiki, or
955 /// a non-editing teacher, if not assigned to a group can create any student wiki, or if assigned to a group can
956 /// create any student wiki in their group.
957 else {
958 return ((($userid == $user->id) and wiki_is_student($wiki, $user->id)) or wiki_is_teacheredit($wiki) or
959 (wiki_is_teacher($wiki) and (!$groupmode or $mygroupid == 0 or (groups_is_member($mygroupid, $userid)))));
961 break;
963 case 'group':
964 /// If mode is 'nogroups', then all participants can add wikis.
965 if (wiki_is_teacheredit($wiki, $user->id)) {
966 return true;
969 if (!$groupmode) {
970 return (wiki_is_student($wiki, $user->id) or wiki_is_teacher($wiki, $user->id));
972 /// If not requesting a group, must be a member of a group.
973 else if ($groupid == 0) {
974 return ($mygroupid != 0);
976 /// If requesting a group, must be an editing teacher, a non-editing teacher with no assigned group,
977 /// or a non-editing teacher requesting their group. or a student in group, but wiki is empty.
978 else {
979 return (wiki_is_teacheredit($wiki) or
980 (wiki_is_teacher($wiki) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))) or
981 (wiki_is_student($wiki, $user->id) and @in_array($groupid, $mygroupid))
984 break;
986 case 'teacher':
987 /// If mode is 'nogroups', then all teachers can add wikis.
988 if (!$groupmode) {
989 return wiki_is_teacher($wiki, $user->id);
991 /// If not requesting a group, must be a member of a group.
992 else if ($groupid == 0) {
993 return ($mygroupid != 0 and wiki_is_teacher($wiki));
995 /// If there is a group mode, non-editing teachers with an assigned group, can only create wikis
996 /// in their group. Non-editing teachers with no assigned group and editing teachers can create any wiki.
997 else {
998 return (wiki_is_teacheredit($wiki) or
999 (wiki_is_teacher($wiki) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))));
1001 break;
1004 return false;
1007 function wiki_can_edit_entry(&$wiki_entry, &$wiki, &$user, &$course) {
1008 /// Returns true or false if the user can edit this wiki entry.
1010 $can_edit = false;
1011 $groupmode = groups_get_activity_groupmode($wiki);
1012 $mygroupid = mygroupid($course->id);
1014 /// Editing teacher's and admins can edit all wikis, non-editing teachers can edit wikis in their groups,
1015 /// or all wikis if group mode is 'no groups' or they don't belong to a group.
1016 if (wiki_is_teacheredit($wiki, $user->id) or
1017 ((!$groupmode or $mygroupid == 0) and wiki_is_teacher($wiki, $user->id))) {
1018 $can_edit = true;
1020 else {
1021 switch ($wiki->wtype) {
1023 /// Only a teacher or the owner of a student wiki can edit it.
1024 case 'student':
1025 $can_edit = (($user->id == $wiki_entry->userid) or
1026 ($groupmode and wiki_is_teacher($wiki, $user->id) and
1027 groups_is_member($mygroupid, $wiki_entry->userid)));
1028 break;
1030 case 'group':
1031 /// If there is a groupmode, determine the user's group status.
1032 if ($groupmode) {
1033 /// If the user is a member of the wiki group, they can edit the wiki.
1034 $can_edit = groups_is_member($wiki_entry->groupid, $user->id);
1036 /// If mode is 'nogroups', then all participants can edit the wiki.
1037 else {
1038 $can_edit = (wiki_is_student($wiki, $user->id) or wiki_is_teacher($wiki, $user->id));
1040 break;
1042 case 'teacher':
1043 /// If there is a groupmode, determine the user's group status.
1044 if ($groupmode) {
1045 /// If the user is a member of the wiki group, they can edit the wiki.
1046 $can_edit = (wiki_is_teacher($wiki, $user->id) and groups_is_member($wiki_entry->groupid, $user->id));
1048 else {
1049 $can_edit = wiki_is_teacher($wiki, $user->id);
1051 break;
1054 return $can_edit;
1057 function wiki_user_can_access_student_wiki(&$wiki, $userid, &$course) {
1058 global $USER;
1060 /// Get the groupmode. It's been added to the wiki object.
1061 $groupmode = groups_get_activity_groupmode($wiki);
1062 $usersgroup = mygroupid($course->id);
1063 $isteacher = wiki_is_teacher($wiki, $USER->id);
1065 /// If this user is allowed to access this wiki then return TRUE.
1066 /// *** THIS COULD BE A PROBLEM, IF STUDENTS COULD EVER BE PART OF MORE THAN ONE GROUP ***
1067 /// A user can access a student wiki, if:
1068 /// - it is their wiki,
1069 /// - group mode is VISIBLEGROUPS,
1070 /// - group mode is SEPARATEGROUPS, and the user is a member of the requested user's group,
1071 /// - they are an editing teacher or administrator,
1072 /// - they are a non-editing teacher not assigned to a specific group,
1073 /// - they are a non-editing teacher and group mode is NOGROUPS.
1074 /// - they are an administrator (mostly for site-level wikis).
1075 if (($userid and ($USER->id == $userid)) or ($groupmode == VISIBLEGROUPS) or
1076 (($groupmode == SEPARATEGROUPS) and groups_is_member($usersgroup, $userid)) or
1077 (wiki_is_teacheredit($wiki, $USER->id)) or
1078 (wiki_is_teacher($wiki, $USER->id) and (!$usersgroup or $groupmode == NOGROUPS))) {
1079 $can_access = true;
1081 else {
1082 $can_access = false;
1084 return $can_access;
1087 function wiki_user_can_access_group_wiki(&$wiki, $groupid, &$course) {
1088 global $USER;
1090 /// Get the groupmode. It's been added to the wiki object.
1091 $groupmode = groups_get_activity_groupmode($wiki);
1092 $usersgroup = mygroupid($course->id);
1093 $isteacher = wiki_is_teacher($wiki, $USER->id);
1095 /// A user can access a group wiki, if:
1096 /// - group mode is NOGROUPS,
1097 /// - group mode is VISIBLEGROUPS,
1098 /// - group mode is SEPARATEGROUPS, and they are a member of the requested group,
1099 /// - they are an editing teacher or administrator,
1100 /// - they are a non-editing teacher not assigned to a specific group.
1101 if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or
1102 (($groupmode == SEPARATEGROUPS) and @in_array($groupid, $usersgroup)/*($usersgroup == $groupid)*/) or
1103 (wiki_is_teacheredit($wiki, $USER->id)) or
1104 (wiki_is_teacher($wiki, $USER->id) and !$usersgroup)) {
1105 $can_access = true;
1107 else {
1108 $can_access = false;
1110 return $can_access;
1113 function wiki_user_can_access_teacher_wiki(&$wiki, $groupid, &$course) {
1114 global $USER;
1116 /// Get the groupmode. It's been added to the wiki object.
1117 $groupmode = groups_get_activity_groupmode($wiki);
1119 /// A user can access a teacher wiki, if:
1120 /// - group mode is NOGROUPS,
1121 /// - group mode is VISIBLEGROUPS,
1122 /// - group mode is SEPARATEGROUPS, and they are a member of the requested group,
1123 /// - they are a teacher or administrator,
1124 if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or
1125 (($groupmode == SEPARATEGROUPS) and (@in_array($groupid, mygroupid($course->id))/*mygroupid($course->id) == $groupid*/)) or
1126 (wiki_is_teacher($wiki, $USER->id))){
1127 $can_access = true;
1129 else {
1130 $can_access = false;
1132 return $can_access;
1135 function wiki_get_owner(&$wiki_entry) {
1136 if ($wiki_entry->userid > 0) {
1137 $user = get_record('user', 'id', $wiki_entry->userid);
1138 $owner = fullname($user);
1140 else if ($wiki_entry->groupid > 0) {
1141 $owner = groups_get_group_name($wiki_entry->groupid); //TODO:check.
1143 else if ($wiki_entry->course > 0) {
1144 $course = get_record('course', 'id', $wiki_entry->course);
1145 $owner = $course->shortname;
1147 else {
1148 $owner = '- '.get_string("ownerunknown","wiki").' -';
1150 return $owner;
1153 function wiki_print_search_form($cmid, $search="", $userid, $groupid, $return=false) {
1154 global $CFG;
1155 # TODO: Add Group and User !!!
1156 $output = "<form id=\"search\" action=\"$CFG->wwwroot/mod/wiki/view.php\">";
1157 $output .="<fieldset class='invisiblefieldset'>";
1158 $output .= "<span style='font-size:0.6em;'>";
1159 $output .= "<input value=\"".get_string("searchwiki", "wiki").":\" type=\"submit\" />";
1160 $output .= "<input name=\"id\" type=\"hidden\" value=\"$cmid\" />";
1161 $output = $output.($groupid?"<input name=\"groupid\" type=\"hidden\" value=\"$groupid\" />":"");
1162 $output = $output.($userid?"<input name=\"userid\" type=\"hidden\" value=\"$userid\" />":"");
1163 $output .= "<input name=\"q\" type=\"text\" size=\"20\" value=\"".s($search)."\" />".' ';
1164 $output .= "</span>";
1165 $output .= "<input name=\"page\" type=\"hidden\" value=\"SearchPages\" />";
1166 $output .= "</fieldset>";
1167 $output .= "</form>";
1169 if ($return) {
1170 return $output;
1172 echo $output;
1175 function wiki_print_wikilinks_block($cmid, $binary=false, $return=false) {
1176 /// Prints a link-list of special wiki-pages
1177 global $CFG, $ewiki_title;
1179 $links=array();
1181 $links["SiteMap"]=get_string("sitemap", "wiki");
1182 $links["PageIndex"]=get_string("pageindex", "wiki");
1183 $links["NewestPages"]=get_string("newestpages", "wiki");
1184 $links["MostVisitedPages"]=get_string("mostvisitedpages", "wiki");
1185 $links["MostOftenChangedPages"]=get_string("mostoftenchangedpages", "wiki");
1186 $links["UpdatedPages"]=get_string("updatedpages", "wiki");
1187 $links["OrphanedPages"]=get_string("orphanedpages", "wiki");
1188 $links["WantedPages"]=get_string("wantedpages", "wiki");
1189 $links["WikiExport"]=get_string("wikiexport", "wiki");
1190 if($binary) {
1191 $links["FileDownload"]=get_string("filedownload", "wiki");
1193 popup_form(EWIKI_SCRIPT, $links, "wikilinks", "", get_string("choosewikilinks", "wiki"), "", "", $return);
1196 function wiki_print_page_actions($cmid, $specialpages, $page, $action, $binary=false, $canedit=true) {
1197 /// Displays actions which can be performed on the page
1199 $page=array();
1201 // Edit this Page
1202 if (in_array($action, array("edit", "links", "info", "attachments"))) {
1203 $page["view/$page"]=get_string("viewpage","wiki");
1205 if ($canedit && !in_array($page, $specialpages) && $action != "edit") {
1206 $page["edit/$page"]=get_string("editthispage","wiki");
1208 if ($action != "links") {
1209 $page["links/$page"]=get_string("backlinks","wiki");
1211 if ($canedit && !in_array($page, $specialpages) && $action!="info") {
1212 $page["info/$page"]=get_string("pageinfo","wiki");
1214 if($canedit && $binary && !in_array($page, $specialpages) && $action != "attachments") {
1215 $page["attachments/$page"]=get_string("attachments","wiki");
1218 popup_form(EWIKI_SCRIPT, $page, "wikiactions", "", get_string("action", "wiki"), "", "", false);
1221 function wiki_print_administration_actions($wiki, $cmid, $userid, $groupid, $page, $noeditor, $course) {
1222 /// Displays actions which can be performed on the page
1224 /// Create the URL
1225 $ewscript = 'admin.php?id='.$cmid;
1226 if (isset($userid) && $userid!=0) $ewscript .= '&amp;userid='.$userid;
1227 if (isset($groupid) && $groupid!=0) $ewscript .= '&amp;groupid='.$groupid;
1228 if (isset($page)) $ewscript .= '&amp;page='.$page;
1229 $ewscript.="&amp;action=";
1232 /// Build that action array according to wiki flags.
1233 $action = array();
1234 $isteacher = wiki_is_teacher($wiki);
1236 if ($wiki->setpageflags or $isteacher) {
1237 $action['setpageflags'] = get_string('setpageflags', 'wiki');
1239 if ($wiki->removepages or $isteacher) {
1240 $action['removepages'] = get_string('removepages', 'wiki');
1242 if ($wiki->strippages or $isteacher) {
1243 $action['strippages'] = get_string('strippages', 'wiki');
1245 if ($wiki->revertchanges or $isteacher) {
1246 $action['revertpages'] = get_string('revertpages', 'wiki');
1249 if($noeditor) {
1250 $action["checklinks"]=get_string("checklinks", "wiki");
1252 popup_form($ewscript, $action, "wikiadministration", "", get_string("chooseadministration", "wiki"), "", "", false);
1255 function wiki_admin_get_flagarray() {
1256 $ret = array(
1257 EWIKI_DB_F_TEXT => get_string("flagtxt","wiki"),
1258 EWIKI_DB_F_BINARY => get_string("flagbin","wiki"),
1259 EWIKI_DB_F_DISABLED => get_string("flagoff","wiki"),
1260 EWIKI_DB_F_HTML => get_string("flaghtm","wiki"),
1261 EWIKI_DB_F_READONLY => get_string("flagro","wiki"),
1262 EWIKI_DB_F_WRITEABLE => get_string("flagwr","wiki"),
1265 return $ret;
1268 ///////// Ewiki Administration. Mostly taken from the ewiki/tools folder and changed
1269 function wiki_admin_setpageflags_list($pageflagstatus) {
1270 $FD = wiki_admin_get_flagarray();
1271 $table = new Object();
1272 $table->head = array(get_string("pagename","wiki"), get_string("flags","wiki"));
1273 if($pageflagstatus) {
1274 $table->head[]=get_string("status","wiki");
1277 $result = ewiki_database("GETALL", array("version", "flags"));
1278 while ($row = $result->get()) {
1279 $id = $row["id"];
1280 $data = ewiki_database("GET", $row);
1282 $cell_pagename="";
1283 $cell_flags="";
1284 if ($data["flags"] & EWIKI_DB_F_TEXT) {
1285 $cell_pagename .= '<a href="' . EWIKI_SCRIPT . $id . '">';
1286 } else {
1287 $cell_pagename .= '<a href="' . EWIKI_SCRIPT_BINARY . $id . '">';
1289 $cell_pagename .= s($id) . '</a> / '.get_string("version","wiki").": ".$row["version"];
1291 foreach ($FD as $n=>$str) {
1292 $cell_flags .='<input type="checkbox" name="flags['. rawurlencode($id)
1293 . '][' . $n . ']" value="1" '
1294 . (($data["flags"] & $n) ? "checked=\"checked\"" : "")
1295 . ' />'.$str. ' ';
1297 if($pageflagstatus) {
1298 $table->data[]=array($cell_pagename, $cell_flags, $pageflagstatus[$id]);
1299 } else {
1300 $table->data[]=array($cell_pagename, $cell_flags);
1303 return $table;
1306 function wiki_admin_setpageflags($pageflags) {
1307 $FD = wiki_admin_get_flagarray();
1309 $status=array();
1310 if($pageflags) {
1311 foreach($pageflags as $page=>$fa) {
1313 $page = rawurldecode($page);
1315 $flags = 0;
1316 $fstr = "";
1317 foreach($fa as $num=>$isset) {
1318 if ($isset) {
1319 $flags += $num;
1320 $fstr .= ($fstr?",":""). $FD[$num];
1324 #$status[$page] .= "{$flags}=[{$fstr}]";
1326 $data = ewiki_database("GET", array("id" => $page));
1328 if ($data["flags"] != $flags) {
1329 $data["flags"] = $flags;
1330 $data["author"] = "ewiki-tools, " . ewiki_author();
1331 $data["version"]++;
1332 ewiki_database("WRITE", $data);
1333 $status[$page] = "<b>".get_string("flagsset","wiki")."</b> ".$status[$page];
1337 return $status;
1341 function wiki_admin_remove_list($listall="") {
1342 /// Table header
1343 $table = new Object();
1344 $table->head = array("&nbsp;", get_string("pagename","wiki"), get_string("errororreason","wiki"));
1346 /// Get all pages
1347 $result = ewiki_database("GETALL", array("version"));
1348 $selected = array();
1350 /// User wants to see all pages
1351 if ($listall) {
1352 while ($row = $result->get()) {
1353 $selected[$row["id"]] = get_string("listall","wiki")."<br />";
1356 while ($page = $result->get()) {
1357 $id = $page["id"];
1358 $page = ewiki_database("GET", array("id"=>$id));
1359 $flags = $page["flags"];
1360 #print "$id ".strlen(trim(($page["content"])))."<br />";
1362 if (!strlen(trim(($page["content"]))) && !($flags & EWIKI_DB_F_BINARY)) {
1363 @$selected[$id] .= get_string("emptypage","wiki")."<br />";
1366 // Check for orphaned pages
1367 $result2 = ewiki_database("SEARCH", array("content" => $id));
1368 $orphanedpage=true;
1369 if ($result2 && $result2->count()) {
1370 while ($row = $result2->get()) {
1371 $checkcontent = ewiki_database("GET", array("id"=>$row["id"]));
1372 $checkcontent = strtolower($checkcontent["content"]);
1374 if(strpos($checkcontent, strtolower($id)) !== false) {
1375 $orphanedpage=false;
1378 #echo "rc({$row['id']})==>($id): $check2 <br />";
1382 /// Some more reasons for Deletion...
1383 if ($orphanedpage && $id!=EWIKI_PAGE_INDEX &&!($flags & EWIKI_DB_F_BINARY)) {
1384 @$selected[$id] .= get_string("orphanedpage","wiki")."<br />";
1387 if ($flags & EWIKI_DB_F_DISABLED) {
1388 @$selected[$id] .= get_string("disabledpage","wiki")."<br />";
1391 if (($flags & 3) == 3) {
1392 @$selected[$id] .= get_string("errorbinandtxt","wiki")."<br />";
1395 if (!($flags & 3)) {
1396 @$selected[$id] .= get_string("errornotype","wiki")."<br />";
1399 if ($flags & EWIKI_DB_F_HTML) {
1400 @$selected[$id] .= get_string("errorhtml","wiki")."<br />";
1403 if (($flags & EWIKI_DB_F_READONLY) && !($flags & EWIKI_DB_F_BINARY)) {
1404 @$selected[$id] .= get_string("readonly","wiki")."<br />";
1407 if (($flags & EWIKI_DB_F_READONLY) && ($flags & EWIKI_DB_F_WRITEABLE)) {
1408 @$selected[$id] .= get_string("errorroandwr","wiki")."<br />";
1411 if (strlen($page["content"]) >= 65536) {
1412 @$selected[$id] .= get_string("errorsize","wiki")."<br />";
1415 if (strpos($page["refs"], "\n".get_string("deletemewikiword","wiki")."\n")!==false) {
1416 @$selected[$id] .= get_string("deletemewikiwordfound","wiki",get_string("deletemewikiword","wiki"))."<br />";
1420 foreach ($selected as $id => $reason) {
1421 $table_checkbox='<input type="checkbox" value="'.rawurlencode($id).'" name="pagestodelete[]" />';
1423 #-- link & id
1424 if (strpos($id, EWIKI_IDF_INTERNAL) === false) {
1425 $table_page='<a href="' . ewiki_script("", $id) . '">';
1426 } else {
1427 $table_page='<a href="' . ewiki_script_binary("", $id) . '">';
1429 $table_page .= s($id) . '</a>';
1431 #-- print reason
1432 $table_reason=$reason;
1434 $table->data[]=array($table_checkbox, $table_page, $table_reason);
1437 return $table;
1440 /// This function actually removes the pages
1441 function wiki_admin_remove($pagestodelete, $course, $wiki, $userid, $groupid) {
1442 $ret="";
1443 foreach ($pagestodelete as $id) {
1445 $id = rawurldecode($id);
1447 $data = ewiki_database("GET", array("id"=>$id));
1448 for ($version=1; $version<=$data["version"]; $version++) {
1449 ewiki_database("DELETE", array("id"=>$id, "version"=>$version));
1450 if($data["flags"] & EWIKI_DB_F_BINARY) {
1451 $filepath=moodle_binary_get_path($id, $data["meta"], $course, $wiki, $userid, $groupid);
1452 @unlink("$filepath");
1457 return $ret;
1460 function wiki_admin_strip_list($pagestostrip="",$version="",$err="") {
1461 /// Table header
1462 $table = new Object();
1463 $table->head = array("&nbsp;", get_string("pagename","wiki"), get_string("deleteversions","wiki"));
1465 $vc=ewiki_database("COUNTVERSIONS", array());
1466 $result = ewiki_database("GETALL",array());
1467 $i=0;
1468 while ($row = $result->get()) {
1469 $id = $row["id"];
1470 if($vc[$id]>1) {
1471 $error="";
1472 if($err[$id]) {
1473 $error=" ".join(", ",$err[$id]);
1475 $checked="";
1476 if($pagestostrip=="" || $pagestostrip[$i]) {
1477 $checked=" checked=\"checked\"";
1479 if($version=="") {
1480 $versiondefault="1-".($row["version"]-1);
1481 } else {
1482 $versiondefault=$version[$i];
1484 $table->data[]=array('<input type="checkbox" value="'.rawurlencode($id).'" name="pagestostrip['.$i.']" '.$checked.' />',
1485 '<A HREF="'.EWIKI_SCRIPT.$id.'">'.s($id).'</A> / '.get_string("version","wiki").": ".$row["version"],
1486 '<input name="version['.$i.']" value="'.$versiondefault.'" size="7" />'.$error);
1489 $i++;
1491 return $table;
1494 function wiki_admin_strip_versions($pagestostrip, $version, &$err) {
1495 $ret=array();
1496 foreach ($pagestostrip as $key => $id_ue) {
1498 $id = rawurldecode($id_ue);
1499 if (preg_match('/^(\d+)[-\s._:]+(\d+)$/', trim($version[$key]), $uu)) {
1500 $versA = $uu[1];
1501 $versZ = $uu[2];
1503 // Let the last Version in the database
1504 $checkdata = ewiki_database("GET", array("id" => $id));
1505 if($versZ>=$checkdata["version"]) {
1506 $err[$id][] = get_string("versionrangetoobig","wiki");
1507 } else {
1508 if($versA<=$versZ) {
1509 for ($v=$versA; $v<=$versZ; $v++) {
1510 $ret[$id][]=$v;
1512 } else {
1513 $err[$id][]=get_string("wrongversionrange","wiki",$version[$key]);
1517 else {
1518 $err[$id][]=get_string("wrongversionrange","wiki",$version[$key]);
1521 return $ret;
1524 function wiki_admin_strip($pagestostrip) {
1525 /// Purges old page-versions
1526 foreach($pagestostrip as $id => $versions) {
1527 foreach($versions as $version) {
1528 ewiki_database("DELETE", array("id"=>$id, "version"=>$version));
1533 function wiki_admin_checklinks_list() {
1534 $ret=array();
1535 $result = ewiki_database("GETALL",array());
1536 while ($row = $result->get()) {
1537 if(!($row["flags"] & EWIKI_DB_F_BINARY)) {
1538 $index=s($row["id"]);
1539 $ret[$index] = $row["id"];
1542 return $ret;
1545 function wiki_admin_checklinks($pagetocheck) {
1546 /// Checks http:// Links
1547 $ret="";
1548 if($pagetocheck) {
1549 $get = ewiki_database("GET", array("id" => $pagetocheck));
1550 $content = $get["content"];
1552 preg_match_all('_(http.?://[^\s"\'<>#,;]+[^\s"\'<>#,;.])_', $content, $links);
1553 $badlinks = array();
1554 if(!$links[1]) {
1555 $ret = get_string("nolinksfound","wiki")."<br /><br />";
1556 } else {
1557 foreach ($links[1] as $href) {
1558 #print "[ $href ]";
1559 #$d = @implode("", @file($href));
1560 $d="";
1561 if($checkfd = @fopen($href, 'r')) {
1562 fclose($checkfd);
1563 $d="OK";
1565 if (empty($d) || !strlen(trim($d)) || stristr("not found", $d) || stristr("error 404", $d)) {
1566 $ret.="[".get_string("linkdead","wiki")."] $href <br />\n";
1567 $badlinks[] = $href;
1568 } else {
1569 $ret.="[".get_string("linkok","wiki")."] $href <br />\n";
1574 /// Remove old Notices
1575 $content = eregi_replace(' µµ__~\['.get_string("offline","wiki").'\]__µµ ','', $content);
1577 #-- replace dead links
1578 foreach ($badlinks as $href) {
1579 $content = preg_replace("\377^(.*)($href)\377m", '$1 µµ__~['.get_string("offline","wiki").']__µµ $2', $content);
1582 #-- compare against db content
1583 if ($content != $get["content"]) {
1584 $get["content"] = $content;
1585 $get["version"]++;
1586 $get["author"] = ewiki_author("ewiki_checklinks");
1587 $get["lastmodified"] = time();
1589 ewiki_database("WRITE", $get);
1592 return $ret;
1595 function wiki_admin_revert($proceed, $authorfieldpattern, $changesfield, $howtooperate, $deleteversions) {
1596 $ret="";
1597 #-- params
1598 $m_time = $changesfield * 3600;
1599 $depth = $deleteversions - 1;
1600 $depth = ($depth>0?$depth:0);
1602 #-- walk through
1603 $result = ewiki_database("GETALL", array("id", "author", "lastmodified"));
1604 while ($row = $result->get()) {
1605 $id = $row["id"];
1606 #-- which versions to check
1607 $verZ = $row["version"];
1608 if ($howtooperate=="lastonly") {
1609 $verA = $verZ;
1611 else {
1612 $verA = $verZ-$depth;
1613 if ($verA <= 0) {
1614 $verA = 1;
1618 for ($ver=$verA; $ver<=$verZ; $ver++) {
1619 #-- load current $ver database entry
1620 if ($verA != $verZ) {
1621 $row = ewiki_database("GET", array("id"=>$id, "version"=>$ver));
1624 #-- match
1625 if (stristr($row["author"], $authorfieldpattern) && ($row["lastmodified"] + $m_time > time())) {
1626 $ret .= "$id (".get_string("versionstodelete","wiki").": ";
1627 #-- delete multiple versions
1628 if ($howtooperate=="allsince") {
1629 while ($ver<=$verZ) {
1630 $ret .= " $ver";
1631 if ($proceed) {
1632 ewiki_database("DELETE", array("id"=>$id, "version"=>$ver));
1634 $ver++;
1637 #-- or just the affected one
1638 else {
1639 $ret .= " $ver";
1640 if ($proceed) {
1641 ewiki_database("DELETE", $row);
1644 $ret .= ")<br />";
1645 break;
1647 } #-- for($ver)
1648 } #-- while($row)
1649 return $ret;
1653 function wiki_get_view_actions() {
1654 return array('view','view all');
1657 function wiki_get_post_actions() {
1658 return array('hack');
1663 * Obtains an editing lock on a wiki page.
1664 * @param int $wikiid ID of wiki object.
1665 * @param string $pagename Name of page.
1666 * @return array Two-element array with a boolean true (if lock has been obtained)
1667 * or false (if lock was held by somebody else). If lock was held by someone else,
1668 * the values of the wiki_locks entry are held in the second element; if lock was
1669 * held by current user then the the second element has a member ->id only.
1671 function wiki_obtain_lock($wikiid,$pagename) {
1672 global $USER;
1674 // Check for lock
1675 $alreadyownlock=false;
1676 if($lock=get_record('wiki_locks','pagename',$pagename,'wikiid', $wikiid)) {
1677 // Consider the page locked if the lock has been confirmed within WIKI_LOCK_PERSISTENCE seconds
1678 if($lock->lockedby==$USER->id) {
1679 // Cool, it's our lock, do nothing except remember it in session
1680 $lockid=$lock->id;
1681 $alreadyownlock=true;
1682 } else if(time()-$lock->lockedseen < WIKI_LOCK_PERSISTENCE) {
1683 return array(false,$lock);
1684 } else {
1685 // Not locked any more. Get rid of the old lock record.
1686 if(!delete_records('wiki_locks','pagename',$pagename,'wikiid', $wikiid)) {
1687 error('Unable to delete lock record');
1692 // Add lock
1693 if(!$alreadyownlock) {
1694 // Lock page
1695 $newlock=new stdClass;
1696 $newlock->lockedby=$USER->id;
1697 $newlock->lockedsince=time();
1698 $newlock->lockedseen=$newlock->lockedsince;
1699 $newlock->wikiid=$wikiid;
1700 $newlock->pagename=$pagename;
1701 if(!$lockid=insert_record('wiki_locks',$newlock)) {
1702 error('Unable to insert lock record');
1706 // Store lock information in session so we can clear it later
1707 if(!array_key_exists(SESSION_WIKI_LOCKS,$_SESSION)) {
1708 $_SESSION[SESSION_WIKI_LOCKS]=array();
1710 $_SESSION[SESSION_WIKI_LOCKS][$wikiid.'_'.$pagename]=$lockid;
1711 $lockdata=new StdClass;
1712 $lockdata->id=$lockid;
1713 return array(true,$lockdata);
1717 * If the user has an editing lock, releases it. Has no effect otherwise.
1718 * Note that it doesn't matter if this isn't called (as happens if their
1719 * browser crashes or something) since locks time out anyway. This is just
1720 * to avoid confusion of the 'what? it says I'm editing that page but I'm
1721 * not, I just saved it!' variety.
1722 * @param int $wikiid ID of wiki object.
1723 * @param string $pagename Name of page.
1725 function wiki_release_lock($wikiid,$pagename) {
1726 if(!array_key_exists(SESSION_WIKI_LOCKS,$_SESSION)) {
1727 // No locks at all in session
1728 return;
1731 $key=$wikiid.'_'.$pagename;
1733 if(array_key_exists($key,$_SESSION[SESSION_WIKI_LOCKS])) {
1734 $lockid=$_SESSION[SESSION_WIKI_LOCKS][$key];
1735 unset($_SESSION[SESSION_WIKI_LOCKS][$key]);
1736 if(!delete_records('wiki_locks','id',$lockid)) {
1737 error("Unable to delete lock record.");
1743 * Returns all other caps used in module
1745 function wiki_get_extra_capabilities() {
1746 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');