MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / mod / wiki / lib.php
blobcf3491d2ec5825935b3070d387085523c7aeb47c
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 foreach ($logs as $log) {
192 //Create a temp valid module structure (course,id)
193 $tempmod = new Object();
194 $tempmod->course = $log->course;
195 $tempmod->id = $log->instance;
197 //Obtain the visible property from the instance
198 $modvisible = instance_is_visible($log->module,$tempmod);
200 //Only if the mod is visible
201 if ($modvisible) {
202 $wikis[$log->info] = wiki_log_info($log);
203 $wikis[$log->info]->pagename = $log->info;
204 $wikis[$log->info]->time = $log->time;
205 $wikis[$log->info]->url = str_replace('&', '&amp;', $log->url);
209 if (isset($wikis)) {
210 $content = true;
211 print_headline(get_string('updatedwikipages', 'wiki').':', 3);
212 foreach ($wikis as $wiki) {
213 print_recent_activity_note($wiki->time, $wiki, $wiki->pagename,
214 $CFG->wwwroot.'/mod/wiki/'.$wiki->url);
217 return true; // True if anything was printed, otherwise false
220 function wiki_log_info($log) {
221 global $CFG;
222 return get_record_sql("SELECT u.firstname, u.lastname
223 FROM {$CFG->prefix}user u
224 WHERE u.id = '$log->userid'");
227 function wiki_cron () {
228 /// Function to be run periodically according to the moodle cron
229 /// This function searches for things that need to be done, such
230 /// as sending out mail, toggling flags etc ...
232 // Delete expired locks
233 $result=delete_records_select('wiki_locks','lockedseen < '.(time()-WIKI_LOCK_PERSISTENCE));
235 return $result;
238 function wiki_grades($wikiid) {
239 /// Must return an array of grades for a given instance of this module,
240 /// indexed by user. It also returns a maximum allowed grade.
242 return NULL;
245 function wiki_get_participants($wikiid) {
246 //Returns the users with data in one wiki
247 //(users with records in wiki_pages and wiki_entries)
249 global $CFG;
251 //Get users from wiki_pages
252 $st_pages = get_records_sql("SELECT DISTINCT u.id, u.id
253 FROM {$CFG->prefix}user u,
254 {$CFG->prefix}wiki_entries e,
255 {$CFG->prefix}wiki_pages p
256 WHERE e.wikiid = '$wikiid' and
257 p.wiki = e.id and
258 u.id = p.userid");
260 //Get users from wiki_entries
261 $st_entries = get_records_sql("SELECT DISTINCT u.id, u.id
262 FROM {$CFG->prefix}user u,
263 {$CFG->prefix}wiki_entries e
264 WHERE e.wikiid = '$wikiid' and
265 u.id = e.userid");
267 //Add entries to pages
268 if ($st_entries) {
269 foreach ($st_entries as $st_entry) {
270 $st_pages[$st_entry->id] = $st_entry;
274 return $st_pages;
278 //////////////////////////////////////////////////////////////////////////////////////
279 /// Any other wiki functions go here. Each of them must have a name that
280 /// starts with wiki_
282 function wiki_wiki_name($wikiname) {
283 /// Return the passed in string in Wiki name format.
284 /// Remove any leading and trailing whitespace, capitalize all the words
285 /// and then remove any internal whitespace.
287 if (wiki_is_wiki_name($wikiname)) {
288 return $wikiname;
290 else {
291 /// Create uppercase words and remove whitespace.
292 $wikiname = preg_replace("/(\w+)\s/", "$1", ucwords(trim($wikiname)));
294 /// Check again - there may only be one word.
295 if (wiki_is_wiki_name($wikiname)) {
296 return $wikiname;
298 /// If there is only one word, append default wiki name to it.
299 else {
300 return $wikiname.get_string('wikidefaultpagename', 'wiki');
305 function wiki_is_wiki_name($wikiname) {
306 /// Check for correct wikiname syntax and return true or false.
308 /// If there are spaces between the words, incorrect format.
309 if (preg_match_all('/\w+/', $wikiname, $out) > 1) {
310 return false;
312 /// If there isn't more than one group of uppercase letters separated by
313 /// lowercase letters or '_', incorrect format.
314 else if (preg_match_all('/[A-Z]+[a-z_]+/', $wikiname, $out) > 1) {
315 return true;
317 else {
318 return false;
322 function wiki_page_name(&$wiki) {
323 /// Determines the wiki's page name and returns it.
324 if (!empty($wiki->initialcontent)) {
325 $ppos = strrpos($wiki->initialcontent, '/');
326 if ($ppos === false) {
327 $pagename = $wiki->initialcontent;
329 else {
330 $pagename = substr($wiki->initialcontent, $ppos+1);
333 else if (!empty($wiki->pagename)) {
334 $pagename = $wiki->pagename;
336 else {
337 $pagename = $wiki->name;
339 return $pagename;
342 function wiki_content_dir(&$wiki) {
343 /// Determines the wiki's default content directory (if there is one).
344 global $CFG;
346 if (!empty($wiki->initialcontent)) {
347 $ppos = strrpos($wiki->initialcontent, '/');
348 if ($ppos === false) {
349 $subdir = '';
351 else {
352 $subdir = substr($wiki->initialcontent, 0, $ppos+1);
354 $contentdir = $CFG->dataroot.'/'.$wiki->course.'/'.$subdir;
356 else {
357 $contentdir = false;
359 return $contentdir;
362 function wiki_get_course_wikis($courseid, $wtype='*') {
363 /// Returns all wikis for the specified course and optionally of the specified type.
365 $select = 'course = '.$courseid;
366 if ($wtype != '*') {
367 $select .= ' AND wtype = \''.$wtype.'\'';
369 return get_records_select('wiki', $select, 'id');
372 function wiki_has_entries(&$wiki) {
373 /// Returns true if wiki already has wiki entries; otherwise false.
375 return record_exists('wiki_entries', 'wikiid', $wiki->id);
378 function wiki_get_entries(&$wiki, $byindex=NULL) {
379 /// Returns an array with all wiki entries indexed by entry id; false if there are none.
380 /// If the optional $byindex is specified, returns the entries indexed by that field.
381 /// Valid values for $byindex are 'student', 'group'.
382 global $CFG;
384 if ($byindex == 'student') {
385 return get_records('wiki_entries', 'wikiid', $wiki->id, '',
386 'userid,id,wikiid,course,groupid,pagename,timemodified');
388 else if ($byindex == 'group') {
389 return get_records('wiki_entries', 'wikiid', $wiki->id, '',
390 'groupid,id,wikiid,course,userid,pagename,timemodified');
392 else {
393 return get_records('wiki_entries', 'wikiid', $wiki->id);
397 function wiki_get_default_entry(&$wiki, &$course, $userid=0, $groupid=0) {
398 /// Returns the wiki entry according to the wiki type.
399 /// Optionally, will return wiki entry for $userid student wiki, or
400 /// $groupid group or teacher wiki.
401 /// Creates one if it needs to and it can.
402 global $USER;
403 /// If there is a groupmode, get the user's group id.
404 $groupmode = groups_get_activity_groupmode($wiki);
405 // if groups mode is in use and no group supplied, use the first one found
406 if ($groupmode && !$groupid) {
407 if(($mygroupids=mygroupid($course->id)) && count($mygroupids)>0) {
408 // Use first group. They ought to be able to change later
409 $groupid=$mygroupids[0];
410 } else {
411 // Whatever groups are in the course, pick one
412 $coursegroups = groups_get_all_groups($course->id);
413 if(!$coursegroups || count($coursegroups)==0) {
414 error("Can't access wiki in group mode when no groups are configured for the course");
416 $unkeyed=array_values($coursegroups); // Make sure first item is index 0
417 $groupid=$unkeyed[0]->id;
421 /// If the wiki entry doesn't exist, can this user create it?
422 if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false) {
423 if (wiki_can_add_entry($wiki, $USER, $course, $userid, $groupid)) {
424 wiki_add_entry($wiki, $course, $userid, $groupid);
425 if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false) {
426 error("Could not add wiki entry.");
430 //print_object($wiki_entry);
431 return $wiki_entry;
434 function wiki_get_entry(&$wiki, &$course, $userid=0, $groupid=0) {
435 /// Returns the wiki entry according to the wiki type.
436 /// Optionally, will return wiki entry for $userid student wiki, or
437 /// $groupid group or teacher wiki.
438 global $USER;
440 switch ($wiki->wtype) {
441 case 'student':
442 /// If a specific user was requested, return it, if allowed.
443 if ($userid and wiki_user_can_access_student_wiki($wiki, $userid, $course)) {
444 $wentry = wiki_get_student_entry($wiki, $userid);
447 /// If there is no entry for this user, check if this user is a teacher.
448 else if (!$wentry = wiki_get_student_entry($wiki, $USER->id)) {
449 /* if (wiki_is_teacher($wiki, $USER->id)) {
450 /// If this user is a teacher, return the first entry.
451 if ($wentries = wiki_get_entries($wiki)) {
452 $wentry = current($wentries);
456 break;
458 case 'group':
459 /// If there is a groupmode, get the user's group id.
460 $groupmode = groups_get_activity_groupmode($wiki);
461 if($groupmode) {
462 if(!$groupid) {
463 if(($mygroupids=mygroupid($course->id)) && count($mygroupids)>0) {
464 // Use first group. They ought to be able to change later
465 $groupid=$mygroupids[0];
466 } else {
467 // Whatever groups are in the course, pick one
468 $coursegroups = groups_get_all_groups($course->id);
469 if(!$coursegroups || count($coursegroups)==0) {
470 error("Can't access wiki in group mode when no groups are configured for the course");
472 $unkeyed=array_values($coursegroups); // Make sure first item is index 0
473 $groupid=$unkeyed[0]->id;
477 //echo "groupid is in wiki_get_entry ".$groupid."<br />";
478 /// If a specific group was requested, return it, if allowed.
479 if ($groupid and wiki_user_can_access_group_wiki($wiki, $groupid, $course)) {
480 $wentry = wiki_get_group_entry($wiki, $groupid);
481 } else {
482 error("Cannot access any groups for this wiki");
485 /// If mode is 'nogroups', then groupid is zero.
486 else {
487 $wentry = wiki_get_group_entry($wiki, 0);
489 break;
491 case 'teacher':
492 /// If there is a groupmode, get the user's group id.
493 if (groupmode($course, $wiki)) {
494 $mygroupids = mygroupid($course->id);//same here, default to the first one
495 $groupid = $groupid ? $groupid : $mygroupids[0]/*mygroupid($course->id)*/;
498 /// If a specific group was requested, return it, if allowed.
499 if (wiki_user_can_access_teacher_wiki($wiki, $groupid, $course)) {
500 $wentry = wiki_get_teacher_entry($wiki, $groupid);
502 break;
504 return $wentry;
507 function wiki_get_teacher_entry(&$wiki, $groupid=0) {
508 /// Returns the wiki entry for the wiki teacher type.
509 return get_record('wiki_entries', 'wikiid', $wiki->id, 'course', $wiki->course, 'groupid', $groupid);
512 function wiki_get_group_entry(&$wiki, $groupid=null) {
513 /// Returns the wiki entry for the given group.
514 return get_record('wiki_entries', 'wikiid', $wiki->id, 'groupid', $groupid);
517 function wiki_get_student_entry(&$wiki, $userid=null) {
518 /// Returns the wiki entry for the given student.
519 global $USER;
521 if (is_null($userid)) {
522 $userid = $USER->id;
524 return get_record('wiki_entries', 'wikiid', $wiki->id, 'userid', $userid);
527 function wiki_get_other_wikis(&$wiki, &$user, &$course, $currentid=0) {
528 /// Returns a list of other wikis to display, depending on the type, group and user.
529 /// Returns the key containing the currently selected entry as well.
531 global $CFG, $id;
533 $wikis = false;
535 $groupmode = groups_get_activity_groupmode($wiki);
536 $mygroupid = mygroupid($course->id);
537 $isteacher = wiki_is_teacher($wiki, $user->id);
538 $isteacheredit = wiki_is_teacheredit($wiki, $user->id);
540 $groupingid = null;
541 $cm = new stdClass;
542 $cm->id = $wiki->cmid;
543 $cm->groupmode = $wiki->groupmode;
544 $cm->groupingid = $wiki->groupingid;
545 $cm->groupmembersonly = $wiki->groupmembersonly;
546 if (!empty($CFG->enablegroupings) && !empty($cm->groupingid)) {
547 $groupingid = $wiki->groupingid;
551 switch ($wiki->wtype) {
553 case 'student':
554 /// Get all the existing entries for this wiki.
555 $wiki_entries = wiki_get_entries($wiki, 'student');
557 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
558 $sql = "SELECT gm.userid FROM {$CFG->prefix}groups_members gm " .
559 "INNER JOIN {$CFG->prefix}groupings_groups gg ON gm.groupid = gg.groupid " .
560 "WHERE gg.groupingid = $wiki->groupingid ";
562 $groupingmembers = get_records_sql($sql);
565 if ($isteacher and (SITEID != $course->id)) {
567 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all student
568 /// wikis, regardless of creation.
569 if ((SITEID != $course->id) and ($isteacheredit or ($groupmode == NOGROUPS))) {
571 if ($students = get_course_students($course->id)) {
572 /// Default pagename is dependent on the wiki settings.
573 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
575 foreach ($students as $student) {
576 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid) && empty($groupingmembers[$student->id])) {
577 continue;
579 /// If this student already has an entry, use its pagename.
580 if ($wiki_entries[$student->id]) {
581 $pagename = $wiki_entries[$student->id]->pagename;
583 else {
584 $pagename = $defpagename;
587 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
588 $wikis[$key] = fullname($student).':'.$pagename;
592 else if ($groupmode == SEPARATEGROUPS) {
594 if ($students = wiki_get_students($wiki, $mygroupid)) {
595 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
596 foreach ($students as $student) {
597 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid) && empty($groupingmembers[$student->id])) {
598 continue;
600 /// If this student already has an entry, use its pagename.
601 if ($wiki_entries[$student->id]) {
602 $pagename = $wiki_entries[$student->id]->pagename;
604 else {
605 $pagename = $defpagename;
608 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
609 $wikis[$key] = fullname($student).':'.$pagename;
613 else if ($groupmode == VISIBLEGROUPS) {
614 /// Get all students in your group.
615 if ($students = wiki_get_students($wiki, $mygroupid)) {
616 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
617 foreach ($students as $student) {
618 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid) && empty($groupingmembers[$student->id])) {
619 continue;
621 /// If this student already has an entry, use its pagename.
622 if ($wiki_entries[$student->id]) {
623 $pagename = $wiki_entries[$student->id]->pagename;
625 else {
626 $pagename = $defpagename;
628 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
629 $wikis[$key] = fullname($student).':'.$pagename;
632 /// Get all student wikis created, regardless of group.
633 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
634 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
635 .' FROM '.$CFG->prefix.'wiki_entries w '
636 .' INNER JOIN '.$CFG->prefix.'user u ON w.userid = u.id '
637 .' INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = u.id '
638 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON gm.groupid = gg.groupid '
639 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
640 .' ORDER BY w.id';
641 } else {
642 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
643 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'user u '
644 .' WHERE w.wikiid = '.$wiki->id.' AND u.id = w.userid '
645 .' ORDER BY w.id';
647 $wiki_entries = get_records_sql($sql);
648 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
649 foreach ($wiki_entries as $wiki_entry) {
650 $key = 'view.php?id='.$id.'&userid='.$wiki_entry->userid.'&page='.$wiki_entry->pagename;
651 $wikis[$key] = fullname($wiki_entry).':'.$wiki_entry->pagename;
652 if ($currentid == $wiki_entry->id) {
653 $wikis['selected'] = $key;
658 else {
659 /// A user can see other student wikis if they are a member of the same
660 /// group (for separate groups) or there are visible groups, or if this is
661 /// a site-level wiki, and they are an administrator.
662 if (($groupmode == VISIBLEGROUPS) or wiki_is_teacheredit($wiki)) {
663 $viewall = true;
665 else if ($groupmode == SEPARATEGROUPS) {
666 $viewall = mygroupid($course->id);
668 else {
669 $viewall = false;
672 if ($viewall !== false) {
673 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
674 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
675 .' FROM '.$CFG->prefix.'wiki_entries w '
676 .' INNER JOIN '.$CFG->prefix.'user u ON w.userid = u.id '
677 .' INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = u.id '
678 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON gm.groupid = gg.groupid '
679 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
680 .' ORDER BY w.id';
681 } else {
682 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
683 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'user u '
684 .' WHERE w.wikiid = '.$wiki->id.' AND u.id = w.userid '
685 .' ORDER BY w.id';
687 $wiki_entries = get_records_sql($sql);
688 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
689 foreach ($wiki_entries as $wiki_entry) {
690 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid) && empty($groupingmembers[$wiki_entry->userid])) {
691 continue;
694 if (($viewall === true) or groups_is_member($viewall, $wiki_entry->userid)) {
695 $key = 'view.php?id='.$id.'&userid='.$wiki_entry->userid.'&page='.$wiki_entry->pagename;
696 $wikis[$key] = fullname($wiki_entry).':'.$wiki_entry->pagename;
697 if ($currentid == $wiki_entry->id) {
698 $wikis['selected'] = $key;
704 break;
706 case 'group':
707 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all group
708 /// wikis, regardless of creation.
710 /// If user is a member of multiple groups, need to show current group etc?
712 /// Get all the existing entries for this wiki.
713 $wiki_entries = wiki_get_entries($wiki, 'group');
715 if ($groupmode and ($isteacheredit or ($isteacher and !$mygroupid))) {
716 if ($groups = groups_get_all_groups($course->id, null, $groupingid)) {
717 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
718 foreach ($groups as $group) {
720 /// If this group already has an entry, use its pagename.
721 if (isset($wiki_entries[$group->id])) {
722 $pagename = $wiki_entries[$group->id]->pagename;
724 else {
725 $pagename = $defpagename;
728 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
729 $wikis[$key] = $group->name.':'.$pagename;
733 //if a studnet with multiple groups in SPG
734 else if ($groupmode == SEPARATEGROUPS){
735 if ($groups = groups_get_all_groups($course->id, $user->id, $groupingid)){
737 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
738 foreach ($groups as $group) {
739 /// If this group already has an entry, use its pagename.
740 if (isset($wiki_entries[$group->id])) {
741 $pagename = $wiki_entries[$group->id]->pagename;
743 else {
744 $pagename = $defpagename;
746 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
747 $wikis[$key] = $group->name.':'.$pagename;
753 /// A user can see other group wikis if there are visible groups.
754 else if ($groupmode == VISIBLEGROUPS) {
755 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
756 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
757 .' FROM '.$CFG->prefix.'wiki_entries w '
758 .' INNER JOIN '.$CFG->prefix.'groups g ON g.id = w.groupid '
759 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON g.id = gg.groupid '
760 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
761 .' ORDER BY w.groupid';
762 } else {
763 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
764 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
765 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
766 .' ORDER BY w.groupid';
768 $wiki_entries = get_records_sql($sql);
769 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
770 foreach ($wiki_entries as $wiki_entry) {
771 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
772 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
773 if ($currentid == $wiki_entry->id) {
774 $wikis['selected'] = $key;
778 break;
780 case 'teacher':
781 if ($isteacher) {
782 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all
783 /// teacher wikis, regardless of creation.
784 if ($groupmode and ($isteacheredit or ($isteacher and !$mygroupid))) {
785 if ($groups = groups_get_all_groups($course->id, null, $groupingid)) {
786 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
787 foreach ($groups as $group) {
788 /// If this group already has an entry, use its pagename.
789 if ($wiki_entries[$group->id]) {
790 $pagename = $wiki_entries[$group->id]->pagename;
792 else {
793 $pagename = $defpagename;
796 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
797 $wikis[$key] = $group->name.':'.$pagename;
801 /// A teacher can see all other group teacher wikis.
802 else if ($groupmode) {
803 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
804 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
805 .' FROM '.$CFG->prefix.'wiki_entries w '
806 .' INNER JOIN '.$CFG->prefix.'groups g ON g.id = w.groupid '
807 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON g.id = gg.groupid '
808 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
809 .' ORDER BY w.groupid';
810 } else {
811 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
812 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
813 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
814 .' ORDER BY w.groupid';
816 $wiki_entries = get_records_sql($sql);
817 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
818 foreach ($wiki_entries as $wiki_entry) {
819 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
820 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
821 if ($currentid == $wiki_entry->id) {
822 $wikis['selected'] = $key;
827 else {
828 /// A user can see other teacher wikis if they are a teacher, a member of the same
829 /// group (for separate groups) or there are visible groups.
830 if ($groupmode == VISIBLEGROUPS) {
831 $viewall = true;
833 else if ($groupmode == SEPARATEGROUPS) {
834 $viewall = $mygroupid;
836 else {
837 $viewall = false;
839 if ($viewall !== false) {
840 if (!empty($CFG->enablegroupings) && !empty($wiki->groupingid)) {
841 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
842 .' FROM '.$CFG->prefix.'wiki_entries w '
843 .' INNER JOIN '.$CFG->prefix.'groups g ON g.id = w.groupid '
844 .' INNER JOIN '.$CFG->prefix.'groupings_groups gg ON g.id = gg.groupid '
845 .' WHERE w.wikiid = '.$wiki->id.' AND gg.groupingid = '.$wiki->groupingid
846 .' ORDER BY w.groupid';
847 } else {
848 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
849 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
850 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
851 .' ORDER BY w.groupid';
853 $wiki_entries = get_records_sql($sql);
854 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
857 foreach ($wiki_entries as $wiki_entry) {
858 if (($viewall === true) or @in_array($wiki_entry->groupid, $viewall)/*$viewall == $wiki_entry->groupid*/) {
859 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
860 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
861 if ($currentid == $wiki_entry->id) {
862 $wikis['selected'] = $key;
868 break;
871 return $wikis;
874 function wiki_add_entry(&$wiki, &$course, $userid=0, $groupid=0) {
875 /// Adds a new wiki entry of the specified type, unless already entered.
876 /// No checking is done here. It is assumed that the caller has the correct
877 /// privileges to add this entry.
879 global $USER;
881 /// If this wiki already has a wiki_type entry, return false.
882 if (wiki_get_entry($wiki, $course, $userid, $groupid) !== false) {
883 return false;
886 $wiki_entry = new Object();
888 switch ($wiki->wtype) {
890 case 'student':
891 $wiki_entry->wikiid = $wiki->id;
892 $wiki_entry->userid = $userid ? $userid : $USER->id;
893 $wiki_entry->pagename = wiki_page_name($wiki);
894 $wiki_entry->timemodified = time();
895 break;
897 case 'group':
898 /// Get the groupmode. It's been added to the wiki object.
899 $groupmode = groups_get_activity_groupmode($wiki);
901 ///give the first groupid by default and try
902 $mygroups = mygroupid($course->id);
904 /// If there is a groupmode, get the group id.
905 if ($groupmode) {
906 $groupid = $groupid ? $groupid : $mygroups[0]/*mygroupid($course->id)*/;
908 /// If mode is 'nogroups', then groupid is zero.
909 else {
910 $groupid = 0;
912 $wiki_entry->wikiid = $wiki->id;
913 $wiki_entry->groupid = $groupid;
914 $wiki_entry->pagename = wiki_page_name($wiki);
915 $wiki_entry->timemodified = time();
917 break;
919 case 'teacher':
920 /// Get the groupmode. It's been added to the wiki object.
921 $groupmode = groups_get_activity_groupmode($wiki);
923 /// If there is a groupmode, get the user's group id.
924 if ($groupmode and $groupid == 0) {
925 $mygroupid = mygroupid($course->id);
926 $groupid = $mygroupid[0]/*mygroupid($course->id)*/;
929 $wiki_entry->wikiid = $wiki->id;
930 $wiki_entry->course = $wiki->course;
931 $wiki_entry->groupid = $groupid;
932 $wiki_entry->pagename = wiki_page_name($wiki);
933 $wiki_entry->timemodified = time();
934 break;
936 $wiki_entry->pagename = addslashes($wiki_entry->pagename);
938 return insert_record("wiki_entries", $wiki_entry, true);
941 function wiki_can_add_entry(&$wiki, &$user, &$course, $userid=0, $groupid=0) {
942 /// Returns true or false if the user can add a wiki entry for this wiki.
944 /// Get the groupmode. It's been added to the wiki object.
945 $groupmode = groups_get_activity_groupmode($wiki);
946 $mygroupid = mygroupid($course->id);
948 switch ($wiki->wtype) {
950 case 'student':
951 /// A student can create their own wiki, if they are a member of that course.
952 /// A user can create their own wiki at the site level.
953 if ($userid == 0) {
954 return (wiki_is_student($wiki, $user->id) or wiki_is_student($wiki, $user->id));
956 /// An editing teacher can create any student wiki, or
957 /// a non-editing teacher, if not assigned to a group can create any student wiki, or if assigned to a group can
958 /// create any student wiki in their group.
959 else {
960 return ((($userid == $user->id) and wiki_is_student($wiki, $user->id)) or wiki_is_teacheredit($wiki) or
961 (wiki_is_teacher($wiki) and (!$groupmode or $mygroupid == 0 or (groups_is_member($mygroupid, $userid)))));
963 break;
965 case 'group':
966 /// If mode is 'nogroups', then all participants can add wikis.
967 if (wiki_is_teacheredit($wiki, $user->id)) {
968 return true;
971 if (!$groupmode) {
972 return (wiki_is_student($wiki, $user->id) or wiki_is_teacher($wiki, $user->id));
974 /// If not requesting a group, must be a member of a group.
975 else if ($groupid == 0) {
976 return ($mygroupid != 0);
978 /// If requesting a group, must be an editing teacher, a non-editing teacher with no assigned group,
979 /// or a non-editing teacher requesting their group. or a student in group, but wiki is empty.
980 else {
981 return (wiki_is_teacheredit($wiki) or
982 (wiki_is_teacher($wiki) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))) or
983 (wiki_is_student($wiki, $user->id) and @in_array($groupid, $mygroupid))
986 break;
988 case 'teacher':
989 /// If mode is 'nogroups', then all teachers can add wikis.
990 if (!$groupmode) {
991 return wiki_is_teacher($wiki, $user->id);
993 /// If not requesting a group, must be a member of a group.
994 else if ($groupid == 0) {
995 return ($mygroupid != 0 and wiki_is_teacher($wiki));
997 /// If there is a group mode, non-editing teachers with an assigned group, can only create wikis
998 /// in their group. Non-editing teachers with no assigned group and editing teachers can create any wiki.
999 else {
1000 return (wiki_is_teacheredit($wiki) or
1001 (wiki_is_teacher($wiki) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))));
1003 break;
1006 return false;
1009 function wiki_can_edit_entry(&$wiki_entry, &$wiki, &$user, &$course) {
1010 /// Returns true or false if the user can edit this wiki entry.
1012 $can_edit = false;
1013 $groupmode = groups_get_activity_groupmode($wiki);
1014 $mygroupid = mygroupid($course->id);
1016 /// Editing teacher's and admins can edit all wikis, non-editing teachers can edit wikis in their groups,
1017 /// or all wikis if group mode is 'no groups' or they don't belong to a group.
1018 if (wiki_is_teacheredit($wiki, $user->id) or
1019 ((!$groupmode or $mygroupid == 0) and wiki_is_teacher($wiki, $user->id))) {
1020 $can_edit = true;
1022 else {
1023 switch ($wiki->wtype) {
1025 /// Only a teacher or the owner of a student wiki can edit it.
1026 case 'student':
1027 $can_edit = (($user->id == $wiki_entry->userid) or
1028 ($groupmode and wiki_is_teacher($wiki, $user->id) and
1029 groups_is_member($mygroupid, $wiki_entry->userid)));
1030 break;
1032 case 'group':
1033 /// If there is a groupmode, determine the user's group status.
1034 if ($groupmode) {
1035 /// If the user is a member of the wiki group, they can edit the wiki.
1036 $can_edit = groups_is_member($wiki_entry->groupid, $user->id);
1038 /// If mode is 'nogroups', then all participants can edit the wiki.
1039 else {
1040 $can_edit = (wiki_is_student($wiki, $user->id) or wiki_is_teacher($wiki, $user->id));
1042 break;
1044 case 'teacher':
1045 /// If there is a groupmode, determine the user's group status.
1046 if ($groupmode) {
1047 /// If the user is a member of the wiki group, they can edit the wiki.
1048 $can_edit = (wiki_is_teacher($wiki, $user->id) and groups_is_member($wiki_entry->groupid, $user->id));
1050 else {
1051 $can_edit = wiki_is_teacher($wiki, $user->id);
1053 break;
1056 return $can_edit;
1059 function wiki_user_can_access_student_wiki(&$wiki, $userid, &$course) {
1060 global $USER;
1062 /// Get the groupmode. It's been added to the wiki object.
1063 $groupmode = groups_get_activity_groupmode($wiki);
1064 $usersgroup = mygroupid($course->id);
1065 $isteacher = wiki_is_teacher($wiki, $USER->id);
1067 /// If this user is allowed to access this wiki then return TRUE.
1068 /// *** THIS COULD BE A PROBLEM, IF STUDENTS COULD EVER BE PART OF MORE THAN ONE GROUP ***
1069 /// A user can access a student wiki, if:
1070 /// - it is their wiki,
1071 /// - group mode is VISIBLEGROUPS,
1072 /// - group mode is SEPARATEGROUPS, and the user is a member of the requested user's group,
1073 /// - they are an editing teacher or administrator,
1074 /// - they are a non-editing teacher not assigned to a specific group,
1075 /// - they are a non-editing teacher and group mode is NOGROUPS.
1076 /// - they are an administrator (mostly for site-level wikis).
1077 if (($userid and ($USER->id == $userid)) or ($groupmode == VISIBLEGROUPS) or
1078 (($groupmode == SEPARATEGROUPS) and groups_is_member($usersgroup, $userid)) or
1079 (wiki_is_teacheredit($wiki, $USER->id)) or
1080 (wiki_is_teacher($wiki, $USER->id) and (!$usersgroup or $groupmode == NOGROUPS))) {
1081 $can_access = true;
1083 else {
1084 $can_access = false;
1086 return $can_access;
1089 function wiki_user_can_access_group_wiki(&$wiki, $groupid, &$course) {
1090 global $USER;
1092 /// Get the groupmode. It's been added to the wiki object.
1093 $groupmode = groups_get_activity_groupmode($wiki);
1094 $usersgroup = mygroupid($course->id);
1095 $isteacher = wiki_is_teacher($wiki, $USER->id);
1097 /// A user can access a group wiki, if:
1098 /// - group mode is NOGROUPS,
1099 /// - group mode is VISIBLEGROUPS,
1100 /// - group mode is SEPARATEGROUPS, and they are a member of the requested group,
1101 /// - they are an editing teacher or administrator,
1102 /// - they are a non-editing teacher not assigned to a specific group.
1103 if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or
1104 (($groupmode == SEPARATEGROUPS) and @in_array($groupid, $usersgroup)/*($usersgroup == $groupid)*/) or
1105 (wiki_is_teacheredit($wiki, $USER->id)) or
1106 (wiki_is_teacher($wiki, $USER->id) and !$usersgroup)) {
1107 $can_access = true;
1109 else {
1110 $can_access = false;
1112 return $can_access;
1115 function wiki_user_can_access_teacher_wiki(&$wiki, $groupid, &$course) {
1116 global $USER;
1118 /// Get the groupmode. It's been added to the wiki object.
1119 $groupmode = groups_get_activity_groupmode($wiki);
1121 /// A user can access a teacher wiki, if:
1122 /// - group mode is NOGROUPS,
1123 /// - group mode is VISIBLEGROUPS,
1124 /// - group mode is SEPARATEGROUPS, and they are a member of the requested group,
1125 /// - they are a teacher or administrator,
1126 if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or
1127 (($groupmode == SEPARATEGROUPS) and (@in_array($groupid, mygroupid($course->id))/*mygroupid($course->id) == $groupid*/)) or
1128 (wiki_is_teacher($wiki, $USER->id))){
1129 $can_access = true;
1131 else {
1132 $can_access = false;
1134 return $can_access;
1137 function wiki_get_owner(&$wiki_entry) {
1138 if ($wiki_entry->userid > 0) {
1139 $user = get_record('user', 'id', $wiki_entry->userid);
1140 $owner = fullname($user);
1142 else if ($wiki_entry->groupid > 0) {
1143 $owner = groups_get_group_name($wiki_entry->groupid); //TODO:check.
1145 else if ($wiki_entry->course > 0) {
1146 $course = get_record('course', 'id', $wiki_entry->course);
1147 $owner = $course->shortname;
1149 else {
1150 $owner = '- '.get_string("ownerunknown","wiki").' -';
1152 return $owner;
1155 function wiki_print_search_form($cmid, $search="", $userid, $groupid, $return=false) {
1156 global $CFG;
1157 # TODO: Add Group and User !!!
1158 $output = "<form id=\"search\" action=\"$CFG->wwwroot/mod/wiki/view.php\">";
1159 $output .="<fieldset class='invisiblefieldset'>";
1160 $output .= "<span style='font-size:0.6em;'>";
1161 $output .= "<input value=\"".get_string("searchwiki", "wiki").":\" type=\"submit\" />";
1162 $output .= "<input name=\"id\" type=\"hidden\" value=\"$cmid\" />";
1163 $output = $output.($groupid?"<input name=\"groupid\" type=\"hidden\" value=\"$groupid\" />":"");
1164 $output = $output.($userid?"<input name=\"userid\" type=\"hidden\" value=\"$userid\" />":"");
1165 $output .= "<input name=\"q\" type=\"text\" size=\"20\" value=\"".s($search)."\" />".' ';
1166 $output .= "</span>";
1167 $output .= "<input name=\"page\" type=\"hidden\" value=\"SearchPages\" />";
1168 $output .= "</fieldset>";
1169 $output .= "</form>";
1171 if ($return) {
1172 return $output;
1174 echo $output;
1177 function wiki_print_wikilinks_block($cmid, $binary=false, $return=false) {
1178 /// Prints a link-list of special wiki-pages
1179 global $CFG, $ewiki_title;
1181 $links=array();
1183 $links["SiteMap"]=get_string("sitemap", "wiki");
1184 $links["PageIndex"]=get_string("pageindex", "wiki");
1185 $links["NewestPages"]=get_string("newestpages", "wiki");
1186 $links["MostVisitedPages"]=get_string("mostvisitedpages", "wiki");
1187 $links["MostOftenChangedPages"]=get_string("mostoftenchangedpages", "wiki");
1188 $links["UpdatedPages"]=get_string("updatedpages", "wiki");
1189 $links["OrphanedPages"]=get_string("orphanedpages", "wiki");
1190 $links["WantedPages"]=get_string("wantedpages", "wiki");
1191 $links["WikiExport"]=get_string("wikiexport", "wiki");
1192 if($binary) {
1193 $links["FileDownload"]=get_string("filedownload", "wiki");
1195 popup_form(EWIKI_SCRIPT, $links, "wikilinks", "", get_string("choosewikilinks", "wiki"), "", "", $return);
1198 function wiki_print_page_actions($cmid, $specialpages, $page, $action, $binary=false, $canedit=true) {
1199 /// Displays actions which can be performed on the page
1201 $page=array();
1203 // Edit this Page
1204 if (in_array($action, array("edit", "links", "info", "attachments"))) {
1205 $page["view/$page"]=get_string("viewpage","wiki");
1207 if ($canedit && !in_array($page, $specialpages) && $action != "edit") {
1208 $page["edit/$page"]=get_string("editthispage","wiki");
1210 if ($action != "links") {
1211 $page["links/$page"]=get_string("backlinks","wiki");
1213 if ($canedit && !in_array($page, $specialpages) && $action!="info") {
1214 $page["info/$page"]=get_string("pageinfo","wiki");
1216 if($canedit && $binary && !in_array($page, $specialpages) && $action != "attachments") {
1217 $page["attachments/$page"]=get_string("attachments","wiki");
1220 popup_form(EWIKI_SCRIPT, $page, "wikiactions", "", get_string("action", "wiki"), "", "", false);
1223 function wiki_print_administration_actions($wiki, $cmid, $userid, $groupid, $page, $noeditor, $course) {
1224 /// Displays actions which can be performed on the page
1226 /// Create the URL
1227 $ewscript = 'admin.php?id='.$cmid;
1228 if (isset($userid) && $userid!=0) $ewscript .= '&amp;userid='.$userid;
1229 if (isset($groupid) && $groupid!=0) $ewscript .= '&amp;groupid='.$groupid;
1230 if (isset($page)) $ewscript .= '&amp;page='.$page;
1231 $ewscript.="&amp;action=";
1234 /// Build that action array according to wiki flags.
1235 $action = array();
1236 $isteacher = wiki_is_teacher($wiki);
1238 if ($wiki->setpageflags or $isteacher) {
1239 $action['setpageflags'] = get_string('setpageflags', 'wiki');
1241 if ($wiki->removepages or $isteacher) {
1242 $action['removepages'] = get_string('removepages', 'wiki');
1244 if ($wiki->strippages or $isteacher) {
1245 $action['strippages'] = get_string('strippages', 'wiki');
1247 if ($wiki->revertchanges or $isteacher) {
1248 $action['revertpages'] = get_string('revertpages', 'wiki');
1251 if($noeditor) {
1252 $action["checklinks"]=get_string("checklinks", "wiki");
1254 popup_form($ewscript, $action, "wikiadministration", "", get_string("chooseadministration", "wiki"), "", "", false);
1257 function wiki_admin_get_flagarray() {
1258 $ret = array(
1259 EWIKI_DB_F_TEXT => get_string("flagtxt","wiki"),
1260 EWIKI_DB_F_BINARY => get_string("flagbin","wiki"),
1261 EWIKI_DB_F_DISABLED => get_string("flagoff","wiki"),
1262 EWIKI_DB_F_HTML => get_string("flaghtm","wiki"),
1263 EWIKI_DB_F_READONLY => get_string("flagro","wiki"),
1264 EWIKI_DB_F_WRITEABLE => get_string("flagwr","wiki"),
1267 return $ret;
1270 ///////// Ewiki Administration. Mostly taken from the ewiki/tools folder and changed
1271 function wiki_admin_setpageflags_list($pageflagstatus) {
1272 $FD = wiki_admin_get_flagarray();
1273 $table = new Object();
1274 $table->head = array(get_string("pagename","wiki"), get_string("flags","wiki"));
1275 if($pageflagstatus) {
1276 $table->head[]=get_string("status","wiki");
1279 $result = ewiki_database("GETALL", array("version", "flags"));
1280 while ($row = $result->get()) {
1281 $id = $row["id"];
1282 $data = ewiki_database("GET", $row);
1284 $cell_pagename="";
1285 $cell_flags="";
1286 if ($data["flags"] & EWIKI_DB_F_TEXT) {
1287 $cell_pagename .= '<a href="' . EWIKI_SCRIPT . $id . '">';
1288 } else {
1289 $cell_pagename .= '<a href="' . EWIKI_SCRIPT_BINARY . $id . '">';
1291 $cell_pagename .= s($id) . '</a> / '.get_string("version","wiki").": ".$row["version"];
1293 foreach ($FD as $n=>$str) {
1294 $cell_flags .='<input type="checkbox" name="flags['. rawurlencode($id)
1295 . '][' . $n . ']" value="1" '
1296 . (($data["flags"] & $n) ? "checked=\"checked\"" : "")
1297 . ' />'.$str. ' ';
1299 if($pageflagstatus) {
1300 $table->data[]=array($cell_pagename, $cell_flags, $pageflagstatus[$id]);
1301 } else {
1302 $table->data[]=array($cell_pagename, $cell_flags);
1305 return $table;
1308 function wiki_admin_setpageflags($pageflags) {
1309 $FD = wiki_admin_get_flagarray();
1311 $status=array();
1312 if($pageflags) {
1313 foreach($pageflags as $page=>$fa) {
1315 $page = rawurldecode($page);
1317 $flags = 0;
1318 $fstr = "";
1319 foreach($fa as $num=>$isset) {
1320 if ($isset) {
1321 $flags += $num;
1322 $fstr .= ($fstr?",":""). $FD[$num];
1326 #$status[$page] .= "{$flags}=[{$fstr}]";
1328 $data = ewiki_database("GET", array("id" => $page));
1330 if ($data["flags"] != $flags) {
1331 $data["flags"] = $flags;
1332 $data["author"] = "ewiki-tools, " . ewiki_author();
1333 $data["version"]++;
1334 ewiki_database("WRITE", $data);
1335 $status[$page] = "<b>".get_string("flagsset","wiki")."</b> ".$status[$page];
1339 return $status;
1343 function wiki_admin_remove_list($listall="") {
1344 /// Table header
1345 $table = new Object();
1346 $table->head = array("&nbsp;", get_string("pagename","wiki"), get_string("errororreason","wiki"));
1348 /// Get all pages
1349 $result = ewiki_database("GETALL", array("version"));
1350 $selected = array();
1352 /// User wants to see all pages
1353 if ($listall) {
1354 while ($row = $result->get()) {
1355 $selected[$row["id"]] = get_string("listall","wiki")."<br />";
1358 while ($page = $result->get()) {
1359 $id = $page["id"];
1360 $page = ewiki_database("GET", array("id"=>$id));
1361 $flags = $page["flags"];
1362 #print "$id ".strlen(trim(($page["content"])))."<br />";
1364 if (!strlen(trim(($page["content"]))) && !($flags & EWIKI_DB_F_BINARY)) {
1365 @$selected[$id] .= get_string("emptypage","wiki")."<br />";
1368 // Check for orphaned pages
1369 $result2 = ewiki_database("SEARCH", array("content" => $id));
1370 $orphanedpage=true;
1371 if ($result2 && $result2->count()) {
1372 while ($row = $result2->get()) {
1373 $checkcontent = ewiki_database("GET", array("id"=>$row["id"]));
1374 $checkcontent = strtolower($checkcontent["content"]);
1376 if(strpos($checkcontent, strtolower($id)) !== false) {
1377 $orphanedpage=false;
1380 #echo "rc({$row['id']})==>($id): $check2 <br />";
1384 /// Some more reasons for Deletion...
1385 if ($orphanedpage && $id!=EWIKI_PAGE_INDEX &&!($flags & EWIKI_DB_F_BINARY)) {
1386 @$selected[$id] .= get_string("orphanedpage","wiki")."<br />";
1389 if ($flags & EWIKI_DB_F_DISABLED) {
1390 @$selected[$id] .= get_string("disabledpage","wiki")."<br />";
1393 if (($flags & 3) == 3) {
1394 @$selected[$id] .= get_string("errorbinandtxt","wiki")."<br />";
1397 if (!($flags & 3)) {
1398 @$selected[$id] .= get_string("errornotype","wiki")."<br />";
1401 if ($flags & EWIKI_DB_F_HTML) {
1402 @$selected[$id] .= get_string("errorhtml","wiki")."<br />";
1405 if (($flags & EWIKI_DB_F_READONLY) && !($flags & EWIKI_DB_F_BINARY)) {
1406 @$selected[$id] .= get_string("readonly","wiki")."<br />";
1409 if (($flags & EWIKI_DB_F_READONLY) && ($flags & EWIKI_DB_F_WRITEABLE)) {
1410 @$selected[$id] .= get_string("errorroandwr","wiki")."<br />";
1413 if (strlen($page["content"]) >= 65536) {
1414 @$selected[$id] .= get_string("errorsize","wiki")."<br />";
1417 if (strpos($page["refs"], "\n".get_string("deletemewikiword","wiki")."\n")!==false) {
1418 @$selected[$id] .= get_string("deletemewikiwordfound","wiki",get_string("deletemewikiword","wiki"))."<br />";
1422 foreach ($selected as $id => $reason) {
1423 $table_checkbox='<input type="checkbox" value="'.rawurlencode($id).'" name="pagestodelete[]" />';
1425 #-- link & id
1426 if (strpos($id, EWIKI_IDF_INTERNAL) === false) {
1427 $table_page='<a href="' . ewiki_script("", $id) . '">';
1428 } else {
1429 $table_page='<a href="' . ewiki_script_binary("", $id) . '">';
1431 $table_page .= s($id) . '</a>';
1433 #-- print reason
1434 $table_reason=$reason;
1436 $table->data[]=array($table_checkbox, $table_page, $table_reason);
1439 return $table;
1442 /// This function actually removes the pages
1443 function wiki_admin_remove($pagestodelete, $course, $wiki, $userid, $groupid) {
1444 $ret="";
1445 foreach ($pagestodelete as $id) {
1447 $id = rawurldecode($id);
1449 $data = ewiki_database("GET", array("id"=>$id));
1450 for ($version=1; $version<=$data["version"]; $version++) {
1451 ewiki_database("DELETE", array("id"=>$id, "version"=>$version));
1452 if($data["flags"] & EWIKI_DB_F_BINARY) {
1453 $filepath=moodle_binary_get_path($id, $data["meta"], $course, $wiki, $userid, $groupid);
1454 @unlink("$filepath");
1459 return $ret;
1462 function wiki_admin_strip_list($pagestostrip="",$version="",$err="") {
1463 /// Table header
1464 $table = new Object();
1465 $table->head = array("&nbsp;", get_string("pagename","wiki"), get_string("deleteversions","wiki"));
1467 $vc=ewiki_database("COUNTVERSIONS", array());
1468 $result = ewiki_database("GETALL",array());
1469 $i=0;
1470 while ($row = $result->get()) {
1471 $id = $row["id"];
1472 if($vc[$id]>1) {
1473 $error="";
1474 if($err[$id]) {
1475 $error=" ".join(", ",$err[$id]);
1477 $checked="";
1478 if($pagestostrip=="" || $pagestostrip[$i]) {
1479 $checked=" checked=\"checked\"";
1481 if($version=="") {
1482 $versiondefault="1-".($row["version"]-1);
1483 } else {
1484 $versiondefault=$version[$i];
1486 $table->data[]=array('<input type="checkbox" value="'.rawurlencode($id).'" name="pagestostrip['.$i.']" '.$checked.' />',
1487 '<A HREF="'.EWIKI_SCRIPT.$id.'">'.s($id).'</A> / '.get_string("version","wiki").": ".$row["version"],
1488 '<input name="version['.$i.']" value="'.$versiondefault.'" size="7" />'.$error);
1491 $i++;
1493 return $table;
1496 function wiki_admin_strip_versions($pagestostrip, $version, &$err) {
1497 $ret=array();
1498 foreach ($pagestostrip as $key => $id_ue) {
1500 $id = rawurldecode($id_ue);
1501 if (preg_match('/^(\d+)[-\s._:]+(\d+)$/', trim($version[$key]), $uu)) {
1502 $versA = $uu[1];
1503 $versZ = $uu[2];
1505 // Let the last Version in the database
1506 $checkdata = ewiki_database("GET", array("id" => $id));
1507 if($versZ>=$checkdata["version"]) {
1508 $err[$id][] = get_string("versionrangetoobig","wiki");
1509 } else {
1510 if($versA<=$versZ) {
1511 for ($v=$versA; $v<=$versZ; $v++) {
1512 $ret[$id][]=$v;
1514 } else {
1515 $err[$id][]=get_string("wrongversionrange","wiki",$version[$key]);
1519 else {
1520 $err[$id][]=get_string("wrongversionrange","wiki",$version[$key]);
1523 return $ret;
1526 function wiki_admin_strip($pagestostrip) {
1527 /// Purges old page-versions
1528 foreach($pagestostrip as $id => $versions) {
1529 foreach($versions as $version) {
1530 ewiki_database("DELETE", array("id"=>$id, "version"=>$version));
1535 function wiki_admin_checklinks_list() {
1536 $ret=array();
1537 $result = ewiki_database("GETALL",array());
1538 while ($row = $result->get()) {
1539 if(!($row["flags"] & EWIKI_DB_F_BINARY)) {
1540 $index=s($row["id"]);
1541 $ret[$index] = $row["id"];
1544 return $ret;
1547 function wiki_admin_checklinks($pagetocheck) {
1548 /// Checks http:// Links
1549 $ret="";
1550 if($pagetocheck) {
1551 $get = ewiki_database("GET", array("id" => $pagetocheck));
1552 $content = $get["content"];
1554 preg_match_all('_(http.?://[^\s"\'<>#,;]+[^\s"\'<>#,;.])_', $content, $links);
1555 $badlinks = array();
1556 if(!$links[1]) {
1557 $ret = get_string("nolinksfound","wiki")."<br /><br />";
1558 } else {
1559 foreach ($links[1] as $href) {
1560 #print "[ $href ]";
1561 #$d = @implode("", @file($href));
1562 $d="";
1563 if($checkfd = @fopen($href, 'r')) {
1564 fclose($checkfd);
1565 $d="OK";
1567 if (empty($d) || !strlen(trim($d)) || stristr("not found", $d) || stristr("error 404", $d)) {
1568 $ret.="[".get_string("linkdead","wiki")."] $href <br />\n";
1569 $badlinks[] = $href;
1570 } else {
1571 $ret.="[".get_string("linkok","wiki")."] $href <br />\n";
1576 /// Remove old Notices
1577 $content = eregi_replace(' µµ__~\['.get_string("offline","wiki").'\]__µµ ','', $content);
1579 #-- replace dead links
1580 foreach ($badlinks as $href) {
1581 $content = preg_replace("\377^(.*)($href)\377m", '$1 µµ__~['.get_string("offline","wiki").']__µµ $2', $content);
1584 #-- compare against db content
1585 if ($content != $get["content"]) {
1586 $get["content"] = $content;
1587 $get["version"]++;
1588 $get["author"] = ewiki_author("ewiki_checklinks");
1589 $get["lastmodified"] = time();
1591 ewiki_database("WRITE", $get);
1594 return $ret;
1597 function wiki_admin_revert($proceed, $authorfieldpattern, $changesfield, $howtooperate, $deleteversions) {
1598 $ret="";
1599 #-- params
1600 $m_time = $changesfield * 3600;
1601 $depth = $deleteversions - 1;
1602 $depth = ($depth>0?$depth:0);
1604 #-- walk through
1605 $result = ewiki_database("GETALL", array("id", "author", "lastmodified"));
1606 while ($row = $result->get()) {
1607 $id = $row["id"];
1608 #-- which versions to check
1609 $verZ = $row["version"];
1610 if ($howtooperate=="lastonly") {
1611 $verA = $verZ;
1613 else {
1614 $verA = $verZ-$depth;
1615 if ($verA <= 0) {
1616 $verA = 1;
1620 for ($ver=$verA; $ver<=$verZ; $ver++) {
1621 #-- load current $ver database entry
1622 if ($verA != $verZ) {
1623 $row = ewiki_database("GET", array("id"=>$id, "version"=>$ver));
1626 #-- match
1627 if (stristr($row["author"], $authorfieldpattern) && ($row["lastmodified"] + $m_time > time())) {
1628 $ret .= "$id (".get_string("versionstodelete","wiki").": ";
1629 #-- delete multiple versions
1630 if ($howtooperate=="allsince") {
1631 while ($ver<=$verZ) {
1632 $ret .= " $ver";
1633 if ($proceed) {
1634 ewiki_database("DELETE", array("id"=>$id, "version"=>$ver));
1636 $ver++;
1639 #-- or just the affected one
1640 else {
1641 $ret .= " $ver";
1642 if ($proceed) {
1643 ewiki_database("DELETE", $row);
1646 $ret .= ")<br />";
1647 break;
1649 } #-- for($ver)
1650 } #-- while($row)
1651 return $ret;
1655 function wiki_get_view_actions() {
1656 return array('view','view all');
1659 function wiki_get_post_actions() {
1660 return array('hack');
1665 * Obtains an editing lock on a wiki page.
1666 * @param int $wikiid ID of wiki object.
1667 * @param string $pagename Name of page.
1668 * @return array Two-element array with a boolean true (if lock has been obtained)
1669 * or false (if lock was held by somebody else). If lock was held by someone else,
1670 * the values of the wiki_locks entry are held in the second element; if lock was
1671 * held by current user then the the second element has a member ->id only.
1673 function wiki_obtain_lock($wikiid,$pagename) {
1674 global $USER;
1676 // Check for lock
1677 $alreadyownlock=false;
1678 if($lock=get_record('wiki_locks','pagename',$pagename,'wikiid', $wikiid)) {
1679 // Consider the page locked if the lock has been confirmed within WIKI_LOCK_PERSISTENCE seconds
1680 if($lock->lockedby==$USER->id) {
1681 // Cool, it's our lock, do nothing except remember it in session
1682 $lockid=$lock->id;
1683 $alreadyownlock=true;
1684 } else if(time()-$lock->lockedseen < WIKI_LOCK_PERSISTENCE) {
1685 return array(false,$lock);
1686 } else {
1687 // Not locked any more. Get rid of the old lock record.
1688 if(!delete_records('wiki_locks','pagename',$pagename,'wikiid', $wikiid)) {
1689 error('Unable to delete lock record');
1694 // Add lock
1695 if(!$alreadyownlock) {
1696 // Lock page
1697 $newlock=new stdClass;
1698 $newlock->lockedby=$USER->id;
1699 $newlock->lockedsince=time();
1700 $newlock->lockedseen=$newlock->lockedsince;
1701 $newlock->wikiid=$wikiid;
1702 $newlock->pagename=$pagename;
1703 if(!$lockid=insert_record('wiki_locks',$newlock)) {
1704 error('Unable to insert lock record');
1708 // Store lock information in session so we can clear it later
1709 if(!array_key_exists(SESSION_WIKI_LOCKS,$_SESSION)) {
1710 $_SESSION[SESSION_WIKI_LOCKS]=array();
1712 $_SESSION[SESSION_WIKI_LOCKS][$wikiid.'_'.$pagename]=$lockid;
1713 $lockdata=new StdClass;
1714 $lockdata->id=$lockid;
1715 return array(true,$lockdata);
1719 * If the user has an editing lock, releases it. Has no effect otherwise.
1720 * Note that it doesn't matter if this isn't called (as happens if their
1721 * browser crashes or something) since locks time out anyway. This is just
1722 * to avoid confusion of the 'what? it says I'm editing that page but I'm
1723 * not, I just saved it!' variety.
1724 * @param int $wikiid ID of wiki object.
1725 * @param string $pagename Name of page.
1727 function wiki_release_lock($wikiid,$pagename) {
1728 if(!array_key_exists(SESSION_WIKI_LOCKS,$_SESSION)) {
1729 // No locks at all in session
1730 return;
1733 $key=$wikiid.'_'.$pagename;
1735 if(array_key_exists($key,$_SESSION[SESSION_WIKI_LOCKS])) {
1736 $lockid=$_SESSION[SESSION_WIKI_LOCKS][$key];
1737 unset($_SESSION[SESSION_WIKI_LOCKS][$key]);
1738 if(!delete_records('wiki_locks','id',$lockid)) {
1739 error("Unable to delete lock record.");