File: lib.php

package info (click to toggle)
moodle 1.6.3-2%2Betch3
  • links: PTS
  • area: main
  • in suites: etch
  • size: 37,172 kB
  • ctags: 51,688
  • sloc: php: 231,916; sql: 5,631; xml: 2,688; sh: 1,185; perl: 638; makefile: 48; pascal: 36
file content (1517 lines) | stat: -rw-r--r-- 56,581 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
<?php  // $Id: lib.php,v 1.29 2006/01/05 16:53:02 stronk7 Exp $

/// Library of functions and constants for module wiki
/// (replace wiki with the name of your module and delete this line)


$wiki_CONSTANT = 7;     /// for example
$site = get_site();
$WIKI_TYPES = array ('teacher' =>   get_string('defaultcourseteacher'),
                     'group' =>     get_string('groups',"wiki"),
                     'student' =>   get_string('defaultcoursestudent') );
define("EWIKI_ESCAPE_AT", 0);       # For the algebraic filter

function wiki_add_instance($wiki) {
/// Given an object containing all the necessary data,
/// (defined by the form in mod.html) this function
/// will create a new instance and return the id number
/// of the new instance.

    $wiki->timemodified = time();

    # May have to add extra stuff in here #

    /// Determine the pagename for this wiki and save.
    $wiki->pagename = wiki_page_name($wiki);

    /// Check 'check boxes'. The variables won't be set at all of they were deselected.
    $wiki->disablecamelcase = (isset($wiki->disablecamelcase)) ? 1 : 0;
    $wiki->setpageflags = (isset($wiki->setpageflags)) ? 1 : 0;
    $wiki->removepages = (isset($wiki->removepages)) ? 1 : 0;
    $wiki->strippages = (isset($wiki->strippages)) ? 1 : 0;
    $wiki->revertchanges = (isset($wiki->revertchanges)) ? 1 : 0;

    return insert_record("wiki", $wiki);
}


function wiki_update_instance($wiki) {
/// Given an object containing all the necessary data,
/// (defined by the form in mod.html) this function
/// will update an existing instance with new data.

    /// Determine the pagename for this wiki.
    $wiki->pagename = wiki_page_name($wiki);

    /// Check 'check boxes'. The variables won't be set at all of they were deselected.
    $wiki->disablecamelcase = (isset($wiki->disablecamelcase)) ? 1 : 0;
    $wiki->setpageflags = (isset($wiki->setpageflags)) ? 1 : 0;
    $wiki->removepages = (isset($wiki->removepages)) ? 1 : 0;
    $wiki->strippages = (isset($wiki->strippages)) ? 1 : 0;
    $wiki->revertchanges = (isset($wiki->revertchanges)) ? 1 : 0;

    $wiki->timemodified = time();
    $wiki->id = $wiki->instance;
    return update_record("wiki", $wiki);
}

/// Delete all Directories recursively
function wiki_rmdir($basedir) {
  $handle = @opendir($basedir);
  if($handle) {
    while (false!==($folder = readdir($handle))) {
       if($folder != "." && $folder != ".." && $Folder != "CVS") {
          wiki_rmdir("$basedir/$folder");  // recursive
       }
    }
    closedir($handle);
  }
  @rmdir($basedir);
}

function wiki_delete_instance($id) {
/// Given an ID of an instance of this module,
/// this function will permanently delete the instance
/// and any data that depends on it.
    global $CFG;

    if (! $wiki = get_record("wiki", "id", $id)) {
        return false;
    }

    $result = true;

    #Delete Files
### Should probably check regardless of this setting in case its been changed...
    if($wiki->ewikiacceptbinary) {
      if ($basedir = $CFG->dataroot."/".$wiki->course."/".$CFG->moddata."/wiki/$id") {
          if ($files = get_directory_list($basedir)) {
              foreach ($files as $file) {
                  #if ($file != $exception) {
                      unlink("$basedir/$file");
                      notify("Existing file '$file' has been deleted!");
                  #}
              }
          }
          #if (!$exception) {  // Delete directory as well, if empty
              wiki_rmdir("$basedir");
          #}
      }
    }

    # Delete any dependent records here #
    if (! delete_records("wiki", "id", $wiki->id)) {
        $result = false;
    }

    /// Delete all wiki_entries and wiki_pages.
    if (($wiki_entries = wiki_get_entries($wiki)) !== false) {
        foreach ($wiki_entries as $wiki_entry) {
            if (! delete_records("wiki_pages", "wiki", "$wiki_entry->id")) {
                $result = false;
            }
            if (! delete_records("wiki_entries", "id", "$wiki_entry->id")) {
                $result = false;
            }
        }
    }

    return $result;
}

function wiki_user_outline($course, $user, $mod, $wiki) {
/// Return a small object with summary information about what a
/// user has done with a given particular instance of this module
/// Used for user activity reports.
/// $return->time = the time they did it
/// $return->info = a short text description

    $return = NULL;
    return $return;
}

function wiki_user_complete($course, $user, $mod, $wiki) {
/// Print a detailed representation of what a  user has done with
/// a given particular instance of this module, for user activity reports.

    return true;
}

function wiki_print_recent_activity($course, $isteacher, $timestart) {
/// Given a course and a time, this module should find recent activity
/// that has occurred in wiki activities and print it out.
/// Return true if there was output, or false is there was none.

    global $CFG;
    if (!$logs = get_records_select('log', 'time > \''.$timestart.'\' AND '.
                                           'course = \''.$course->id.'\' AND '.
                                           'module = \'wiki\' AND '.
                                           'action LIKE \'edit%\' ', 'time ASC')){
        return false;
    }

    foreach ($logs as $log) {
        //Create a temp valid module structure (course,id)
        $tempmod->course = $log->course;
        $tempmod->id = $log->cmid;
        //Obtain the visible property from the instance
        $modvisible = instance_is_visible($log->module,$tempmod);

        //Only if the mod is visible
        if ($modvisible) {
            $wikis[$log->info] = wiki_log_info($log);
            $wikis[$log->info]->pagename = $log->info;
            $wikis[$log->info]->time = $log->time;
            $wikis[$log->info]->url  = str_replace('&', '&amp;', $log->url);
        }
    }

    if ($wikis) {
        $content = true;
        print_headline(get_string('updatedwikipages', 'wiki').':', 3);
        foreach ($wikis as $wiki) {
            print_recent_activity_note($wiki->time, $wiki, $isteacher, $wiki->pagename,
                                       $CFG->wwwroot.'/mod/wiki/'.$wiki->url);
        }
    }
    return true;  //  True if anything was printed, otherwise false
}

