MDL-9716
[moodle-linuxchix.git] / mod / wiki / lib.php
blob251970565252fd449cd9004cfff77bfd84217774
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;
180 if (!$logs = get_records_select('log', 'time > \''.$timestart.'\' AND '.
181 'course = \''.$course->id.'\' AND '.
182 'module = \'wiki\' AND '.
183 'action LIKE \'edit%\' ', 'time ASC')){
184 return false;
187 foreach ($logs as $log) {
188 //Create a temp valid module structure (course,id)
189 $tempmod = new Object();
190 $tempmod->course = $log->course;
191 $tempmod->id = $log->cmid;
192 //Obtain the visible property from the instance
193 $modvisible = instance_is_visible($log->module,$tempmod);
195 //Only if the mod is visible
196 if ($modvisible) {
197 $wikis[$log->info] = wiki_log_info($log);
198 $wikis[$log->info]->pagename = $log->info;
199 $wikis[$log->info]->time = $log->time;
200 $wikis[$log->info]->url = str_replace('&', '&amp;', $log->url);
204 if ($wikis) {
205 $content = true;
206 print_headline(get_string('updatedwikipages', 'wiki').':', 3);
207 foreach ($wikis as $wiki) {
208 print_recent_activity_note($wiki->time, $wiki, $wiki->pagename,
209 $CFG->wwwroot.'/mod/wiki/'.$wiki->url);
212 return true; // True if anything was printed, otherwise false
215 function wiki_log_info($log) {
216 global $CFG;
217 return get_record_sql("SELECT u.firstname, u.lastname
218 FROM {$CFG->prefix}user u
219 WHERE u.id = '$log->userid'");
222 function wiki_cron () {
223 /// Function to be run periodically according to the moodle cron
224 /// This function searches for things that need to be done, such
225 /// as sending out mail, toggling flags etc ...
227 // Delete expired locks
228 $result=delete_records_select('wiki_locks','lockedseen < '.(time()-WIKI_LOCK_PERSISTENCE));
230 return $result;
233 function wiki_grades($wikiid) {
234 /// Must return an array of grades for a given instance of this module,
235 /// indexed by user. It also returns a maximum allowed grade.
237 return NULL;
240 function wiki_get_participants($wikiid) {
241 //Returns the users with data in one wiki
242 //(users with records in wiki_pages and wiki_entries)
244 global $CFG;
246 //Get users from wiki_pages
247 $st_pages = get_records_sql("SELECT DISTINCT u.id, u.id
248 FROM {$CFG->prefix}user u,
249 {$CFG->prefix}wiki_entries e,
250 {$CFG->prefix}wiki_pages p
251 WHERE e.wikiid = '$wikiid' and
252 p.wiki = e.id and
253 u.id = p.userid");
255 //Get users from wiki_entries
256 $st_entries = get_records_sql("SELECT DISTINCT u.id, u.id
257 FROM {$CFG->prefix}user u,
258 {$CFG->prefix}wiki_entries e
259 WHERE e.wikiid = '$wikiid' and
260 u.id = e.userid");
262 //Add entries to pages
263 if ($st_entries) {
264 foreach ($st_entries as $st_entry) {
265 $st_pages[$st_entry->id] = $st_entry;
269 return $st_pages;
273 //////////////////////////////////////////////////////////////////////////////////////
274 /// Any other wiki functions go here. Each of them must have a name that
275 /// starts with wiki_
277 function wiki_wiki_name($wikiname) {
278 /// Return the passed in string in Wiki name format.
279 /// Remove any leading and trailing whitespace, capitalize all the words
280 /// and then remove any internal whitespace.
282 if (wiki_is_wiki_name($wikiname)) {
283 return $wikiname;
285 else {
286 /// Create uppercase words and remove whitespace.
287 $wikiname = preg_replace("/(\w+)\s/", "$1", ucwords(trim($wikiname)));
289 /// Check again - there may only be one word.
290 if (wiki_is_wiki_name($wikiname)) {
291 return $wikiname;
293 /// If there is only one word, append default wiki name to it.
294 else {
295 return $wikiname.get_string('wikidefaultpagename', 'wiki');
300 function wiki_is_wiki_name($wikiname) {
301 /// Check for correct wikiname syntax and return true or false.
303 /// If there are spaces between the words, incorrect format.
304 if (preg_match_all('/\w+/', $wikiname, $out) > 1) {
305 return false;
307 /// If there isn't more than one group of uppercase letters separated by
308 /// lowercase letters or '_', incorrect format.
309 else if (preg_match_all('/[A-Z]+[a-z_]+/', $wikiname, $out) > 1) {
310 return true;
312 else {
313 return false;
317 function wiki_page_name(&$wiki) {
318 /// Determines the wiki's page name and returns it.
319 if (!empty($wiki->initialcontent)) {
320 $ppos = strrpos($wiki->initialcontent, '/');
321 if ($ppos === false) {
322 $pagename = $wiki->initialcontent;
324 else {
325 $pagename = substr($wiki->initialcontent, $ppos+1);
328 else if (!empty($wiki->pagename)) {
329 $pagename = $wiki->pagename;
331 else {
332 $pagename = $wiki->name;
334 return $pagename;
337 function wiki_content_dir(&$wiki) {
338 /// Determines the wiki's default content directory (if there is one).
339 global $CFG;
341 if (!empty($wiki->initialcontent)) {
342 $ppos = strrpos($wiki->initialcontent, '/');
343 if ($ppos === false) {
344 $subdir = '';
346 else {
347 $subdir = substr($wiki->initialcontent, 0, $ppos+1);
349 $contentdir = $CFG->dataroot.'/'.$wiki->course.'/'.$subdir;
351 else {
352 $contentdir = false;
354 return $contentdir;
357 function wiki_get_course_wikis($courseid, $wtype='*') {
358 /// Returns all wikis for the specified course and optionally of the specified type.
360 $select = 'course = '.$courseid;
361 if ($wtype != '*') {
362 $select .= ' AND wtype = \''.$wtype.'\'';
364 return get_records_select('wiki', $select, 'id');
367 function wiki_has_entries(&$wiki) {
368 /// Returns true if wiki already has wiki entries; otherwise false.
370 return record_exists('wiki_entries', 'wikiid', $wiki->id);
373 function wiki_get_entries(&$wiki, $byindex=NULL) {
374 /// Returns an array with all wiki entries indexed by entry id; false if there are none.
375 /// If the optional $byindex is specified, returns the entries indexed by that field.
376 /// Valid values for $byindex are 'student', 'group'.
378 if ($byindex == 'student') {
379 return get_records('wiki_entries', 'wikiid', $wiki->id, '',
380 'userid,id,wikiid,course,groupid,pagename,timemodified');
382 else if ($byindex == 'group') {
383 return get_records('wiki_entries', 'wikiid', $wiki->id, '',
384 'groupid,id,wikiid,course,userid,pagename,timemodified');
386 else {
387 return get_records('wiki_entries', 'wikiid', $wiki->id);
391 function wiki_get_default_entry(&$wiki, &$course, $userid=0, $groupid=0) {
392 /// Returns the wiki entry according to the wiki type.
393 /// Optionally, will return wiki entry for $userid student wiki, or
394 /// $groupid group or teacher wiki.
395 /// Creates one if it needs to and it can.
396 global $USER;
397 /// If there is a groupmode, get the user's group id.
398 $groupmode = groupmode($course, $wiki);
399 // if groups mode is in use and no group supplied, use the first one found
400 if ($groupmode && !$groupid) {
401 if(($mygroupids=mygroupid($course->id)) && count($mygroupids)>0) {
402 // Use first group. They ought to be able to change later
403 $groupid=$mygroupids[0];
404 } else {
405 // Whatever groups are in the course, pick one
406 $coursegroups = get_groups($course->id);
407 if(!$coursegroups || count($coursegroups)==0) {
408 error("Can't access wiki in group mode when no groups are configured for the course");
410 $unkeyed=array_values($coursegroups); // Make sure first item is index 0
411 $groupid=$unkeyed[0]->id;
415 /// If the wiki entry doesn't exist, can this user create it?
416 if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false) {
417 if (wiki_can_add_entry($wiki, $USER, $course, $userid, $groupid)) {
418 wiki_add_entry($wiki, $course, $userid, $groupid);
419 if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false) {
420 error("Could not add wiki entry.");
424 //print_object($wiki_entry);
425 return $wiki_entry;
428 function wiki_get_entry(&$wiki, &$course, $userid=0, $groupid=0) {
429 /// Returns the wiki entry according to the wiki type.
430 /// Optionally, will return wiki entry for $userid student wiki, or
431 /// $groupid group or teacher wiki.
432 global $USER;
434 switch ($wiki->wtype) {
435 case 'student':
436 /// If a specific user was requested, return it, if allowed.
437 if ($userid and wiki_user_can_access_student_wiki($wiki, $userid, $course)) {
438 $wentry = wiki_get_student_entry($wiki, $userid);
441 /// If there is no entry for this user, check if this user is a teacher.
442 else if (!$wentry = wiki_get_student_entry($wiki, $USER->id)) {
443 /* if (wiki_is_teacher($wiki, $USER->id)) {
444 /// If this user is a teacher, return the first entry.
445 if ($wentries = wiki_get_entries($wiki)) {
446 $wentry = current($wentries);
450 break;
452 case 'group':
453 /// If there is a groupmode, get the user's group id.
454 $groupmode = groupmode($course, $wiki);
455 if($groupmode) {
456 if(!$groupid) {
457 if(($mygroupids=mygroupid($course->id)) && count($mygroupids)>0) {
458 // Use first group. They ought to be able to change later
459 $groupid=$mygroupids[0];
460 } else {
461 // Whatever groups are in the course, pick one
462 $coursegroups = get_groups($course->id);
463 if(!$coursegroups || count($coursegroups)==0) {
464 error("Can't access wiki in group mode when no groups are configured for the course");
466 $unkeyed=array_values($coursegroups); // Make sure first item is index 0
467 $groupid=$unkeyed[0]->id;
471 //echo "groupid is in wiki_get_entry ".$groupid."<br />";
472 /// If a specific group was requested, return it, if allowed.
473 if ($groupid and wiki_user_can_access_group_wiki($wiki, $groupid, $course)) {
474 $wentry = wiki_get_group_entry($wiki, $groupid);
475 } else {
476 error("Cannot access any groups for this wiki");
479 /// If mode is 'nogroups', then groupid is zero.
480 else {
481 $wentry = wiki_get_group_entry($wiki, 0);
483 break;
485 case 'teacher':
486 /// If there is a groupmode, get the user's group id.
487 if (groupmode($course, $wiki)) {
488 $mygroupids = mygroupid($course->id);//same here, default to the first one
489 $groupid = $groupid ? $groupid : $mygroupids[0]/*mygroupid($course->id)*/;
492 /// If a specific group was requested, return it, if allowed.
493 if (wiki_user_can_access_teacher_wiki($wiki, $groupid, $course)) {
494 $wentry = wiki_get_teacher_entry($wiki, $groupid);
496 break;
498 return $wentry;
501 function wiki_get_teacher_entry(&$wiki, $groupid=0) {
502 /// Returns the wiki entry for the wiki teacher type.
503 return get_record('wiki_entries', 'wikiid', $wiki->id, 'course', $wiki->course, 'groupid', $groupid);
506 function wiki_get_group_entry(&$wiki, $groupid=null) {
507 /// Returns the wiki entry for the given group.
508 return get_record('wiki_entries', 'wikiid', $wiki->id, 'groupid', $groupid);
511 function wiki_get_student_entry(&$wiki, $userid=null) {
512 /// Returns the wiki entry for the given student.
513 global $USER;
515 if (is_null($userid)) {
516 $userid = $USER->id;
518 return get_record('wiki_entries', 'wikiid', $wiki->id, 'userid', $userid);
521 function wiki_get_other_wikis(&$wiki, &$user, &$course, $currentid=0) {
522 /// Returns a list of other wikis to display, depending on the type, group and user.
523 /// Returns the key containing the currently selected entry as well.
525 global $CFG, $id;
527 $wikis = false;
529 $groupmode = groupmode($course, $wiki);
530 $mygroupid = mygroupid($course->id);
531 $isteacher = wiki_is_teacher($wiki, $user->id);
532 $isteacheredit = wiki_is_teacheredit($wiki, $user->id);
534 switch ($wiki->wtype) {
536 case 'student':
537 /// Get all the existing entries for this wiki.
538 $wiki_entries = wiki_get_entries($wiki, 'student');
539 if ($isteacher and (SITEID != $course->id)) {
541 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all student
542 /// wikis, regardless of creation.
543 if ((SITEID != $course->id) and ($isteacheredit or ($groupmode == NOGROUPS))) {
545 if ($students = get_course_students($course->id)) {
546 /// Default pagename is dependent on the wiki settings.
547 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
549 foreach ($students as $student) {
551 /// If this student already has an entry, use its pagename.
552 if ($wiki_entries[$student->id]) {
553 $pagename = $wiki_entries[$student->id]->pagename;
555 else {
556 $pagename = $defpagename;
559 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
560 $wikis[$key] = fullname($student).':'.$pagename;
564 else if ($groupmode == SEPARATEGROUPS) {
566 if ($students = wiki_get_students($wiki, $mygroupid)) {
567 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
568 foreach ($students as $student) {
570 /// If this student already has an entry, use its pagename.
571 if ($wiki_entries[$student->id]) {
572 $pagename = $wiki_entries[$student->id]->pagename;
574 else {
575 $pagename = $defpagename;
578 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
579 $wikis[$key] = fullname($student).':'.$pagename;
583 else if ($groupmode == VISIBLEGROUPS) {
584 /// Get all students in your group.
585 if ($students = wiki_get_students($wiki, $mygroupid)) {
586 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
587 foreach ($students as $student) {
588 /// If this student already has an entry, use its pagename.
589 if ($wiki_entries[$student->id]) {
590 $pagename = $wiki_entries[$student->id]->pagename;
592 else {
593 $pagename = $defpagename;
595 $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
596 $wikis[$key] = fullname($student).':'.$pagename;
599 /// Get all student wikis created, regardless of group.
600 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
601 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'user u '
602 .' WHERE w.wikiid = '.$wiki->id.' AND u.id = w.userid '
603 .' ORDER BY w.id';
604 $wiki_entries = get_records_sql($sql);
605 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
606 foreach ($wiki_entries as $wiki_entry) {
607 $key = 'view.php?id='.$id.'&userid='.$wiki_entry->userid.'&page='.$wiki_entry->pagename;
608 $wikis[$key] = fullname($wiki_entry).':'.$wiki_entry->pagename;
609 if ($currentid == $wiki_entry->id) {
610 $wikis['selected'] = $key;
615 else {
616 /// A user can see other student wikis if they are a member of the same
617 /// group (for separate groups) or there are visible groups, or if this is
618 /// a site-level wiki, and they are an administrator.
619 if (($groupmode == VISIBLEGROUPS) or wiki_is_teacheredit($wiki)) {
620 $viewall = true;
622 else if ($groupmode == SEPARATEGROUPS) {
623 $viewall = mygroupid($course->id);
625 else {
626 $viewall = false;
629 if ($viewall !== false) {
631 $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
632 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'user u '
633 .' WHERE w.wikiid = '.$wiki->id.' AND u.id = w.userid '
634 .' ORDER BY w.id';
635 $wiki_entries = get_records_sql($sql);
636 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
637 foreach ($wiki_entries as $wiki_entry) {
638 if (($viewall === true) or ismember($viewall, $wiki_entry->userid)) {
639 $key = 'view.php?id='.$id.'&userid='.$wiki_entry->userid.'&page='.$wiki_entry->pagename;
640 $wikis[$key] = fullname($wiki_entry).':'.$wiki_entry->pagename;
641 if ($currentid == $wiki_entry->id) {
642 $wikis['selected'] = $key;
648 break;
650 case 'group':
651 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all group
652 /// wikis, regardless of creation.
654 /// If user is a member of multiple groups, need to show current group etc?
656 /// Get all the existing entries for this wiki.
657 $wiki_entries = wiki_get_entries($wiki, 'group');
659 if ($groupmode and ($isteacheredit or ($isteacher and !$mygroupid))) {
660 if ($groups = get_groups($course->id)) {
661 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
662 foreach ($groups as $group) {
664 /// If this group already has an entry, use its pagename.
665 if (isset($wiki_entries[$group->id])) {
666 $pagename = $wiki_entries[$group->id]->pagename;
668 else {
669 $pagename = $defpagename;
672 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
673 $wikis[$key] = $group->name.':'.$pagename;
677 //if a studnet with multiple groups in SPG
678 else if ($groupmode == SEPARATEGROUPS){
679 if ($groups = get_groups($course->id, $user->id)){
681 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
682 foreach ($groups as $group) {
683 /// If this group already has an entry, use its pagename.
684 if (isset($wiki_entries[$group->id])) {
685 $pagename = $wiki_entries[$group->id]->pagename;
687 else {
688 $pagename = $defpagename;
690 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
691 $wikis[$key] = $group->name.':'.$pagename;
697 /// A user can see other group wikis if there are visible groups.
698 else if ($groupmode == VISIBLEGROUPS) {
699 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
700 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
701 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
702 .' ORDER BY w.groupid';
703 $wiki_entries = get_records_sql($sql);
704 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
705 foreach ($wiki_entries as $wiki_entry) {
706 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
707 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
708 if ($currentid == $wiki_entry->id) {
709 $wikis['selected'] = $key;
713 break;
715 case 'teacher':
716 if ($isteacher) {
717 /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all
718 /// teacher wikis, regardless of creation.
719 if ($groupmode and ($isteacheredit or ($isteacher and !$mygroupid))) {
720 if ($groups = get_groups($course->id)) {
721 $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
723 foreach ($groups as $group) {
724 /// If this group already has an entry, use its pagename.
725 if ($wiki_entries[$group->id]) {
726 $pagename = $wiki_entries[$group->id]->pagename;
728 else {
729 $pagename = $defpagename;
732 $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
733 $wikis[$key] = $group->name.':'.$pagename;
737 /// A teacher can see all other group teacher wikis.
738 else if ($groupmode) {
739 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
740 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
741 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
742 .' ORDER BY w.groupid';
743 $wiki_entries = get_records_sql($sql);
744 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
745 foreach ($wiki_entries as $wiki_entry) {
746 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
747 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
748 if ($currentid == $wiki_entry->id) {
749 $wikis['selected'] = $key;
754 else {
755 /// A user can see other teacher wikis if they are a teacher, a member of the same
756 /// group (for separate groups) or there are visible groups.
757 if ($groupmode == VISIBLEGROUPS) {
758 $viewall = true;
760 else if ($groupmode == SEPARATEGROUPS) {
761 $viewall = $mygroupid;
763 else {
764 $viewall = false;
766 if ($viewall !== false) {
767 $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
768 .' FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
769 .' WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
770 .' ORDER BY w.groupid';
771 $wiki_entries = get_records_sql($sql);
772 $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
775 foreach ($wiki_entries as $wiki_entry) {
776 if (($viewall === true) or @in_array($wiki_entry->groupid, $viewall)/*$viewall == $wiki_entry->groupid*/) {
777 $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
778 $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
779 if ($currentid == $wiki_entry->id) {
780 $wikis['selected'] = $key;
786 break;
789 return $wikis;
792 function wiki_add_entry(&$wiki, &$course, $userid=0, $groupid=0) {
793 /// Adds a new wiki entry of the specified type, unless already entered.
794 /// No checking is done here. It is assumed that the caller has the correct
795 /// privileges to add this entry.
797 global $USER;
799 /// If this wiki already has a wiki_type entry, return false.
800 if (wiki_get_entry($wiki, $course, $userid, $groupid) !== false) {
801 return false;
804 $wiki_entry = new Object();
806 switch ($wiki->wtype) {
808 case 'student':
809 $wiki_entry->wikiid = $wiki->id;
810 $wiki_entry->userid = $userid ? $userid : $USER->id;
811 $wiki_entry->pagename = wiki_page_name($wiki);
812 $wiki_entry->timemodified = time();
813 break;
815 case 'group':
816 /// Get the groupmode. It's been added to the wiki object.
817 $groupmode = groupmode($course, $wiki);
819 ///give the first groupid by default and try
820 $mygroups = mygroupid($course->id);
822 /// If there is a groupmode, get the group id.
823 if ($groupmode) {
824 $groupid = $groupid ? $groupid : $mygroups[0]/*mygroupid($course->id)*/;
826 /// If mode is 'nogroups', then groupid is zero.
827 else {
828 $groupid = 0;
830 $wiki_entry->wikiid = $wiki->id;
831 $wiki_entry->groupid = $groupid;
832 $wiki_entry->pagename = wiki_page_name($wiki);
833 $wiki_entry->timemodified = time();
835 break;
837 case 'teacher':
838 /// Get the groupmode. It's been added to the wiki object.
839 $groupmode = groupmode($course, $wiki);
841 /// If there is a groupmode, get the user's group id.
842 if ($groupmode and $groupid == 0) {
843 $mygroupid = mygroupid($course->id);
844 $groupid = $mygroupid[0]/*mygroupid($course->id)*/;
847 $wiki_entry->wikiid = $wiki->id;
848 $wiki_entry->course = $wiki->course;
849 $wiki_entry->groupid = $groupid;
850 $wiki_entry->pagename = wiki_page_name($wiki);
851 $wiki_entry->timemodified = time();
852 break;
854 $wiki_entry->pagename = addslashes($wiki_entry->pagename);
856 return insert_record("wiki_entries", $wiki_entry, true);
859 function wiki_can_add_entry(&$wiki, &$user, &$course, $userid=0, $groupid=0) {
860 /// Returns true or false if the user can add a wiki entry for this wiki.
862 /// Get the groupmode. It's been added to the wiki object.
863 $groupmode = groupmode($course, $wiki);
864 $mygroupid = mygroupid($course->id);
866 switch ($wiki->wtype) {
868 case 'student':
869 /// A student can create their own wiki, if they are a member of that course.
870 /// A user can create their own wiki at the site level.
871 if ($userid == 0) {
872 return (wiki_is_student($wiki, $user->id) or wiki_is_student($wiki, $user->id));
874 /// An editing teacher can create any student wiki, or
875 /// a non-editing teacher, if not assigned to a group can create any student wiki, or if assigned to a group can
876 /// create any student wiki in their group.
877 else {
878 return ((($userid == $user->id) and wiki_is_student($wiki, $user->id)) or wiki_is_teacheredit($wiki) or
879 (wiki_is_teacher($wiki) and (!$groupmode or $mygroupid == 0 or (ismember($mygroupid, $userid)))));
881 break;
883 case 'group':
884 /// If mode is 'nogroups', then all participants can add wikis.
885 if (wiki_is_teacheredit($wiki, $user->id)) {
886 return true;
889 if (!$groupmode) {
890 return (wiki_is_student($wiki, $user->id) or wiki_is_teacher($wiki, $user->id));
892 /// If not requesting a group, must be a member of a group.
893 else if ($groupid == 0) {
894 return ($mygroupid != 0);
896 /// If requesting a group, must be an editing teacher, a non-editing teacher with no assigned group,
897 /// or a non-editing teacher requesting their group. or a student in group, but wiki is empty.
898 else {
899 return (wiki_is_teacheredit($wiki) or
900 (wiki_is_teacher($wiki) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))) or
901 (wiki_is_student($wiki, $user->id) and @in_array($groupid, $mygroupid))
904 break;
906 case 'teacher':
907 /// If mode is 'nogroups', then all teachers can add wikis.
908 if (!$groupmode) {
909 return wiki_is_teacher($wiki, $user->id);
911 /// If not requesting a group, must be a member of a group.
912 else if ($groupid == 0) {
913 return ($mygroupid != 0 and wiki_is_teacher($wiki));
915 /// If there is a group mode, non-editing teachers with an assigned group, can only create wikis
916 /// in their group. Non-editing teachers with no assigned group and editing teachers can create any wiki.
917 else {
918 return (wiki_is_teacheredit($wiki) or
919 (wiki_is_teacher($wiki) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))));
921 break;
924 return false;
927 function wiki_can_edit_entry(&$wiki_entry, &$wiki, &$user, &$course) {
928 /// Returns true or false if the user can edit this wiki entry.
930 $can_edit = false;
931 $groupmode = groupmode($course, $wiki);
932 $mygroupid = mygroupid($course->id);
934 /// Editing teacher's and admins can edit all wikis, non-editing teachers can edit wikis in their groups,
935 /// or all wikis if group mode is 'no groups' or they don't belong to a group.
936 if (wiki_is_teacheredit($wiki, $user->id) or
937 ((!$groupmode or $mygroupid == 0) and wiki_is_teacher($wiki, $user->id))) {
938 $can_edit = true;
940 else {
941 switch ($wiki->wtype) {
943 /// Only a teacher or the owner of a student wiki can edit it.
944 case 'student':
945 $can_edit = (($user->id == $wiki_entry->userid) or
946 ($groupmode and wiki_is_teacher($wiki, $user->id) and
947 ismember($mygroupid, $wiki_entry->userid)));
948 break;
950 case 'group':
951 /// If there is a groupmode, determine the user's group status.
952 if ($groupmode) {
953 /// If the user is a member of the wiki group, they can edit the wiki.
954 $can_edit = ismember($wiki_entry->groupid, $user->id);
956 /// If mode is 'nogroups', then all participants can edit the wiki.
957 else {
958 $can_edit = (wiki_is_student($wiki, $user->id) or wiki_is_teacher($wiki, $user->id));
960 break;
962 case 'teacher':
963 /// If there is a groupmode, determine the user's group status.
964 if ($groupmode) {
965 /// If the user is a member of the wiki group, they can edit the wiki.
966 $can_edit = (wiki_is_teacher($wiki, $user->id) and ismember($wiki_entry->groupid, $user->id));
968 else {
969 $can_edit = wiki_is_teacher($wiki, $user->id);
971 break;
974 return $can_edit;
977 function wiki_user_can_access_student_wiki(&$wiki, $userid, &$course) {
978 global $USER;
980 /// Get the groupmode. It's been added to the wiki object.
981 $groupmode = groupmode($course, $wiki);
982 $usersgroup = mygroupid($course->id);
983 $isteacher = wiki_is_teacher($wiki, $USER->id);
985 /// If this user is allowed to access this wiki then return TRUE.
986 /// *** THIS COULD BE A PROBLEM, IF STUDENTS COULD EVER BE PART OF MORE THAN ONE GROUP ***
987 /// A user can access a student wiki, if:
988 /// - it is their wiki,
989 /// - group mode is VISIBLEGROUPS,
990 /// - group mode is SEPARATEGROUPS, and the user is a member of the requested user's group,
991 /// - they are an editing teacher or administrator,
992 /// - they are a non-editing teacher not assigned to a specific group,
993 /// - they are a non-editing teacher and group mode is NOGROUPS.
994 /// - they are an administrator (mostly for site-level wikis).
995 if (($userid and ($USER->id == $userid)) or ($groupmode == VISIBLEGROUPS) or
996 (($groupmode == SEPARATEGROUPS) and ismember($usersgroup, $userid)) or
997 (wiki_is_teacheredit($wiki, $USER->id)) or
998 (wiki_is_teacher($wiki, $USER->id) and (!$usersgroup or $groupmode == NOGROUPS))) {
999 $can_access = true;
1001 else {
1002 $can_access = false;
1004 return $can_access;
1007 function wiki_user_can_access_group_wiki(&$wiki, $groupid, &$course) {
1008 global $USER;
1010 /// Get the groupmode. It's been added to the wiki object.
1011 $groupmode = groupmode($course, $wiki);
1012 $usersgroup = mygroupid($course->id);
1013 $isteacher = wiki_is_teacher($wiki, $USER->id);
1015 /// A user can access a group wiki, if:
1016 /// - group mode is NOGROUPS,
1017 /// - group mode is VISIBLEGROUPS,
1018 /// - group mode is SEPARATEGROUPS, and they are a member of the requested group,
1019 /// - they are an editing teacher or administrator,
1020 /// - they are a non-editing teacher not assigned to a specific group.
1021 if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or
1022 (($groupmode == SEPARATEGROUPS) and @in_array($groupid, $usersgroup)/*($usersgroup == $groupid)*/) or
1023 (wiki_is_teacheredit($wiki, $USER->id)) or
1024 (wiki_is_teacher($wiki, $USER->id) and !$usersgroup)) {
1025 $can_access = true;
1027 else {
1028 $can_access = false;
1030 return $can_access;
1033 function wiki_user_can_access_teacher_wiki(&$wiki, $groupid, &$course) {
1034 global $USER;
1036 /// Get the groupmode. It's been added to the wiki object.
1037 $groupmode = groupmode($course, $wiki);
1039 /// A user can access a teacher wiki, if:
1040 /// - group mode is NOGROUPS,
1041 /// - group mode is VISIBLEGROUPS,
1042 /// - group mode is SEPARATEGROUPS, and they are a member of the requested group,
1043 /// - they are a teacher or administrator,
1044 if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or
1045 (($groupmode == SEPARATEGROUPS) and (@in_array($groupid, mygroupid($course->id))/*mygroupid($course->id) == $groupid*/)) or
1046 (wiki_is_teacher($wiki, $USER->id))){
1047 $can_access = true;
1049 else {
1050 $can_access = false;
1052 return $can_access;
1055 function wiki_get_owner(&$wiki_entry) {
1056 if ($wiki_entry->userid > 0) {
1057 $user = get_record('user', 'id', $wiki_entry->userid);
1058 $owner = fullname($user);
1060 else if ($wiki_entry->groupid > 0) {
1061 $owner = groups_get_group_name($wiki_entry->groupid); //TODO:check.
1063 else if ($wiki_entry->course > 0) {
1064 $course = get_record('course', 'id', $wiki_entry->course);
1065 $owner = $course->shortname;
1067 else {
1068 $owner = '- '.get_string("ownerunknown","wiki").' -';
1070 return $owner;
1073 function wiki_print_search_form($cmid, $search="", $userid, $groupid, $return=false) {
1074 global $CFG;
1075 # TODO: Add Group and User !!!
1076 $output = "<form id=\"search\" action=\"$CFG->wwwroot/mod/wiki/view.php\">";
1077 $output .="<fieldset class='invisiblefieldset'>";
1078 $output .= "<span style='font-size:0.6em;'>";
1079 $output .= "<input value=\"".get_string("searchwiki", "wiki").":\" type=\"submit\" />";
1080 $output .= "<input name=\"id\" type=\"hidden\" value=\"$cmid\" />";
1081 $output = $output.($groupid?"<input name=\"groupid\" type=\"hidden\" value=\"$groupid\" />":"");
1082 $output = $output.($userid?"<input name=\"userid\" type=\"hidden\" value=\"$userid\" />":"");
1083 $output .= "<input name=\"q\" type=\"text\" size=\"20\" value=\"".s($search)."\" />".' ';
1084 $output .= "</span>";
1085 $output .= "<input name=\"page\" type=\"hidden\" value=\"SearchPages\" />";
1086 $output .= "</fieldset>";
1087 $output .= "</form>";
1089 if ($return) {
1090 return $output;
1092 echo $output;
1095 function wiki_print_wikilinks_block($cmid, $binary=false, $return=false) {
1096 /// Prints a link-list of special wiki-pages
1097 global $CFG, $ewiki_title;
1099 $links=array();
1101 $links["SiteMap"]=get_string("sitemap", "wiki");
1102 $links["PageIndex"]=get_string("pageindex", "wiki");
1103 $links["NewestPages"]=get_string("newestpages", "wiki");
1104 $links["MostVisitedPages"]=get_string("mostvisitedpages", "wiki");
1105 $links["MostOftenChangedPages"]=get_string("mostoftenchangedpages", "wiki");
1106 $links["UpdatedPages"]=get_string("updatedpages", "wiki");
1107 $links["OrphanedPages"]=get_string("orphanedpages", "wiki");
1108 $links["WantedPages"]=get_string("wantedpages", "wiki");
1109 $links["WikiExport"]=get_string("wikiexport", "wiki");
1110 if($binary) {
1111 $links["FileDownload"]=get_string("filedownload", "wiki");
1113 popup_form(EWIKI_SCRIPT, $links, "wikilinks", "", get_string("choosewikilinks", "wiki"), "", "", $return);
1116 function wiki_print_page_actions($cmid, $specialpages, $page, $action, $binary=false, $canedit=true) {
1117 /// Displays actions which can be performed on the page
1119 $page=array();
1121 // Edit this Page
1122 if (in_array($action, array("edit", "links", "info", "attachments"))) {
1123 $page["view/$page"]=get_string("viewpage","wiki");
1125 if ($canedit && !in_array($page, $specialpages) && $action != "edit") {
1126 $page["edit/$page"]=get_string("editthispage","wiki");
1128 if ($action != "links") {
1129 $page["links/$page"]=get_string("backlinks","wiki");
1131 if ($canedit && !in_array($page, $specialpages) && $action!="info") {
1132 $page["info/$page"]=get_string("pageinfo","wiki");
1134 if($canedit && $binary && !in_array($page, $specialpages) && $action != "attachments") {
1135 $page["attachments/$page"]=get_string("attachments","wiki");
1138 popup_form(EWIKI_SCRIPT, $page, "wikiactions", "", get_string("action", "wiki"), "", "", false);
1141 function wiki_print_administration_actions($wiki, $cmid, $userid, $groupid, $page, $noeditor, $course) {
1142 /// Displays actions which can be performed on the page
1144 /// Create the URL
1145 $ewscript = 'admin.php?id='.$cmid;
1146 if (isset($userid) && $userid!=0) $ewscript .= '&amp;userid='.$userid;
1147 if (isset($groupid) && $groupid!=0) $ewscript .= '&amp;groupid='.$groupid;
1148 if (isset($page)) $ewscript .= '&amp;page='.$page;
1149 $ewscript.="&amp;action=";
1152 /// Build that action array according to wiki flags.
1153 $action = array();
1154 $isteacher = wiki_is_teacher($wiki);
1156 if ($wiki->setpageflags or $isteacher) {
1157 $action['setpageflags'] = get_string('setpageflags', 'wiki');
1159 if ($wiki->removepages or $isteacher) {
1160 $action['removepages'] = get_string('removepages', 'wiki');
1162 if ($wiki->strippages or $isteacher) {
1163 $action['strippages'] = get_string('strippages', 'wiki');
1165 if ($wiki->revertchanges or $isteacher) {
1166 $action['revertpages'] = get_string('revertpages', 'wiki');
1169 if($noeditor) {
1170 $action["checklinks"]=get_string("checklinks", "wiki");
1172 popup_form($ewscript, $action, "wikiadministration", "", get_string("chooseadministration", "wiki"), "", "", false);
1175 function wiki_admin_get_flagarray() {
1176 $ret = array(
1177 EWIKI_DB_F_TEXT => get_string("flagtxt","wiki"),
1178 EWIKI_DB_F_BINARY => get_string("flagbin","wiki"),
1179 EWIKI_DB_F_DISABLED => get_string("flagoff","wiki"),
1180 EWIKI_DB_F_HTML => get_string("flaghtm","wiki"),
1181 EWIKI_DB_F_READONLY => get_string("flagro","wiki"),
1182 EWIKI_DB_F_WRITEABLE => get_string("flagwr","wiki"),
1185 return $ret;
1188 ///////// Ewiki Administration. Mostly taken from the ewiki/tools folder and changed
1189 function wiki_admin_setpageflags_list($pageflagstatus) {
1190 $FD = wiki_admin_get_flagarray();
1191 $table = new Object();
1192 $table->head = array(get_string("pagename","wiki"), get_string("flags","wiki"));
1193 if($pageflagstatus) {
1194 $table->head[]=get_string("status","wiki");
1197 $result = ewiki_database("GETALL", array("version", "flags"));
1198 while ($row = $result->get()) {
1199 $id = $row["id"];
1200 $data = ewiki_database("GET", $row);
1202 $cell_pagename="";
1203 $cell_flags="";
1204 if ($data["flags"] & EWIKI_DB_F_TEXT) {
1205 $cell_pagename .= '<a href="' . EWIKI_SCRIPT . $id . '">';
1206 } else {
1207 $cell_pagename .= '<a href="' . EWIKI_SCRIPT_BINARY . $id . '">';
1209 $cell_pagename .= s($id) . '</a> / '.get_string("version","wiki").": ".$row["version"];
1211 foreach ($FD as $n=>$str) {
1212 $cell_flags .='<input type="checkbox" name="flags['. rawurlencode($id)
1213 . '][' . $n . ']" value="1" '
1214 . (($data["flags"] & $n) ? "checked=\"checked\"" : "")
1215 . ' />'.$str. ' ';
1217 if($pageflagstatus) {
1218 $table->data[]=array($cell_pagename, $cell_flags, $pageflagstatus[$id]);
1219 } else {
1220 $table->data[]=array($cell_pagename, $cell_flags);
1223 return $table;
1226 function wiki_admin_setpageflags($pageflags) {
1227 $FD = wiki_admin_get_flagarray();
1229 $status=array();
1230 if($pageflags) {
1231 foreach($pageflags as $page=>$fa) {
1233 $page = rawurldecode($page);
1235 $flags = 0;
1236 $fstr = "";
1237 foreach($fa as $num=>$isset) {
1238 if ($isset) {
1239 $flags += $num;
1240 $fstr .= ($fstr?",":""). $FD[$num];
1244 #$status[$page] .= "{$flags}=[{$fstr}]";
1246 $data = ewiki_database("GET", array("id" => $page));
1248 if ($data["flags"] != $flags) {
1249 $data["flags"] = $flags;
1250 $data["author"] = "ewiki-tools, " . ewiki_author();
1251 $data["version"]++;
1252 ewiki_database("WRITE", $data);
1253 $status[$page] = "<b>".get_string("flagsset","wiki")."</b> ".$status[$page];
1257 return $status;
1261 function wiki_admin_remove_list($listall="") {
1262 /// Table header
1263 $table = new Object();
1264 $table->head = array("&nbsp;", get_string("pagename","wiki"), get_string("errororreason","wiki"));
1266 /// Get all pages
1267 $result = ewiki_database("GETALL", array("version"));
1268 $selected = array();
1270 /// User wants to see all pages
1271 if ($listall) {
1272 while ($row = $result->get()) {
1273 $selected[$row["id"]] = get_string("listall","wiki")."<br />";
1276 while ($page = $result->get()) {
1277 $id = $page["id"];
1278 $page = ewiki_database("GET", array("id"=>$id));
1279 $flags = $page["flags"];
1280 #print "$id ".strlen(trim(($page["content"])))."<br />";
1282 if (!strlen(trim(($page["content"]))) && !($flags & EWIKI_DB_F_BINARY)) {
1283 @$selected[$id] .= get_string("emptypage","wiki")."<br />";
1286 // Check for orphaned pages
1287 $result2 = ewiki_database("SEARCH", array("content" => $id));
1288 $orphanedpage=true;
1289 if ($result2 && $result2->count()) {
1290 while ($row = $result2->get()) {
1291 $checkcontent = ewiki_database("GET", array("id"=>$row["id"]));
1292 $checkcontent = strtolower($checkcontent["content"]);
1294 if(strpos($checkcontent, strtolower($id)) !== false) {
1295 $orphanedpage=false;
1298 #echo "rc({$row['id']})==>($id): $check2 <br />";
1302 /// Some more reasons for Deletion...
1303 if ($orphanedpage && $id!=EWIKI_PAGE_INDEX &&!($flags & EWIKI_DB_F_BINARY)) {
1304 @$selected[$id] .= get_string("orphanedpage","wiki")."<br />";
1307 if ($flags & EWIKI_DB_F_DISABLED) {
1308 @$selected[$id] .= get_string("disabledpage","wiki")."<br />";
1311 if (($flags & 3) == 3) {
1312 @$selected[$id] .= get_string("errorbinandtxt","wiki")."<br />";
1315 if (!($flags & 3)) {
1316 @$selected[$id] .= get_string("errornotype","wiki")."<br />";
1319 if ($flags & EWIKI_DB_F_HTML) {
1320 @$selected[$id] .= get_string("errorhtml","wiki")."<br />";
1323 if (($flags & EWIKI_DB_F_READONLY) && !($flags & EWIKI_DB_F_BINARY)) {
1324 @$selected[$id] .= get_string("readonly","wiki")."<br />";
1327 if (($flags & EWIKI_DB_F_READONLY) && ($flags & EWIKI_DB_F_WRITEABLE)) {
1328 @$selected[$id] .= get_string("errorroandwr","wiki")."<br />";
1331 if (strlen($page["content"]) >= 65536) {
1332 @$selected[$id] .= get_string("errorsize","wiki")."<br />";
1335 if (strpos($page["refs"], "\n".get_string("deletemewikiword","wiki")."\n")!==false) {
1336 @$selected[$id] .= get_string("deletemewikiwordfound","wiki",get_string("deletemewikiword","wiki"))."<br />";
1340 foreach ($selected as $id => $reason) {
1341 $table_checkbox='<input type="checkbox" value="'.rawurlencode($id).'" name="pagestodelete[]" />';
1343 #-- link & id
1344 if (strpos($id, EWIKI_IDF_INTERNAL) === false) {
1345 $table_page='<a href="' . ewiki_script("", $id) . '">';
1346 } else {
1347 $table_page='<a href="' . ewiki_script_binary("", $id) . '">';
1349 $table_page .= s($id) . '</a>';
1351 #-- print reason
1352 $table_reason=$reason;
1354 $table->data[]=array($table_checkbox, $table_page, $table_reason);
1357 return $table;
1360 /// This function actually removes the pages
1361 function wiki_admin_remove($pagestodelete, $course, $wiki, $userid, $groupid) {
1362 $ret="";
1363 foreach ($pagestodelete as $id) {
1365 $id = rawurldecode($id);
1367 $data = ewiki_database("GET", array("id"=>$id));
1368 for ($version=1; $version<=$data["version"]; $version++) {
1369 ewiki_database("DELETE", array("id"=>$id, "version"=>$version));
1370 if($data["flags"] & EWIKI_DB_F_BINARY) {
1371 $filepath=moodle_binary_get_path($id, $data["meta"], $course, $wiki, $userid, $groupid);
1372 @unlink("$filepath");
1377 return $ret;
1380 function wiki_admin_strip_list($pagestostrip="",$version="",$err="") {
1381 /// Table header
1382 $table = new Object();
1383 $table->head = array("&nbsp;", get_string("pagename","wiki"), get_string("deleteversions","wiki"));
1385 $vc=ewiki_database("COUNTVERSIONS", array());
1386 $result = ewiki_database("GETALL",array());
1387 $i=0;
1388 while ($row = $result->get()) {
1389 $id = $row["id"];
1390 if($vc[$id]>1) {
1391 $error="";
1392 if($err[$id]) {
1393 $error=" ".join(", ",$err[$id]);
1395 $checked="";
1396 if($pagestostrip=="" || $pagestostrip[$i]) {
1397 $checked=" checked=\"checked\"";
1399 if($version=="") {
1400 $versiondefault="1-".($row["version"]-1);
1401 } else {
1402 $versiondefault=$version[$i];
1404 $table->data[]=array('<input type="checkbox" value="'.rawurlencode($id).'" name="pagestostrip['.$i.']" '.$checked.' />',
1405 '<A HREF="'.EWIKI_SCRIPT.$id.'">'.s($id).'</A> / '.get_string("version","wiki").": ".$row["version"],
1406 '<input name="version['.$i.']" value="'.$versiondefault.'" size="7" />'.$error);
1409 $i++;
1411 return $table;
1414 function wiki_admin_strip_versions($pagestostrip, $version, &$err) {
1415 $ret=array();
1416 foreach ($pagestostrip as $key => $id_ue) {
1418 $id = rawurldecode($id_ue);
1419 if (preg_match('/^(\d+)[-\s._:]+(\d+)$/', trim($version[$key]), $uu)) {
1420 $versA = $uu[1];
1421 $versZ = $uu[2];
1423 // Let the last Version in the database
1424 $checkdata = ewiki_database("GET", array("id" => $id));
1425 if($versZ>=$checkdata["version"]) {
1426 $err[$id][] = get_string("versionrangetoobig","wiki");
1427 } else {
1428 if($versA<=$versZ) {
1429 for ($v=$versA; $v<=$versZ; $v++) {
1430 $ret[$id][]=$v;
1432 } else {
1433 $err[$id][]=get_string("wrongversionrange","wiki",$version[$key]);
1437 else {
1438 $err[$id][]=get_string("wrongversionrange","wiki",$version[$key]);
1441 return $ret;
1444 function wiki_admin_strip($pagestostrip) {
1445 /// Purges old page-versions
1446 foreach($pagestostrip as $id => $versions) {
1447 foreach($versions as $version) {
1448 ewiki_database("DELETE", array("id"=>$id, "version"=>$version));
1453 function wiki_admin_checklinks_list() {
1454 $ret=array();
1455 $result = ewiki_database("GETALL",array());
1456 while ($row = $result->get()) {
1457 if(!($row["flags"] & EWIKI_DB_F_BINARY)) {
1458 $index=s($row["id"]);
1459 $ret[$index] = $row["id"];
1462 return $ret;
1465 function wiki_admin_checklinks($pagetocheck) {
1466 /// Checks http:// Links
1467 $ret="";
1468 if($pagetocheck) {
1469 $get = ewiki_database("GET", array("id" => $pagetocheck));
1470 $content = $get["content"];
1472 preg_match_all('_(http.?://[^\s"\'<>#,;]+[^\s"\'<>#,;.])_', $content, $links);
1473 $badlinks = array();
1474 if(!$links[1]) {
1475 $ret = get_string("nolinksfound","wiki")."<br /><br />";
1476 } else {
1477 foreach ($links[1] as $href) {
1478 #print "[ $href ]";
1479 #$d = @implode("", @file($href));
1480 $d="";
1481 if($checkfd = @fopen($href, 'r')) {
1482 fclose($checkfd);
1483 $d="OK";
1485 if (empty($d) || !strlen(trim($d)) || stristr("not found", $d) || stristr("error 404", $d)) {
1486 $ret.="[".get_string("linkdead","wiki")."] $href <br />\n";
1487 $badlinks[] = $href;
1488 } else {
1489 $ret.="[".get_string("linkok","wiki")."] $href <br />\n";
1494 /// Remove old Notices
1495 $content = eregi_replace(' µµ__~\['.get_string("offline","wiki").'\]__µµ ','', $content);
1497 #-- replace dead links
1498 foreach ($badlinks as $href) {
1499 $content = preg_replace("\377^(.*)($href)\377m", '$1 µµ__~['.get_string("offline","wiki").']__µµ $2', $content);
1502 #-- compare against db content
1503 if ($content != $get["content"]) {
1504 $get["content"] = $content;
1505 $get["version"]++;
1506 $get["author"] = ewiki_author("ewiki_checklinks");
1507 $get["lastmodified"] = time();
1509 ewiki_database("WRITE", $get);
1512 return $ret;
1515 function wiki_admin_revert($proceed, $authorfieldpattern, $changesfield, $howtooperate, $deleteversions) {
1516 $ret="";
1517 #-- params
1518 $m_time = $changesfield * 3600;
1519 $depth = $deleteversions - 1;
1520 $depth = ($depth>0?$depth:0);
1522 #-- walk through
1523 $result = ewiki_database("GETALL", array("id", "author", "lastmodified"));
1524 while ($row = $result->get()) {
1525 $id = $row["id"];
1526 #-- which versions to check
1527 $verZ = $row["version"];
1528 if ($howtooperate=="lastonly") {
1529 $verA = $verZ;
1531 else {
1532 $verA = $verZ-$depth;
1533 if ($verA <= 0) {
1534 $verA = 1;
1538 for ($ver=$verA; $ver<=$verZ; $ver++) {
1539 #-- load current $ver database entry
1540 if ($verA != $verZ) {
1541 $row = ewiki_database("GET", array("id"=>$id, "version"=>$ver));
1544 #-- match
1545 if (stristr($row["author"], $authorfieldpattern) && ($row["lastmodified"] + $m_time > time())) {
1546 $ret .= "$id (".get_string("versionstodelete","wiki").": ";
1547 #-- delete multiple versions
1548 if ($howtooperate=="allsince") {
1549 while ($ver<=$verZ) {
1550 $ret .= " $ver";
1551 if ($proceed) {
1552 ewiki_database("DELETE", array("id"=>$id, "version"=>$ver));
1554 $ver++;
1557 #-- or just the affected one
1558 else {
1559 $ret .= " $ver";
1560 if ($proceed) {
1561 ewiki_database("DELETE", $row);
1564 $ret .= ")<br />";
1565 break;
1567 } #-- for($ver)
1568 } #-- while($row)
1569 return $ret;
1573 function wiki_get_view_actions() {
1574 return array('view','view all');
1577 function wiki_get_post_actions() {
1578 return array('hack');
1583 * Obtains an editing lock on a wiki page.
1584 * @param int $wikiid ID of wiki object.
1585 * @param string $pagename Name of page.
1586 * @return array Two-element array with a boolean true (if lock has been obtained)
1587 * or false (if lock was held by somebody else). If lock was held by someone else,
1588 * the values of the wiki_locks entry are held in the second element; if lock was
1589 * held by current user then the the second element has a member ->id only.
1591 function wiki_obtain_lock($wikiid,$pagename) {
1592 global $USER;
1594 // Check for lock
1595 $alreadyownlock=false;
1596 if($lock=get_record('wiki_locks','pagename',$pagename,'wikiid', $wikiid)) {
1597 // Consider the page locked if the lock has been confirmed within WIKI_LOCK_PERSISTENCE seconds
1598 if($lock->lockedby==$USER->id) {
1599 // Cool, it's our lock, do nothing except remember it in session
1600 $lockid=$lock->id;
1601 $alreadyownlock=true;
1602 } else if(time()-$lock->lockedseen < WIKI_LOCK_PERSISTENCE) {
1603 return array(false,$lock);
1604 } else {
1605 // Not locked any more. Get rid of the old lock record.
1606 if(!delete_records('wiki_locks','pagename',$pagename,'wikiid', $wikiid)) {
1607 error('Unable to delete lock record');
1612 // Add lock
1613 if(!$alreadyownlock) {
1614 // Lock page
1615 $newlock=new stdClass;
1616 $newlock->lockedby=$USER->id;
1617 $newlock->lockedsince=time();
1618 $newlock->lockedseen=$newlock->lockedsince;
1619 $newlock->wikiid=$wikiid;
1620 $newlock->pagename=$pagename;
1621 if(!$lockid=insert_record('wiki_locks',$newlock)) {
1622 error('Unable to insert lock record');
1626 // Store lock information in session so we can clear it later
1627 if(!array_key_exists(SESSION_WIKI_LOCKS,$_SESSION)) {
1628 $_SESSION[SESSION_WIKI_LOCKS]=array();
1630 $_SESSION[SESSION_WIKI_LOCKS][$wikiid.'_'.$pagename]=$lockid;
1631 $lockdata=new StdClass;
1632 $lockdata->id=$lockid;
1633 return array(true,$lockdata);
1637 * If the user has an editing lock, releases it. Has no effect otherwise.
1638 * Note that it doesn't matter if this isn't called (as happens if their
1639 * browser crashes or something) since locks time out anyway. This is just
1640 * to avoid confusion of the 'what? it says I'm editing that page but I'm
1641 * not, I just saved it!' variety.
1642 * @param int $wikiid ID of wiki object.
1643 * @param string $pagename Name of page.
1645 function wiki_release_lock($wikiid,$pagename) {
1646 if(!array_key_exists(SESSION_WIKI_LOCKS,$_SESSION)) {
1647 // No locks at all in session
1648 return;
1651 $key=$wikiid.'_'.$pagename;
1653 if(array_key_exists($key,$_SESSION[SESSION_WIKI_LOCKS])) {
1654 $lockid=$_SESSION[SESSION_WIKI_LOCKS][$key];
1655 unset($_SESSION[SESSION_WIKI_LOCKS][$key]);
1656 if(!delete_records('wiki_locks','id',$lockid)) {
1657 error("Unable to delete lock record.");