function wiki_log_info($log) {
    global $CFG;
    return get_record_sql("SELECT u.firstname, u.lastname
                             FROM {$CFG->prefix}user u
                            WHERE u.id = '$log->userid'");
}

function wiki_cron () {
/// Function to be run periodically according to the moodle cron
/// This function searches for things that need to be done, such
/// as sending out mail, toggling flags etc ...

    global $CFG;

    return true;
}

function wiki_grades($wikiid) {
/// Must return an array of grades for a given instance of this module,
/// indexed by user.  It also returns a maximum allowed grade.

    return NULL;
}

function wiki_get_participants($wikiid) {
//Returns the users with data in one wiki
//(users with records in wiki_pages and wiki_entries)

    global $CFG;

    //Get users from wiki_pages
    $st_pages = get_records_sql("SELECT DISTINCT u.id, u.id
                                 FROM {$CFG->prefix}user u,
                                      {$CFG->prefix}wiki_entries e,
                                      {$CFG->prefix}wiki_pages p
                                 WHERE e.wikiid = '$wikiid' and
                                       p.wiki = e.id and
                                       u.id = p.userid");

    //Get users from wiki_entries
    $st_entries = get_records_sql("SELECT DISTINCT u.id, u.id
                                   FROM {$CFG->prefix}user u,
                                        {$CFG->prefix}wiki_entries e
                                   WHERE e.wikiid = '$wikiid' and
                                         u.id = e.userid");

    //Add entries to pages
    if ($st_entries) {
        foreach ($st_entries as $st_entry) {
            $st_pages[$st_entry->id] = $st_entry;
        }
    }

    return $st_pages;
}


//////////////////////////////////////////////////////////////////////////////////////
/// Any other wiki functions go here.  Each of them must have a name that
/// starts with wiki_

function wiki_wiki_name($wikiname) {
/// Return the passed in string in Wiki name format.
/// Remove any leading and trailing whitespace, capitalize all the words
/// and then remove any internal whitespace.

    if (wiki_is_wiki_name($wikiname)) {
        return $wikiname;
    }
    else {
        /// Create uppercase words and remove whitespace.
        $wikiname = preg_replace("/(\w+)\s/", "$1", ucwords(trim($wikiname)));

        /// Check again - there may only be one word.
        if (wiki_is_wiki_name($wikiname)) {
            return $wikiname;
        }
        /// If there is only one word, append default wiki name to it.
        else {
            return $wikiname.get_string('wikidefaultpagename', 'wiki');
        }
    }
}

function wiki_is_wiki_name($wikiname) {
/// Check for correct wikiname syntax and return true or false.

    /// If there are spaces between the words, incorrect format.
    if (preg_match_all('/\w+/', $wikiname, $out) > 1) {
        return false;
    }
    /// If there isn't more than one group of uppercase letters separated by
    /// lowercase letters or '_', incorrect format.
    else if (preg_match_all('/[A-Z]+[a-z_]+/', $wikiname, $out) > 1) {
        return true;
    }
    else {
        return false;
    }
}

function wiki_page_name(&$wiki) {
/// Determines the wiki's page name and returns it.
    if (!empty($wiki->initialcontent)) {
        $ppos = strrpos($wiki->initialcontent, '/');
        if ($ppos === false) {
            $pagename = $wiki->initialcontent;
        }
        else {
            $pagename = substr($wiki->initialcontent, $ppos+1);
        }
    }
    else if (!empty($wiki->pagename)) {
        $pagename = $wiki->pagename;
    }
    else {
        $pagename = $wiki->name;
    }
    return $pagename;
}

function wiki_content_dir(&$wiki) {
/// Determines the wiki's default content directory (if there is one).
    global $CFG;

    if (!empty($wiki->initialcontent)) {
        $ppos = strrpos($wiki->initialcontent, '/');
        if ($ppos === false) {
            $subdir = '';
        }
        else {
            $subdir = substr($wiki->initialcontent, 0, $ppos+1);
        }
        $contentdir = $CFG->dataroot.'/'.$wiki->course.'/'.$subdir;
    }
    else {
        $contentdir = false;
    }
    return $contentdir;
}

function wiki_get_course_wikis($courseid, $wtype='*') {
/// Returns all wikis for the specified course and optionally of the specified type.

    $select = 'course = '.$courseid;
    if ($wtype != '*') {
        $select .= ' AND wtype = \''.$wtype.'\'';
    }
    return get_records_select('wiki', $select, 'id');
}

function wiki_has_entries(&$wiki) {
/// Returns true if wiki already has wiki entries; otherwise false.

    return record_exists('wiki_entries', 'wikiid', $wiki->id);
}

function wiki_get_entries(&$wiki, $byindex=NULL) {
/// Returns an array with all wiki entries indexed by entry id; false if there are none.
/// If the optional $byindex is specified, returns the entries indexed by that field.
/// Valid values for $byindex are 'student', 'group'.

    if ($byindex == 'student') {
        return get_records('wiki_entries', 'wikiid', $wiki->id, '',
                           'userid,id,wikiid,course,groupid,pagename,timemodified');
    }
    else if ($byindex == 'group') {
        return get_records('wiki_entries', 'wikiid', $wiki->id, '',
                           'groupid,id,wikiid,course,userid,pagename,timemodified');
    }
    else {
        return get_records('wiki_entries', 'wikiid', $wiki->id);
    }
}

function wiki_get_default_entry(&$wiki, &$course, $userid=0, $groupid=0) {
/// Returns the wiki entry according to the wiki type.
/// Optionally, will return wiki entry for $userid student wiki, or
/// $groupid group or teacher wiki.
/// Creates one if it needs to and it can.
    global $USER;
    /// If the wiki entry doesn't exist, can this user create it?
    if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false) {
        if (wiki_can_add_entry($wiki, $USER, $course, $userid, $groupid)) {
            wiki_add_entry($wiki, $course, $userid, $groupid);
            if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false) {
                error("Could not add wiki entry.");
            }
        }
    }
    //print_object($wiki_entry);
    return $wiki_entry;
}

function wiki_get_entry(&$wiki, &$course, $userid=0, $groupid=0) {
/// Returns the wiki entry according to the wiki type.
/// Optionally, will return wiki entry for $userid student wiki, or
/// $groupid group or teacher wiki.
    global $USER;

    switch ($wiki->wtype) {
    case 'student':
        /// If a specific user was requested, return it, if allowed.
        if ($userid and wiki_user_can_access_student_wiki($wiki, $userid, $course)) {
            $wentry = wiki_get_student_entry($wiki, $userid);
        }

        /// If there is no entry for this user, check if this user is a teacher.
        else if (!$wentry = wiki_get_student_entry($wiki, $USER->id)) {
/*            if (isteacher($course->id, $USER->id)) {
                /// If this user is a teacher, return the first entry.
                if ($wentries = wiki_get_entries($wiki)) {
                    $wentry = current($wentries);
                }
            }*/
        }
        break;

    case 'group':
        /// If there is a groupmode, get the user's group id.
        $groupmode = groupmode($course, $wiki);
        //echo "groupid is in wiki_get_entry ".$groupid."<br />";
        /// If a specific group was requested, return it, if allowed.
        if ($groupid and wiki_user_can_access_group_wiki($wiki, $groupid, $course)) {
            $wentry = wiki_get_group_entry($wiki, $groupid);
        }
        else if ($groupmode) {
            $mygroupids = mygroupid($course->id);
            /// If there is no entry for this user, check if this user is a teacher.
            //this is broken for multiple groups /*mygroupid($course->id)*/
            //while ($groupindex < size(mygroupids) AND !$wentry = wiki_get_group_entry($))
            if (!$wentry = wiki_get_group_entry($wiki, $mygroupids[0])){//always default to first group it returns, can change later!
    /*  if (isteacher($course->id, $USER->id)) {
                    /// If this user is a teacher, return the first entry.
                    if ($wentries = wiki_get_entries($wiki)) {
                        $wentry = current($wentries);
                    }
                } */
            }
        }
        /// If mode is 'nogroups', then groupid is zero.
        else {
            $wentry = wiki_get_group_entry($wiki, 0);
        }
        break;

    case 'teacher':
        /// If there is a groupmode, get the user's group id.
        if (groupmode($course, $wiki)) {
            $mygroupids = mygroupid($course->id);//same here, default to the first one
            $groupid = $groupid ? $groupid : $mygroupids[0]/*mygroupid($course->id)*/;
        }

        /// If a specific group was requested, return it, if allowed.
        if (wiki_user_can_access_teacher_wiki($wiki, $groupid, $course)) {
            $wentry = wiki_get_teacher_entry($wiki, $groupid);
        }
        break;
    }
    return $wentry;
}

function wiki_get_teacher_entry(&$wiki, $groupid=0) {
/// Returns the wiki entry for the wiki teacher type.
    return get_record('wiki_entries', 'wikiid', $wiki->id, 'course', $wiki->course, 'groupid', $groupid);
}

function wiki_get_group_entry(&$wiki, $groupid=null) {
/// Returns the wiki entry for the given group.
    return get_record('wiki_entries', 'wikiid', $wiki->id, 'groupid', $groupid);
}

function wiki_get_student_entry(&$wiki, $userid=null) {
/// Returns the wiki entry for the given student.
    global $USER;

    if (is_null($userid)) {
        $userid = $USER->id;
    }
    return get_record('wiki_entries', 'wikiid', $wiki->id, 'userid', $userid);
}

function wiki_get_other_wikis(&$wiki, &$user, &$course, $currentid=0) {
    /// Returns a list of other wikis to display, depending on the type, group and user.
    /// Returns the key containing the currently selected entry as well.

    global $CFG, $id;

    $wikis = false;

    $groupmode = groupmode($course, $wiki);
    $mygroupid = mygroupid($course->id);
    $isteacher = isteacher($course->id, $user->id);
    $isteacheredit = isteacheredit($course->id, $user->id);

    switch ($wiki->wtype) {

    case 'student':
        /// Get all the existing entries for this wiki.
        $wiki_entries = wiki_get_entries($wiki, 'student');
        if ($isteacher and (SITEID != $course->id)) {

            /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all student
            /// wikis, regardless of creation.
            if ((SITEID != $course->id) and ($isteacheredit or ($groupmode == NOGROUPS))) {

                if ($students = get_course_students($course->id)) {
                    /// Default pagename is dependent on the wiki settings.
                    $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;

                    foreach ($students as $student) {

                        /// If this student already has an entry, use its pagename.
                        if ($wiki_entries[$student->id]) {
                            $pagename = $wiki_entries[$student->id]->pagename;
                        }
                        else {
                            $pagename = $defpagename;
                        }

                        $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
                        $wikis[$key] = fullname($student).':'.$pagename;
                    }
                }
            }
            else if ($groupmode == SEPARATEGROUPS) {

                if ($students = get_group_students($mygroupid)) {
                    $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
                    foreach ($students as $student) {

                        /// If this student already has an entry, use its pagename.
                        if ($wiki_entries[$student->id]) {
                            $pagename = $wiki_entries[$student->id]->pagename;
                        }
                        else {
                            $pagename = $defpagename;
                        }

                        $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
                        $wikis[$key] = fullname($student).':'.$pagename;
                    }
                }
            }
            else if ($groupmode == VISIBLEGROUPS) {
                /// Get all students in your group.
                if ($students = get_group_students($mygroupid)) {
                    $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
                    foreach ($students as $student) {
                        /// If this student already has an entry, use its pagename.
                        if ($wiki_entries[$student->id]) {
                            $pagename = $wiki_entries[$student->id]->pagename;
                        }
                        else {
                            $pagename = $defpagename;
                        }
                        $key = 'view.php?id='.$id.'&userid='.$student->id.'&page='.$pagename;
                        $wikis[$key] = fullname($student).':'.$pagename;
                    }
                }
                /// Get all student wikis created, regardless of group.
                $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
                      .'    FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'user u '
                      .'    WHERE w.wikiid = '.$wiki->id.' AND u.id = w.userid '
                      .'    ORDER BY w.id';
                $wiki_entries = get_records_sql($sql);
                $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
                foreach ($wiki_entries as $wiki_entry) {
                    $key = 'view.php?id='.$id.'&userid='.$wiki_entry->userid.'&page='.$wiki_entry->pagename;
                    $wikis[$key] = fullname($wiki_entry).':'.$wiki_entry->pagename;
                    if ($currentid == $wiki_entry->id) {
                        $wikis['selected'] = $key;
                    }
                }
            }
        }
        else {
            /// A user can see other student wikis if they are a member of the same
            /// group (for separate groups) or there are visible groups, or if this is
            /// a site-level wiki, and they are an administrator.
            if (($groupmode == VISIBLEGROUPS) or
                ((SITEID == $course->id) and isadmin())) {
                $viewall = true;
            }
            else if ($groupmode == SEPARATEGROUPS) {
                $viewall = mygroupid($course->id);
            }
            else {
                $viewall = false;
            }

            if ($viewall !== false) {

                $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname '
                      .'    FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'user u '
                      .'    WHERE w.wikiid = '.$wiki->id.' AND u.id = w.userid '
                      .'    ORDER BY w.id';
                $wiki_entries = get_records_sql($sql);
                $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
                foreach ($wiki_entries as $wiki_entry) {
                    if (($viewall === true) or ismember($viewall, $wiki_entry->userid)) {
                        $key = 'view.php?id='.$id.'&userid='.$wiki_entry->userid.'&page='.$wiki_entry->pagename;
                        $wikis[$key] = fullname($wiki_entry).':'.$wiki_entry->pagename;
                        if ($currentid == $wiki_entry->id) {
                            $wikis['selected'] = $key;
                        }
                    }
                }
            }
        }
        break;

    case 'group':
        /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all group
        /// wikis, regardless of creation.
        
        /// If user is a member of multiple groups, need to show current group etc?

        /// Get all the existing entries for this wiki.
        $wiki_entries = wiki_get_entries($wiki, 'group');

        if ($groupmode and ($isteacheredit or ($isteacher and !$mygroupid))) {
            if ($groups = get_groups($course->id)) {
                $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
                foreach ($groups as $group) {

                    /// If this group already has an entry, use its pagename.
                    if (isset($wiki_entries[$group->id])) {
                        $pagename = $wiki_entries[$group->id]->pagename;
                    }
                    else {
                        $pagename = $defpagename;
                    }

                    $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
                    $wikis[$key] = $group->name.':'.$pagename;
                }
            }
        }
        //if a studnet with multiple groups in SPG
        else if ($groupmode == SEPARATEGROUPS){
            if ($groups = get_groups($course->id, $user->id)){

                $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;
                foreach ($groups as $group) {
                    /// If this group already has an entry, use its pagename.
                    if (isset($wiki_entries[$group->id])) {
                        $pagename = $wiki_entries[$group->id]->pagename;
                    }
                    else {
                        $pagename = $defpagename;
                    }
                    $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
                    $wikis[$key] = $group->name.':'.$pagename;
                }

            }

        }
        /// A user can see other group wikis if there are visible groups.
        else if ($groupmode == VISIBLEGROUPS) {
            $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
                  .'    FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
                  .'    WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
                  .'    ORDER BY w.groupid';
            $wiki_entries = get_records_sql($sql);
            $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
            foreach ($wiki_entries as $wiki_entry) {
                $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
                $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
                if ($currentid == $wiki_entry->id) {
                    $wikis['selected'] = $key;
                }
            }
        }
        break;

    case 'teacher':
        if ($isteacher) {
            /// If the user is an editing teacher, or a non-editing teacher not assigned to a group, show all
            /// teacher wikis, regardless of creation.
            if ($groupmode and ($isteacheredit or ($isteacher and !$mygroupid))) {
                if ($groups = get_groups($course->id)) {
                    $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename;

                    foreach ($groups as $group) {
                        /// If this group already has an entry, use its pagename.
                        if ($wiki_entries[$group->id]) {
                            $pagename = $wiki_entries[$group->id]->pagename;
                        }
                        else {
                            $pagename = $defpagename;
                        }

                        $key = 'view.php?id='.$id.($group->id?"&groupid=".$group->id:"").'&page='.$pagename;
                        $wikis[$key] = $group->name.':'.$pagename;
                    }
                }
            }
            /// A teacher can see all other group teacher wikis.
            else if ($groupmode) {
                $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
                      .'    FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
                      .'    WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
                      .'    ORDER BY w.groupid';
                $wiki_entries = get_records_sql($sql);
                $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();
                foreach ($wiki_entries as $wiki_entry) {
                    $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
                    $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
                    if ($currentid == $wiki_entry->id) {
                        $wikis['selected'] = $key;
                    }
                }
            }
        }
        else {
            /// A user can see other teacher wikis if they are a teacher, a member of the same
            /// group (for separate groups) or there are visible groups.
            if ($groupmode == VISIBLEGROUPS) {
                $viewall = true;
            }
            else if ($groupmode == SEPARATEGROUPS) {
                $viewall = $mygroupid;
            }
            else {
                $viewall = false;
            }
            if ($viewall !== false) {
                $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname '
                      .'    FROM '.$CFG->prefix.'wiki_entries w, '.$CFG->prefix.'groups g '
                      .'    WHERE w.wikiid = '.$wiki->id.' AND g.id = w.groupid '
                      .'    ORDER BY w.groupid';
                $wiki_entries = get_records_sql($sql);
                $wiki_entries=is_array($wiki_entries)?$wiki_entries:array();


                foreach ($wiki_entries as $wiki_entry) {
                    if (($viewall === true) or @in_array($wiki_entry->groupid, $viewall)/*$viewall == $wiki_entry->groupid*/) {
                        $key = 'view.php?id='.$id.($wiki_entry->groupid?"&groupid=".$wiki_entry->groupid:"").'&page='.$wiki_entry->pagename;
                        $wikis[$key] = $wiki_entry->gname.':'.$wiki_entry->pagename;
                        if ($currentid == $wiki_entry->id) {
                            $wikis['selected'] = $key;
                        }
                    }
                }
            }
        }
        break;
    }

    return $wikis;
}

function wiki_add_entry(&$wiki, &$course, $userid=0, $groupid=0) {
/// Adds a new wiki entry of the specified type, unless already entered.
/// No checking is done here. It is assumed that the caller has the correct
/// privileges to add this entry.

    global $USER;

    /// If this wiki already has a wiki_type entry, return false.
    if (wiki_get_entry($wiki, $course, $userid, $groupid) !== false) {
        return false;
    }

    switch ($wiki->wtype) {

    case 'student':
        $wiki_entry->wikiid = $wiki->id;
        $wiki_entry->userid = $userid ? $userid : $USER->id;
        $wiki_entry->pagename = wiki_page_name($wiki);
        $wiki_entry->timemodified = time();
        break;

    case 'group':
        /// Get the groupmode. It's been added to the wiki object.
        $groupmode = groupmode($course, $wiki);

        ///give the first groupid by default and try
        $mygroups = mygroupid($course->id);

        /// If there is a groupmode, get the group id.
        if ($groupmode) {
            $groupid = $groupid ? $groupid : $mygroups[0]/*mygroupid($course->id)*/;
        }
        /// If mode is 'nogroups', then groupid is zero.
        else {
            $groupid = 0;
        }
        $wiki_entry->wikiid = $wiki->id;
        $wiki_entry->groupid = $groupid;
        $wiki_entry->pagename = wiki_page_name($wiki);
        $wiki_entry->timemodified = time();
        break;

    case 'teacher':
        /// Get the groupmode. It's been added to the wiki object.
        $groupmode = groupmode($course, $wiki);

        /// If there is a groupmode, get the user's group id.
        if ($groupmode and $groupid == 0) {
            $mygroupid = mygroupid($course->id);
            $groupid = $mygroupid[0]/*mygroupid($course->id)*/;
        }

        $wiki_entry->wikiid = $wiki->id;
        $wiki_entry->course = $wiki->course;
        $wiki_entry->groupid = $groupid;
        $wiki_entry->pagename = wiki_page_name($wiki);
        $wiki_entry->timemodified = time();
        break;
    }
    $wiki_entry->pagename = addslashes($wiki_entry->pagename);

    return insert_record("wiki_entries", $wiki_entry, true);
}

function wiki_can_add_entry(&$wiki, &$user, &$course, $userid=0, $groupid=0) {
/// Returns true or false if the user can add a wiki entry for this wiki.

    /// Get the groupmode. It's been added to the wiki object.
    $groupmode = groupmode($course, $wiki);
    $mygroupid = mygroupid($course->id);

    switch ($wiki->wtype) {

    case 'student':
///     A student can create their own wiki, if they are a member of that course.
///     A user can create their own wiki at the site level.
        if ($userid == 0) {
            return (isstudent($course->id, $user->id) or
                    ((SITEID == $course->id) and !empty($user) and !isguest()));
        }
///     An editing teacher can create any student wiki, or
///     a non-editing teacher, if not assigned to a group can create any student wiki, or if assigned to a group can
///     create any student wiki in their group.
        else {
            return ((($userid == $user->id) and isstudent($course->id, $user->id)) or isteacheredit($course->id) or
                    (isteacher($course->id) and (!$groupmode or $mygroupid == 0 or (ismember($mygroupid, $userid)))));
        }
        break;

    case 'group':
        /// If mode is 'nogroups', then all participants can add wikis.
        if (!$groupmode) {
            return (isstudent($course->id, $user->id) or isteacher($course->id, $user->id) or
                    ((SITEID == $course->id) and !empty($user) and !isguest()));
        }
        /// If not requesting a group, must be a member of a group.
        else if ($groupid == 0) {
            return ($mygroupid != 0);
        }
        /// If requesting a group, must be an editing teacher, a non-editing teacher with no assigned group,
        /// or a non-editing teacher requesting their group. or a student in group, but wiki is empty.
        else {
            return (isteacheredit($course->id) or
                   (isteacher($course->id) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))) or
                   (isstudent($course->id, $user->id) and @in_array($groupid, $mygroupid))
                   );
        }
        break;

    case 'teacher':
        /// If mode is 'nogroups', then all teachers can add wikis.
        if (!$groupmode) {
            return (isteacher($course->id, $user->id) or ((SITEID == $course->id) and isadmin()));
        }
        /// If not requesting a group, must be a member of a group.
        else if ($groupid == 0) {
            return ($mygroupid != 0 and isteacher($course->id));
        }
        /// If there is a group mode, non-editing teachers with an assigned group, can only create wikis
        /// in their group. Non-editing teachers with no assigned group and editing teachers can create any wiki.
        else {
            return (isteacheredit($course->id) or
                    (isteacher($course->id) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))));
        }
        break;
    }

    return false;
}

function wiki_can_edit_entry(&$wiki_entry, &$wiki, &$user, &$course) {
/// Returns true or false if the user can edit this wiki entry.

    $can_edit = false;
    $groupmode = groupmode($course, $wiki);
    $mygroupid = mygroupid($course->id);

    /// Editing teacher's and admins can edit all wikis, non-editing teachers can edit wikis in their groups,
    /// or all wikis if group mode is 'no groups' or they don't belong to a group.
    if (isadmin($user->id) or isteacheredit($course->id, $user->id) or
        ((!$groupmode or $mygroupid == 0) and isteacher($course->id, $user->id))) {
        $can_edit = true;
    }
    else {
        switch ($wiki->wtype) {

        /// Only a teacher or the owner of a student wiki can edit it.
        case 'student':
            $can_edit = (($user->id == $wiki_entry->userid) or
                         ($groupmode and isteacher($course->id, $user->id) and
                          ismember($mygroupid, $wiki_entry->userid)));
            break;

        case 'group':
            /// If there is a groupmode, determine the user's group status.
            if ($groupmode) {
                /// If the user is a member of the wiki group, they can edit the wiki.
                $can_edit = ismember($wiki_entry->groupid, $user->id);
            }
            /// If mode is 'nogroups', then all participants can edit the wiki.
            else {
                $can_edit = (isstudent($course->id, $user->id) or isteacher($course->id, $user->id) or
                            ((SITEID == $course->id) and !empty($user) and !isguest()));
            }
            break;

        case 'teacher':
            /// If there is a groupmode, determine the user's group status.
            if ($groupmode) {
                /// If the user is a member of the wiki group, they can edit the wiki.
                $can_edit = (isteacher($course->id, $user->id) and ismember($wiki_entry->groupid, $user->id));
            }
            else {
                $can_edit = (isteacher($course->id, $user->id) or ((SITEID == $course->id) and isadmin()));
            }
            break;
        }
    }
    return $can_edit;
}

function wiki_user_can_access_student_wiki(&$wiki, $userid, &$course) {
    global $USER;

    /// Get the groupmode. It's been added to the wiki object.
    $groupmode = groupmode($course, $wiki);
    $usersgroup = mygroupid($course->id);
    $isteacher = isteacher($course->id, $USER->id);

    /// If this user is allowed to access this wiki then return TRUE.
    /// *** THIS COULD BE A PROBLEM, IF STUDENTS COULD EVER BE PART OF MORE THAN ONE GROUP ***
    /// A user can access a student wiki, if:
    ///     - it is their wiki,
    ///     - group mode is VISIBLEGROUPS,
    ///     - group mode is SEPARATEGROUPS, and the user is a member of the requested user's group,
    ///     - they are an editing teacher or administrator,
    ///     - they are a non-editing teacher not assigned to a specific group,
    ///     - they are a non-editing teacher and group mode is NOGROUPS.
    ///     - they are an administrator (mostly for site-level wikis).
    if (($userid and ($USER->id == $userid)) or ($groupmode == VISIBLEGROUPS) or
        (($groupmode == SEPARATEGROUPS) and ismember($usersgroup, $userid)) or
        (isteacheredit($course->id, $USER->id)) or
        (isteacher($course->id, $USER->id) and (!$usersgroup or ($groupmode == NOGROUPS))) or
        (isadmin())) {
        $can_access = true;
    }
    else {
        $can_access = false;
    }
    return $can_access;
}

function wiki_user_can_access_group_wiki(&$wiki, $groupid, &$course) {
    global $USER;

    /// Get the groupmode. It's been added to the wiki object.
    $groupmode = groupmode($course, $wiki);
    $usersgroup = mygroupid($course->id);
    $isteacher = isteacher($course->id, $USER->id);

    /// A user can access a group wiki, if:
    ///     - group mode is NOGROUPS,
    ///     - group mode is VISIBLEGROUPS,
    ///     - group mode is SEPARATEGROUPS, and they are a member of the requested group,
    ///     - they are an editing teacher or administrator,
    ///     - they are a non-editing teacher not assigned to a specific group.
    if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or
        (($groupmode == SEPARATEGROUPS) and @in_array($groupid, $usersgroup)/*($usersgroup == $groupid)*/) or
        (isteacheredit($course->id, $USER->id)) or
        (isteacher($course->id, $USER->id) and !$usersgroup)) {
        $can_access = true;
    }
    else {
        $can_access = false;
    }
    return $can_access;
}

function wiki_user_can_access_teacher_wiki(&$wiki, $groupid, &$course) {
    global $USER;

    /// Get the groupmode. It's been added to the wiki object.
    $groupmode = groupmode($course, $wiki);

    /// A user can access a teacher wiki, if:
    ///     - group mode is NOGROUPS,
    ///     - group mode is VISIBLEGROUPS,
    ///     - group mode is SEPARATEGROUPS, and they are a member of the requested group,
    ///     - they are a teacher or administrator,
    if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or
        (($groupmode == SEPARATEGROUPS) and (@in_array($groupid, mygroupid($course->id))/*mygroupid($course->id) == $groupid*/)) or
        (isteacher($course->id, $USER->id))){
        $can_access = true;
    }
    else {
        $can_access = false;
    }
    return $can_access;
}

function wiki_get_owner(&$wiki_entry) {
    if ($wiki_entry->userid > 0) {
        $user = get_record('user', 'id', $wiki_entry->userid);
        $owner = fullname($user);
    }
    else if ($wiki_entry->groupid > 0) {
        $group = get_record('groups', 'id', $wiki_entry->groupid);
        $owner = $group->name;
    }
    else if ($wiki_entry->course > 0) {
        $course = get_record('course', 'id', $wiki_entry->course);
        $owner = $course->shortname;
    }
    else {
        $owner = '- '.get_string("ownerunknown","wiki").' -';
    }
    return $owner;
}

function wiki_print_search_form($cmid, $search="", $userid, $groupid, $return=false) {
    global $CFG;
    # TODO: Add Group and User !!!
    $output = "<form name=\"search\" action=\"$CFG->wwwroot/mod/wiki/view.php\">";
    $output .= "<font size=\"-1\">";
    $output .= "<input value=\"".get_string("searchwiki", "wiki").":\" type=\"submit\" />";
    $output .= "<input name=\"id\" type=\"hidden\" value=\"$cmid\" />";
    $output = $output.($groupid?"<input name=\"groupid\" type=\"hidden\" value=\"$groupid\" />":"");
    $output = $output.($userid?"<input name=\"userid\" type=\"hidden\" value=\"$userid\" />":"");
    $output .= "<input name=\"q\" type=\"text\" size=\"20\" value=\"".s($search)."\" />".' ';
    $output .= "</font>";
    $output .= "<input name=\"page\" type=\"hidden\" value=\"SearchPages\" />";
    $output .= "</form>";

    if ($return) {
        return $output;
    }
    echo $output;
}

function wiki_print_wikilinks_block($cmid, $binary=false, $return=false) {
/// Prints a link-list of special wiki-pages
   global $CFG, $ewiki_title;

   $links=array();

   $links["SiteMap"]=get_string("sitemap", "wiki");
   $links["PageIndex"]=get_string("pageindex", "wiki");
   $links["NewestPages"]=get_string("newestpages", "wiki");
   $links["MostVisitedPages"]=get_string("mostvisitedpages", "wiki");
   $links["MostOftenChangedPages"]=get_string("mostoftenchangedpages", "wiki");
   $links["UpdatedPages"]=get_string("updatedpages", "wiki");
   $links["OrphanedPages"]=get_string("orphanedpages", "wiki");
   $links["WantedPages"]=get_string("wantedpages", "wiki");
   $links["WikiExport"]=get_string("wikiexport", "wiki");
   if($binary) {
     $links["FileDownload"]=get_string("filedownload", "wiki");
   }
   popup_form(EWIKI_SCRIPT, $links, "wikilinks", "", get_string("choosewikilinks", "wiki"), "", "", $return);
}

function wiki_print_page_actions($cmid, $specialpages, $page, $action, $binary=false, $canedit=true) {
/// Displays actions which can be performed on the page

  $page=array();

  // Edit this Page
  if (in_array($action, array("edit", "links", "info", "attachments"))) {
    $page["view/$page"]=get_string("viewpage","wiki");
  }
  if ($canedit && !in_array($page, $specialpages) && $action != "edit") {
    $page["edit/$page"]=get_string("editthispage","wiki");
  }
  if ($action != "links") {
    $page["links/$page"]=get_string("backlinks","wiki");
  }
  if ($canedit && !in_array($page, $specialpages) && $action!="info") {
    $page["info/$page"]=get_string("pageinfo","wiki");
  }
  if($canedit && $binary && !in_array($page, $specialpages) && $action != "attachments") {
    $page["attachments/$page"]=get_string("attachments","wiki");
  }

  popup_form(EWIKI_SCRIPT, $page, "wikiactions", "", get_string("action", "wiki"), "", "", false);
}

function wiki_print_administration_actions($wiki, $cmid, $userid, $groupid, $page, $noeditor, $course) {
/// Displays actions which can be performed on the page
    
  /// Create the URL        
  $ewscript = 'admin.php?id='.$cmid;
  if (isset($userid) && $userid!=0) $ewscript .= '&amp;userid='.$userid;
  if (isset($groupid) && $groupid!=0) $ewscript .= '&amp;groupid='.$groupid;
  if (isset($page)) $ewscript .= '&amp;page='.$page;
  $ewscript.="&amp;action=";


    /// Build that action array according to wiki flags.
    $action = array();
    $isteacher = isteacher($course->id);

    if ($wiki->setpageflags or $isteacher) {
        $action['setpageflags'] = get_string('setpageflags', 'wiki');
    }
    if ($wiki->removepages or $isteacher) {
        $action['removepages']  = get_string('removepages', 'wiki');
    }
    if ($wiki->strippages or $isteacher) {
        $action['strippages']  = get_string('strippages', 'wiki');
    }
    if ($wiki->revertchanges or $isteacher) {
        $action['revertpages'] = get_string('revertpages', 'wiki');
    }

  if($noeditor) {
    $action["checklinks"]=get_string("checklinks", "wiki");
  }
  popup_form($ewscript, $action, "wikiadministration", "", get_string("chooseadministration", "wiki"), "", "", false);
}

function wiki_admin_get_flagarray() {
  $ret = array(
     EWIKI_DB_F_TEXT => get_string("flagtxt","wiki"),
     EWIKI_DB_F_BINARY => get_string("flagbin","wiki"),
     EWIKI_DB_F_DISABLED => get_string("flagoff","wiki"),
     EWIKI_DB_F_HTML => get_string("flaghtm","wiki"),
     EWIKI_DB_F_READONLY => get_string("flagro","wiki"),
     EWIKI_DB_F_WRITEABLE => get_string("flagwr","wiki"),
  );

  return $ret;
}

///////// Ewiki Administration. Mostly taken from the ewiki/tools folder and changed
function wiki_admin_setpageflags_list($pageflagstatus) {
  $FD = wiki_admin_get_flagarray();
  $table->head = array(get_string("pagename","wiki"), get_string("flags","wiki"));
  if($pageflagstatus) {
    $table->head[]=get_string("status","wiki");
  }

  $result = ewiki_database("GETALL", array("version", "flags"));
  while ($row = $result->get()) {
    $id = $row["id"];
    $data = ewiki_database("GET", $row);

    $cell_pagename="";
    $cell_flags="";
    if ($data["flags"] & EWIKI_DB_F_TEXT) {
        $cell_pagename .= '<A HREF="' . EWIKI_SCRIPT . $id . '">';
    } else {
        $cell_pagename .= '<A HREF="' . EWIKI_SCRIPT_BINARY . $id . '">';
    }
    $cell_pagename .= s($id) . '</A> / '.get_string("version","wiki").": ".$row["version"];

    foreach ($FD as $n=>$str) {
        $cell_flags .='<INPUT TYPE="checkbox" NAME="flags['. rawurlencode($id)
            . '][' . $n . ']" VALUE="1" '
            . (($data["flags"] & $n) ? "CHECKED=\"checked\"" : "")
            . ' />'.$str. ' ';
    }
    if($pageflagstatus) {
      $table->data[]=array($cell_pagename, $cell_flags, $pageflagstatus[$id]);
    } else {
      $table->data[]=array($cell_pagename, $cell_flags);
    }
  }
  return $table;
}

function wiki_admin_setpageflags($pageflags) {
  $FD = wiki_admin_get_flagarray();

  $status=array();
  if($pageflags) {
     foreach($pageflags as $page=>$fa) {

        $page = rawurldecode($page);

        $flags = 0;
        $fstr = "";
        foreach($fa as $num=>$isset) {
           if ($isset) {
              $flags += $num;
              $fstr .= ($fstr?",":""). $FD[$num];
           }
        }

        #$status[$page] .= "{$flags}=[{$fstr}]";

        $data = ewiki_database("GET", array("id" => $page));

        if ($data["flags"] != $flags) {
           $data["flags"] = $flags;
           $data["author"] = "ewiki-tools, " . ewiki_author();
           $data["version"]++;
           ewiki_database("WRITE", $data);
           $status[$page] =  "<b>".get_string("flagsset","wiki")."</b> ".$status[$page];
        }
     }
  }
  return $status;
}


function wiki_admin_remove_list($listall="") {
  /// Table header
  $table->head = array("&nbsp;", get_string("pagename","wiki"), get_string("errororreason","wiki"));

  /// Get all pages
  $result = ewiki_database("GETALL", array("version"));
  $selected = array();

  /// User wants to see all pages
  if ($listall) {
    while ($row = $result->get()) {
      $selected[$row["id"]] = get_string("listall","wiki")."<br />";
    }
  }
  while ($page = $result->get()) {
    $id = $page["id"];
    $page = ewiki_database("GET", array("id"=>$id));
    $flags = $page["flags"];
    #print "$id ".strlen(trim(($page["content"])))."<br />";

    if (!strlen(trim(($page["content"]))) && !($flags & EWIKI_DB_F_BINARY)) {
        @$selected[$id] .= get_string("emptypage","wiki")."<br />";
    }

    // Check for orphaned pages
    $result2 = ewiki_database("SEARCH", array("content" => $id));
    $orphanedpage=true;
    if ($result2 && $result2->count()) {
        while ($row = $result2->get()) {
          $checkcontent = ewiki_database("GET", array("id"=>$row["id"]));
          $checkcontent = strtolower($checkcontent["content"]);

          if(strpos($checkcontent, strtolower($id)) !== false) {
            $orphanedpage=false;
          }

          #echo "rc({$row['id']})==>($id): $check2 <br />";
        }
    }

    /// Some more reasons for Deletion...
    if ($orphanedpage && $id!=EWIKI_PAGE_INDEX &&!($flags & EWIKI_DB_F_BINARY)) {
        @$selected[$id] .= get_string("orphanedpage","wiki")."<br />";
    }

    if ($flags & EWIKI_DB_F_DISABLED) {
        @$selected[$id] .= get_string("disabledpage","wiki")."<br />";
    }

    if (($flags & 3) == 3) {
        @$selected[$id] .= get_string("errorbinandtxt","wiki")."<br />";
    }

    if (!($flags & 3)) {
        @$selected[$id] .= get_string("errornotype","wiki")."<br />";
    }

    if ($flags & EWIKI_DB_F_HTML) {
        @$selected[$id] .= get_string("errorhtml","wiki")."<br />";
    }

    if (($flags & EWIKI_DB_F_READONLY) && !($flags & EWIKI_DB_F_BINARY)) {
        @$selected[$id] .= get_string("readonly","wiki")."<br />";
    }

    if (($flags & EWIKI_DB_F_READONLY) && ($flags & EWIKI_DB_F_WRITEABLE)) {
        @$selected[$id] .= get_string("errorroandwr","wiki")."<br />";
    }

    if (strlen($page["content"]) >= 65536) {
        @$selected[$id] .= get_string("errorsize","wiki")."<br />";
    }

    if (strpos($page["refs"], "\n".get_string("deletemewikiword","wiki")."\n")!==false) {
        @$selected[$id] .= get_string("deletemewikiwordfound","wiki",get_string("deletemewikiword","wiki"))."<br />";
    }
  }

  foreach ($selected as $id => $reason) {
    $table_checkbox='<INPUT TYPE="checkbox" VALUE="'.rawurlencode($id).'" NAME="pagestodelete[]" />';

    #-- link & id
    if (strpos($id, EWIKI_IDF_INTERNAL) === false) {
        $table_page='<A HREF="' . ewiki_script("", $id) . '">';
    } else {
        $table_page='<A HREF="' . ewiki_script_binary("", $id) . '">';
    }
    $table_page .= s($id) . '</A>';

    #-- print reason
    $table_reason=$reason;

    $table->data[]=array($table_checkbox, $table_page, $table_reason);
  }

  return $table;
}

/// This function actually removes the pages
function wiki_admin_remove($pagestodelete, $course, $wiki, $userid, $groupid) {
  $ret="";
  foreach ($pagestodelete as $id) {

    $id = rawurldecode($id);

    $data = ewiki_database("GET", array("id"=>$id));
    for ($version=1; $version<=$data["version"]; $version++) {
        ewiki_database("DELETE", array("id"=>$id, "version"=>$version));
        if($data["flags"] & EWIKI_DB_F_BINARY) {
          $filepath=moodle_binary_get_path($id, $data["meta"], $course, $wiki, $userid, $groupid);
          @unlink("$filepath");
        }
    }

  }
  return $ret;
}

function wiki_admin_strip_list($pagestostrip="",$version="",$err="") {
  /// Table header
  $table->head = array("&nbsp;", get_string("pagename","wiki"), get_string("deleteversions","wiki"));

  $vc=ewiki_database("COUNTVERSIONS", array());
  $result = ewiki_database("GETALL",array());
  $i=0;
  while ($row = $result->get()) {
     $id = $row["id"];
     if($vc[$id]>1) {
        $error="";
        if($err[$id]) {
          $error=" ".join(", ",$err[$id]);
        }
        $checked="";
        if($pagestostrip=="" || $pagestostrip[$i]) {
          $checked=" CHECKED";
        }
        if($version=="") {
          $versiondefault="1-".($row["version"]-1);
        } else {
          $versiondefault=$version[$i];
        }
        $table->data[]=array('<input type="checkbox" value="'.rawurlencode($id).'" name="pagestostrip['.$i.']" '.$checked.' />',
                        '<A HREF="'.EWIKI_SCRIPT.$id.'">'.s($id).'</A> / '.get_string("version","wiki").": ".$row["version"],
                        '<input name="version['.$i.']" value="'.$versiondefault.'" size="7" />'.$error);

      }
      $i++;
  }
  return $table;
}

function wiki_admin_strip_versions($pagestostrip, $version, &$err) {
  $ret=array();
  foreach ($pagestostrip as $key => $id_ue) {

    $id = rawurldecode($id_ue);
    if (preg_match('/^(\d+)[-\s._:]+(\d+)$/', trim($version[$key]), $uu)) {
      $versA = $uu[1];
      $versZ = $uu[2];

      // Let the last Version in the database
      $checkdata = ewiki_database("GET", array("id" => $id));
      if($versZ>=$checkdata["version"]) {
            $err[$id][] = get_string("versionrangetoobig","wiki");
      } else {
        if($versA<=$versZ) {
          for ($v=$versA; $v<=$versZ; $v++) {
              $ret[$id][]=$v;
          }
        } else {
          $err[$id][]=get_string("wrongversionrange","wiki",$version[$key]);
        }
      }
    }
    else {
      $err[$id][]=get_string("wrongversionrange","wiki",$version[$key]);
    }
  }
  return $ret;
}

function wiki_admin_strip($pagestostrip) {
  /// Purges old page-versions
  foreach($pagestostrip as $id => $versions) {
    foreach($versions as $version) {
      ewiki_database("DELETE", array("id"=>$id, "version"=>$version));
    }
  }
}

function wiki_admin_checklinks_list() {
  $ret=array();
  $result = ewiki_database("GETALL",array());
  while ($row = $result->get()) {
    if(!($row["flags"] & EWIKI_DB_F_BINARY)) {
      $index=s($row["id"]);
      $ret[$index] = $row["id"];
    }
  }
  return $ret;
}

function wiki_admin_checklinks($pagetocheck) {
  /// Checks http:// Links
  $ret="";
  if($pagetocheck) {
     $get = ewiki_database("GET", array("id" => $pagetocheck));
     $content = $get["content"];

     preg_match_all('_(http.?://[^\s"\'<>#,;]+[^\s"\'<>#,;.])_', $content, $links);
     $badlinks = array();
     if(!$links[1]) {
       $ret = get_string("nolinksfound","wiki")."<br /><br />";
     } else {
       foreach ($links[1] as $href) {
          #print "[ $href ]";
          #$d = @implode("", @file($href));
          $d="";
          if($checkfd = @fopen($href, 'r')) {
            fclose($checkfd);
            $d="OK";
          }
          if (empty($d) || !strlen(trim($d)) || stristr("not found", $d) || stristr("error 404", $d)) {
             $ret.="[".get_string("linkdead","wiki")."] $href <br />\n";
             $badlinks[] = $href;
          } else {
             $ret.="[".get_string("linkok","wiki")."] $href <br />\n";
          }
       }
     }

     /// Remove old Notices
     $content = eregi_replace(' __~\['.get_string("offline","wiki").'\]__ ','', $content);

     #-- replace dead links
     foreach ($badlinks as $href) {
        $content = preg_replace("\377^(.*)($href)\377m", '$1 __~['.get_string("offline","wiki").']__ $2', $content);
     }

     #-- compare against db content
     if ($content != $get["content"]) {
        $get["content"] = $content;
        $get["version"]++;
        $get["author"] = ewiki_author("ewiki_checklinks");
        $get["lastmodified"] = time();

        ewiki_database("WRITE", $get);
     }
  }
  return $ret;
}

function wiki_admin_revert($proceed, $authorfieldpattern, $changesfield, $howtooperate, $deleteversions) {
  $ret="";
  #-- params
  $m_time = $changesfield * 3600;
  $depth = $deleteversions - 1;
  $depth = ($depth>0?$depth:0);

  #-- walk through
  $result = ewiki_database("GETALL", array("id", "author", "lastmodified"));
  while ($row = $result->get()) {
    $id = $row["id"];
    #-- which versions to check
    $verZ = $row["version"];
    if ($howtooperate=="lastonly") {
      $verA = $verZ;
    }
    else {
      $verA = $verZ-$depth;
      if ($verA <= 0) {
          $verA = 1;
      }
    }

    for ($ver=$verA; $ver<=$verZ; $ver++) {
      #-- load current $ver database entry
      if ($verA != $verZ) {
          $row = ewiki_database("GET", array("id"=>$id, "version"=>$ver));
      }

      #-- match
      if (stristr($row["author"], $authorfieldpattern) && ($row["lastmodified"] + $m_time > time())) {
        $ret .= "$id (".get_string("versionstodelete","wiki").": ";
        #-- delete multiple versions
        if ($howtooperate=="allsince") {
          while ($ver<=$verZ) {
              $ret .= " $ver";
              if ($proceed) {
                ewiki_database("DELETE", array("id"=>$id, "version"=>$ver));
              }
              $ver++;
          }
        }
        #-- or just the affected one
        else {
          $ret .= " $ver";
          if ($proceed) {
            ewiki_database("DELETE", $row);
          }
        }
        $ret .= ")<br />";
        break;
      }
    } #-- for($ver)
  } #-- while($row)
  return $ret;
}


function wiki_get_view_actions() {
    return array('view','view all');
}

function wiki_get_post_actions() {
    return array('hack');
}


?>