From 00710f4cc17c9519c02dd2c4a7fa7c1dd8545dbf Mon Sep 17 00:00:00 2001 From: Dongsheng Cai Date: Sun, 2 May 2010 11:28:11 +0000 Subject: [PATCH] MDL-22112, push wiki 2.0 into head --- mod/wiki/README | 5 + mod/wiki/TODO.txt | 22 - mod/wiki/admin.php | 366 --- mod/wiki/backuplib.php | 255 +- mod/wiki/checklinks.html | 18 - mod/wiki/comments.php | 73 + mod/wiki/comments_form.php | 38 + mod/wiki/confirmlock.php | 34 - mod/wiki/create.php | 106 + mod/wiki/create_form.php | 60 + mod/wiki/db/access.php | 77 +- mod/wiki/db/install.php | 9 +- mod/wiki/db/install.xml | 148 +- mod/wiki/db/migration/lib.php | 66 + .../{ => db/migration/wiki}/ewiki/ewiki.php | 90 +- .../plugins/moodle/moodle_rescue_html.php | 10 +- .../migration/wiki}/ewikimoodlelib.php | 6 +- mod/wiki/db/upgrade.php | 340 ++- mod/wiki/db/upgradelib.php | 303 +++ mod/wiki/diff.php | 83 + mod/wiki/diff/diff_added_begins.gif | Bin 0 -> 61 bytes mod/wiki/diff/diff_added_ends.gif | Bin 0 -> 51 bytes mod/wiki/diff/diff_nwiki.php | 1093 ++++++++ mod/wiki/diff/difflib.php | 728 +++++ mod/wiki/edit.php | 138 + mod/wiki/edit_form.php | 95 + mod/wiki/editcomments.php | 72 + mod/wiki/editors/html.php | 34 + mod/wiki/editors/wiki/buttons.js | 82 + mod/wiki/editors/wiki/images/ed_about.gif | Bin 0 -> 87 bytes mod/wiki/editors/wiki/images/ed_anchor.gif | Bin 0 -> 118 bytes mod/wiki/editors/wiki/images/ed_bold.gif | Bin 0 -> 658 bytes mod/wiki/editors/wiki/images/ed_center.gif | Bin 0 -> 642 bytes mod/wiki/editors/wiki/images/ed_custom.gif | Bin 0 -> 67 bytes mod/wiki/editors/wiki/images/ed_external.gif | Bin 0 -> 724 bytes .../editors/wiki/images/ed_format_strike.gif | Bin 0 -> 78 bytes .../editors/wiki/images/ed_format_sub.gif | Bin 0 -> 78 bytes .../editors/wiki/images/ed_format_sup.gif | Bin 0 -> 77 bytes .../wiki/images/ed_format_underline.gif | Bin 0 -> 85 bytes mod/wiki/editors/wiki/images/ed_h1.gif | Bin 0 -> 706 bytes mod/wiki/editors/wiki/images/ed_h2.gif | Bin 0 -> 719 bytes mod/wiki/editors/wiki/images/ed_h3.gif | Bin 0 -> 728 bytes mod/wiki/editors/wiki/images/ed_help.gif | Bin 0 -> 70 bytes mod/wiki/editors/wiki/images/ed_hr.gif | Bin 0 -> 643 bytes mod/wiki/editors/wiki/images/ed_image.gif | Bin 0 -> 148 bytes mod/wiki/editors/wiki/images/ed_img.gif | Bin 0 -> 704 bytes .../editors/wiki/images/ed_indent_more.gif | Bin 0 -> 87 bytes mod/wiki/editors/wiki/images/ed_internal.gif | Bin 0 -> 672 bytes mod/wiki/editors/wiki/images/ed_italic.gif | Bin 0 -> 657 bytes mod/wiki/editors/wiki/images/ed_justify.gif | Bin 0 -> 636 bytes mod/wiki/editors/wiki/images/ed_left.gif | Bin 0 -> 642 bytes mod/wiki/editors/wiki/images/ed_math.gif | Bin 0 -> 666 bytes mod/wiki/editors/wiki/images/ed_nowiki.gif | Bin 0 -> 687 bytes mod/wiki/editors/wiki/images/ed_ol.gif | Bin 0 -> 661 bytes mod/wiki/editors/wiki/images/ed_right.gif | Bin 0 -> 639 bytes mod/wiki/editors/wiki/images/ed_smiley.gif | Bin 0 -> 881 bytes mod/wiki/editors/wiki/images/ed_smiley1.gif | Bin 0 -> 742 bytes mod/wiki/editors/wiki/images/ed_smiley2.gif | Bin 0 -> 1004 bytes mod/wiki/editors/wiki/images/ed_stamp.gif | Bin 0 -> 1347 bytes mod/wiki/editors/wiki/images/ed_table.gif | Bin 0 -> 657 bytes mod/wiki/editors/wiki/images/ed_ul.gif | Bin 0 -> 653 bytes mod/wiki/editors/wiki/images/file_view.gif | Bin 0 -> 157 bytes mod/wiki/editors/wiki/images/folderup.gif | Bin 0 -> 196 bytes mod/wiki/editors/wiki/images/spell-check.gif | Bin 0 -> 107 bytes mod/wiki/editors/wiki_editor.php | 82 + mod/wiki/editors/wikieditor.php | 141 + mod/wiki/editors/wikifiletable.php | 138 + mod/wiki/ewiki/CREDITS | 82 - mod/wiki/ewiki/INSTALL | 22 - mod/wiki/ewiki/UPGRADE | 2 - mod/wiki/ewiki/fragments/README | 114 - mod/wiki/ewiki/fragments/auth.php | 41 - mod/wiki/ewiki/fragments/binary.php | 21 - mod/wiki/ewiki/fragments/calendar.css | 39 - mod/wiki/ewiki/fragments/core.css | 63 - mod/wiki/ewiki/fragments/funcs.inc | 33 - mod/wiki/ewiki/fragments/homepage.src | 172 -- mod/wiki/ewiki/fragments/htaccess | 25 - mod/wiki/ewiki/fragments/mkhuge | 61 - mod/wiki/ewiki/fragments/nuke_mod_wiki_index | 58 - .../fragments/strip_wonderful_slashes.php | 52 - mod/wiki/ewiki/fragments/wiki_format.inc | 291 -- mod/wiki/ewiki/plugins/aview/backlinks.php | 21 - mod/wiki/ewiki/plugins/aview/downloads.php | 61 - mod/wiki/ewiki/plugins/email_protect.php | 313 --- .../ewiki/plugins/feature/imgresize_gd.php | 121 - mod/wiki/ewiki/plugins/init.php | 125 - mod/wiki/ewiki/plugins/jump.php | 100 - mod/wiki/ewiki/plugins/lib/mime_magic.php | 571 ---- mod/wiki/ewiki/plugins/markup/footnotes.php | 60 - mod/wiki/ewiki/plugins/moodle/diff.php | 114 - mod/wiki/ewiki/plugins/moodle/downloads.php | 399 --- mod/wiki/ewiki/plugins/moodle/f_fixhtml.php | 177 -- .../plugins/moodle/moodle_binary_store.php | 119 - .../ewiki/plugins/moodle/moodle_highlight.php | 79 - .../ewiki/plugins/moodle/moodle_wikidump.php | 456 ---- mod/wiki/ewiki/plugins/moodle/sitemap.php | 242 -- mod/wiki/ewiki/plugins/moodle/wantedpages.php | 65 - mod/wiki/ewiki/plugins/notify.php | 232 -- mod/wiki/ewiki/plugins/page/orphanedpages.php | 62 - mod/wiki/ewiki/plugins/page/pageindex.php | 44 - mod/wiki/ewiki/plugins/patchsaving.php | 89 - mod/wiki/ewiki/plugins/pluginloader.php | 126 - mod/wiki/ewiki/plugins/spages.php | 182 -- mod/wiki/filter.php | 73 - mod/wiki/history.php | 76 + mod/wiki/index.php | 163 +- mod/wiki/instancecomments.php | 89 + mod/wiki/lang/en/wiki.php | 389 ++- mod/wiki/lib.php | 2333 +++-------------- mod/wiki/locallib.php | 1378 ++++++++++ mod/wiki/lock.php | 85 + mod/wiki/map.php | 72 + mod/wiki/mod_form.php | 147 +- mod/wiki/module.js | 76 + mod/wiki/overridelock.php | 52 - mod/wiki/overridelocks.php | 89 + mod/wiki/pagelib.php | 2260 ++++++++++++++++ mod/wiki/parser/markups/creole.php | 212 ++ mod/wiki/parser/markups/html.php | 80 + mod/wiki/parser/markups/nwiki.php | 282 ++ mod/wiki/parser/markups/wikimarkup.php | 433 +++ mod/wiki/parser/parser.php | 284 ++ mod/wiki/parser/utils.php | 98 + mod/wiki/pix/attachment.png | Bin 0 -> 309 bytes mod/wiki/prettyview.php | 69 + mod/wiki/removepages.html | 33 - mod/wiki/renderer.php | 401 +++ mod/wiki/restorelib.php | 426 +-- mod/wiki/restoreversion.php | 84 + mod/wiki/revertpages.html | 63 - mod/wiki/search.php | 62 + mod/wiki/setpageflags.html | 19 - mod/wiki/simpletest/input/creole/1 | 5 + mod/wiki/simpletest/input/creole/2 | 19 + mod/wiki/simpletest/input/creole/3 | 8 + mod/wiki/simpletest/input/creole/4 | 10 + mod/wiki/simpletest/input/creole/5 | 6 + mod/wiki/simpletest/input/creole/6 | 18 + mod/wiki/simpletest/input/creole/7 | 4 + mod/wiki/simpletest/input/creole/8 | 28 + mod/wiki/simpletest/input/creole/9 | 133 + mod/wiki/simpletest/input/html/1 | 20 + mod/wiki/simpletest/input/html/2 | 7 + mod/wiki/simpletest/input/nwiki/1 | 20 + mod/wiki/simpletest/input/nwiki/2 | 23 + mod/wiki/simpletest/input/nwiki/3 | 22 + mod/wiki/simpletest/input/nwiki/4 | 13 + mod/wiki/simpletest/input/nwiki/5 | 0 mod/wiki/simpletest/output/creole/1 | 3 + mod/wiki/simpletest/output/creole/2 | 12 + mod/wiki/simpletest/output/creole/3 | 5 + mod/wiki/simpletest/output/creole/4 | 6 + mod/wiki/simpletest/output/creole/5 | 4 + mod/wiki/simpletest/output/creole/6 | 21 + mod/wiki/simpletest/output/creole/7 | 3 + mod/wiki/simpletest/output/creole/8 | 85 + mod/wiki/simpletest/output/creole/9 | 146 ++ mod/wiki/simpletest/output/html/1 | 20 + mod/wiki/simpletest/output/html/2 | 7 + mod/wiki/simpletest/output/nwiki/1 | 11 + mod/wiki/simpletest/output/nwiki/2 | 12 + mod/wiki/simpletest/output/nwiki/3 | 39 + mod/wiki/simpletest/output/nwiki/4 | 26 + mod/wiki/simpletest/output/nwiki/5 | 1 + mod/wiki/simpletest/testwikiparser.php | 81 + mod/wiki/strippages.html | 23 - mod/wiki/styles.css | 353 ++- mod/wiki/test.php | 2 - mod/wiki/version.php | 40 +- mod/wiki/view.php | 763 ++---- mod/wiki/viewversion.php | 75 + mod/wiki/wiki.js | 3 - 173 files changed, 12180 insertions(+), 9271 deletions(-) create mode 100644 mod/wiki/README delete mode 100644 mod/wiki/TODO.txt delete mode 100644 mod/wiki/admin.php delete mode 100644 mod/wiki/checklinks.html create mode 100644 mod/wiki/comments.php create mode 100644 mod/wiki/comments_form.php delete mode 100644 mod/wiki/confirmlock.php create mode 100644 mod/wiki/create.php create mode 100644 mod/wiki/create_form.php create mode 100644 mod/wiki/db/migration/lib.php rename mod/wiki/{ => db/migration/wiki}/ewiki/ewiki.php (97%) rename mod/wiki/{ => db/migration/wiki}/ewiki/plugins/moodle/moodle_rescue_html.php (97%) rename mod/wiki/{ => db/migration/wiki}/ewikimoodlelib.php (97%) create mode 100644 mod/wiki/db/upgradelib.php create mode 100644 mod/wiki/diff.php create mode 100644 mod/wiki/diff/diff_added_begins.gif create mode 100644 mod/wiki/diff/diff_added_ends.gif create mode 100644 mod/wiki/diff/diff_nwiki.php create mode 100644 mod/wiki/diff/difflib.php create mode 100644 mod/wiki/edit.php create mode 100644 mod/wiki/edit_form.php create mode 100644 mod/wiki/editcomments.php create mode 100644 mod/wiki/editors/html.php create mode 100644 mod/wiki/editors/wiki/buttons.js create mode 100644 mod/wiki/editors/wiki/images/ed_about.gif create mode 100644 mod/wiki/editors/wiki/images/ed_anchor.gif create mode 100644 mod/wiki/editors/wiki/images/ed_bold.gif create mode 100644 mod/wiki/editors/wiki/images/ed_center.gif create mode 100644 mod/wiki/editors/wiki/images/ed_custom.gif create mode 100644 mod/wiki/editors/wiki/images/ed_external.gif create mode 100644 mod/wiki/editors/wiki/images/ed_format_strike.gif create mode 100644 mod/wiki/editors/wiki/images/ed_format_sub.gif create mode 100644 mod/wiki/editors/wiki/images/ed_format_sup.gif create mode 100644 mod/wiki/editors/wiki/images/ed_format_underline.gif create mode 100644 mod/wiki/editors/wiki/images/ed_h1.gif create mode 100644 mod/wiki/editors/wiki/images/ed_h2.gif create mode 100644 mod/wiki/editors/wiki/images/ed_h3.gif create mode 100644 mod/wiki/editors/wiki/images/ed_help.gif create mode 100644 mod/wiki/editors/wiki/images/ed_hr.gif create mode 100644 mod/wiki/editors/wiki/images/ed_image.gif create mode 100644 mod/wiki/editors/wiki/images/ed_img.gif create mode 100644 mod/wiki/editors/wiki/images/ed_indent_more.gif create mode 100644 mod/wiki/editors/wiki/images/ed_internal.gif create mode 100644 mod/wiki/editors/wiki/images/ed_italic.gif create mode 100644 mod/wiki/editors/wiki/images/ed_justify.gif create mode 100644 mod/wiki/editors/wiki/images/ed_left.gif create mode 100644 mod/wiki/editors/wiki/images/ed_math.gif create mode 100644 mod/wiki/editors/wiki/images/ed_nowiki.gif create mode 100644 mod/wiki/editors/wiki/images/ed_ol.gif create mode 100644 mod/wiki/editors/wiki/images/ed_right.gif create mode 100644 mod/wiki/editors/wiki/images/ed_smiley.gif create mode 100644 mod/wiki/editors/wiki/images/ed_smiley1.gif create mode 100644 mod/wiki/editors/wiki/images/ed_smiley2.gif create mode 100644 mod/wiki/editors/wiki/images/ed_stamp.gif create mode 100644 mod/wiki/editors/wiki/images/ed_table.gif create mode 100644 mod/wiki/editors/wiki/images/ed_ul.gif create mode 100644 mod/wiki/editors/wiki/images/file_view.gif create mode 100644 mod/wiki/editors/wiki/images/folderup.gif create mode 100644 mod/wiki/editors/wiki/images/spell-check.gif create mode 100644 mod/wiki/editors/wiki_editor.php create mode 100644 mod/wiki/editors/wikieditor.php create mode 100644 mod/wiki/editors/wikifiletable.php delete mode 100644 mod/wiki/ewiki/CREDITS delete mode 100644 mod/wiki/ewiki/INSTALL delete mode 100644 mod/wiki/ewiki/UPGRADE delete mode 100644 mod/wiki/ewiki/fragments/README delete mode 100644 mod/wiki/ewiki/fragments/auth.php delete mode 100644 mod/wiki/ewiki/fragments/binary.php delete mode 100644 mod/wiki/ewiki/fragments/calendar.css delete mode 100644 mod/wiki/ewiki/fragments/core.css delete mode 100644 mod/wiki/ewiki/fragments/funcs.inc delete mode 100644 mod/wiki/ewiki/fragments/homepage.src delete mode 100644 mod/wiki/ewiki/fragments/htaccess delete mode 100644 mod/wiki/ewiki/fragments/mkhuge delete mode 100644 mod/wiki/ewiki/fragments/nuke_mod_wiki_index delete mode 100644 mod/wiki/ewiki/fragments/strip_wonderful_slashes.php delete mode 100644 mod/wiki/ewiki/fragments/wiki_format.inc delete mode 100755 mod/wiki/ewiki/plugins/aview/backlinks.php delete mode 100644 mod/wiki/ewiki/plugins/aview/downloads.php delete mode 100644 mod/wiki/ewiki/plugins/email_protect.php delete mode 100755 mod/wiki/ewiki/plugins/feature/imgresize_gd.php delete mode 100644 mod/wiki/ewiki/plugins/init.php delete mode 100644 mod/wiki/ewiki/plugins/jump.php delete mode 100644 mod/wiki/ewiki/plugins/lib/mime_magic.php delete mode 100755 mod/wiki/ewiki/plugins/markup/footnotes.php delete mode 100755 mod/wiki/ewiki/plugins/moodle/diff.php delete mode 100644 mod/wiki/ewiki/plugins/moodle/downloads.php delete mode 100644 mod/wiki/ewiki/plugins/moodle/f_fixhtml.php delete mode 100644 mod/wiki/ewiki/plugins/moodle/moodle_binary_store.php delete mode 100644 mod/wiki/ewiki/plugins/moodle/moodle_highlight.php delete mode 100644 mod/wiki/ewiki/plugins/moodle/moodle_wikidump.php delete mode 100644 mod/wiki/ewiki/plugins/moodle/sitemap.php delete mode 100644 mod/wiki/ewiki/plugins/moodle/wantedpages.php delete mode 100644 mod/wiki/ewiki/plugins/notify.php delete mode 100755 mod/wiki/ewiki/plugins/page/orphanedpages.php delete mode 100755 mod/wiki/ewiki/plugins/page/pageindex.php delete mode 100644 mod/wiki/ewiki/plugins/patchsaving.php delete mode 100644 mod/wiki/ewiki/plugins/pluginloader.php delete mode 100644 mod/wiki/ewiki/plugins/spages.php delete mode 100755 mod/wiki/filter.php create mode 100644 mod/wiki/history.php create mode 100644 mod/wiki/instancecomments.php create mode 100644 mod/wiki/locallib.php create mode 100644 mod/wiki/lock.php create mode 100644 mod/wiki/map.php create mode 100644 mod/wiki/module.js delete mode 100644 mod/wiki/overridelock.php create mode 100644 mod/wiki/overridelocks.php create mode 100644 mod/wiki/pagelib.php create mode 100644 mod/wiki/parser/markups/creole.php create mode 100644 mod/wiki/parser/markups/html.php create mode 100644 mod/wiki/parser/markups/nwiki.php create mode 100644 mod/wiki/parser/markups/wikimarkup.php create mode 100644 mod/wiki/parser/parser.php create mode 100644 mod/wiki/parser/utils.php create mode 100644 mod/wiki/pix/attachment.png create mode 100644 mod/wiki/prettyview.php delete mode 100644 mod/wiki/removepages.html create mode 100644 mod/wiki/renderer.php create mode 100644 mod/wiki/restoreversion.php delete mode 100644 mod/wiki/revertpages.html create mode 100644 mod/wiki/search.php delete mode 100644 mod/wiki/setpageflags.html create mode 100644 mod/wiki/simpletest/input/creole/1 create mode 100644 mod/wiki/simpletest/input/creole/2 create mode 100644 mod/wiki/simpletest/input/creole/3 create mode 100644 mod/wiki/simpletest/input/creole/4 create mode 100644 mod/wiki/simpletest/input/creole/5 create mode 100644 mod/wiki/simpletest/input/creole/6 create mode 100644 mod/wiki/simpletest/input/creole/7 create mode 100644 mod/wiki/simpletest/input/creole/8 create mode 100644 mod/wiki/simpletest/input/creole/9 create mode 100644 mod/wiki/simpletest/input/html/1 create mode 100644 mod/wiki/simpletest/input/html/2 create mode 100644 mod/wiki/simpletest/input/nwiki/1 create mode 100644 mod/wiki/simpletest/input/nwiki/2 create mode 100644 mod/wiki/simpletest/input/nwiki/3 create mode 100644 mod/wiki/simpletest/input/nwiki/4 create mode 100644 mod/wiki/simpletest/input/nwiki/5 create mode 100644 mod/wiki/simpletest/output/creole/1 create mode 100644 mod/wiki/simpletest/output/creole/2 create mode 100644 mod/wiki/simpletest/output/creole/3 create mode 100644 mod/wiki/simpletest/output/creole/4 create mode 100644 mod/wiki/simpletest/output/creole/5 create mode 100644 mod/wiki/simpletest/output/creole/6 create mode 100644 mod/wiki/simpletest/output/creole/7 create mode 100644 mod/wiki/simpletest/output/creole/8 create mode 100644 mod/wiki/simpletest/output/creole/9 create mode 100644 mod/wiki/simpletest/output/html/1 create mode 100644 mod/wiki/simpletest/output/html/2 create mode 100644 mod/wiki/simpletest/output/nwiki/1 create mode 100644 mod/wiki/simpletest/output/nwiki/2 create mode 100644 mod/wiki/simpletest/output/nwiki/3 create mode 100644 mod/wiki/simpletest/output/nwiki/4 create mode 100644 mod/wiki/simpletest/output/nwiki/5 create mode 100644 mod/wiki/simpletest/testwikiparser.php delete mode 100644 mod/wiki/strippages.html delete mode 100644 mod/wiki/test.php create mode 100644 mod/wiki/viewversion.php delete mode 100644 mod/wiki/wiki.js diff --git a/mod/wiki/README b/mod/wiki/README new file mode 100644 index 00000000000..e7eaf50a849 --- /dev/null +++ b/mod/wiki/README @@ -0,0 +1,5 @@ +Wiki 2.0 + +by Jordi Piguillem and Ludo (Marc Alier) 2008 - Universitat Politecnica de +Catalunya +http://www.upc.edu - http://dfwikilabs.org \ No newline at end of file diff --git a/mod/wiki/TODO.txt b/mod/wiki/TODO.txt deleted file mode 100644 index d40862b929d..00000000000 --- a/mod/wiki/TODO.txt +++ /dev/null @@ -1,22 +0,0 @@ -ToDo -Mike: - - Group Handling (Mike) - > deal with changing group mode on active wikis - > handle group mode for teacher wikis - - Rating - - Commenting - - Grading - -Michael: - - Upload: There is an error when having a bin html-wiki: File does not show up - - Log when up- or download - - Notify when page changes - -Unassigned or not ready: - - Wiki HTML: http://moodle.org/mod/forum/discuss.php?d=8920 - - http://moodle.org/mod/forum/discuss.php?d=7768#36954 - - Image Thumbnails http://moodle.org/mod/forum/discuss.php?d=8351 - - -ewiki Preparation: - - Current Version: 1.01d diff --git a/mod/wiki/admin.php b/mod/wiki/admin.php deleted file mode 100644 index 1be7801e36d..00000000000 --- a/mod/wiki/admin.php +++ /dev/null @@ -1,366 +0,0 @@ -get_record("course", array("id"=>$cm->course))) { - print_error('coursemisconf'); - } - - if (! $wiki = $DB->get_record("wiki", array("id"=>$cm->instance))) { - print_error('invalidcoursemodule'); - } - - } else { - if (! $wiki = $DB->get_record("wiki", array("id"=>$a))) { - print_error('coursemisconf'); - } - if (! $course = $DB->get_record("course", array("id"=>$wiki->course))) { - print_error('coursemisconf'); - } - if (! $cm = get_coursemodule_from_instance("wiki", $wiki->id, $course->id)) { - print_error('invalidcoursemodule'); - } - } - - $url = new moodle_url('/mod/wiki/admin.php', array('id'=>$cm->id)); - if ($page !== false) { - $url->param('page', $page); - } - if ($confirm !== '') { - $url->param('confirm', $confirm); - } - if ($action !== '') { - $url->param('action', $action); - } - if ($userid !== 0) { - $url->param('userid', $userid); - } - if ($groupid !== 0) { - $url->param('groupid', $groupid); - } - $PAGE->set_url($url); - - require_login($course->id, false, $cm); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); - require_capability('mod/wiki:manage', $context); - - /// Build the ewsiki script constant - $ewbase = 'view.php?id='.$id; - if (isset($userid) && $userid!=0) $ewbase .= '&userid='.$userid; - if (isset($groupid) && $groupid!=0) $ewbase .= '&groupid='.$groupid; - $ewscript = $ewbase.'&page='; - define("EWIKI_SCRIPT", $ewscript); - if($wiki->ewikiacceptbinary) { - define("EWIKI_UPLOAD_MAXSIZE", get_max_upload_file_size()); - define("EWIKI_SCRIPT_BINARY", $ewbase."&binary="); - } - - - /// Add the course module 'groupmode' to the wiki object, for easy access. - $wiki->groupmode = $cm->groupmode; - - /// Is an Action given ? - if(!$action) { - print_error('noadministrationaction','wiki'); - } - - /// Correct Action ? - if(!in_array($action, array("setpageflags", "removepages", "strippages", "checklinks", "revertpages"))) { - print_error('unknowaction'); - } - - - /// May the User administrate it ? - if (($wiki_entry = wiki_get_entry($wiki, $course, $userid, $groupid)) === false || wiki_can_edit_entry($wiki_entry, $wiki, $USER, $course) === false) { - print_error('notadministratewiki', 'wiki'); - } - - $canedit = wiki_can_edit_entry($wiki_entry, $wiki, $USER, $course); - # Check for dangerous events (hacking) ! - if(in_array($action,array("removepages","strippages","revertpages"))) { - if(!($wiki->wtype=="student" || ($wiki->wtype=="group" and $canedit) || wiki_is_teacher($wiki))) { - add_to_log($course->id, "wiki", "hack", "", $wiki->name.": Tried to trick admin.php with action=$action."); - print_error('hackdetected'); - } - } - - # Database and Binary Handler - include_once($CFG->dirroot."/mod/wiki/ewikimoodlelib.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/moodle_binary_store.php"); - - /// The wiki_entry->pagename is set to the specified value of the wiki, - /// or the default value in the 'lang' file if the specified value was empty. - define("EWIKI_PAGE_INDEX",$wiki_entry->pagename); - # The mighty Wiki itself - include_once($CFG->dirroot."/mod/wiki/ewiki/ewiki.php"); - - $strwikis = get_string("modulenameplural", "wiki"); - $strwiki = get_string("modulename", "wiki"); - - /// Validate Form - if ($form = data_submitted()) { - switch($action) { - case "revertpages": - if(!$form->deleteversions || 0 > $form->deleteversions || $form->deleteversions > 1000) { - $focus="form.deleteversions"; - $err->deleteversions=get_string("deleteversionserror","wiki"); - } - if(!$form->changesfield || 0 > $form->changesfield || $form->changesfield > 100000) { - $focus="form.changesfield"; - $err->changesfield=get_string("changesfielderror","wiki"); - } - if($form->authorfieldpattern=="") { - $focus="form.authorfieldpattern"; - $err->authorfieldpattern=get_string("authorfieldpatternerror","wiki"); - } - break; - default: break; - } - } - - $PAGE->navbar->add(get_string("administration","wiki")); - $PAGE->set_title($wiki_entry->pagename); - $PAGE->set_focuscontrol($focus); - $PAGE->set_button($OUTPUT->update_module_button($cm->id, 'wiki')); - echo $OUTPUT->header(); - - //////////////////////////////////////////////////////////// - /// Check if the Form has been submitted and display confirmation - //////////////////////////////////////////////////////////// - if ($form = data_submitted()) { - /// Moodle Log - /// Get additional info - $addloginfo=""; - switch($action) { - case "removepages": - $addloginfo=@join(", ", $form->pagestodelete); - break; - case "strippages": - $addloginfo=@join(", ", $form->pagestostrip); - break; - case "checklinks": - $addloginfo=$form->pagetocheck; - break; - case "setpageflags": - // No additional info - break; - case "revertpages": - // No additional info - break; - } - add_to_log($course->id, "wiki", $action, "admin.php?action=$action&userid=$userid&groupid=$groupid&id=$id", $wiki->name.($addloginfo?": ".$addloginfo:"")); - $link="admin.php?action=$action".($userid?"&userid=".$userid:"").($groupid?"&groupid=".$groupid:"")."&id=$id&page=$page"; - switch($action) { - case "removepages": - if($form->proceed) { - if(!$confirm && $form->pagestodelete) { - echo $OUTPUT->confirm(get_string("removepagecheck", "wiki")."
".join(", ", $form->pagestodelete), - $link."&confirm=".urlencode(join(" ",$form->pagestodelete)), $link); - echo $OUTPUT->footer(); - exit; - } - } - break; - case "strippages": - if($form->proceed) { - if(!$confirm && $form->pagestostrip) { - $err=array(); - $strippages=wiki_admin_strip_versions($form->pagestostrip,$form->version, $err); - $confirm=""; - foreach($strippages as $cnfid => $cnfver) { - $confirm.="&confirm[$cnfid]=".urlencode(join(" ",$cnfver)); - } - if(count($err)==0) { - $pagestostrip=array(); - foreach($form->pagestostrip as $pagetostrip) { - $pagestostrip[]=htmlspecialchars(urldecode($pagetostrip)); - } - echo $OUTPUT->confirm(get_string("strippagecheck", "wiki")."
".join(", ", $pagestostrip), $link.$confirm, $link); - echo $OUTPUT->footer(); - exit; - } - } - } - break; - case "checklinks": - if($form->proceed) { - if(!$confirm && $form->pagetocheck) { - $confirm="&confirm=".$form->pagetocheck; - echo $OUTPUT->confirm(get_string("checklinkscheck", "wiki").$form->pagetocheck, $link.$confirm, $link); - echo $OUTPUT->footer(); - exit; - } - } - break; - case "setpageflags": - // pageflagstatus is used in setpageflags.html - $pageflagstatus=wiki_admin_setpageflags($form->flags); - break; - case "revertpages": - if(!$err) { - if(!$confirm) { - $confirm="&confirm[changesfield]=".urlencode($form->changesfield). - "&confirm[authorfieldpattern]=".urlencode($form->authorfieldpattern). - "&confirm[howtooperate]=".urlencode($form->howtooperate). - "&confirm[deleteversions]=".urlencode($form->deleteversions); - $revertedpages=wiki_admin_revert("", $form->authorfieldpattern, $form->changesfield, $form->howtooperate, $form->deleteversions); - if($revertedpages) { - echo $OUTPUT->confirm(get_string("revertpagescheck", "wiki")."
".$revertedpages, $link.$confirm, $link); - echo $OUTPUT->footer(); - exit; - } else { - $err->remark=get_string("nochangestorevert","wiki"); - } - } - } - break; - default: print_error('unknowaction'); - break; - } - } - - /// Actions which need a confirmation. If confirmed, do the action - $redirect="view.php?".($groupid?"&groupid=".$groupid:"").($userid?"&userid=".$userid:"")."&id=$id&page=$page"; - if($confirm && !$err) { - switch($action) { - case "removepages": - $ret=wiki_admin_remove(split(" ",$confirm), $course, $wiki, $userid, $groupid); - if(!$ret) { - redirect($redirect, get_string("pagesremoved","wiki"), 1); - } else { - print_error('invalidaction'); - } - exit; - case "strippages": - $strippages=array(); - foreach($confirm as $pageid => $versions) { - $strippages[$pageid]=split(" ",$versions); - } - $ret=wiki_admin_strip($strippages); - if(!$ret) { - redirect($redirect, get_string("pagesstripped","wiki"), 1); - } else { - print_error('invalidaction'); - } - exit; - case "checklinks": - $ret=wiki_admin_checklinks($confirm); - redirect($redirect, get_string("linkschecked","wiki")."
".$ret, 5); - exit; - case "revertpages": - $revertedpages=wiki_admin_revert(1, $confirm["authorfieldpattern"], $confirm["changesfield"], $confirm["howtooperate"], $confirm["deleteversions"]); - redirect($redirect, get_string("pagesreverted","wiki"), 1); - exit; - case "setpageflags": - # No confirmation needed - break; - default: print_error('unknowaction'); - } - } - - - /// The top row contains links to other wikis, if applicable. - if ($wiki_list = wiki_get_other_wikis($wiki, $USER, $course, $wiki_entry->id)) { - if (isset($wiki_list['selected'])) { - $selected = $wiki_list['selected']; - unset($wiki_list['selected']); - } - echo ''; - - echo '
'; - echo '
'; - echo ''; - echo ''; - - echo ''; - echo '
 ' - .$WIKI_TYPES[$wiki->wtype].' ' - .get_string('modulename', 'wiki').' for ' - .wiki_get_owner($wiki_entry).':' - .get_string('otherwikis', 'wiki').':  '; - $script = 'self.location=getElementById(\'otherwikis\').wikiselect.options[getElementById(\'otherwikis\').wikiselect.selectedIndex].value'; - - /// Add Admin-Action - reset($wiki_list); - $wiki_admin_list=array(); - while(list($key,$val)=each($wiki_list)) { - $wiki_admin_list[$key."&action=$action"]=$val; - } - $aid = $OUTPUT->add_action_handler(new component_action('change', 'go_to_wiki')); - $attributes = array('id'=>$aid); - echo html_writer::select($wiki_admin_list, 'wikiselect', $selected, array(''=>'choose'), $attributes); - echo '
'; - echo '
'; - - echo ''; - echo ''; - } - - if ($wiki_entry) { - - - /// Page Actions - echo ''; - echo ''; -/* echo '';*/ - - /// Searchform - echo ''; - - /// Internal Wikilinks - - /// TODO: DOES NOT WORK !!!! - echo ''; - - /// Administrative Links - echo ''; - -/** if($wiki->htmlmode!=2) { -* echo ''; -* }*/ - - echo '
'; -* $specialpages=array("SearchPages", "PageIndex","NewestPages","MostVisitedPages","MostOftenChangedPages","UpdatedPages","FileDownload","FileUpload","OrphanedPages","WantedPages"); -* wiki_print_page_actions($cm->id, $specialpages, $ewiki_id, $ewiki_action, $wiki->ewikiacceptbinary, $canedit); -* echo ''; - wiki_print_search_form($cm->id, $q, $userid, $groupid, false); - echo ''; - wiki_print_wikilinks_block($cm->id, $wiki->ewikiacceptbinary); - echo ''; - wiki_print_administration_actions($wiki, $cm->id, $userid, $groupid, $page, $wiki->htmlmode!=2, $course); - echo ''; -* helpbutton('formattingrules', get_string('formattingrules', 'wiki'), 'wiki'); -* echo get_string("formattingrules","wiki"); -* echo '
'; - } - - // The wiki Contents - echo $OUTPUT->box_start(); - // Do the Action - # "setpageflags", "removepages", "strippages", "checklinks", "revertpages" - - echo $OUTPUT->heading_with_help(get_string($action,"wiki"), $action, 'wiki'); - - include $action.".html"; - echo $OUTPUT->box_end(); - -/// Finish the page - echo $OUTPUT->footer(); - exit; - - diff --git a/mod/wiki/backuplib.php b/mod/wiki/backuplib.php index 7953c09f70e..94c9002ca2e 100644 --- a/mod/wiki/backuplib.php +++ b/mod/wiki/backuplib.php @@ -1,243 +1,16 @@ id) - // - // wiki_entries - // (pk->id, fk->wikiid) - // - // wiki_pages - // (pk->pagename,version,wiki, fk->wiki) - // - // Meaning: pk->primary key field of the table - // fk->foreign key to link with parent - // nt->nested field (recursive data) - // CL->course level info - // UL->user level info - // files->table may have files) - // - //----------------------------------------------------------- - - //This function executes all the backup procedure about this mod - function wiki_backup_mods($bf,$preferences) { - global $CFG, $DB; - - $status = true; - - ////Iterate over wiki table - if ($wikis = $DB->get_records ("wiki","course", array($preferences->backup_course=>"id"))) { - foreach ($wikis as $wiki) { - if (backup_mod_selected($preferences,'wiki',$wiki->id)) { - wiki_backup_one_mod($bf,$preferences,$wiki); - } - } - } - - return $status; - } - - function wiki_backup_one_mod($bf,$preferences,$wiki) { - global $DB; - - $status = true; - - if (is_numeric($wiki)) { - $wiki = $DB->get_record('wiki', array('id'=>$wiki)); - } - - //Start mod - fwrite ($bf,start_tag("MOD",3,true)); - //Print assignment data - fwrite ($bf,full_tag("ID",4,false,$wiki->id)); - fwrite ($bf,full_tag("MODTYPE",4,false,"wiki")); - fwrite ($bf,full_tag("NAME",4,false,$wiki->name)); - fwrite ($bf,full_tag("SUMMARY",4,false,$wiki->intro)); - fwrite ($bf,full_tag("PAGENAME",4,false,$wiki->pagename)); - fwrite ($bf,full_tag("WTYPE",4,false,$wiki->wtype)); - fwrite ($bf,full_tag("EWIKIPRINTTITLE",4,false,$wiki->ewikiprinttitle)); - fwrite ($bf,full_tag("HTMLMODE",4,false,$wiki->htmlmode)); - fwrite ($bf,full_tag("EWIKIACCEPTBINARY",4,false,$wiki->ewikiacceptbinary)); - fwrite ($bf,full_tag("DISABLECAMELCASE",4,false,$wiki->disablecamelcase)); - fwrite ($bf,full_tag("SETPAGEFLAGS",4,false,$wiki->setpageflags)); - fwrite ($bf,full_tag("STRIPPAGES",4,false,$wiki->strippages)); - fwrite ($bf,full_tag("REMOVEPAGES",4,false,$wiki->removepages)); - fwrite ($bf,full_tag("REVERTCHANGES",4,false,$wiki->revertchanges)); - fwrite ($bf,full_tag("INITIALCONTENT",4,false,$wiki->initialcontent)); - fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$wiki->timemodified)); - - //backup entries and pages - if (backup_userdata_selected($preferences,'wiki',$wiki->id)) { - $status = backup_wiki_entries($bf,$preferences,$wiki->id, $preferences->mods["wiki"]->userinfo); - $status = backup_wiki_files_instance($bf,$preferences,$wiki->id); - } - - //End mod - fwrite ($bf,end_tag("MOD",3,true)); - - return $status; - } - - function wiki_check_backup_mods_instances($instance,$backup_unique_code) { - $info[$instance->id.'0'][0] = $instance->name; - $info[$instance->id.'0'][1] = ''; - // wiki_check_backup_mods ignores userdata, so we do too. - return $info; - } - - ////Return an array of info (name,value) - function wiki_check_backup_mods($course,$user_data=false,$backup_unique_code,$instances=null) { - global $DB; - if (!empty($instances) && is_array($instances) && count($instances)) { - $info = array(); - foreach ($instances as $id => $instance) { - $info += wiki_check_backup_mods_instances($instance,$backup_unique_code); - } - return $info; - } - //First the course data - $info[0][0] = get_string("modulenameplural","wiki"); - $info[0][1] = $DB->count_records("wiki", array("course"=>$course)); - return $info; - } - - //Backup wiki_entries contents (executed from wiki_backup_mods) - function backup_wiki_entries ($bf,$preferences,$wiki, $userinfo) { - global $CFG, $DB; - - $status = true; - - $wiki_entries = $DB->get_records("wiki_entries", array("wikiid"=>$wiki), "id"); - //If there are entries - if ($wiki_entries) { - //Write start tag - $status =fwrite ($bf,start_tag("ENTRIES",4,true)); - //Iterate over each entry - foreach ($wiki_entries as $wik_ent) { - //Entry start - $status =fwrite ($bf,start_tag("ENTRY",5,true)); - - fwrite ($bf,full_tag("ID",6,false,$wik_ent->id)); - fwrite ($bf,full_tag("GROUPID",6,false,$wik_ent->groupid)); - fwrite ($bf,full_tag("USERID",6,false,$wik_ent->userid)); - fwrite ($bf,full_tag("PAGENAME",6,false,$wik_ent->pagename)); - fwrite ($bf,full_tag("TIMEMODIFIED",6,false,$wik_ent->timemodified)); - - //Now save entry pages - $status = backup_wiki_pages($bf,$preferences,$wik_ent->id); - - //Entry end - $status =fwrite ($bf,end_tag("ENTRY",5,true)); - } - //Write end tag - $status =fwrite ($bf,end_tag("ENTRIES",4,true)); - } - return $status; - } - - //Write wiki_pages contents - function backup_wiki_pages ($bf,$preferences,$entryid) { - global $CFG, $DB; - - $status = true; - - $pages = $DB->get_records("wiki_pages", array("wiki"=>$entryid)); - if ($pages) { - //Start tag - $status =fwrite ($bf,start_tag("PAGES",6,true)); - //Iterate over each page - foreach ($pages as $page) { - $status =fwrite ($bf,start_tag("PAGE",7,true)); - - fwrite ($bf,full_tag("ID",8,false,$page->id)); - fwrite ($bf,full_tag("PAGENAME",8,false,$page->pagename)); - fwrite ($bf,full_tag("VERSION",8,false,$page->version)); - fwrite ($bf,full_tag("FLAGS",8,false,$page->flags)); - fwrite ($bf,full_tag("CONTENT",8,false,$page->content)); - fwrite ($bf,full_tag("AUTHOR",8,false,$page->author)); - fwrite ($bf,full_tag("USERID",8,false,$page->userid)); - fwrite ($bf,full_tag("CREATED",8,false,$page->created)); - fwrite ($bf,full_tag("LASTMODIFIED",8,false,$page->lastmodified)); - fwrite ($bf,full_tag("REFS",8,false,str_replace("\n","$@LINEFEED@$",$page->refs))); - fwrite ($bf,full_tag("META",8,false,$page->meta)); - fwrite ($bf,full_tag("HITS",8,false,$page->hits)); - - $status =fwrite ($bf,end_tag("PAGE",7,true)); - } - $status =fwrite ($bf,end_tag("PAGES",6,true)); - } - return $status; - } - - function backup_wiki_files_instance($bf,$preferences,$instanceid) { - global $CFG, $DB; - - $status = true; - - //First we check to moddata exists and create it as necessary - //in temp/backup/$backup_code dir - $status = check_and_create_moddata_dir($preferences->backup_unique_code); - $status = check_dir_exists($CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/moddata/wiki/",true); - //Now copy the forum dir - if ($status) { - //Only if it exists !! Thanks to Daniel Miksik. - if (is_dir($CFG->dataroot."/".$preferences->backup_course."/".$CFG->moddata."/wiki/".$instanceid)) { - $status = backup_copy_file($CFG->dataroot."/".$preferences->backup_course."/".$CFG->moddata."/wiki/".$instanceid, - $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/moddata/wiki/".$instanceid); - } - } - - return $status; - } - - //Backup wiki binary files - function backup_wiki_files($bf,$preferences) { - global $CFG; - - $status = true; - - //First we check to moddata exists and create it as necessary - //in temp/backup/$backup_code dir - $status = check_and_create_moddata_dir($preferences->backup_unique_code); - //Now copy the forum dir - if ($status) { - //Only if it exists !! Thanks to Daniel Miksik. - if (is_dir($CFG->dataroot."/".$preferences->backup_course."/".$CFG->moddata."/wiki")) { - $handle = opendir($CFG->dataroot."/".$preferences->backup_course."/".$CFG->moddata."/wiki"); - while (false!==($item = readdir($handle))) { - if ($item != '.' && $item != '..' && is_dir($CFG->dataroot."/".$preferences->backup_course."/".$CFG->moddata."/wiki/".$item) - && array_key_exists($item,$preferences->mods['wiki']->instances) - && !empty($preferences->mods['wiki']->instances[$item]->backup)) { - $status = backup_copy_file($CFG->dataroot."/".$preferences->backup_course."/".$CFG->moddata."/wiki/".$item, - $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/moddata/wiki/",$item); - } - } - } - } - - return $status; - - } - - //Return a content encoded to support interactivities linking. Every module - //should have its own. They are called automatically from the backup procedure. - function wiki_encode_content_links ($content,$preferences) { - global $CFG; - - $base = preg_quote($CFG->wwwroot,"/"); - - //Link to the list of wikis - $buscar="/(".$base."\/mod\/wiki\/index.php\?id\=)([0-9]+)/"; - $result= preg_replace($buscar,'$@WIKIINDEX*$2@$',$content); - - //Link to wiki view by moduleid - $buscar="/(".$base."\/mod\/wiki\/view.php\?id\=)([0-9]+)/"; - $result= preg_replace($buscar,'$@WIKIVIEWBYID*$2@$',$result); - - return $result; - } - +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . diff --git a/mod/wiki/checklinks.html b/mod/wiki/checklinks.html deleted file mode 100644 index ed4ebbf5430..00000000000 --- a/mod/wiki/checklinks.html +++ /dev/null @@ -1,18 +0,0 @@ - -
-
- - - - - - - " /> -
-
diff --git a/mod/wiki/comments.php b/mod/wiki/comments.php new file mode 100644 index 00000000000..6469438dd4d --- /dev/null +++ b/mod/wiki/comments.php @@ -0,0 +1,73 @@ +. + +/** + * This file contains all necessary code to view a discussion page + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); + +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$pageid = required_param('pageid', PARAM_TEXT); + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} + +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} + +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +if (!$cm = get_coursemodule_from_instance('wiki', $wiki->id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} + +require_course_login($course->id, true, $cm); + +add_to_log($course->id, 'wiki', 'comments', 'comments.php?id='.$cm->id, $wiki->id); + +/// Print the page header +$wikipage = new page_wiki_comments($wiki, $subwiki, $cm); + +$wikipage->set_page($page); + +$wikipage->print_header(); +$wikipage->print_content(); +$wikipage->print_footer(); diff --git a/mod/wiki/comments_form.php b/mod/wiki/comments_form.php new file mode 100644 index 00000000000..72c85aa97be --- /dev/null +++ b/mod/wiki/comments_form.php @@ -0,0 +1,38 @@ +dirroot . '/lib/formslib.php'); + +class mod_wiki_comments_form extends moodleform { + function definition() { + $pageid = optional_param('pageid', 0, PARAM_INT); + $mform =& $this->_form; + + $current = $this->_customdata['current']; + $commentoptions = $this->_customdata['commentoptions']; + + // visible elements + $mform->addElement('editor', 'entrycomment_editor', get_string('comment', 'glossary'), null, $commentoptions); + $mform->addRule('entrycomment_editor', get_string('required'), 'required', null, 'client'); + $mform->setType('entrycomment_editor', PARAM_RAW); // processed by trust text or cleaned before the display + + // hidden optional params + $mform->addElement('hidden', 'id', ''); + $mform->setType('id', PARAM_INT); + + $mform->addElement('hidden', 'action', ''); + $mform->setType('action', PARAM_ACTION); + + //------------------------------------------------------------------------------- + // buttons + $this->add_action_buttons(false); + + //------------------------------------------------------------------------------- + $this->set_data($current); + } + + public function edit_definition($current, $commentoptions) { + $this->set_data($current); + $this->set_data($commentoptions); + } +} + diff --git a/mod/wiki/confirmlock.php b/mod/wiki/confirmlock.php deleted file mode 100644 index f56c80ecb35..00000000000 --- a/mod/wiki/confirmlock.php +++ /dev/null @@ -1,34 +0,0 @@ -set_url('/mod/wiki/confirmlock.php'); - -header('Content-Type: text/plain'); - -$lockid = optional_param('lockid', 0, PARAM_INT); - -if($lockid == 0) { - print 'noid'; - exit; -} - -if($lock=$DB->get_record('wiki_locks', array('id'=>$lockid))) { - $lock->lockedseen=time(); - $DB->update_record('wiki_locks',$lock); - print 'ok'; -} else { - print 'cancel'; // Tells user their lock has been cancelled. -} - diff --git a/mod/wiki/create.php b/mod/wiki/create.php new file mode 100644 index 00000000000..a89b46bef1f --- /dev/null +++ b/mod/wiki/create.php @@ -0,0 +1,106 @@ +. + + +require_once('../../config.php'); +require_once(dirname(__FILE__).'/create_form.php'); +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +// this page accepts two actions: new and create +// 'new' action will display a form contains page title and page format +// selections +// 'create' action will create a new page in db, and redirect to +// page editing page. +$action = optional_param('action', 'new', PARAM_TEXT); +// The title of the new page, can be empty +$title = optional_param('title', '', PARAM_TEXT); +$swid = optional_param('swid', 0, PARAM_INT); +$wid = optional_param('wid', 0, PARAM_INT); +$gid = optional_param('gid', 0, PARAM_INT); +$uid = optional_param('uid', 0, PARAM_INT); + +// 'create' action must be submitted by moodle form +// so sesskey must be checked +if ($action == 'create') { + if (!confirm_sesskey()) { + print_error('invalidsesskey'); + } +} + +$swiki = null; + +if (!empty($wid)) { + // @TODO: Check for capabilities + if (!$swid = wiki_add_subwiki($wid, $gid, $uid)) { + print_error('invalidwikiid'); + } + +} + +if (!$subwiki = wiki_get_subwiki($swid)) { + print_error('invalidswid', 'wiki'); +} + +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('invalidwikiid', 'wiki'); +} + +if (!$cm = get_coursemodule_from_instance('wiki', $wiki->id)) { + print_error('invalidcoursemoduleid', 'wiki'); +} + +if (!$course = get_course_by_id($cm->course)) { + print_error('invalidcourseid', 'wiki'); +} + +require_course_login($course->id, true, $cm); + +add_to_log($course->id, 'createpage', 'createpage', 'view.php?id='.$cm->id, $wiki->id); + +$wikipage = new page_wiki_create($wiki, $subwiki, $cm); + +$wikipage->set_gid($gid); +$wikipage->set_swid($swid); +if (!empty($title)) { + $wikipage->set_title($title); +} else { + $wikipage->set_title(get_string('newpage', 'wiki')); +} + +// set page action, and initialise moodle form +$wikipage->set_action($action); + +switch ($action) { +case 'create': + $wikipage->create_page($title); + break; +case 'new': + if (!empty($title)) { + // create page from interlink with pagetitle + $wikipage->print_header(); + $wikipage->print_content($title); + } else { + // create link from moodle navigation block without pagetitle + $wikipage->print_header(); + // new page without page title + $wikipage->print_content(); + } + $wikipage->print_footer(); + break; +} diff --git a/mod/wiki/create_form.php b/mod/wiki/create_form.php new file mode 100644 index 00000000000..00c62be4d7b --- /dev/null +++ b/mod/wiki/create_form.php @@ -0,0 +1,60 @@ +. + +/** + * This file contains all necessary code to define and process an edit form + * + * @package mod-wiki-2.0 + * @copyright 2010 Dongsheng Cai + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +class mod_wiki_create_form extends moodleform { + + protected function definition() { + global $CFG; + $mform =& $this->_form; + + $formats = $this->_customdata['formats']; + + $mform->addElement('header', 'general', get_string('createpage', 'wiki')); + + $textoptions = array(); + if (!empty($this->_customdata['disable_pagetitle'])) { + $textoptions = array('disabled'=>'disabled'); + } + $mform->addElement('text', 'pagetitle', get_string('newpagetitle', 'wiki'), $textoptions); + + // TODO: disable creole and nwiki format until moodle core text format lib added + $disabled_formats = array('creole', 'nwiki'); + foreach ($formats as $format) { + if (in_array($format, $disabled_formats)) { + $attr = array('disabled'=>'disabled'); + } else { + $attr = array('checked'=>'checked'); + } + $mform->addElement('radio', 'pageformat', '', get_string('format'.$format, 'wiki'), $format, $attr); + } + + //hiddens + $mform->addElement('hidden', 'action'); + $mform->setDefault('action', 'create'); + + $this->add_action_buttons(false, get_string('createpage', 'wiki')); + } +} diff --git a/mod/wiki/db/access.php b/mod/wiki/db/access.php index 9818e9da57c..0983cb13350 100644 --- a/mod/wiki/db/access.php +++ b/mod/wiki/db/access.php @@ -1,12 +1,30 @@ array( + 'mod/wiki:viewpage' => array( + + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_ALLOW, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ) + ), + + 'mod/wiki:editpage' => array( 'riskbitmask' => RISK_SPAM, @@ -20,10 +38,48 @@ $capabilities = array( ) ), - 'mod/wiki:manage' => array( + 'mod/wiki:createpage' => array( 'riskbitmask' => RISK_SPAM, + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ) + ), + + 'mod/wiki:viewcomment' => array( + + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ) + ), + + 'mod/wiki:editcomment' => array( + + 'riskbitmask' => RISK_SPAM, + + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ) + ), + + 'mod/wiki:managecomment' => array( + 'captype' => 'write', 'contextlevel' => CONTEXT_MODULE, 'legacy' => array( @@ -35,7 +91,16 @@ $capabilities = array( 'mod/wiki:overridelock' => array( - 'riskbitmask' => 0, + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ) + ), + + 'mod/wiki:managewiki' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_MODULE, @@ -44,5 +109,5 @@ $capabilities = array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) - ) + ), ); diff --git a/mod/wiki/db/install.php b/mod/wiki/db/install.php index c8fe08e75dc..bb58bd28fda 100644 --- a/mod/wiki/db/install.php +++ b/mod/wiki/db/install.php @@ -1,13 +1,8 @@ - - +
- - - - - - - - - - - - - - - - + + + + + + + + + + + + @@ -31,68 +27,90 @@
- +
- - - - - - + + + - - + + + - - - - - -
- +
- - - - - - - - - - - - - + + + + + + + + + + - - + + + - - -
- +
- - - - - - + + + + + + + - - + + + +
+ + + + + + + + + + + +
+ + + + + + + + + + + + + +
+ + + + + + + + + + - - - -
diff --git a/mod/wiki/db/migration/lib.php b/mod/wiki/db/migration/lib.php new file mode 100644 index 00000000000..63aaa4cd7e6 --- /dev/null +++ b/mod/wiki/db/migration/lib.php @@ -0,0 +1,66 @@ +disablecamelcase == 1); + + // Block of dinamic ewiki defines + wiki_set_define("EWIKI_NAME", $wiki_entry->pagename); + wiki_set_define("EWIKI_DEFAULT_LANG", current_language()); + if ($moodle_disable_camel_case) { + wiki_set_define("EWIKI_CHARS_L", ""); + wiki_set_define("EWIKI_CHARS_U", ""); + } else { + wiki_set_define("EWIKI_CHARS_L", "a-z_µ¤$\337-\377"); + wiki_set_define("EWIKI_CHARS_U", "A-Z0-9\300-\336"); + } + + wiki_set_define("EWIKI_CHARS", wiki_get_define('EWIKI_CHARS_L') . wiki_get_define('EWIKI_CHARS_U')); + + require_once($CFG->dirroot . '/mod/wiki/db/migration/wiki/ewikimoodlelib.php'); + require_once($CFG->dirroot . '/mod/wiki/db/migration/wiki/ewiki/ewiki.php'); + + if ($oldwiki->htmlmode == 0) { + # No HTML + $ewiki_config["htmlentities"] = array(); // HTML is managed by moodle + $moodle_format = FORMAT_TEXT; + } + if ($oldwiki->htmlmode == 1) { + # Safe HTML + include_once($CFG->dirroot . "/mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php"); + $moodle_format = FORMAT_HTML; + } + if ($oldwiki->htmlmode == 2) { + # HTML Only + $moodle_format = FORMAT_HTML; + $ewiki_use_editor = 1; + $ewiki_config["htmlentities"] = array(); // HTML is allowed + $ewiki_config["wiki_link_regex"] = "\007 [!~]?( + \#?\[[^<>\[\]\n]+\] | + \^[-" . + wiki_get_define('EWIKI_CHARS_U') . wiki_get_define('EWIKI_CHARS_L') . "]{3,} | + \b([\w]{3,}:)*([" . + wiki_get_define('EWIKI_CHARS_U') . "]+[" . wiki_get_define('EWIKI_CHARS_L') . "]+){2,}\#?[\w\d]* | + \w[-_.+\w]+@(\w[-_\w]+[.])+\w{2,} ) \007x"; + } + + $content = ewiki_format($oldpage->content); + + return format_text($content, $moodle_format); + +} + +function wiki_set_define($key, $value) { + global $ewikidefines; + + $ewikidefines[$key] = $value; +} + +function wiki_get_define($key) { + global $ewikidefines; + + return $ewikidefines[$key]; +} + diff --git a/mod/wiki/ewiki/ewiki.php b/mod/wiki/db/migration/wiki/ewiki/ewiki.php similarity index 97% rename from mod/wiki/ewiki/ewiki.php rename to mod/wiki/db/migration/wiki/ewiki/ewiki.php index 9716b2c56a1..a5da3027c4b 100644 --- a/mod/wiki/ewiki/ewiki.php +++ b/mod/wiki/db/migration/wiki/ewiki/ewiki.php @@ -37,7 +37,7 @@ # define("EWIKI_SCRIPT_URL", "http://...?id="); # absolute URL #-- change to your needs (site lang) - define("EWIKI_NAME", "ErfurtWiki"); + //define("EWIKI_NAME", "ErfurtWiki"); define("EWIKI_PAGE_INDEX", "ErfurtWiki"); define("EWIKI_PAGE_NEWEST", "NewestPages"); define("EWIKI_PAGE_SEARCH", "SearchPages"); @@ -75,7 +75,7 @@ define("EWIKI_UP_BINARY", "binary"); define("EWIKI_UP_UPLOAD", "upload"); #- other stuff - define("EWIKI_DEFAULT_LANG", "en"); + //define("EWIKI_DEFAULT_LANG", "en"); define("EWIKI_CHARSET", "UTF-8"); #- user permissions define("EWIKI_PROTECTED_MODE", 0); # disable funcs + require auth @@ -86,22 +86,24 @@ #-- allowed WikiPageNameCharacters #### BEGIN MOODLE CHANGES - to remove auto-camelcase linking. - global $moodle_disable_camel_case; - if ($moodle_disable_camel_case) { - define("EWIKI_CHARS_L", ""); - define("EWIKI_CHARS_U", ""); - } - else { -#### END MOODLE CHANGES - - define("EWIKI_CHARS_L", "a-z_µ¤$\337-\377"); - define("EWIKI_CHARS_U", "A-Z0-9\300-\336"); - -#### BEGIN MOODLE CHANGES - } -#### END MOODLE CHANGES - - define("EWIKI_CHARS", EWIKI_CHARS_L.EWIKI_CHARS_U); +// global $moodle_disable_camel_case; +// if ($moodle_disable_camel_case) { +// define("EWIKI_CHARS_L", ""); +// define("EWIKI_CHARS_U", ""); +// } +// else { +//#### END MOODLE CHANGES +// +// define("EWIKI_CHARS_L", "a-z_µ¤$\337-\377"); +// define("EWIKI_CHARS_U", "A-Z0-9\300-\336"); +// +//#### BEGIN MOODLE CHANGES +// } +//#### END MOODLE CHANGES +// +// define("EWIKI_CHARS", EWIKI_CHARS_L.EWIKI_CHARS_U); +// +// COMMENTED BY PIGUI BECOUSE OF MIGRATION #-- database define("EWIKI_DB_TABLE_NAME", "ewiki"); # MySQL / ADOdb @@ -214,15 +216,15 @@ "wiki_pre_scan_regex" => '/ (? "\007 [!~]?( \#?\[[^<>\[\]\n]+\] | - \^[-".EWIKI_CHARS_U.EWIKI_CHARS_L."]{3,} | - \b([\w]{3,}:)*([".EWIKI_CHARS_U."]+[".EWIKI_CHARS_L."]+){2,}\#?[\w\d]* | + \^[-".wiki_get_define('EWIKI_CHARS_U').wiki_get_define('EWIKI_CHARS_L')."]{3,} | + \b([\w]{3,}:)*([".wiki_get_define('EWIKI_CHARS_U')."]+[".wiki_get_define('EWIKI_CHARS_L')."]+){2,}\#?[\w\d]* | ([a-z]{2,9}://|mailto:)[^\s\[\]\'\"\)\,<]+ | \w[-_.+\w]+@(\w[-_\w]+[.])+\w{2,} ) \007x", @@ -300,9 +302,9 @@ #### MOODLE CHANGE TO BE COMPATIBLE WITH PHP 4.1 #if(headers_sent($file,$line)) { # print_error('headersent'); - if(headers_sent()) { + /*if(headers_sent()) { print_error('headersent'); - } + }*/ $pf($GLOBALS); } unset($ewiki_plugins["init"]); @@ -660,7 +662,7 @@ function ewiki_page_css_container(&$o, &$id, &$data, &$action) { function ewiki_split_title ($id='', $split=EWIKI_SPLIT_TITLE, $entities=1) { strlen($id) or ($id = $GLOBALS["ewiki_id"]); if ($split) { - $id = preg_replace("/([".EWIKI_CHARS_L."])([".EWIKI_CHARS_U."]+)/", "$1 $2", $id); + $id = preg_replace("/([".wiki_get_define('EWIKI_CHARS_L')."])([".wiki_get_define('EWIKI_CHARS_U')."]+)/", "$1 $2", $id); } return($entities ? s($id) : $id); } @@ -1273,7 +1275,7 @@ function ewiki_page_info($id, &$data, $action) { elseif ($i == "author") { continue; $ewiki_links=1; - $value = preg_replace_callback("/((\w+:)?([".EWIKI_CHARS_U."]+[".EWIKI_CHARS_L."]+){2,}[\w\d]*)/", "ewiki_link_regex_callback", $value); + $value = preg_replace_callback("/((\w+:)?([".wiki_get_define('EWIKI_CHARS_U')."]+[".wiki_get_define('EWIKI_CHARS_L')."]+){2,}[\w\d]*)/", "ewiki_link_regex_callback", $value); } elseif ($i == "userid") { $i = 'author'; @@ -1742,11 +1744,7 @@ function ewiki_control_links($id, &$data, $action) { process. The $params array can activate various features and extensions. only accepts UNIX newlines! */ -function ewiki_format ( - $wiki_source, - $params = array() - ) -{ +function ewiki_format ( $wiki_source, $params = array()) { global $ewiki_links, $ewiki_plugins, $ewiki_config; #-- state vars @@ -2296,6 +2294,7 @@ function ewiki_merge_links(&$ewiki_links) { (ooutch, this is a complicated one) */ function ewiki_link_regex_callback($uu, $force_noimg=0) { + global $DB, $CFG; #print "
"; print_r($uu); print "
"; global $ewiki_links, $ewiki_plugins, $ewiki_config, $ewiki_id; @@ -2319,7 +2318,8 @@ function ewiki_link_regex_callback($uu, $force_noimg=0) { #-- explicit title given via [ title | WikiLink ] $href = $title = strtok($str, "|"); if ($uu = strtok("|")) { - $href = $uu; + $parts = explode('|', $str); + $title = $parts[1] . ' | ' .$parts[0]; $states["titled"] = 1; } #-- title and href swapped: swap back @@ -2395,8 +2395,7 @@ function ewiki_link_regex_callback($uu, $force_noimg=0) { #### BEGIN MOODLE CHANGES global $ewiki_link_case; $href_realcase=array_key_exists($href_i,$ewiki_link_case) ? $ewiki_link_case[$href_i] : $href; - $str = '' . $title . ''; + $str = '[[' . $title . ']]'; #### END MOODLE CHANGES } #-- guess for mail@addresses, convert to URI if @@ -2418,8 +2417,9 @@ function ewiki_link_regex_callback($uu, $force_noimg=0) { #-- (QuestionMarkLink to edit/ action) if (!$str) { $type = array("notfound"); - $str = '' . $title . '?'; + //$str = '' . $title . '?'; + $str = '[['. $title . ']]'; } } @@ -2446,8 +2446,15 @@ function ewiki_link_regex_callback($uu, $force_noimg=0) { if (EWIKI_SCRIPT_BINARY && ((strpos($href, EWIKI_IDF_INTERNAL)===0) || EWIKI_IMAGE_MAXSIZE && EWIKI_CACHE_IMAGES && $img && !$nocache) ) { - $type = array("binary"); - $href = ewiki_script_binary("", $href); + $type = array("binary"); + //$href = ewiki_script_binary("", $href); + //##### BEGIN MOODLE ADDITION ##### + $pattern = 'internal://'; + $matches = array(); + $filename = str_replace($pattern, '', $href); + $filename = clean_param($filename, PARAM_FILE); + $href = "@@PLUGINFILE@@/$filename"; + //##### END MOODLE ADDITION ##### } #-- output html reference @@ -2501,12 +2508,11 @@ function ewiki_link_regex_callback($uu, $force_noimg=0) { function ewiki_interwiki($href, &$type) { global $ewiki_config, $ewiki_plugins; - if (strpos($href, ":") and !strpos($href, "//") - and ($p1 = strtok($href, ":"))) { + if (strpos($href, ":") and !strpos($href, "//") and ($p1 = strtok($href, ":"))) { $page = strtok("\000"); - if (($p1 = ewiki_array($ewiki_config["interwiki"], $p1)) !== NULL) { + if (!empty($ewiki_config["interwiki"]) && (($p1 = ewiki_array($ewiki_config["interwiki"], $p1)) !== NULL)) { $type = array("interwiki", $uu); while ($p1_alias = $ewiki_config["interwiki"][$p1]) { $type[] = $p1; @@ -2877,7 +2883,7 @@ function ewiki_localization() { global $ewiki_t, $ewiki_plugins; $deflangs = ','.@$_ENV["LANGUAGE"] . ','.@$_ENV["LANG"] - . ",".EWIKI_DEFAULT_LANG . ",en,C"; + . ",".wiki_get_define('EWIKI_DEFAULT_LANG') . ",en,C"; foreach (explode(",", @$_SERVER["HTTP_ACCEPT_LANGUAGE"].$deflangs) as $l) { diff --git a/mod/wiki/ewiki/plugins/moodle/moodle_rescue_html.php b/mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php similarity index 97% rename from mod/wiki/ewiki/plugins/moodle/moodle_rescue_html.php rename to mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php index 591c7d1198d..64de6712e73 100644 --- a/mod/wiki/ewiki/plugins/moodle/moodle_rescue_html.php +++ b/mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php @@ -1,4 +1,4 @@ - @@ -23,11 +23,11 @@ function ewiki_moodle_rescue_html(&$wiki_source) { $rescue_html = array( "br", "tt", "b", "i", "strong", "em", "s", "kbd", "var", "xmp", "sup", "sub", - "pre", "q", "h1", "h2", "h3", "h4", "h5", "h6", "cite", "code", "u", + "pre", "q", "h1", "h2", "h3", "h4", "h5", "h6", "cite", "code", "u", ); - - + + #-- unescape allowed html if ($safe_html) { /* @@ -43,4 +43,4 @@ function ewiki_moodle_rescue_html(&$wiki_source) { } - +?> diff --git a/mod/wiki/ewikimoodlelib.php b/mod/wiki/db/migration/wiki/ewikimoodlelib.php similarity index 97% rename from mod/wiki/ewikimoodlelib.php rename to mod/wiki/db/migration/wiki/ewikimoodlelib.php index f74307ae884..9d0d1c7f9c0 100644 --- a/mod/wiki/ewikimoodlelib.php +++ b/mod/wiki/db/migration/wiki/ewikimoodlelib.php @@ -9,13 +9,13 @@ $ewiki_plugins["database"][0] = "ewiki_database_moodle"; /// #-- predefine some of the configuration constants -define("EWIKI_NAME", $wiki_entry->pagename); +//define("EWIKI_NAME", $wiki_entry->pagename); COMMENTED BY PIGUI BECOUSE OF MIGRATION define("EWIKI_CONTROL_LINE", 0); define("EWIKI_LIST_LIMIT", 25); -define("EWIKI_DEFAULT_LANG", current_language()); +//define("EWIKI_DEFAULT_LANG", current_language()); COMMENTED BY PIGUI BECOUSE OF MIGRATION define("EWIKI_HTML_CHARS", 1); -define("EWIKI_DB_TABLE_NAME", "wiki_pages"); +define("EWIKI_DB_TABLE_NAME", "wiki_pages_old"); function ewiki_database_moodle($action, &$args, $sw1, $sw2) { diff --git a/mod/wiki/db/upgrade.php b/mod/wiki/db/upgrade.php index 25d5d0b702f..532150d56d6 100644 --- a/mod/wiki/db/upgrade.php +++ b/mod/wiki/db/upgrade.php @@ -1,74 +1,316 @@ . + +/** + * This file keeps track of upgrades to the wiki module + * + * Sometimes, changes between versions involve + * alterations to database structures and other + * major things that may break installations. + * + * The upgrade function in this file will attempt + * to perform all the necessary actions to upgrade + * your older installtion to the current version. + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * + * @license http://www.gnu.org/copyleft/gpl.html GNU Public License + * + */ + +/** + * + * TODO LIST: + * + * 1. Add needed fields to wiki table. DONE + * 2. Rename other wiki tables. DONE + * 3. Create new wiki tables. DONE BUT NOT FINISHED, WATING FOR NEW TABLES + * 4. Move/Adapt/Transform configurations info to new structure + * 5. Migrate wiki entries to subwikis. DONE + * 6. Fill pages table with latest versions of every page. DONE + * 7. Migrate page history to new table (transforming formats). DONE, BUT STILL WORKING + * 8. Fill links table + * 9. Drop useless information + * + * ADITIONAL THINGS AFTER CHAT WITH ELOY: + * + * 1. addField is deprecated. DONE + * 2. Fix SQL error at block 3. DONE + * 3. Merge set_field_select with previous update sentence. DONE + * 4. Don't insert id fields on database (it won't work on mssql, oracle, pg). DONE. + * 5. Use upgrade_set_timeout function. + * 6. Use grafic of progess + * + * OTHER THINGS: + * + * 1. Use recordset instead of record when migrating historic + * 2. Select only usefull data on block 06 + * + */ function xmldb_wiki_upgrade($oldversion) { - global $CFG, $DB; + global $CFG, $DB, $OUTPUT; $dbman = $DB->get_manager(); $result = true; -//===== 1.9.0 upgrade line ======// + // Step 0: Add new fields to main wiki table + if ($result && $oldversion < 2010040100) { + require_once(dirname(__FILE__) . '/upgradelib.php'); + echo $OUTPUT->notification('Adding new fields to wiki table', 'notifysuccess'); + wiki_add_wiki_fields(); - if ($result && $oldversion < 2009042000) { - - /// Rename field summary on table wiki to intro - $table = new xmldb_table('wiki'); - $field = new xmldb_field('summary', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, 'name'); - - /// Launch rename field summary - $dbman->rename_field($table, $field, 'intro'); - - /// wiki savepoint reached - upgrade_mod_savepoint($result, 2009042000, 'wiki'); + upgrade_mod_savepoint($result, 2010040100, 'wiki'); } - if ($result && $oldversion < 2009042001) { + // Step 1: Rename old tables + if ($result && $oldversion < 2010040101) { + $tables = array('wiki_pages', 'wiki_locks', 'wiki_entries'); - /// Define field introformat to be added to wiki - $table = new xmldb_table('wiki'); - $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro'); - - /// Launch add field introformat - $dbman->add_field($table, $field); - - /// wiki savepoint reached - upgrade_mod_savepoint($result, 2009042001, 'wiki'); + echo $OUTPUT->notification('Renaming old wiki module tables', 'notifysuccess'); + foreach ($tables as $tablename) { + $table = new xmldb_table($tablename); + if ($dbman->table_exists($table)) { + if ($dbman->table_exists($table)) { + $dbman->rename_table($table, $tablename . '_old'); + } + } + } + upgrade_mod_savepoint($result, 2010040101, 'wiki'); } -/// Dropping all enums/check contraints from core. MDL-18577 - if ($result && $oldversion < 2009042700) { + // Step 2: Creating new tables + if ($result && $oldversion < 2010040102) { + require_once(dirname(__FILE__) . '/upgradelib.php'); + echo $OUTPUT->notification('Installing new wiki module tables', 'notifysuccess'); + wiki_upgrade_install_20_tables(); + upgrade_mod_savepoint($result, 2010040102, 'wiki'); + } - /// Changing list of values (enum) of field wtype on table wiki to none + // Step 3: migrating wiki instances + if ($result && $oldversion < 2010040103) { + upgrade_set_timeout(); + + // Setting up wiki configuration + $sql = 'UPDATE {wiki} w ' . + 'SET w.intro = w.summary, ' . + 'w.firstpagetitle = w.pagename, ' . + 'w.defaultformat = "html"'; + + $DB->execute($sql); + + $sql = 'UPDATE {wiki} w ' . + 'SET w.wikimode = "collaborative" ' . + 'WHERE w.wtype = "group"'; + $DB->execute($sql); + + $sql = 'UPDATE {wiki} w ' . + 'SET w.wikimode = "individual" ' . + 'WHERE w.wtype != "group"'; + $DB->execute($sql); + + // Removing edit & create capability to students in old teacher wikis + $studentroles = $DB->get_records('role', array('archetype' => 'student')); + $wikis = $DB->get_records('wiki'); + foreach ($wikis as $wiki) { + echo $OUTPUT->notification('Migrating '.$wiki->wtype.' type wiki instance: '.$wiki->name, 'notifysuccess'); + if ($wiki->wtype == 'teacher') { + $cm = get_coursemodule_from_instance('wiki', $wiki->id); + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + foreach ($studentroles as $studentrole) { + role_change_permission($studentrole->id, $context, 'mod/wiki:editpage', CAP_PROHIBIT); + role_change_permission($studentrole->id, $context, 'mod/wiki:createpage', CAP_PROHIBIT); + } + } + } + + echo $OUTPUT->notification('Migrating old wikis to new wikis', 'notifysuccess'); + upgrade_mod_savepoint($result, 2010040103, 'wiki'); + } + + // Step 4: migrating wiki entries to new subwikis + if ($result && $oldversion < 2010040104) { + /** + * Migrating wiki entries to new subwikis + */ + $sql = 'INSERT into {wiki_subwikis} (wikiid, groupid, userid) ' . + 'SELECT e.wikiid, e.groupid, e.userid ' . + 'FROM {wiki_entries_old} e '; + echo $OUTPUT->notification('Migrating old entries to new subwikis', 'notifysuccess'); + + $DB->execute($sql, array()); + + upgrade_mod_savepoint($result, 2010040104, 'wiki'); + } + + // Step 5: Migrating pages + if ($result && $oldversion < 2010040105) { + /** + * Filling pages table with latest versions of every page. + * + * @TODO: Ensure that ALL versions of every page are always in database and + * they can be removed or cleaned. + * That fact could let us rewrite the subselect to execute a count(*) to avoid + * the order by and it would be much faster. + */ + + $sql = 'INSERT into {wiki_pages} (subwikiid, title, cachedcontent, timecreated, timemodified, userid, pageviews) ' . + 'SELECT s.id, p.pagename, "**reparse needed**", p.created, p.lastmodified, p.userid, p.hits ' . + 'FROM {wiki_pages_old} p '. + 'LEFT OUTER JOIN {wiki_entries_old} e ON e.id = p.wiki ' . + 'LEFT OUTER JOIN {wiki_subwikis} s ' . + 'ON s.wikiid = e.wikiid AND s.groupid = e.groupid AND s.userid = e.userid ' . + 'WHERE p.version = (' . + ' SELECT po.version ' . + ' FROM {wiki_pages_old} po ' . + ' WHERE p.pagename = po.pagename and ' . + ' p.wiki = po.wiki ' . + ' ORDER BY p.version DESC ' . + ' LIMIT 1)'; + echo $OUTPUT->notification('Migrating old pages to new pages', 'notifysuccess'); + + $DB->execute($sql, array()); + + upgrade_mod_savepoint($result, 2010040105, 'wiki'); + } + + // Step 6: Migrating versions + if ($result && $oldversion < 2010040106) { + require_once(dirname(__FILE__) . '/upgradelib.php'); + echo $OUTPUT->notification('Migrating old history to new history', 'notifysuccess'); + wiki_upgrade_migrate_versions(); + upgrade_mod_savepoint($result, 2010040106, 'wiki'); + } + + // Step 7: refresh cachedcontent and fill wiki links table + if ($result && $oldversion < 2010040107) { + require_once($CFG->dirroot. '/mod/wiki/locallib.php'); + upgrade_set_timeout(); + + $pages = $DB->get_recordset('wiki_pages'); + + while ($pages->valid()) { + $page = $pages->current(); + wiki_refresh_cachedcontent($page); + $pages->next(); + } + + $pages->close(); + + echo $OUTPUT->notification('Caching content', 'notifysuccess'); + upgrade_mod_savepoint($result, 2010040107, 'wiki'); + } + // Step 8, migrating files + if ($result && $oldversion < 2010040108) { + $fs = get_file_storage(); + $sql = "SELECT DISTINCT po.pagename, w.id AS wikiid, po.userid, + po.meta AS filemeta, eo.id AS entryid, eo.groupid, s.id AS subwiki, + w.course AS courseid, cm.id AS cmid + FROM {wiki_pages_old} po + LEFT OUTER JOIN {wiki_entries_old} eo + ON eo.id=po.wiki + LEFT OUTER JOIN {wiki} w + ON w.id = eo.wikiid + LEFT OUTER JOIN {wiki_subwikis} s + ON s.groupid = eo.groupid AND s.wikiid = eo.wikiid AND eo.userid = s.userid + JOIN {modules} m ON m.name = 'wiki' + JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = w.id) + "; + + $rs = $DB->get_recordset_sql($sql); + foreach ($rs as $r) { + if (strpos($r->pagename, 'internal://') !== false) { + // Found a file resource! + $pattern = 'internal://'; + $matches = array(); + $filename = str_replace($pattern, '', $r->pagename); + $orgifilename = $filename = clean_param($filename, PARAM_FILE); + $context = get_context_instance(CONTEXT_MODULE, $r->cmid); + $filemeta = unserialize($r->filemeta); + $filesection = $filemeta['section']; + // When attach a file to wiki page, user can customize the file name instead of original file name + // if user did, old wiki will create two pages, internal://original_pagename and internal://renamed_pagename + // internal://original_pagename record has renamed pagename in meta field + // but all file have this field + // old wiki will rename file names to filter space and special character + if (!empty($filemeta['Content-Location'])) { + $orgifilename = urldecode($filemeta['Content-Location']); + $orgifilename = str_replace(' ', '_', $orgifilename); + } + $thefile = $CFG->dataroot . '/' . $r->courseid . '/moddata/wiki/' . $r->wikiid .'/' . $r->entryid . '/'. $filesection .'/'. $filename; + + if (is_readable($thefile)) { + $filerecord = array('contextid' => $context->id, + 'filearea' => 'wiki_attachments', + 'itemid' => $r->subwiki, + 'filepath' => '/', + 'filename' => $orgifilename, + 'userid' => $r->userid); + if (!$fs->file_exists($context->id, 'wiki_attachments', $r->subwiki, '/', $orgifilename)) { + echo $OUTPUT->notification('Migrating file '.$orgifilename, 'notifysuccess'); + $storedfile = $fs->create_file_from_pathname($filerecord, $thefile); + } + // we have to create another file here to make sure interlinks work + if (!$fs->file_exists($context->id, 'wiki_attachments', $r->subwiki, '/', $filename)) { + $filerecord['filename'] = $filename; + echo $OUTPUT->notification('Migrating file '.$filename, 'notifysuccess'); + $storedfile = $fs->create_file_from_pathname($filerecord, $thefile); + } + } + } + } + $rs->close(); + upgrade_mod_savepoint($result, 2010040108, 'wiki'); + } + + // Step 9: clean wiki table + if ($result && $oldversion < 2010040109) { + $fields = array('summary', 'pagename', 'wtype', 'ewikiprinttitle', 'htmlmode', 'ewikiacceptbinary', 'disablecamelcase', 'setpageflags', 'strippages', 'removepages', 'revertchanges', 'initialcontent'); $table = new xmldb_table('wiki'); - $field = new xmldb_field('wtype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'group', 'pagename'); + foreach ($fields as $fieldname) { + $field = new xmldb_field($fieldname); + if ($dbman->field_exists($table, $field)) { + $dbman->drop_field($table, $field); + } - /// Launch change of list of values for field wtype - $dbman->drop_enum_from_field($table, $field); + } + echo $OUTPUT->notification('Cleaning wiki table', 'notifysuccess'); + upgrade_mod_savepoint($result, 2010040109, 'wiki'); + } - /// wiki savepoint reached - upgrade_mod_savepoint($result, 2009042700, 'wiki'); + // TODO: Will hold the old tables so we will have chance to fix problems + // Will remove old tables once migrating 100% stable + // Step 10: delete old tables + if ($result && $oldversion < 2010040120) { + //$tables = array('wiki_pages', 'wiki_locks', 'wiki_entries'); + + //foreach ($tables as $tablename) { + //$table = new xmldb_table($tablename . '_old'); + //if ($dbman->table_exists($table)) { + //$dbman->drop_table($table); + //} + //} + //echo $OUTPUT->notification('Droping old tables', 'notifysuccess'); + //upgrade_mod_savepoint($result, 2010040110, 'wiki'); } return $result; } - - diff --git a/mod/wiki/db/upgradelib.php b/mod/wiki/db/upgradelib.php new file mode 100644 index 00000000000..40f667af67b --- /dev/null +++ b/mod/wiki/db/upgradelib.php @@ -0,0 +1,303 @@ +. + +/** + * @package mod-wiki + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +function wiki_add_wiki_fields() { + global $DB; + + upgrade_set_timeout(); + $dbman = $DB->get_manager(); + /// Define table wiki to be created + $table = new xmldb_table('wiki'); + + // Adding fields to wiki table + $wikitable = new xmldb_table('wiki'); + + // in MOODLE_20_SABLE branch, summary field is renamed as intro + // so we renamed it back to summary to keep upgrade going as moodle 1.9 + $field = new xmldb_field('intro', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null); + if ($dbman->field_exists($wikitable, $field)) { + $dbman->rename_field($wikitable, $field, 'summary'); + } + $dbman->add_field($wikitable, $field); + + $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null); + if (!$dbman->field_exists($wikitable, $field)) { + $dbman->add_field($wikitable, $field); + } + + $field = new xmldb_field('firstpagetitle', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'First Page', null); + $dbman->add_field($wikitable, $field); + + $field = new xmldb_field('wikimode', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'collaborative', null); + $dbman->add_field($wikitable, $field); + + $field = new xmldb_field('defaultformat', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'creole', null); + $dbman->add_field($wikitable, $field); + + $field = new xmldb_field('forceformat', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1', null); + $dbman->add_field($wikitable, $field); + + $field = new xmldb_field('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null); + $dbman->add_field($wikitable, $field); + + $field = new xmldb_field('editbegin', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null); + $dbman->add_field($wikitable, $field); + + $field = new xmldb_field('editend', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0', null); + $dbman->add_field($wikitable, $field); + +} + +/** + * Install wiki 2.0 tables + */ +function wiki_upgrade_install_20_tables() { + global $DB; + upgrade_set_timeout(); + $dbman = $DB->get_manager(); + + /// Define table wiki_subwikis to be created + $table = new xmldb_table('wiki_subwikis'); + + /// Adding fields to table wiki_subwikis + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('wikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('groupid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + + /// Adding keys to table wiki_subwikis + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + $table->add_key('wikiidgroupiduserid', XMLDB_KEY_UNIQUE, array('wikiid', 'groupid', 'userid')); + $table->add_key('wikifk', XMLDB_KEY_FOREIGN, array('wikiid'), 'wiki', array('id')); + + /// Conditionally launch create table for wiki_subwikis + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + /// Define table wiki_pages to be created + $table = new xmldb_table('wiki_pages'); + + /// Adding fields to table wiki_pages + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('subwikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'title'); + $table->add_field('cachedcontent', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null); + $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('timerendered', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('pageviews', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('readonly', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + + /// Adding keys to table wiki_pages + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + $table->add_key('subwikititleuser', XMLDB_KEY_UNIQUE, array('subwikiid', 'title', 'userid')); + $table->add_key('subwikifk', XMLDB_KEY_FOREIGN, array('subwikiid'), 'wiki_subwiki', array('id')); + + /// Conditionally launch create table for wiki_pages + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + /// Define table wiki_versions to be created + $table = new xmldb_table('wiki_versions'); + + /// Adding fields to table wiki_versions + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('content', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null); + $table->add_field('contentformat', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'creole'); + $table->add_field('version', XMLDB_TYPE_INTEGER, '5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + + /// Adding keys to table wiki_versions + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + $table->add_key('pagefk', XMLDB_KEY_FOREIGN, array('pageid'), 'wiki_pages', array('id')); + + /// Conditionally launch create table for wiki_versions + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + /// Define table wiki_synonyms to be created + $table = new xmldb_table('wiki_synonyms'); + + /// Adding fields to table wiki_synonyms + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('subwikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('pagesynonym', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'Pagesynonym'); + + /// Adding keys to table wiki_synonyms + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + $table->add_key('pageidsyn', XMLDB_KEY_UNIQUE, array('pageid', 'pagesynonym')); + + /// Conditionally launch create table for wiki_synonyms + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + /// Define table wiki_links to be created + $table = new xmldb_table('wiki_links'); + + /// Adding fields to table wiki_links + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('subwikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('frompageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('topageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('tomissingpage', XMLDB_TYPE_CHAR, '255', null, null, null, null); + + /// Adding keys to table wiki_links + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + $table->add_key('frompageidfk', XMLDB_KEY_FOREIGN, array('frompageid'), 'wiki_pages', array('id')); + $table->add_key('subwikifk', XMLDB_KEY_FOREIGN, array('subwikiid'), 'wiki_subwiki', array('id')); + + /// Conditionally launch create table for wiki_links + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + /// Define table wiki_locks to be created + $table = new xmldb_table('wiki_locks'); + + /// Adding fields to table wiki_locks + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('sectionname', XMLDB_TYPE_CHAR, '255', null, null, null, null); + $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('lockedat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + + /// Adding keys to table wiki_locks + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + + /// Conditionally launch create table for wiki_locks + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } +} + +/** + * Migrating wiki pages history + */ +function wiki_upgrade_migrate_versions() { + global $DB, $CFG; + upgrade_set_timeout(); + require_once($CFG->dirroot . '/mod/wiki/db/migration/lib.php'); + $sql = 'SELECT po.id as oldpage_id, po.pagename as oldpage_pagename, po.version, po.flags, po.content, po.author, po.userid as oldpage_userid, po.created, po.lastmodified, po.refs, po.meta, po.hits, po.wiki, ' . + 'p.id as newpage_id, p.subwikiid, p.title, p.cachedcontent, p.timecreated, p.timemodified as newpage_timemodified, p.timerendered, p.userid as newpage_userid, p.pageviews, p.readonly, ' . + 'e.id as entry_id, e.wikiid, e.course as entrycourse, e.groupid, e.userid as entry_userid, e.pagename as entry_pagename, e.timemodified as entry_timemodified, ' . + 'w.id as wiki_id, w.course as wiki_course, w.name, w.summary as summary, w.pagename as wiki_pagename, w.wtype, w.ewikiprinttitle, w.htmlmode, w.ewikiacceptbinary, w.disablecamelcase, w.setpageflags, w.strippages, w.removepages, w.revertchanges, w.initialcontent, w.timemodified as wiki_timemodified ' . + 'FROM {wiki_pages_old} po LEFT OUTER JOIN {wiki_entries_old} e ' . + 'ON e.id = po.wiki ' . + 'LEFT OUTER JOIN {wiki} w ' . + 'ON w.id = e.wikiid ' . + 'LEFT OUTER JOIN {wiki_subwikis} s ' . + 'ON e.groupid = s.groupid AND e.wikiid = s.wikiid AND e.userid = s.userid ' . + 'LEFT OUTER JOIN {wiki_pages} p ' . + 'ON po.pagename = p.title AND p.subwikiid = s.id'; + $pagesinfo = $DB->get_recordset_sql($sql, array()); + + while ($pagesinfo->valid()) { + $pageinfo = $pagesinfo->current(); + + $oldpage = new StdClass(); + $oldpage->id = $pageinfo->oldpage_id; + $oldpage->pagename = $pageinfo->oldpage_pagename; + $oldpage->version = $pageinfo->version; + $oldpage->flags = $pageinfo->flags; + $oldpage->content = $pageinfo->content; + $oldpage->author = $pageinfo->author; + $oldpage->userid = $pageinfo->oldpage_userid; + $oldpage->created = $pageinfo->created; + $oldpage->lastmodified = $pageinfo->lastmodified; + $oldpage->refs = $pageinfo->refs; + $oldpage->meta = $pageinfo->meta; + $oldpage->hits = $pageinfo->hits; + $oldpage->wiki = $pageinfo->wiki; + + $page = new StdClass(); + $page->id = $pageinfo->newpage_id; + $page->subwikiid = $pageinfo->subwikiid; + $page->title = $pageinfo->title; + $page->cachedcontent = $pageinfo->cachedcontent; + $page->timecreated = $pageinfo->timecreated; + $page->timemodified = $pageinfo->newpage_timemodified; + $page->timerendered = $pageinfo->timerendered; + $page->userid = $pageinfo->newpage_userid; + $page->pageviews = $pageinfo->pageviews; + $page->readonly = $pageinfo->readonly; + + $entry = new StdClass(); + $entry->id = $pageinfo->entry_id; + $entry->wikiid = $pageinfo->wikiid; + $entry->course = $pageinfo->entrycourse; + $entry->groupid = $pageinfo->groupid; + $entry->userid = $pageinfo->entry_userid; + $entry->pagename = $pageinfo->entry_pagename; + $entry->timemodified = $pageinfo->entry_timemodified; + + $wiki = new StdClass(); + $wiki->id = $pageinfo->wiki_id; + $wiki->course = $pageinfo->wiki_course; + $wiki->name = $pageinfo->name; + $wiki->summary = $pageinfo->summary; + $wiki->pagename = $pageinfo->wiki_pagename; + $wiki->wtype = $pageinfo->wtype; + $wiki->ewikiprinttitle = $pageinfo->ewikiprinttitle; + $wiki->htmlmode = $pageinfo->htmlmode; + $wiki->ewikiacceptbinary = $pageinfo->ewikiacceptbinary; + $wiki->disablecamelcase = $pageinfo->disablecamelcase; + $wiki->setpageflags = $pageinfo->setpageflags; + $wiki->strippages = $pageinfo->strippages; + $wiki->removepages = $pageinfo->removepages; + $wiki->revertchanges = $pageinfo->revertchanges; + $wiki->initialcontent = $pageinfo->initialcontent; + $wiki->timemodified = $pageinfo->wiki_timemodified; + + $version = new StdClass(); + $version->pageid = $page->id; + $version->content = wiki_ewiki_2_html($entry, $oldpage, $wiki); + $version->contentformat = "html"; + $version->version = $oldpage->version; + $version->timecreated = $oldpage->lastmodified; + $version->userid = $oldpage->userid; + if ($version->version == 1) { + // The oldest version of page in moodle 2.0 is 0 which has empty content + // so we need to insert an extra record + $content = $version->content; + $version->version = 0; + $version->content == ''; + $DB->insert_record('wiki_versions', $version); + $version->version = 1; + $version->content == $content; + $DB->insert_record('wiki_versions', $version); + } else { + $DB->insert_record('wiki_versions', $version); + } + + $pagesinfo->next(); + } + + $pagesinfo->close(); +} diff --git a/mod/wiki/diff.php b/mod/wiki/diff.php new file mode 100644 index 00000000000..6e89f3d7def --- /dev/null +++ b/mod/wiki/diff.php @@ -0,0 +1,83 @@ +. + +/** + * This file contains all necessary code to view a diff page + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); + +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +require_once($CFG->dirroot . '/mod/wiki/diff/difflib.php'); +require_once($CFG->dirroot . '/mod/wiki/diff/diff_nwiki.php'); + +$pageid = required_param('pageid', PARAM_TEXT); +$compare = required_param('compare', PARAM_INT); +$comparewith = required_param('comparewith', PARAM_INT); + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} + +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} + +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +if (!$cm = get_coursemodule_from_instance('wiki', $wiki->id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} + +if ($compare >= $comparewith) { + print_error("A page version can only be compared with an older version."); +} + +require_course_login($course->id, true, $cm); +add_to_log($course->id, "wiki", "diff", "diff.php?id=$cm->id", "$wiki->id"); + +$wikipage = new page_wiki_diff($wiki, $subwiki, $cm); + +$wikipage->set_page($page); +$wikipage->set_comparison($compare, $comparewith); + +$wikipage->print_header(); + +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/diff/diff_added_begins.gif b/mod/wiki/diff/diff_added_begins.gif new file mode 100644 index 0000000000000000000000000000000000000000..a4e4299bcc450e332492746c1b3922b4f3c6b359 GIT binary patch literal 61 zcmZ?wbhEHbjEB<6*R0A%l{Gr literal 0 HcmV?d00001 diff --git a/mod/wiki/diff/diff_added_ends.gif b/mod/wiki/diff/diff_added_ends.gif new file mode 100644 index 0000000000000000000000000000000000000000..a696fedf8939014f225179d3395111d1fbefe118 GIT binary patch literal 51 zcmZ?wbhEHbWMSZDXkcUjg8%>jEB<6* +// You may copy this code freely under the conditions of the GPL. +// + +define('USE_ASSERTS_IN_WIKI', function_exists('assert')); + +class _WikiDiffOp { + var $type; + var $orig; + var $closing; + + function reverse() { + trigger_error("pure virtual", E_USER_ERROR); + } + + function norig() { + return $this->orig ? sizeof($this->orig) : 0; + } + + function nclosing() { + return $this->closing ? sizeof($this->closing) : 0; + } +} + +class _WikiDiffOp_Copy extends _WikiDiffOp { + var $type = 'copy'; + + function _WikiDiffOp_Copy ($orig, $closing = false) { + if (!is_array($closing)) + $closing = $orig; + $this->orig = $orig; + $this->closing = $closing; + } + + function reverse() { + return new _WikiDiffOp_Copy($this->closing, $this->orig); + } +} + +class _WikiDiffOp_Delete extends _WikiDiffOp { + var $type = 'delete'; + + function _WikiDiffOp_Delete ($lines) { + $this->orig = $lines; + $this->closing = false; + } + + function reverse() { + return new _WikiDiffOp_Add($this->orig); + } +} + +class _WikiDiffOp_Add extends _WikiDiffOp { + var $type = 'add'; + + function _WikiDiffOp_Add ($lines) { + $this->closing = $lines; + $this->orig = false; + } + + function reverse() { + return new _WikiDiffOp_Delete($this->closing); + } +} + +class _WikiDiffOp_Change extends _WikiDiffOp { + var $type = 'change'; + + function _WikiDiffOp_Change ($orig, $closing) { + $this->orig = $orig; + $this->closing = $closing; + } + + function reverse() { + return new _WikiDiffOp_Change($this->closing, $this->orig); + } +} + + +/** + * Class used internally by Diff to actually compute the diffs. + * + * The algorithm used here is mostly lifted from the perl module + * Algorithm::Diff (version 1.06) by Ned Konz, which is available at: + * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip + * + * More ideas are taken from: + * http://www.ics.uci.edu/~eppstein/161/960229.html + * + * Some ideas are (and a bit of code) are from from analyze.c, from GNU + * diffutils-2.7, which can be found at: + * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz + * + * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations) + * are my own. + * + * @author Geoffrey T. Dairiki + * @access private + */ +class _WikiDiffEngine +{ + function diff ($from_lines, $to_lines) { + $n_from = sizeof($from_lines); + $n_to = sizeof($to_lines); + + $this->xchanged = $this->ychanged = array(); + $this->xv = $this->yv = array(); + $this->xind = $this->yind = array(); + unset($this->seq); + unset($this->in_seq); + unset($this->lcs); + + // Skip leading common lines. + for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) { + if ($from_lines[$skip] != $to_lines[$skip]) + break; + $this->xchanged[$skip] = $this->ychanged[$skip] = false; + } + // Skip trailing common lines. + $xi = $n_from; $yi = $n_to; + for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) { + if ($from_lines[$xi] != $to_lines[$yi]) + break; + $this->xchanged[$xi] = $this->ychanged[$yi] = false; + } + + // Ignore lines which do not exist in both files. + for ($xi = $skip; $xi < $n_from - $endskip; $xi++) + $xhash[$from_lines[$xi]] = 1; + for ($yi = $skip; $yi < $n_to - $endskip; $yi++) { + $line = $to_lines[$yi]; + if ( ($this->ychanged[$yi] = empty($xhash[$line])) ) + continue; + $yhash[$line] = 1; + $this->yv[] = $line; + $this->yind[] = $yi; + } + for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { + $line = $from_lines[$xi]; + if ( ($this->xchanged[$xi] = empty($yhash[$line])) ) + continue; + $this->xv[] = $line; + $this->xind[] = $xi; + } + + // Find the LCS. + $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv)); + + // Merge edits when possible + $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged); + $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged); + + // Compute the edit operations. + $edits = array(); + $xi = $yi = 0; + while ($xi < $n_from || $yi < $n_to) { + USE_ASSERTS_IN_WIKI && assert($yi < $n_to || $this->xchanged[$xi]); + USE_ASSERTS_IN_WIKI && assert($xi < $n_from || $this->ychanged[$yi]); + + // Skip matching "snake". + $copy = array(); + while ( $xi < $n_from && $yi < $n_to + && !$this->xchanged[$xi] && !$this->ychanged[$yi]) { + $copy[] = $from_lines[$xi++]; + ++$yi; + } + if ($copy) + $edits[] = new _WikiDiffOp_Copy($copy); + + // Find deletes & adds. + $delete = array(); + while ($xi < $n_from && $this->xchanged[$xi]) + $delete[] = $from_lines[$xi++]; + + $add = array(); + while ($yi < $n_to && $this->ychanged[$yi]) + $add[] = $to_lines[$yi++]; + + if ($delete && $add) + $edits[] = new _WikiDiffOp_Change($delete, $add); + elseif ($delete) + $edits[] = new _WikiDiffOp_Delete($delete); + elseif ($add) + $edits[] = new _WikiDiffOp_Add($add); + } + return $edits; + } + + + /* Divide the Largest Common Subsequence (LCS) of the sequences + * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally + * sized segments. + * + * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an + * array of NCHUNKS+1 (X, Y) indexes giving the diving points between + * sub sequences. The first sub-sequence is contained in [X0, X1), + * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note + * that (X0, Y0) == (XOFF, YOFF) and + * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM). + * + * This function assumes that the first lines of the specified portions + * of the two files do not match, and likewise that the last lines do not + * match. The caller must trim matching lines from the beginning and end + * of the portions it is going to specify. + */ + function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) { + $flip = false; + + if ($xlim - $xoff > $ylim - $yoff) { + // Things seems faster (I'm not sure I understand why) + // when the shortest sequence in X. + $flip = true; + list ($xoff, $xlim, $yoff, $ylim) + = array( $yoff, $ylim, $xoff, $xlim); + } + + if ($flip) + for ($i = $ylim - 1; $i >= $yoff; $i--) + $ymatches[$this->xv[$i]][] = $i; + else + for ($i = $ylim - 1; $i >= $yoff; $i--) + $ymatches[$this->yv[$i]][] = $i; + + $this->lcs = 0; + $this->seq[0]= $yoff - 1; + $this->in_seq = array(); + $ymids[0] = array(); + + $numer = $xlim - $xoff + $nchunks - 1; + $x = $xoff; + for ($chunk = 0; $chunk < $nchunks; $chunk++) { + if ($chunk > 0) + for ($i = 0; $i <= $this->lcs; $i++) + $ymids[$i][$chunk-1] = $this->seq[$i]; + + $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks); + for ( ; $x < $x1; $x++) { + $line = $flip ? $this->yv[$x] : $this->xv[$x]; + if (empty($ymatches[$line])) + continue; + $matches = $ymatches[$line]; + reset($matches); + while (list ($junk, $y) = each($matches)) + if (empty($this->in_seq[$y])) { + $k = $this->_lcs_pos($y); + USE_ASSERTS_IN_WIKI && assert($k > 0); + $ymids[$k] = $ymids[$k-1]; + break; + } + while (list ($junk, $y) = each($matches)) { + if ($y > $this->seq[$k-1]) { + USE_ASSERTS_IN_WIKI && assert($y < $this->seq[$k]); + // Optimization: this is a common case: + // next match is just replacing previous match. + $this->in_seq[$this->seq[$k]] = false; + $this->seq[$k] = $y; + $this->in_seq[$y] = 1; + } + else if (empty($this->in_seq[$y])) { + $k = $this->_lcs_pos($y); + USE_ASSERTS_IN_WIKI && assert($k > 0); + $ymids[$k] = $ymids[$k-1]; + } + } + } + } + + $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff); + $ymid = $ymids[$this->lcs]; + for ($n = 0; $n < $nchunks - 1; $n++) { + $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks); + $y1 = $ymid[$n] + 1; + $seps[] = $flip ? array($y1, $x1) : array($x1, $y1); + } + $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim); + + return array($this->lcs, $seps); + } + + function _lcs_pos ($ypos) { + $end = $this->lcs; + if ($end == 0 || $ypos > $this->seq[$end]) { + $this->seq[++$this->lcs] = $ypos; + $this->in_seq[$ypos] = 1; + return $this->lcs; + } + + $beg = 1; + while ($beg < $end) { + $mid = (int)(($beg + $end) / 2); + if ( $ypos > $this->seq[$mid] ) + $beg = $mid + 1; + else + $end = $mid; + } + + USE_ASSERTS_IN_WIKI && assert($ypos != $this->seq[$end]); + + $this->in_seq[$this->seq[$end]] = false; + $this->seq[$end] = $ypos; + $this->in_seq[$ypos] = 1; + return $end; + } + + /* Find LCS of two sequences. + * + * The results are recorded in the vectors $this->{x,y}changed[], by + * storing a 1 in the element for each line that is an insertion + * or deletion (ie. is not in the LCS). + * + * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1. + * + * Note that XLIM, YLIM are exclusive bounds. + * All line numbers are origin-0 and discarded lines are not counted. + */ + function _compareseq ($xoff, $xlim, $yoff, $ylim) { + // Slide down the bottom initial diagonal. + while ($xoff < $xlim && $yoff < $ylim + && $this->xv[$xoff] == $this->yv[$yoff]) { + ++$xoff; + ++$yoff; + } + + // Slide up the top initial diagonal. + while ($xlim > $xoff && $ylim > $yoff + && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) { + --$xlim; + --$ylim; + } + + if ($xoff == $xlim || $yoff == $ylim) + $lcs = 0; + else { + // This is ad hoc but seems to work well. + //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); + //$nchunks = max(2,min(8,(int)$nchunks)); + $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1; + list ($lcs, $seps) + = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks); + } + + if ($lcs == 0) { + // X and Y sequences have no common subsequence: + // mark all changed. + while ($yoff < $ylim) + $this->ychanged[$this->yind[$yoff++]] = 1; + while ($xoff < $xlim) + $this->xchanged[$this->xind[$xoff++]] = 1; + } + else { + // Use the partitions to split this problem into subproblems. + reset($seps); + $pt1 = $seps[0]; + while ($pt2 = next($seps)) { + $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]); + $pt1 = $pt2; + } + } + } + + /* Adjust inserts/deletes of identical lines to join changes + * as much as possible. + * + * We do something when a run of changed lines include a + * line at one end and has an excluded, identical line at the other. + * We are free to choose which identical line is included. + * `compareseq' usually chooses the one at the beginning, + * but usually it is cleaner to consider the following identical line + * to be the "change". + * + * This is extracted verbatim from analyze.c (GNU diffutils-2.7). + */ + function _shift_boundaries ($lines, &$changed, $other_changed) { + $i = 0; + $j = 0; + + USE_ASSERTS_IN_WIKI && assert('sizeof($lines) == sizeof($changed)'); + $len = sizeof($lines); + $other_len = sizeof($other_changed); + + while (1) { + /* + * Scan forwards to find beginning of another run of changes. + * Also keep track of the corresponding point in the other file. + * + * Throughout this code, $i and $j are adjusted together so that + * the first $i elements of $changed and the first $j elements + * of $other_changed both contain the same number of zeros + * (unchanged lines). + * Furthermore, $j is always kept so that $j == $other_len or + * $other_changed[$j] == false. + */ + while ($j < $other_len && $other_changed[$j]) + $j++; + + while ($i < $len && ! $changed[$i]) { + USE_ASSERTS_IN_WIKI && assert('$j < $other_len && ! $other_changed[$j]'); + $i++; $j++; + while ($j < $other_len && $other_changed[$j]) + $j++; + } + + if ($i == $len) + break; + + $start = $i; + + // Find the end of this run of changes. + while (++$i < $len && $changed[$i]) + continue; + + do { + /* + * Record the length of this run of changes, so that + * we can later determine whether the run has grown. + */ + $runlength = $i - $start; + + /* + * Move the changed region back, so long as the + * previous unchanged line matches the last changed one. + * This merges with previous changed regions. + */ + while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) { + $changed[--$start] = 1; + $changed[--$i] = false; + while ($start > 0 && $changed[$start - 1]) + $start--; + USE_ASSERTS_IN_WIKI && assert('$j > 0'); + while ($other_changed[--$j]) + continue; + USE_ASSERTS_IN_WIKI && assert('$j >= 0 && !$other_changed[$j]'); + } + + /* + * Set CORRESPONDING to the end of the changed run, at the last + * point where it corresponds to a changed run in the other file. + * CORRESPONDING == LEN means no such point has been found. + */ + $corresponding = $j < $other_len ? $i : $len; + + /* + * Move the changed region forward, so long as the + * first changed line matches the following unchanged one. + * This merges with following changed regions. + * Do this second, so that if there are no merges, + * the changed region is moved forward as far as possible. + */ + while ($i < $len && $lines[$start] == $lines[$i]) { + $changed[$start++] = false; + $changed[$i++] = 1; + while ($i < $len && $changed[$i]) + $i++; + + USE_ASSERTS_IN_WIKI && assert('$j < $other_len && ! $other_changed[$j]'); + $j++; + if ($j < $other_len && $other_changed[$j]) { + $corresponding = $i; + while ($j < $other_len && $other_changed[$j]) + $j++; + } + } + } while ($runlength != $i - $start); + + /* + * If possible, move the fully-merged run of changes + * back to a corresponding run in the other file. + */ + while ($corresponding < $i) { + $changed[--$start] = 1; + $changed[--$i] = 0; + USE_ASSERTS_IN_WIKI && assert('$j > 0'); + while ($other_changed[--$j]) + continue; + USE_ASSERTS_IN_WIKI && assert('$j >= 0 && !$other_changed[$j]'); + } + } + } +} + +/** + * Class representing a 'diff' between two sequences of strings. + */ +class WikiDiff +{ + var $edits; + + /** + * Constructor. + * Computes diff between sequences of strings. + * + * @param $from_lines array An array of strings. + * (Typically these are lines from a file.) + * @param $to_lines array An array of strings. + */ + function WikiDiff($from_lines, $to_lines) { + $eng = new _WikiDiffEngine; + $this->edits = $eng->diff($from_lines, $to_lines); + //$this->_check($from_lines, $to_lines); + } + + /** + * Compute reversed WikiDiff. + * + * SYNOPSIS: + * + * $diff = new WikiDiff($lines1, $lines2); + * $rev = $diff->reverse(); + * @return object A WikiDiff object representing the inverse of the + * original diff. + */ + function reverse () { + $rev = $this; + $rev->edits = array(); + foreach ($this->edits as $edit) { + $rev->edits[] = $edit->reverse(); + } + return $rev; + } + + /** + * Check for empty diff. + * + * @return bool True iff two sequences were identical. + */ + function isEmpty () { + foreach ($this->edits as $edit) { + if ($edit->type != 'copy') + return false; + } + return true; + } + + /** + * Compute the length of the Longest Common Subsequence (LCS). + * + * This is mostly for diagnostic purposed. + * + * @return int The length of the LCS. + */ + function lcs () { + $lcs = 0; + foreach ($this->edits as $edit) { + if ($edit->type == 'copy') + $lcs += sizeof($edit->orig); + } + return $lcs; + } + + /** + * Get the original set of lines. + * + * This reconstructs the $from_lines parameter passed to the + * constructor. + * + * @return array The original sequence of strings. + */ + function orig() { + $lines = array(); + + foreach ($this->edits as $edit) { + if ($edit->orig) + array_splice($lines, sizeof($lines), 0, $edit->orig); + } + return $lines; + } + + /** + * Get the closing set of lines. + * + * This reconstructs the $to_lines parameter passed to the + * constructor. + * + * @return array The sequence of strings. + */ + function closing() { + $lines = array(); + + foreach ($this->edits as $edit) { + if ($edit->closing) + array_splice($lines, sizeof($lines), 0, $edit->closing); + } + return $lines; + } + + /** + * Check a WikiDiff for validity. + * + * This is here only for debugging purposes. + */ + function _check ($from_lines, $to_lines) { + if (serialize($from_lines) != serialize($this->orig())) + trigger_error("Reconstructed original doesn't match", E_USER_ERROR); + if (serialize($to_lines) != serialize($this->closing())) + trigger_error("Reconstructed closing doesn't match", E_USER_ERROR); + + $rev = $this->reverse(); + if (serialize($to_lines) != serialize($rev->orig())) + trigger_error("Reversed original doesn't match", E_USER_ERROR); + if (serialize($from_lines) != serialize($rev->closing())) + trigger_error("Reversed closing doesn't match", E_USER_ERROR); + + + $prevtype = 'none'; + foreach ($this->edits as $edit) { + if ( $prevtype == $edit->type ) + trigger_error("Edit sequence is non-optimal", E_USER_ERROR); + $prevtype = $edit->type; + } + + $lcs = $this->lcs(); + trigger_error("WikiDiff okay: LCS = $lcs", E_USER_NOTICE); + } +} + +/** + * FIXME: bad name. + */ + +class MappedWikiDiff +extends WikiDiff +{ + /** + * Constructor. + * + * Computes diff between sequences of strings. + * + * This can be used to compute things like + * case-insensitve diffs, or diffs which ignore + * changes in white-space. + * + * @param $from_lines array An array of strings. + * (Typically these are lines from a file.) + * + * @param $to_lines array An array of strings. + * + * @param $mapped_from_lines array This array should + * have the same size number of elements as $from_lines. + * The elements in $mapped_from_lines and + * $mapped_to_lines are what is actually compared + * when computing the diff. + * + * @param $mapped_to_lines array This array should + * have the same number of elements as $to_lines. + */ + function MappedWikiDiff($from_lines, $to_lines, + $mapped_from_lines, $mapped_to_lines) { + + assert(sizeof($from_lines) == sizeof($mapped_from_lines)); + assert(sizeof($to_lines) == sizeof($mapped_to_lines)); + + $this->WikiDiff($mapped_from_lines, $mapped_to_lines); + + $xi = $yi = 0; + for ($i = 0; $i < sizeof($this->edits); $i++) { + $orig = &$this->edits[$i]->orig; + if (is_array($orig)) { + $orig = array_slice($from_lines, $xi, sizeof($orig)); + $xi += sizeof($orig); + } + + $closing = &$this->edits[$i]->closing; + if (is_array($closing)) { + $closing = array_slice($to_lines, $yi, sizeof($closing)); + $yi += sizeof($closing); + } + } + } +} + +/** + * A class to format WikiDiffs + * + * This class formats the diff in classic diff format. + * It is intended that this class be customized via inheritance, + * to obtain fancier outputs. + */ +class WikiDiffFormatter +{ + /** + * Number of leading context "lines" to preserve. + * + * This should be left at zero for this class, but subclasses + * may want to set this to other values. + */ + var $leading_context_lines = 0; + + /** + * Number of trailing context "lines" to preserve. + * + * This should be left at zero for this class, but subclasses + * may want to set this to other values. + */ + var $trailing_context_lines = 0; + + /** + * Format a diff. + * + * @param $diff object A WikiDiff object. + * @return string The formatted output. + */ + function format($diff) { + + $xi = $yi = 1; + $block = false; + $context = array(); + + $nlead = $this->leading_context_lines; + $ntrail = $this->trailing_context_lines; + + $this->_start_diff(); + + foreach ($diff->edits as $edit) { + if ($edit->type == 'copy') { + if (is_array($block)) { + if (sizeof($edit->orig) <= $nlead + $ntrail) { + $block[] = $edit; + } + else{ + if ($ntrail) { + $context = array_slice($edit->orig, 0, $ntrail); + $block[] = new _WikiWikiDiffOp_Copy($context); + } + $this->_block($x0, $ntrail + $xi - $x0, + $y0, $ntrail + $yi - $y0, + $block); + $block = false; + } + } + $context = $edit->orig; + } + else { + if (! is_array($block)) { + $context = array_slice($context, sizeof($context) - $nlead); + $x0 = $xi - sizeof($context); + $y0 = $yi - sizeof($context); + $block = array(); + if ($context) + $block[] = new _WikiWikiDiffOp_Copy($context); + } + $block[] = $edit; + } + + if ($edit->orig) + $xi += sizeof($edit->orig); + if ($edit->closing) + $yi += sizeof($edit->closing); + } + + if (is_array($block)) + $this->_block($x0, $xi - $x0, + $y0, $yi - $y0, + $block); + + return $this->_end_diff(); + } + + function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) { + $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen)); + foreach ($edits as $edit) { + if ($edit->type == 'copy') + $this->_context($edit->orig); + elseif ($edit->type == 'add') + $this->_added($edit->closing); + elseif ($edit->type == 'delete') + $this->_deleted($edit->orig); + elseif ($edit->type == 'change') + $this->_changed($edit->orig, $edit->closing); + else + trigger_error("Unknown edit type", E_USER_ERROR); + } + $this->_end_block(); + } + + function _start_diff() { + ob_start(); + } + + function _end_diff() { + $val = ob_get_contents(); + ob_end_clean(); + return $val; + } + + function _block_header($xbeg, $xlen, $ybeg, $ylen) { + if ($xlen > 1) + $xbeg .= "," . ($xbeg + $xlen - 1); + if ($ylen > 1) + $ybeg .= "," . ($ybeg + $ylen - 1); + + return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg; + } + + function _start_block($header) { + echo $header; + } + + function _end_block() { + } + + function _lines($lines, $prefix = ' ') { + foreach ($lines as $line) + echo "$prefix $line\n"; + } + + function _context($lines) { + $this->_lines($lines); + } + + function _added($lines) { + $this->_lines($lines, ">"); + } + function _deleted($lines) { + $this->_lines($lines, "<"); + } + + function _changed($orig, $closing) { + $this->_deleted($orig); + echo "---\n"; + $this->_added($closing); + } +} + + +/** + * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3 + * + */ + +define('NBSP', ' '); // iso-8859-x non-breaking space. + +class _WikiHWLDF_WordAccumulator { + function _WikiHWLDF_WordAccumulator () { + $this->_lines = array(); + $this->_line = ''; + $this->_group = ''; + $this->_tag = ''; + } + + function _flushGroup ($new_tag) { + if ($this->_group !== '') { + if ($this->_tag == 'mark') + $this->_line .= ''.$this->_group.''; + else + $this->_line .= $this->_group; + } + $this->_group = ''; + $this->_tag = $new_tag; + } + + function _flushLine ($new_tag) { + $this->_flushGroup($new_tag); + if ($this->_line != '') + $this->_lines[] = $this->_line; + $this->_line = ''; + } + + function addWords ($words, $tag = '') { + if ($tag != $this->_tag) + $this->_flushGroup($tag); + + foreach ($words as $word) { + // new-line should only come as first char of word. + if ($word == '') + continue; + if ($word[0] == "\n") { + $this->_group .= NBSP; + $this->_flushLine($tag); + $word = substr($word, 1); + } + assert(!strstr($word, "\n")); + $this->_group .= $word; + } + } + + function getLines() { + $this->_flushLine('~done'); + return $this->_lines; + } +} + +class WordLevelWikiDiff extends MappedWikiDiff +{ + function WordLevelWikiDiff ($orig_lines, $closing_lines) { + list ($orig_words, $orig_stripped) = $this->_split($orig_lines); + list ($closing_words, $closing_stripped) = $this->_split($closing_lines); + + + $this->MappedWikiDiff($orig_words, $closing_words, + $orig_stripped, $closing_stripped); + } + + function _split($lines) { + // FIXME: fix POSIX char class. +# if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs', + if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs', + implode("\n", $lines), + $m)) { + return array(array(''), array('')); + } + return array($m[0], $m[1]); + } + + function orig () { + $orig = new _WikiHWLDF_WordAccumulator; + + foreach ($this->edits as $edit) { + if ($edit->type == 'copy') + $orig->addWords($edit->orig); + elseif ($edit->orig) + $orig->addWords($edit->orig, 'mark'); + } + return $orig->getLines(); + } + + function closing () { + $closing = new _WikiHWLDF_WordAccumulator; + + foreach ($this->edits as $edit) { + if ($edit->type == 'copy') + $closing->addWords($edit->closing); + elseif ($edit->closing) + $closing->addWords($edit->closing, 'mark'); + } + return $closing->getLines(); + } +} + +/** + * @TODO: Doc this class + */ +class TableWikiDiffFormatter extends WikiDiffFormatter +{ + var $htmltable = array(); + + function TableWikiDiffFormatter() { + $this->leading_context_lines = 2; + $this->trailing_context_lines = 2; + } + + function _block_header( $xbeg, $xlen, $ybeg, $ylen) { + + } + + function _start_block ($header) { + + } + + function _end_block() { + + } + + function _lines($lines, $prefix=' ', $color="white") { + + } + + function _added($lines) { + global $htmltable; + foreach ($lines as $line) { + $htmltable[] = array('','+','
'.$line.'
'); + } + } + + function _deleted($lines) { + global $htmltable; + foreach ($lines as $line) { + $htmltable[] = array('
'.$line.'
','-',''); + } + } + + function _context($lines) { + global $htmltable; + foreach ($lines as $line) { + $htmltable[] = array($line,'',$line); + } + } + + function _changed( $orig, $closing ) { + global $htmltable; + $diff = new WordLevelWikiDiff( $orig, $closing ); + $del = $diff->orig(); + $add = $diff->closing(); + + while ( $line = array_shift( $del ) ) { + $aline = array_shift( $add ); + $htmltable[] = array('
'.$line.'
','-','
'.$aline.'
'); + } + $this->_added( $add ); # If any leftovers + } + + function get_result() { + global $htmltable; + return $htmltable; + } + +} + + +/** + * Wikipedia Table style diff formatter. + * + */ +class TableWikiDiffFormatterOld extends WikiDiffFormatter +{ + function TableWikiDiffFormatter() { + $this->leading_context_lines = 2; + $this->trailing_context_lines = 2; + } + + function _block_header( $xbeg, $xlen, $ybeg, $ylen ) { + $l1 = wfMsg( "lineno", $xbeg ); + $l2 = wfMsg( "lineno", $ybeg ); + + $r = ''.$l1."\n" . + ''.$l2."\n"; + return $r; + } + + function _start_block( $header ) { + global $wgOut; + $wgOut->addHTML( $header ); + } + + function _end_block() { + } + + function _lines( $lines, $prefix=' ', $color="white" ) { + } + + function addedLine( $line ) { + return '+' . + $line.''; + } + + function deletedLine( $line ) { + return '-' . + $line.''; + } + + function emptyLine() { + return ' '; + } + + function contextLine( $line ) { + return ' '.$line.''; + } + + function _added($lines) { + global $wgOut; + foreach ($lines as $line) { + $wgOut->addHTML( '' . $this->emptyLine() . + $this->addedLine( $line ) . "\n" ); + } + } + + function _deleted($lines) { + global $wgOut; + foreach ($lines as $line) { + $wgOut->addHTML( '' . $this->deletedLine( $line ) . + $this->emptyLine() . "\n" ); + } + } + + function _context( $lines ) { + global $wgOut; + foreach ($lines as $line) { + $wgOut->addHTML( '' . $this->contextLine( $line ) . + $this->contextLine( $line ) . "\n" ); + } + } + + function _changed( $orig, $closing ) { + global $wgOut; + $diff = new WordLevelWikiDiff( $orig, $closing ); + $del = $diff->orig(); + $add = $diff->closing(); + + while ( $line = array_shift( $del ) ) { + $aline = array_shift( $add ); + $wgOut->addHTML( '' . $this->deletedLine( $line ) . + $this->addedLine( $aline ) . "\n" ); + } + $this->_added( $add ); # If any leftovers + } +} + diff --git a/mod/wiki/diff/difflib.php b/mod/wiki/diff/difflib.php new file mode 100644 index 00000000000..d7389ed9558 --- /dev/null +++ b/mod/wiki/diff/difflib.php @@ -0,0 +1,728 @@ +serial=$j; + $V[$j]->hash=crc32($file2[$j]); + } + + // Step 2 Sort by hash,serial + ///////// + + usort($V,"ouwiki_diff_sort_v"); + + // Make it start from 1 again + array_unshift($V,'bogus'); + unset($V[0]); + + // $V is now an array including the line number 'serial' and hash + // of each line in file 2, sorted by hash and then serial. + + // Step 3 Equivalence classes + ///////// + + $E=array(); + $E[0]=new StdClass; + $E[0]->serial=0; + $E[0]->last=true; + for($j=1;$j<=$n;$j++) { + $E[$j]=new StdClass; + $E[$j]->serial=$V[$j]->serial; + $E[$j]->last=$j===$n || $V[$j]->hash!==$V[$j+1]->hash; + } + + // E is now an array sorted the same way as $V which includes + // the line number 'serial' and whether or not that is the 'last' + // line in the given equivalence class, i.e. set of identical lines + + // Step 4 For each line in file1, finds start of equivalence class + ///////// + $P=array(); + for($i=1;$i<=$m;$i++) { + // Find matching last entry from equivalence list + $P[$i]=ouwiki_diff_find_last($V,$E,crc32($file1[$i])); + } + + // P is now an array that finds the index (within $V) of the *first* + // matching line in $V (referencing file 2, but not a line number, + // because sorted in $V order) for each line in file 1. In other words + // if you were to start at the P-value in $V and continue through, you + // would find all the lines from file 2 that are equal to the given line + // from file 1. + + // Step 5 Initialise vector of candidates + ///////// + + // I do not trust PHP references further than I can throw them (preferably + // at the idiot who came up with the idea) so I am using a separate array + // to store candidates and all references are integers into that. + + $candidates=array(); + $candidates[0]=new StdClass; + $candidates[0]->a=0; + $candidates[0]->b=0; + $candidates[0]->previous=null; + $candidates[1]=new StdClass; + $candidates[1]->a=$m+1; + $candidates[1]->b=$n+1; + $candidates[1]->previous=null; + + $K=array(); + $K[0]=0; // Ref to candidate 0 + $K[1]=1; // Ref to candidate 1 + $k=0; + + // Step 6 Merge stage + ///////// + + for($i=1;$i<=$m;$i++) { + if($P[$i]!==0) { + ouwiki_diff_merge($K,$k,$i,$E,$P[$i],$candidates); + } + } + + // Step 7 + ///////// + + $J=array(); + for($i=1;$i<=$m;$i++) { + $J[$i]=0; + } + + // Step 8 Follow candidate chain to make nice representation + ///////// + + $index=$K[$k]; + while(!is_null($index)) { + // Stop when we reach the first, dummy candidate + if($candidates[$index]->a!=0) { + $J[$candidates[$index]->a]=$candidates[$index]->b; + } + $index=$candidates[$index]->previous; + } + + // Step 9 Get rid of 'jackpots' (hash collisions) + ///////// + + for($i=1;$i<=$m;$i++) { + if($J[$i]!=0 && $file1[$i]!=$file2[$J[$i]]) { + $J[$i]=0; + } + } + + // Done! (Maybe.) + return $J; +} + +// Functions needed by parts of the algorithm +///////////////////////////////////////////// + +// Merge, from step 7 (Appendix A.3) +function ouwiki_diff_merge(&$K,&$k,$i,&$E,$p,&$candidates) { + $r=0; + $c=$K[0]; + + while(true) { + $j=$E[$p]->serial; // Paper says 'i' but this is wrong (OCR) + + // Binary search in $K from $r to $k + $min=$r; + $max=$k+1; + + while(true) { + $try = (int)(($min+$max)/2); + if($candidates[$K[$try]]->b >= $j) { + $max=$try; + } else if($candidates[$K[$try+1]]->b <= $j) { + $min=$try+1; + } else { // $try is less and $try+1 is more + $s=$try; + break; + } + if($max<=$min) { + $s=-1; + break; + } + } + + if($s>-1) { + if($candidates[$K[$s+1]]->b > $j) { + // Create new candidate + $index=count($candidates); + $candidates[$index]=new StdClass; + $candidates[$index]->a=$i; + $candidates[$index]->b=$j; + $candidates[$index]->previous=$K[$s]; + $K[$r]=$c; + $r=$s+1; + $c=$index; // Or should this go before? + } + + if($s===$k) { + $K[$k+2]=$K[$k+1]; + $k++; + break; + } + } + + if($E[$p]->last) { + break; + } + + $p++; + } + $K[$r]=$c; + +} + +// From Step 2 +function ouwiki_diff_sort_v($a,$b) { + if($a->hash < $b->hash) { + return -1; + } else if($a->hash > $b->hash) { + return 1; + } else if($a->serial < $b->serial) { + return -1; + } else if($a->serial > $b->serial) { + return 1; + } else { + return 0; + } +} + +// From Step 4 +function ouwiki_diff_find_last(&$V,&$E,$hash) { + // Binary search in $V until we find something with $hash + + // Min = 1, array is 1-indexed + $min=1; + // Max = 1 higher than highest key + end($V); + $max=key($V)+1; + while(true) { + $try = (int)(($min+$max)/2); + if($V[$try]->hash > $hash) { + $max=$try; + } else if($V[$try]->hash < $hash) { + $min=$try+1; + } else { // Equal + break; + } + if($max<=$min) { + // No matching line + return 0; + } + } + + // Now check back in $E to find the first line of that equivalence class + for($j=$try;!$E[$j-1]->last;$j--) ; + return $j; +} + +/////////////////////////// + + +/** + * Class representing one 'line' of HTML content for the purpose of + * text comparison. + */ +class ouwiki_line { + /** Array of ouwiki_words */ + var $words=array(); + + /** + * Construct line object based on a chunk of text. + * @param string $data Text data that makes up this 'line'. (May include line breaks etc.) + * @param int $linepos Position number for first character in text + */ + function ouwiki_line($data,$linepos) { + // 1. Turn things we don't want into spaces (so that positioning stays same) + + // Whitespace replaced with space + $data=preg_replace('/\s/',' ',$data); + + // Various ways of writing non-breaking space replaced with space + // Note that using a single param for replace only works because all + // the search strings are 6 characters long + $data=str_replace(array(' ',' ',' '),' ',$data); + + // Tags replaced with equal number of spaces + $data=preg_replace_callback('/<.*?'.'>/',create_function( + '$matches','return preg_replace("/./"," ",$matches[0]);'),$data); + + // 2. Analyse string so that each space-separated thing + // is counted as a 'word' (note these may not be real words, + // for instance words may include punctuation at either end) + $pos=0; + while(true) { + // Find a non-space + for(;$pos < strlen($data) && substr($data,$pos,1)===' ';$pos++) ; + if($pos==strlen($data)) { + // No more content + break; + } + + // Aaaand find the next space after that + $space2=strpos($data,' ',$pos); + if($space2===false) { + // No more spaces? Everything left must be a word + $this->words[]=new ouwiki_word(substr($data,$pos),$pos+$linepos); + break; + } else { + $this->words[]=new ouwiki_word(substr($data,$pos,$space2-$pos),$pos+$linepos); + $pos=$space2; + } + } + } + + /** + * @return string Normalised string representation of this line object + */ + function get_as_string() { + $result=''; + foreach($this->words as $word) { + if($result!=='') { + $result.=' '; + } + $result.=$word->word; + } + return $result; + } + + /** + * Static function converts lines to strings. + * @param array $lines Array of ouwiki_line + * @return array Array of strings + */ + function get_as_strings($lines) { + $strings=array(); + foreach($lines as $key=>$value) { + $strings[$key]=$value->get_as_string(); + } + return $strings; + } + + + /** + * @return True if there are no words in the line + */ + function is_empty() { + return count($this->words)===0; + } +} + +/** + * Represents single word for html comparison. Note that words + * are just chunks of plain text and may not be actual words; + * they could include punctuation or (if there was e.g. a span + * in the middle of something) even be part-words. + */ +class ouwiki_word { + /** Word as plain string */ + var $word; + /** Start position in original xhtml */ + var $start; + + function ouwiki_word($word,$start) { + $this->word=$word; + $this->start=$start; + } +} + +/** + * Prepares XHTML content for text difference comparison. + * @param string $content XHTML content [NO SLASHES] + * @return array Array of ouwiki_line objects + */ +function ouwiki_diff_html_to_lines($content) { + // These functions are a pain mostly because PHP preg_* don't provide + // proper information as to the start/end position of matches. As a + // consequence there is a lot of hackery going down. At every point we + // replace things with spaces rather than getting rid, in order to store + // positions within original content. + + // Get rid of all script, style, object tags (that might contain non-text + // outside tags) + $content=preg_replace_callback( + '^( - - - - - -
- - - - - - -
- - - -
- -
-
- - - diff --git a/mod/wiki/ewiki/fragments/htaccess b/mod/wiki/ewiki/fragments/htaccess deleted file mode 100644 index be77518798c..00000000000 --- a/mod/wiki/ewiki/fragments/htaccess +++ /dev/null @@ -1,25 +0,0 @@ -# This is file is to be used with the Apache or Nanoweb webserver. -# -# Rename it to .htaccess (or .nwaccess for Nanoweb) in a dedicated -# directory for your Wiki. -# -# It uses the mod_rewrite to look a bit more professionall than -# the usual GET-vars at the end of our URLs. This is highly -# recommended as things like "script.php?edit=1&id=page" usually -# scare search engines and may prevent your Wiki from getting -# indexed. -# -# Please edit ewiki.php and enable EWIKI_USE_PATH_INFO for Apache -# webservers - the PATH_INFO implementation is very broken for many -# versions (mostly commercial Unicies and for PHP-CGI variants), -# because to the Apache Group once choosed to follo that never -# finished and heavily broken (proposed) CGI/1.1 specification. - -#-- enable mod_rewrite (Apache + Nanoweb) -RewriteEngine On - -#-- pass WikiWord-URLs to the wiki wrapper script: -RewriteRule ^((\w+/)?[A-Z]+[a-z]+\w*[A-Z]+\w+)$ yoursite.php/$1 [L] - -#-- or this one, if there is really nothing else in the same directory: -#RewriteRule ^(.*)$ yoursite.php?id=$1 [L] diff --git a/mod/wiki/ewiki/fragments/mkhuge b/mod/wiki/ewiki/fragments/mkhuge deleted file mode 100644 index 0723e7da561..00000000000 --- a/mod/wiki/ewiki/fragments/mkhuge +++ /dev/null @@ -1,61 +0,0 @@ -#!/bin/sh -# -# a shell script, which combines the ewiki.php library and some -# default plugins into a huger include library -# - - -HUGE_FILE="huge-ewiki.php" -CORE_FILE="ewiki.php" - - -#-- current dir -if [ -e "ewiki.php" ] ; then - DWP=. -else - DWP=.. -fi - - -#-- help -if [ "$1" == "-h" -o "$1" == "--help" ] ; then - echo "syntax: mkhuge" - echo "combines many of the plugins and the core ewiki.php file into a bigger lib." - exit -fi - - -#-- choose size -N=$1 -if [ -z "$N" ] ; then - N=0 -fi -if [ "$1" -ge "3" ] ; then - PLUGINS="markup_phpwiki.php markup_bbcode.php spellcheck.php $PLUGINS" -fi -if [ "$1" -ge "2" ] ; then - PLUGINS="more_interwiki.php page_imagegallery.php $PLUGINS" -fi -if [ "$1" -ge "1" ] ; then - PLUGINS="diff.php page_randompage.php markup_footnotes.php page_wordindex.php $PLUGINS" -fi -PLUGINS="strip_wonderful_slashes.php calendar.php email_protect.php like_pages.php page_pageindex.php page_powersearch.php $PLUGINS" - - -#-- proceed -echo -n "writing: $CORE_FILE" -cat $DWP/$CORE_FILE > $DWP/$HUGE_FILE -for ADD in $PLUGINS -do - echo -n "+$ADD" - for SUB in plugins fragments ; do - if [ -e "$DWP/$SUB/$ADD" ] ; then - ADD=$DWP/$SUB/$ADD - fi - done - cat $ADD >> $DWP/$HUGE_FILE -done -echo " > $DWP/$HUGE_FILE" -echo "done." - - diff --git a/mod/wiki/ewiki/fragments/nuke_mod_wiki_index b/mod/wiki/ewiki/fragments/nuke_mod_wiki_index deleted file mode 100644 index a5c7382b028..00000000000 --- a/mod/wiki/ewiki/fragments/nuke_mod_wiki_index +++ /dev/null @@ -1,58 +0,0 @@ - $value) { - - if (!is_array($value)) { - $GLOBALS[$AREA][$name] = stripslashes($value); - } - } - } - - - - diff --git a/mod/wiki/ewiki/fragments/wiki_format.inc b/mod/wiki/ewiki/fragments/wiki_format.inc deleted file mode 100644 index e84ec48411f..00000000000 --- a/mod/wiki/ewiki/fragments/wiki_format.inc +++ /dev/null @@ -1,291 +0,0 @@ - - * Adapted by Frank Luithle - * - * WikiLinks and binary already stripped off -> just the rendering core - */ - -// URL prefixes -$ewiki_idf_url = array( "http://", - "mailto:", - "ftp://", - "irc://", - "telnet://", - "news://", - "internal://", - "chrome://", - "file://" ); - -// allowed wikinames -//define( "EWIKI_CHARS_L", "a-z����_��$" ); -//define( "EWIKI_CHARS_U", "A-Z���" ); - -function wiki_format( $wiki_source, - $strip_slashes = true, - $safe_html_allowed = true, - $table_html_allowed = false ) { - - if ( $strip_slashes ) { - $wiki_source = stripslashes( $wiki_source ); - } - - // formatted output - $o = "

\n"; - - // state vars - $li_o = ""; - $tbl_o = 0; - $post = ""; - - $wm_whole_line = array( "!!!" => "h2", - "!!" => "h3", - "!" => "h4", - " " => "tt", - ";:" => 'div style="left-margin:10pt;"' ); - - $table_defaults = 'cellpadding="2" border="1" cellspacing="0"'; - - // these tags will be preserved if the $safe_html_allowed argument - // is set to 'true' - $rescue_html = array( "tt", "b", "i", "strong", "em", "s", "kbd", "var", - "xmp", "sup", "sub", "pre", "q", "h2", "h3", "h4", - "h5", "h6", "cite", "code", "u" ); - - $syn_htmlentities = array( "&" => "&", - ">" => ">", - "<" => "<", - "%%%" => "
" ); - - $wm_list = array( "-" => array('ul type="square"', "", "li"), - "*" => array('ul type="circle"', "", "li"), - "#" => array("ol", "", "li"), - ":" => array("dl", "dt", "dd") ); - - $wm_text_style = array( "'''" => array("''__", "__''"), - "___" => array("''__", "__''"), - "''" => array("", ""), - "__" => array("", ""), - // "^^" => array("", ""), - // "***" => array("", ""), - // "###" => array("", ""), - "**" => array("", ""), - "##" => array("", ""), - "��" => array("", "") ); - - $link_regex = "#(!?\[[^[\]\n]+\])|((?:!?[a-z]{2,6}://|mailto:)[^\s\[\]\'\"\)\,<]+)#"; - - #$link_regex = "#(!?\[[^[\]\n]+\])|((?:!?[".EWIKI_CHARS_U."]+[".EWIKI_CHARS_L. - # ":]+){2}[\w\d]*)|((?:!?[a-z]{2,6}://|mailto:)[^\s\[\]\'\"\)\,<]+)#"; - - // eliminate html - foreach ( $syn_htmlentities as $find => $replace ) { - $wiki_source = str_replace( $find, $replace, $wiki_source ); - } - array_pop( $syn_htmlentities ); - - // unescape allowed html - if ( $safe_html_allowed ) { - foreach ( $rescue_html as $tag ) { - foreach( array( $tag, "/$tag", ( $tag = strtoupper($tag) ), "/$tag" ) - as $tag ) { - $wiki_source = str_replace( '<' . $tag . '>', - "<" . $tag . ">", - $wiki_source ); - } - } - } - - $wiki_source = trim( $wiki_source ) . "\n"; - - foreach ( explode( "\n", $wiki_source ) as $line ) { - $line = rtrim( $line ); - $post = ""; - - // paragraphs - if ( empty($line) ) { - $post .= "

\n\n

"; - } elseif ( strpos( $line, "----" ) === 0 ) { - $o .= "


\n"; - continue; - } elseif ( strpos( $line, "<!--" ) === 0 ) { - $o .= "\n"; - continue; - } - - // unescape html markup || tables wiki markup - if ( strlen( $line ) && ( $line[0] == "|" ) ) { - if ( strlen( $line ) > - strlen( trim( $line, "|" ) ) + 1 ) { - $line = substr( $line, 1, strlen( $line ) - 2 ); - if ( !$tbl_o ) { - $o .= "\n"; - } - $line = "\n\n\n"; - $tbl_o = 1; - } elseif ( $table_html_allowed ) { - $line = ltrim( substr( $line, 1 ) ); - foreach ( array_flip( $syn_htmlentities ) as $find => $replace ) { - $line = str_replace( $find, $replace, $line ); - } - } - } elseif ($tbl_o) { - $o .= "
" . str_replace("|", "", $line) . "
\n"; - $tbl_o = 0; - } - - // whole-line wikimarkup - foreach ( $wm_whole_line as $find => $replace ) { - if ( substr( $line, 0, strlen($find) ) == $find ) { - $line = ltrim( substr( $line, strlen($find) ) ); - $o .= "<$replace>"; - $post = "" . $post; - } - } - - // wiki list markup - if ( strlen( $li_o ) || - strlen( $line ) && isset( $wm_list[@$line[0]] ) ) { - $n = 0; - $li = ""; - // count differences to previous list wikimarkup - while ( strlen( $line ) && ( $li0 = $line[0] ) && isset( $wm_list[$li0] ) ) { - $li .= $li0; - $n++; - $line = substr($line, 1); - } - $line = ltrim($line); - - // fetch list definition - if ( strlen( $li ) && ( $last_list_i = $li[strlen($li)-1] ) ) - list( $list_tag, $list_dt0, $list_entry_tag ) = $wm_list[$last_list_i]; - - // output
    until new list wikimarkup rule matched - while ( strlen($li_o) < strlen($li) ) { - $add = $li[ strlen($li_o) ]; - $o .= "<" . $wm_list[ $add ][ 0 ] . ">\n"; - $li_o .= $add; - } - - // close
lists until "$li_o" == "$li" (list wikimarkup state var) - while ( strlen($li_o) > strlen($li) ) { - $del = $li_o[ strlen($li_o) - 1 ]; - $o .= "\n"; - $li_o = substr( $li_o, 0, strlen($li_o) - 1 ); - } - - // more work for
lists - if ( !empty($list_dt0) ) { - list( $line_dt, $line ) = explode( $last_list_i, $line, 2 ); - $o .= "<$list_dt0>$line_dt"; - $list_dt0 = $last_list_i = false; - } - - // finally enclose current line in
  • ...
  • - if ( !empty($line) ) { - $o .= "<$list_entry_tag>"; - $post = "" . $post; - } - - $li_o = $li; - } - - // link-regex here?? - // (was formerly, may be faster if applied to the whole formatted - // page, but this could also introduce some rendering bugs) - - // text style triggers - foreach ( $wm_text_style as $find => $replace ) { - $n = strlen( $find ); - $loop = 20; - while( ( $loop-- ) && - ( ($l = strpos($line, $find)) !== false ) && - ( $r = strpos($line, $find, $l + $n) ) ) { - $line = substr( $line, 0, $l ) . $replace[0] . - substr( $line, $l + strlen($find), $r - $l - $n ) . - $replace[1] . substr( $line, $r + $n ); - } - } - - // add formatted line to page-output - $o .= $line . $post . "\n"; - - } - - // close last line - $o .= "

    \n"; - - // finally the link-detection-regex - // (impossible to do with simple string arithmetics) - $o = preg_replace_callback( $link_regex, "wiki_link_regex_callback", $o ); - - return( $o ); -} - - -function wiki_link_regex_callback( $uu ) { - - global $ewiki_idf_url; - - $str = $uu[0]; - - // link bracket '[' escaped with '!' - if ( $str[0] == "!" ) { - return(substr($str, 1)); - } elseif ( $str[0] == "[" ) { - $str = substr( $str, 1, strlen($str) - 2 ); - } - - // explicit title given via [ foo | bar ] - $href = $title = strtok( $str, "|" ); - if ( $uu = strtok("|") ) { - $href = $uu; - } - - // title and href swapped: swap back - if ( strpos( "://", $title ) || - strpos( $title, ":" ) && !strpos( $href, ":" ) ) { - $uu = $title; - $title = $href; - $href = $uu; - } - - $title = trim($title); - $href = trim($href); - - /* create _no_ WikiLinks */ - if ( false ){ - // interwiki links - if ( strpos($href, ":") && - !strpos($href, "//") && - ($p1 = @$ewiki_interwiki[strtok($href, ":")]) ) { - while ($p1_alias = @$ewiki_interwiki[$p1]) { - $p1 = $p1_alias; - } - $href = $p1 . strtok("\000"); - } elseif (($ewiki_links === true) || - @$ewiki_links[$href] || - @$ewiki_internal_pages[$href]) { - // ordinary internal WikiLinks - $str = '' . $title . ''; - } else { - $str = '' . $title . '?'; - } - } - - // convert normal URLs - foreach ( $ewiki_idf_url as $find ) { - if ( strpos( $href, $find ) === 0 ) { - $str = '' . $title . ''; - break; - } - } - - return($str); -} - - diff --git a/mod/wiki/ewiki/plugins/aview/backlinks.php b/mod/wiki/ewiki/plugins/aview/backlinks.php deleted file mode 100755 index fd64363bd89..00000000000 --- a/mod/wiki/ewiki/plugins/aview/backlinks.php +++ /dev/null @@ -1,21 +0,0 @@ -'.$id.''; - } - ($o) && ($o = "
    ".get_string('backlinks', 'wiki').":
    $o
    \n"); - - return($o); -} diff --git a/mod/wiki/ewiki/plugins/aview/downloads.php b/mod/wiki/ewiki/plugins/aview/downloads.php deleted file mode 100644 index 00ca4a9fa69..00000000000 --- a/mod/wiki/ewiki/plugins/aview/downloads.php +++ /dev/null @@ -1,61 +0,0 @@ -

    ' . ewiki_t("ATTACHMENTS") . '

    '; - - $scan = 's:7:"section";' . serialize($id); - $result = ewiki_database("SEARCH", array("meta" => $scan)); - -#### BEGIN MOODLE CHANGES - show attachments link only if there are attachments. -#### - don't show the attachments on the content page. - if (count($result->entries) <= 0) { - $o = ''; - } -// $ord = array(); -// while ($row = $result->get()) { -// $ord[$row["id"]] = $row["created"]; -// } -// arsort($ord); -// -// foreach ($ord as $id => $uu) { -// $row = ewiki_database("GET", array("id"=>$id)); -// if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($row["id"], $row, "view")) { -// continue; -// } -// $o .= ewiki_entry_downloads($row, "*"); -// } -#### END MOODLE CHANGES - - return($o); -} - - - - -function ewiki_attachments() { - global $ewiki_title, $ewiki_id; - return(ewiki_view_append_attachments($ewiki_title, array("id"=>$ewiki_id), "view")); -} - - - - diff --git a/mod/wiki/ewiki/plugins/email_protect.php b/mod/wiki/ewiki/plugins/email_protect.php deleted file mode 100644 index 65af4a5e470..00000000000 --- a/mod/wiki/ewiki/plugins/email_protect.php +++ /dev/null @@ -1,313 +0,0 @@ - before the real email address gets shown on a page (it seems - # impossible to me, that there are already all that intelligent spambots - # available, which can automatically fill out a
    to access the - # following page). - # The 'cipher' method is really unimportant, when it comes to tricking - # automated harvesters. - # - # Additionally it generates faked/trap email addresses to annoy the - # marketing mafia. - - - #-- change these from time to time: - define("EWIKI_PAGE_EMAIL", "ProtectedEmail"); - define("EWIKI_UP_ENCEMAIL", "encoded_email"); - define("EWIKI_UP_NOSPAMBOT", "i_am_no_spambot"); - define("EWIKI_UP_REQUESTLV", "rl"); - define("EWIKI_FAKE_EMAIL_LOOP", 5); - $ewiki_config["feedbots_tarpits"] = "@spamassassin.taint.org,@123webhosting.org,@e.mailsiphon.com,@heypete.com,@ncifcrf.gov"; - $ewiki_config["feedbots_badguys"] = "@riaa.com,@whitehouse.gov,@aol.com,@microsoft.com"; - - #-- text, translations - $ewiki_t["en"]["PROTE0"] = "Protected Email Address"; - $ewiki_t["en"]["PROTE1"] = "The email address you've clicked on is protected by this form, so it won't get found by spambots (automated search engines, which crawl the net for addresses just for the entertainment of the marketing mafia)."; - $ewiki_t["en"]["PROTE2"] = "The page you're going to edit contains at least one email address. To protect it we must ensure that no spambot reaches the edit box (with the email address in cleartext)."; - $ewiki_t["en"]["PROTE4"] = "I'm no spambot, really!"; - $ewiki_t["en"]["PROTE5"] = "generate more faked email addresses"; - $ewiki_t["en"]["PROTE6"] = "the email address you've clicked on is:"; - $ewiki_t["en"]["PROTE7"] = "spammers, please eat these:"; - - $ewiki_t["de"]["PROTE0"] = "Gesch�tzte EMail-Adresse"; - $ewiki_t["de"]["PROTE1"] = "Die EMail-Adresse, die du angeklickt hast, wird durch dieses Formular vor spambots (automatisierte Suchwerkzeuge, die das Netz zur Freude der MarketingMafia nach Adressen abgrasen) besch�tzt."; - $ewiki_t["de"]["PROTE2"] = "Die Seite, die du �ndern willst, enth�lt momentan wenigstens eine EMail-Adresse. Um diese zu sch�tzen m�ssen wir sicherstellen, da� kein Spambot an die Edit-Box kommt (weil dort die Adresse ja im Klartext steht)."; - $ewiki_t["de"]["PROTE4"] = "Ich bin wirklich kein Spambot!"; - $ewiki_t["de"]["PROTE5"] = "noch mehr fingierte Adressen anzeigen"; - $ewiki_t["de"]["PROTE6"] = "die EMail-Adresse die du angeklickt hast lautet:"; - $ewiki_t["de"]["PROTE7"] = "Liebe Spammer, bitte fre�t das:"; - - #-- plugin glue - $ewiki_plugins["link_url"][] = "ewiki_email_protect_link"; - $ewiki_plugins["page"][EWIKI_PAGE_EMAIL] = "ewiki_email_protect_form"; - $ewiki_plugins["edit_hook"][] = "ewiki_email_protect_edit_hook"; - $ewiki_plugins["page_final"][] = "ewiki_email_protect_enctext"; - - - - function ewiki_email_protect_enctext(&$html, $id, $data, $action) { - - $a_secure = array("info", "diff"); - - if (in_array($action, $a_secure)) { - - $html = preg_replace('/([-_+\w\d.]+@[-\w\d.]+\.[\w]{2,5})\b/me', - '"".ewiki_email_protect_encode("\1",0).""', - $html); - } - } - - - /* ewiki_format() callback function to replace mailto: links with - * encoded redirection URLs - */ - function ewiki_email_protect_link(&$href, &$title) { - - if (substr($href, 0, 7) == "mailto:") { - - $href = substr($href, 7); - - $href = ewiki_email_protect_encode($href, 2); - $title = ewiki_email_protect_encode($title, 0); - } - } - - - - /* the edit box for every page must be protected as well - else all - * mail addresses would still show up in the wikimarkup (cleartext) - */ - function ewiki_email_protect_edit_hook($id, &$data, &$hidden_postdata) { - - $ewiki_up_nospambot = optional_param(EWIKI_UP_NOSPAMBOT, null); - - $hidden_postdata[EWIKI_UP_NOSPAMBOT] = 1; - - if (empty($ewiki_up_nospambot ) - && strpos($data["content"], "@") - && preg_match('/\w\w@([-\w]+\.)+\w\w/', $data["content"]) ) - { - $url = ewiki_script("edit", $id); - $o = ewiki_email_protect_form($id, $data, "edit", "PROTE2", $url); - return($o); - } - - if (!empty($ewiki_up_nospambot) && empty($_COOKIE[EWIKI_UP_NOSPAMBOT]) && EWIKI_HTTP_HEADERS) { - setcookie(EWIKI_UP_NOSPAMBOT, "grant_access", time()+7*24*3600, "/"); - } - - } - - - - /* this places a in between the WikiPage with the - * encoded mail address URL and the page with the clearly readable - * mailto: string - */ - function ewiki_email_protect_form($id, $data=0, $action=0, $text="PROTE1", $url="") { - - $ewiki_up_encemail = optional_param(EWIKI_UP_ENCEMAIL, null); - $ewiki_up_nospambot = optional_param(EWIKI_UP_NOSPAMBOT, null); - - if ($url || ($email = $ewiki_up_encemail)) { - - $html = "

    " . ewiki_t("PROTE0") . "

    \n"; - - if (empty($ewiki_up_nospambot)) { #// from GET,POST,COOKIE - - (empty($url)) and ($url = ewiki_script("", EWIKI_PAGE_EMAIL)); - - $html .= ewiki_t($text) . "


    \n"; - - $html .= ''; - $html .= '
    '; - $html .= ''; - foreach (array_merge($_GET, $_POST) as $var=>$value) { - if (($var != "id") && ($var != EWIKI_UP_ENCEMAIL) && ($var != EWIKI_UP_NOSPAMBOT)) { - $html .= ''; - } - } - $html .= ' ' . ewiki_t("PROTE4") . '

    '; - $html .= '


    '; - - if (EWIKI_FAKE_EMAIL_LOOP) { - $html .= "\n" . ewiki_t("PROTE7") . "
    \n"; - $html .= ewiki_email_protect_feedbots(); - } - - } - else { - - $email = ewiki_email_protect_encode($email, -1); - - $html .= ewiki_t("PROTE6") . "
    "; - $html .= '' . $email . ''; - - if (EWIKI_HTTP_HEADERS && empty($_COOKIE[EWIKI_UP_NOSPAMBOT])) { - setcookie(EWIKI_UP_NOSPAMBOT, "grant_access", time()+7*24*3600, "/"); - } - - } - - } - - return($html); - } - - - - /* security really does not depend on how good "encoding" is, because - * bots cannot automatically guess that one is actually used - */ - function ewiki_email_protect_encode($string, $func) { - - switch ($func) { - - case 0: // garbage shown email address - if (strpos($string, "mailto:") === 0) { - $string = substr($string, 7); - } - while (($rd = strrpos($string, ".")) > strpos($string, "@")) { - $string = substr($string, 0, $rd); - } - $string = strtr($string, "@.-_", "����"); - break; - - case 1: // encode - $string = str_rot17($string); - $string = base64_encode($string); - break; - - case -1: // decode - $string = base64_decode($string); - $string = str_rot17($string); - break; - - case 2: // url - $string = ewiki_script("", EWIKI_PAGE_EMAIL, - array(EWIKI_UP_ENCEMAIL => ewiki_email_protect_encode($string, 1)) - ); - break; - - } - - return($string); - } - - - - /* this is a non-portable string encoding fucntion which ensures, that - * encoded strings can only be decoded when requested by the same client - * or user in the same dialup session (IP address must match) - * feel free to exchange the random garbage string with anything else - */ - function str_rot17($string) { - if (!defined("STR_ROT17")) { - $i = @$_SERVER["SERVER_SOFTWARE"] . - @$_SERVER["HTTP_USER_AGENT"] . - getremoteaddr(); - $i .= 'MxQXF^e-0OKC1\\s{\"?i!8PRoNnljHf65`Eb&A(\':g[D}_|S#~3hG>*9yvdI%<=.urcp/@$ZkqL,TWBw]a;72UzYJ)4mt+ V'; - $f = ""; - while (strlen($i)) { - if (strpos($f, $i[0]) === false) { - $f .= $i[0]; - } - $i = substr($i, 1); - } - define("STR_ROT17", $f); - } - return(strtr($string, STR_ROT17, strrev(STR_ROT17))); - } - - - - /* this function emits some html with random (fake) email addresses - * and spambot traps - */ - function ewiki_email_protect_feedbots() { - - global $ewiki_config; - - $ewiki_up_requestlv = optional_param(EWIKI_UP_REQUESTLV, 0, PARAM_CLEAN); - - $html = ""; - srand(time()/17-1000*microtime()); - - #-- spamtraps, and companys/orgs fighting for spammers rights - $domains = explode(",", - $ewiki_config["feedbots_tarpits"]. "," .$ewiki_config["feedbots_badguys"] - ); - $traps = explode(" ", "blockme@relays.osirusoft.com simon.templar@rfc1149.net james.bond@ada-france.org anton.dvorak@ada.eu.org amandahannah44@hotmail.com usenet@fsck.me.uk meatcan2@beatrice.rutgers.edu heystupid@artsackett.com listme@dsbl.org bill@caradoc.org spamtrap@spambouncer.org spamtrap@woozle.org gfy@spamblocked.com listme@blacklist.woody.ch tarpit@lathi.net"); - $word_parts = explode(" ", "er an Ma ar on in el en le ll Ca ne ri De Mar Ha Br La Co St Ro ie Sh Mc re or Be li ra Al la al Da Ja il es te Le ha na Ka Ch is Ba nn ey nd He tt ch Ho Ke Ga Pa Wi Do st ma Mi Sa Me he to Car ro et ol ck ic Lo Mo ni ell Gr Bu Bo Ra ia de Jo El am An Re rt at Pe Li Je She Sch ea Sc it se Cha Har Sha Tr as ng rd rr Wa so Ki Ar Bra th Ta ta Wil be Cl ur ee ge ac ay au Fr ns son Ge us nt lo ti ss Cr os Hu We Cor Di ton Ri ke Ste Du No me Go Va Si man Bri ce Lu rn ad da ill Gi Th and rl ry Ros Sta sh To Se ett ley ou Ne ld Bar Ber lin ai Mac Dar Na ve no ul Fa ann Bur ow Ko rs ing Fe Ru Te Ni hi ki yn ly lle Ju Del Su mi Bl di lli Gu ine do Ve Gar ei Hi vi Gra Sto Ti Hol Vi ed ir oo em Bre Man ter Bi Van Bro Col id Fo Po Kr ard ber sa Con ick Cla Mu Bla Pr Ad So om io ho ris un her Wo Chr Her Kat Mil Tre Fra ig Mel od nc yl Ale Jer Mcc Lan lan si Dan Kar Mat Gre ue rg Fi Sp ari Str Mer San Cu rm Mon Win Bel Nor ut ah Pi gh av ci Don ot dr lt ger co Ben Lor Fl Jac Wal Ger tte mo Er ga ert tr ian Cro ff Ver Lin Gil Ken Che Jan nne arr va ers all Cal Cas Hil Han Dor Gl ag we Ed Em ran han Cle im arl wa ug ls ca Ric Par Kel Hen Nic len sk uc ina ste ab err Or Am Mor Fer Rob Luc ob Lar Bea ner pe lm ba ren lla der ec ric Ash Ant Fre rri Den Ham Mic Dem Is As Au che Leo nna rin enn Mal Jam Mad Mcg Wh Ab War Ol ler Whi Es All For ud ord Dea eb nk Woo tin ore art Dr tz Ly Pat Per Kri Min Bet rie Flo rne Joh nni Ce Ty Za ins eli ye rc eo ene ist ev Der Des Val And Can Shi ak Gal Cat Eli May Ea rk nge Fu Qu nie oc um ath oll bi ew Far ich Cra The Ran ani Dav Tra Sal Gri Mos Ang Ter mb Jay les Kir Tu hr oe Tri lia Fin mm aw dy cke itt ale wi eg est ier ze ru sc My lb har ka mer sti br ya Gen Hay a b c d e f g h i j k l m n o p q r s t u v w x y z"); - $word_delims = explode(" ", "0 1 2 3 3 3 4 5 5 6 7 8 9 - - - - - - - _ _ _ _ _ _ _ . . . . . . ."); - $n_dom = count($domains)-1; - $n_trp = count($traps)-1; - $n_wpt = count($word_parts)-1; - $n_wdl = count($word_delims)-1; - - for ($n = 1; $n < EWIKI_FAKE_EMAIL_LOOP; $n++) { - - // email name part - $m = ""; - while (strlen($m) < rand(3,17)) { - $a = $word_parts[nat_rand($n_wpt)]; - if (!empty($m)) { - $a = strtolower($a); - if (rand(1,9)==5) { - $m .= $word_delims[rand(0,$n_wdl)]; - } - } - $m .= $a; - } - - // add domain - switch ($dom = $domains[rand(0, $n_dom)]) { - - case "123webhosting.org": - $m = strtr(".", "-", getremoteaddr())."-".$_SERVER["SERVER_NAME"]."-".time(); - break; - - default: - } - $m .= $dom; - - $html .= ''.$m.''.",\n"; - } - - $html .= ''.$traps[rand(0, $n_trp)].''; - - if (($rl = 1 + $ewiki_up_requestlv) < EWIKI_FAKE_EMAIL_LOOP) { - $html .= ",\n" . '
    ewiki_email_protect_encode($m, 1), - EWIKI_UP_REQUESTLV=>"$rl" - ) - ) . '">' . ewiki_t("PROTE5") . '
    ' . "\n"; - ($rl > 1) && sleep(3); - } - - sleep(1); - return($html); - } - - - - function nat_rand($max, $dr=0.5) { - $x = $max+1; - while ($x > $max) { - $x = rand(0, $max * 1000)/100; - $x = $x * $dr + $x * $x / 2 * (1-$dr) / $max; - } - return((int)$x); - } - - - diff --git a/mod/wiki/ewiki/plugins/feature/imgresize_gd.php b/mod/wiki/ewiki/plugins/feature/imgresize_gd.php deleted file mode 100755 index d3eef74460b..00000000000 --- a/mod/wiki/ewiki/plugins/feature/imgresize_gd.php +++ /dev/null @@ -1,121 +0,0 @@ - EWIKI_IMAGE_MAXSIZE)) { - - if ($filename == $tmp_rescale) { - $tmp_rescale = tempnam(EWIKI_TMP, "ewiki.img_resize_gd.tmp."); - } - - #-- sizes - $new_x = (int) ($orig_x * $r); - $new_y = (int) ($orig_y * $r); - - #-- new gd image - $tc = function_exists("imageistruecolor") && imageistruecolor($orig_image); - if (!$tc || ($type == "gif")) { - $new_image = imagecreate($new_x, $new_y); - imagepalettecopy($new_image, $orig_image); - } - else { - $new_image = imagecreatetruecolor($new_x, $new_y); - } - - #-- resize action - imagecopyresized($new_image, $orig_image, 0,0, 0,0, $new_x,$new_y, $orig_x,$orig_y); - - #-- special things - if ( ($type == "png") && function_exists("imagesavealpha") ) { - imagesavealpha($new_image, 1); - } - - #-- save - if (function_exists($pf = "image$type")) { - $pf($new_image, $tmp_rescale); - } - else { - return(false); # cannot save in orig format (.gif) - } - - #-- prepare next run - imagedestroy($new_image); - clearstatcache(); - $r *= 0.95; - } - - #-- stop - imagedestroy($orig_image); - - #-- security check filesizes, abort - if (!filesize($filename) || !filesize($tmp_rescale) || (filesize($tmp_rescale) > EWIKI_IMAGE_MAXSIZE)) { - unlink($tmp_rescale); - return($false); - } - - #-- set $mime, as it may have changed (.gif) - $mime = strtok($mime, "/") . "/" . $type; - if (!strstr($filename, ".$type")) { - unlink($filename); - $filename .= ".$type"; - } - - #-- move tmp file to old name - copy($tmp_rescale, $filename); - unlink($tmp_rescale); - return(true); - -} - diff --git a/mod/wiki/ewiki/plugins/init.php b/mod/wiki/ewiki/plugins/init.php deleted file mode 100644 index 8f3c049bf77..00000000000 --- a/mod/wiki/ewiki/plugins/init.php +++ /dev/null @@ -1,125 +0,0 @@ -WikiSetupWizard\n"; - $o .= "You don't have any pages in your Wiki yet, so we should try to read-in the default ones from init-pages/ now.

    "; - - $o .= '"now")).'">[InitializeWikiDatabase]'; - $o .= "   "; - $o .= '"this")).'">[NoThanks]'; - $o .= "

    "; - - #-- analyze and print settings and misconfigurations - $pf_db = $ewiki_plugins["database"][0]; - $xdb = substr($pf_db, strrpos($pf_db, "_") + 1); - $o .= ''; - $o .= '"; - - $o .= '"; - $o .= "
    DatabaseBackend'; - $o .= "" . $xdb . "
    "; - if ($xdb == "files") { - $o .= "_DBFILES_DIR='" . EWIKI_DBFILES_DIRECTORY . "'"; - if (strpos(EWIKI_DBFILES_DIRECTORY, "tmp")) { - $o .= "
    Warning: Storing your pages into a temporary directory is not what you want (there they would get deleted randomly), except for testing purposes of course. See the README."; - } - } - else { - $o .= "(looks ok)"; - } - $o .= "
    WikiSoftwareewiki '.EWIKI_VERSION."
    "; - - #-- more diagnosis - if (ini_get("magic_quotes")) { - $o.= "Warning: Your PHP interpreter has enabled the ugly and outdated 'magic_quotes'. This will lead to problems, so please ask your provider to correct it; or fix it yourself with .htaccess settings as documented in the README. Otherwise don't forget to include() the fragments/strip_wonderful_slashes.php (it's ok to proceed for the moment).

    "; - } - if (ini_get("register_globals")) { - $o.= "Security warning: The horrible 'register_globals' setting is enabled. Without always using fragments/strike_register_globals.php or letting your provider fix that, you could get into trouble some day.

    "; - } - - return('
    ' . $o . '
    '); - } - - - #-- actually initialize the database - else { - ewiki_database("INIT", array()); - if ($dh = @opendir($path=EWIKI_INIT_PAGES)) { - while (false !== ($filename = readdir($dh))) { - if (preg_match('/^(['.EWIKI_CHARS_U.']+['.EWIKI_CHARS_L.']+\w*)+/', $filename)) { - $found = ewiki_database("FIND", array($filename)); - if (! $found[$filename]) { - $content = implode("", file("$path/$filename")); - ewiki_scan_wikiwords($content, $ewiki_links, "_STRIP_EMAIL=1"); - $refs = "\n\n" . implode("\n", array_keys($ewiki_links)) . "\n\n"; - $save = array( - "id" => "$filename", - "version" => "1", - "flags" => "1", - "content" => $content, - "author" => ewiki_author("ewiki_initialize"), - "refs" => $refs, - "lastmodified" => filemtime("$path/$filename"), - "created" => filectime("$path/$filename") // (not exact) - ); - ewiki_database("WRITE", $save); - } - } - } - closedir($dh); - } - else { - return("ewiki error: could not read from directory ". realpath($path) ."
    \n"); - } - - #-- try to view/ that newly inserted page - if ($data = ewiki_database("GET", array("id"=>$id))) { - $action = "view"; - } - - #-- let ewiki_page() proceed as usual - return(""); - } - } - -} - - - diff --git a/mod/wiki/ewiki/plugins/jump.php b/mod/wiki/ewiki/plugins/jump.php deleted file mode 100644 index 391bf8b4456..00000000000 --- a/mod/wiki/ewiki/plugins/jump.php +++ /dev/null @@ -1,100 +0,0 @@ -Redirection loop detected

    \nOperation stopped, because we're traped in an infinite redirection loop with page \$id."; - -#-- plugin glue -$ewiki_plugins["handler"][] = "ewiki_handler_jump"; -$ewiki_config["interwiki"]["jump"] = ""; -$ewiki_config["interwiki"]["goto"] = ""; - - -function ewiki_handler_jump(&$id, &$data, &$action) { - - global $ewiki_config; - static $redirect_count = 5; - - $redirect_count = optional_param("EWIKI_UP_REDIRECT_COUNT", $redirect_count, PARAM_INT); - - $jump_markup = array("jump", "goto", "redirect", "location"); - - #-- we only care about "view" action - if ($action != "view") { - return; - } - - #-- escape from loop - if ($redirect_count-- <= 0) { - return(ewiki_t("REDIRECTION_LOOP", array("id"=>$id))); - } - - #-- search for [jump:...] - if ($links = explode("\n", trim($data["refs"]))) - foreach ($links as $link) { - - if (strlen($link) && strpos($link, ":") - && in_array(strtolower(strtok($link, ":")), $jump_markup) - && ($dest = trim(strtok("\n"))) ) - { - $url = ""; - if (strpos($dest, "://")) { - $url = $dest; - } - else { - $url = ewiki_interwiki($dest); - } - - #-- Location: - if (EWIKI_JUMP_HTTP && EWIKI_HTTP_HEADERS && !headers_sent()) { - - if (empty($url)) { - $url = ewiki_script("", $dest, - array(EWIKI_UP_REDIRECT_COUNT=>$redirect_count), - 0, 0, ewiki_script_url() - ); - } - header("Location: $url"); - die(); - - } - #-- show page as usual, what will reveal dest URL - elseif ($url) { - return(""); - # the rendering kernel will just show up the [jump:]! - # (without the jump: of course) - } - #-- it's simply about another WikiPage - else { - - #-- we'll just restart ewiki - $data = array(); - $id = $dest; - return(ewiki_page("view/".$id)); - } - } - }#-search -} - - diff --git a/mod/wiki/ewiki/plugins/lib/mime_magic.php b/mod/wiki/ewiki/plugins/lib/mime_magic.php deleted file mode 100644 index c891a9ba61b..00000000000 --- a/mod/wiki/ewiki/plugins/lib/mime_magic.php +++ /dev/null @@ -1,571 +0,0 @@ -GPL ##################### - -/* - -# this was originally implemented for Nanoweb, but can now be used -# within ewiki to enhance the download/upload plugin. -# As it was created from Debians mime-magic data, it is covered by -# the GNU GPL [http://www.gnu.org/]: - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - -*/ - - -$ewiki_plugins["mime_magic"][] = "ewiki_mime_magic"; - - - -function ewiki_mime_magic(&$binary_data) { - - global $mime_magic_data; - - $fd = substr($binary_data, 0, 3072); - - foreach ($mime_magic_data as $def) { - - if ($def[0] >= $f_read) { - continue; - } - - $pos0 = $def[0]; - - if ($pos0[0] == ">") { - - $pos0 = substr($pos0, 1); - - if (strpos($fd, $def[3], $pos0) !== false) { - - return($def[4]); - } - - } - else { - - $part = substr($fd, $pos0, $def[1]); - - if ($mask = $def[2]) { - - $value = 1 * ('0x'.bin2hex($part)); - - if (($value & $mask) == $def[3]) { - - return($def[4]); - } - - } - else { - - if ($part == $def[3]) { - - return($def[4]); - } - - } - } - - } - -} - - - - - - $GLOBALS["mime_magic_data"] = array( - array(0, 2, 0, "\x06\x02", "application/x-alan-adventure-game"), - array(0, 4, 0, "TADS", "application/x-tads-game"), - array(0, 2, 0, "\x01\x10", "application/x-executable-file"), - array(0, 2, 0, "\x01\x11", "application/x-executable-file"), - array(0, 2, 0, "\x01�", "application/x-executable-file"), - array(0, 5, 0, "Core\001", "application/x-executable-file"), - array(0, 22, 0, "AMANDA: TAPESTART DATE", "application/x-amanda-header"), - array(0, 2, 0xfff0, 0xf0ff, "audio/mpeg"), - array(4, 2, 0, "�\x11", "video/fli"), - array(4, 2, 0, "�\x12", "video/flc"), - array(0, 4, 0, "MOVI", "video/x-sgi-movie"), - array(4, 4, 0, "moov", "video/quicktime"), - array(4, 4, 0, "mdat", "video/quicktime"), - array(0, 18, 0, "FiLeStArTfIlEsTaRt", "text/x-apple-binscii"), - array(0, 3, 0, "\x0aGL", "application/data"), - array(0, 2, 0, "\x76\xff", "application/data"), - array(0, 6, 0, "NuFile", "application/data"), - array(0, 6, 0, "N\xf5F\xe9l\xe5", "application/data"), - array(0, 4, 0, "\x00\x16\x05\x00", "application/data"), - array(0, 4, 0, "\x07\x16\x05\x00", "application/data"), - array(257, 6, 0, "ustar\0", "application/x-tar"), - array(257, 8, 0, "ustar\040\040\0", "application/x-gtar"), - array(0, 2, 0, "q�", "application/x-cpio"), - array(0, 2, 0, "�q", "application/x-bcpio"), - array(0, 6, 0, "070707", "application/x-cpio"), - array(0, 6, 0, "070701", "application/x-cpio"), - array(0, 6, 0, "070702", "application/x-cpio"), - array(0, 2, 0, "�m", "application/data"), - array(0, 2, 0, "�e", "application/data"), - array(0, 5, 0, "=", "application/x-ar"), - array(0, 19, 0, "!\n__________E", "application/x-ar"), - array(0, 3, 0, "-h-", "application/data"), - array(0, 7, 0, "!", "application/x-ar"), - array(0, 4, 0, "", "application/x-ar"), - array(0, 4, 0, ">ra<", "application/x-ar"), - array(0, 4, 0, "!\n\n________64E", "application/data"), - array(0, 2, 0, "\x01�", "application/x-executable-file"), - array(0, 2, 0, "\x01�", "application/x-object-file"), - array(0, 3, 0, "\377\377\177", "application/data"), - array(0, 3, 0, "\377\377\174", "application/data"), - array(0, 3, 0, "\377\377\176", "application/data"), - array(0, 3, 0, "\033c\033", "application/data"), - array(0, 4, 0, "\x00\x12և", "image/x11"), - array(0, 8, 0, "!!\n", "application/x-prof"), - array(0, 2, 0, "\x05\x01", "application/x-locale"), - array(0, 4, 0, "\177ELF", "application/x-executable-file"), - array(0, 2, 0, "\x01T", "application/data"), - array(0, 2, 0, "\x01U", "application/x-executable-file"), - array(0x438, 2, 0, "�S", "application/x-linux-ext2fs"), - array(0, 4, 0, "\366\366\366\366", "application/x-pc-floppy"), - array(0774, 2, 0, "��", "application/data"), - array(0x1FE, 2, 0, "�U", "application/data"), - array(0x410, 2, 0, "\x13", "application/x-filesystem"), - array(0x410, 2, 0, "\x13�", "application/x-filesystem"), - array(0x410, 2, 0, "\x24h", "application/x-filesystem"), - array(0x410, 2, 0, "\x24x", "application/x-filesystem"), - array(0, 9, 0, "-rom1fs-\0", "application/x-filesystem"), - array(0, 4, 0, "\x1b\x03\x136", "application/x-bootable"), - array(0x18b, 4, 0, "OS/2", "application/x-bootable"), - array(0, 4, 0, "FONT", "font/x-vfont"), - array(0, 2, 0, "\x01\x1e", "font/x-vfont"), - array(0, 2, 0, "\x1e\x01", "font/x-vfont"), - array(0, 18, 0, "%!PS-AdobeFont-1.0", "font/type1"), - array(6, 18, 0, "%!PS-AdobeFont-1.0", "font/type1"), - array(0, 10, 0, "STARTFONT\040", "font/x-bdf"), - array(0, 4, 0, "\001fcp", "font/x-pcf"), - array(0, 5, 0, "D1.0\015", "font/x-speedo"), - array(0, 3, 0, "flf", "font/x-figlet"), - array(0, 3, 0, "flc", "application/x-font"), - array(0, 4, 0, "\x19Y\x02\x14", "font/x-libgrx"), - array(0, 4, 0, "NOF�", "font/x-dos"), - array(7, 4, 0, "AGE\x00", "font/x-dos"), - array(7, 4, 0, "DIV\x00", "font/x-dos"), - array(0, 10, 0, "2', 2, 0, "��", "application/java"), - array(8, 4, 0, "AIFF", "audio/x-aiff"), - array(8, 4, 0, "AIFC", "audio/x-aiff"), - array(8, 4, 0, "8SVX", "audio/x-aiff"), - array('>8', 4, 0, "WAVE", "audio/x-wav"), - array('>8', 3, 0, "AVI", "video/x-msvideo"), - array(0, 3, 0, "ID3", "audio/mpeg"), - array(0, 4, 0, "OggS", "audio/x-ogg"), - array(0, 6, 0, "/* XPM", "image/x-xpm"), - array(16, 2, 0, "==", "image/x-3ds"), - array(0, 11, 0, "#!/bin/tcsh", "application/x-shellscript"), - array(0, 12, 0, "#! /bin/tcsh", "application/x-shellscript"), - array(0, 18, 0, "#! /usr/local/tcsh", "application/x-shellscript"), - array('>8', 6, 0, "debian", "application/x-debian-package"), - array('>2', 2, 0, "��", "application/x-rpm"), - array(2, 5, 0, "-lh -", "application/x-lha"), - array(2, 5, 0, "-lh6-", "application/x-lha"), - array(2, 5, 0, "-lh7-", "application/x-lha"), - array(0, 15, 0, "8', 4, 0, "AVI ", "video/avi"), - array(0, 1, 0, "\x01", "video/unknown"), - array(0, 1, 0, "\x02", "video/unknown"), - array(0, 19, 0, "[KDE Desktop Entry]", "application/x-kdelnk"), - array(0, 18, 0, "\# KDE Config File", "application/x-kdelnk"), - array(0, 7, 0, "\# xmcd", "text/xmcd"), - array(0, 4, 0, "\x8aMNG", "video/x-mng"), - array(0, 4, 0, "�\x03\x00\x00", "application/x-executable-file"), - array(0, 4, 0, "�\x03\x00\x00", "application/x-library-file"), - array(0, 4, 0, "�\x01\x00\x00", "video/mpeg"), - array(0, 4, 0, "�\x01\x00\x00", "video/mpeg"), - array(0, 4, 0, "\x00\x00�l", "application/x-apl-workspace"), - array(0, 4, 0, "\x00\x00�m", "application/x-ar"), - array(0, 4, 0, "\x00\x00�e", "application/data"), - array(0, 4, 0, "\x00\x00\x01\x06", "application/x-executable-file"), - array(0, 4, 0, "G\x01\x00\x00", "application/x-object-file"), - array(0, 4, 0, "K\x01\x00\x00", "application/x-executable-file"), - array(0, 4, 0, "M\x01\x00\x00", "application/x-executable-file"), - array(0, 4, 0, "O\x01\x00\x00", "application/x-executable-file"), - array(24, 4, 0, "k�\x00\x00", "application/data"), - array(24, 4, 0, "l�\x00\x00", "application/data"), - array(24, 4, 0, "m�\x00\x00", "application/data"), - array(24, 4, 0, "n�\x00\x00", "application/data"), - array(0, 4, 0, "�\x01\x00\x00", "application/x-object-file"), - array(0, 4, 0, "�\x01\x00\x00", "application/data"), - array(24, 4, 0, "\x00\x00�l", "application/x-dump"), - array(24, 4, 0, "\x00\x00�k", "application/x-dump"), - array(0, 4, 0, "\x00\x00�1", "text/vnd.ms-word"), - array(0, 2, 0, "\x00\x00", "audio/mpeg"), - array('>16', 2, 0, "\x00\x01", "application/x-object"), - array('>16', 2, 0, "\x00\x02", "application/x-executable"), - array('>16', 2, 0, "\x00\x03", "application/x-sharedlib"), - array('>16', 2, 0, "\x00\x04", "application/x-coredump"), - array(0, 4, 0, "\x00\x00\x00�", "application/x-executable-file"), - array(0, 4, 0, "\x04\x00\x00\x00", "font/x-snf"), - array(0, 4, 0, "\x00\x00\x00\x04", "font/x-snf"), - array('>12', 4, 0, "\x01\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x02\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x03\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x04\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x05\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x06\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x07\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x17\x00\x00\x00", "audio/x-adpcm"), - array('>12', 4, 0, "\x00\x00\x00\x01", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x02", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x03", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x04", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x05", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x06", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x07", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x17", "audio/x-dec-adpcm") - ); - - - diff --git a/mod/wiki/ewiki/plugins/markup/footnotes.php b/mod/wiki/ewiki/plugins/markup/footnotes.php deleted file mode 100755 index 7392221f1cb..00000000000 --- a/mod/wiki/ewiki/plugins/markup/footnotes.php +++ /dev/null @@ -1,60 +0,0 @@ -�$notenum" - . substr($source, $r + 2); - - #-- add "footnote" to the end of the wiki page source - if ($notenum==1) { - $source .= "\n----"; - } - $source .= "\n" . - "�$notenum ". $footnote . "\n
    "; - - } -} - - diff --git a/mod/wiki/ewiki/plugins/moodle/diff.php b/mod/wiki/ewiki/plugins/moodle/diff.php deleted file mode 100755 index 2d255e77b16..00000000000 --- a/mod/wiki/ewiki/plugins/moodle/diff.php +++ /dev/null @@ -1,114 +0,0 @@ - $id, "version" => $new_ver)); - } - else { - $new_ver = $data["version"]; - $old_ver = $new_ver - 1; - } - if ($old_ver > 0) { - $data0 = ewiki_database("GET", array("id" => $id, "version" => $old_ver)); - } - - $a->new_ver=$new_ver; - $a->old_ver=$old_ver; - $a->pagename=$id; - $o = ewiki_make_title($id, get_string("differences","wiki",$a)); - - # Different handling for html: closes Bug #1530 - Wiki diffs useless when using HTML editor - if($wiki->htmlmode==2) { - /// first do the formatiing to get normal display format without filters - $options = new object(); - $options->smiley = false; - $options->filter = false; - $content0 = format_text($data0['content'], $moodle_format, $options); - $content = format_text($data['content'], $moodle_format, $options); - - /// Remove all new line characters. They will be placed at HTML line breaks. - $content0 = preg_replace('/\n|\r/i', ' ', $content0); - $content0 = preg_replace('/(\S)\s+(\S)/', '$1 $2', $content0); // Remove multiple spaces. - $content = preg_replace('/\n|\r/i', ' ', $content); - $content = preg_replace('/(\S)\s+(\S)/', '$1 $2', $content); - - /// Replace

     

    - $content0 = preg_replace('#(]*)?>( |\s+)

    )|(]*)?>

    )#i', "\n", $content0); - $content = preg_replace('#(]*)?>( |\s+)

    )|(]*)?>

    )#i', "\n", $content); - - - /// Place new line characters at logical HTML positions. - $htmlendings = array('+()+iU', '+(]*)?>)+iU', '+(

    )+i', '+()+iU', '+()+iU', - '+()+i', '+()+iU', '+()+i', '+()+iU', '+()+i', - '+()+i', '+()+iU', '+()+i'); - $htmlrepl = array("\n\$1\n", "\n\$1\n", "\n\$1\n", "\n\$1\n", "\n\$1\n", - "\n\$1\n", "\n\$1\n", "\n\$1\n", "\n\$1\n", "\n\$1\n", - "\n\$1\n", "\n\$1\n", "\n\$1\n"); - $content0 = preg_replace($htmlendings, $htmlrepl, $content0); - $content = preg_replace($htmlendings, $htmlrepl, $content); - } else { - $content0=$data0["content"]; - $content=$data["content"]; - } - $txt0 = preg_split("+\s*\n+", trim($content0)); - $txt2 = preg_split("+\s*\n+", trim($content)); - - $diff0 = array_diff($txt0, $txt2); - $diff2 = array_diff($txt2, $txt0); - - foreach ($txt2 as $i => $line) { - $i2 = $i; - while ($rm = $diff0[$i2++]) { - if($wiki->htmlmode == 2) { - if ($rm == '
    ') { //ugly hack to fix line breaks - $rm = ''; - } - $o .= "-".format_text($rm, $moodle_format, $options)."
    \n"; - } else { - $o .= "-".s($rm)."
    \n"; - } - unset($diff0[$i2-1]); - } - - if (in_array($line, $diff2)) { - if($wiki->htmlmode == 2) { - if ($line == '
    ') { //ugly hack to fix line breaks - $line = ''; - } - $o .= "+".format_text($line, $moodle_format, $options)."
    \n"; - } else { - $o .= "+".s($line)."
    \n"; - } - } - else { - if($wiki->htmlmode == 2) { - $o .= format_text($line, $moodle_format, $options)."\n"; - } else { - $o .= "  ".s($line)."
    \n"; - } - } - - } - - foreach ($diff0 as $rm) { - $o .= "- ".s($rm)."
    \n"; - } - - return($o); - } -?> diff --git a/mod/wiki/ewiki/plugins/moodle/downloads.php b/mod/wiki/ewiki/plugins/moodle/downloads.php deleted file mode 100644 index cbb6f0e78ae..00000000000 --- a/mod/wiki/ewiki/plugins/moodle/downloads.php +++ /dev/null @@ -1,399 +0,0 @@ -libdir.'/filelib.php'); - -# this is the upload/download plugin, which allows to put arbitrary binary -# files into the ewiki database using the provided specialized form, or the -# standard image upload form below every edit page (if EWIKI_ALLOW_BINARY) - - -#-- settings - -# Defined in view.php -#define("EWIKI_UPLOAD_MAXSIZE", 2*1024*1024); -define("EWIKI_PAGE_UPLOAD", "FileUpload"); -define("EWIKI_PAGE_DOWNLOAD", "FileDownload"); -define("EWIKI_ACTION_ATTACHMENTS", "attachments"); #-- define to 0 to disable - -#-- register plugin (main part) -$ewiki_plugins["page"][EWIKI_PAGE_UPLOAD] = "ewiki_page_fileupload"; -$ewiki_plugins["page"][EWIKI_PAGE_DOWNLOAD] = "ewiki_page_filedownload"; -$ewiki_plugins["action"]["binary"] = "ewiki_binary"; - -#-- allow per-page downloads -if (defined("EWIKI_ACTION_ATTACHMENTS") && EWIKI_ACTION_ATTACHMENTS) { - $ewiki_plugins["action"][EWIKI_ACTION_ATTACHMENTS] = "ewiki_action_attachments"; - $ewiki_config["action_links"]["view"][EWIKI_ACTION_ATTACHMENTS] = "Attachments"; -} - - -#-- icons (best given absolute to www root) -/*$ewiki_binary_icons = array( - ".bin" => "/icons/exec.gif", - "application/" => "/icons/exec.gif", - "application/octet-stream" => "/icons/exec.gif", - ".ogg" => "/icons/son.gif", - ".jpeg" => "/icons/pic.gif", - "text/" => "/icons/txt.gif", - ".pdf" => "/icons/txt.gif", -);*/ - - -#-- the upload function __can__ use different sections -$ewiki_upload_sections = array( - "" => "main", -# "section2" => "section2", -); - - -#-- text, translations -$ewiki_t["en"]["UPLOAD0"] = "Use this form to upload an arbitrary binary file into the wiki:
    "; -$ewiki_t["en"]["UPL_NEWNAM"] = "Save with different filename"; -$ewiki_t["en"]["UPL_INSECT"] = "Upload into section"; -$ewiki_t["en"]["UPL_TOOLARGE"] = "Your upload has been rejected, because that file was too large!"; -$ewiki_t["en"]["UPL_REJSECT"] = 'The given download section "$sect" has been rejected. Please only use the default ones, or tell the WikiAdmin to reenable per-page uploads; else others can\'t find your uploaded files easily.

    '; -$ewiki_t["en"]["UPL_OK"] = "Your file was uploaded correctly, please see ".EWIKI_PAGE_DOWNLOAD.".

    "; -$ewiki_t["en"]["UPL_ERROR"] = "We're sorry, but something went wrong during the file upload.

    "; -$ewiki_t["en"]["DWNL_SEEUPL"] = 'See also FileUpload, this page is only about downloading.

    '; -$ewiki_t["en"]["DWNL_NOFILES"] = "No files uploaded yet.
    \n"; -$ewiki_t["en"]["file"] = "File"; -$ewiki_t["en"]["of"] = "of"; -$ewiki_t["en"]["comment"] = "Comment"; -$ewiki_t["en"]["dwnl_section"] = "download section"; -$ewiki_t["en"]["DWNL_ENTRY_FORMAT"] = - '
    $icon$title$size
    '. - 'uploaded on $time, downloaded $hits times
    '. - '($id)
    '. - '$section'.'file is of type $type'. - '$comment'."

    \n"; - -$ewiki_t["de"]["UPLOAD0"] = "Mit diesem Formular kannst du beliebige Dateien in das Wiki abspeichern:
    "; -$ewiki_t["de"]["UPL_NEWNAM"] = "Mit unterschiedlichem Dateinamen speichern"; -$ewiki_t["de"]["UPL_INSECT"] = "Hochladen in Bereich:"; -$ewiki_t["de"]["UPL_TOOLARGE"] = "Deine Datei wurde nicht aufgenommen, weil sie zu gro� war!"; -$ewiki_t["de"]["UPL_REJSECT"] = 'Der angegebene Download-Bereich "$sect" wird nicht verwendet. Bitte verwende einen von den voreingestellten Bereichen, damit Andere die Datei sp�ter auch finden k�nnen, oder frag den Administrator das Hochladen f�r beliebige Seiten zu aktivieren.

    '; -$ewiki_t["de"]["UPL_OK"] = "Deine Datei wurde korrekt hochgeladen, sehe einfach auf der ".EWIKI_PAGE_DOWNLOAD." nach.

    "; -$ewiki_t["de"]["UPL_ERROR"] = "'Tschuldige, aber irgend etwas ist w�hrend des Hochladens gr�ndlich schief gelaufen.

    "; -$ewiki_t["de"]["DWNL_SEEUPL"] = 'Siehe auch DateiHochladen, auf dieser Seite stehen nur die Downloads.

    '; -$ewiki_t["de"]["DWNL_NOFILES"] = "Noch keine Dateien hochgeladen.
    \n"; -$ewiki_t["de"]["file"] = "Datei"; -$ewiki_t["de"]["of"] = "von"; -$ewiki_t["de"]["comment"] = "Kommentar"; -$ewiki_t["de"]["dwnl_section"] = "Download Bereich"; -$ewiki_t["de"]["DWNL_ENTRY_FORMAT"] = - '
    $icon$title$size
    '. - 'am $time hochgeladen, $hits mal abgerufen
    '. - '($id)
    '. - '$section'.'Datei ist vom Typ $type'. - '$comment'."

    \n"; - - - - -function ewiki_page_fileupload($id, $data, $action, $def_sec="") { - - global $CFG, $ewiki_upload_sections, $ewiki_plugins; - - $o = ewiki_make_title($id, $id, 2); - - $upload_file = $_FILES[EWIKI_UP_UPLOAD]; - if (empty($upload_file)) { - - $o .= ewiki_t("UPLOAD0"); - - $o .= '
    '. - '
    ' ; - $o .= '
    '; - require_once($CFG->dirroot.'/lib/uploadlib.php'); - $o .= upload_print_form_fragment(1,array(EWIKI_UP_UPLOAD),array(ewiki_t("file")),false,null,0,0,true); - $o .= '

    ' - .'' . ewiki_t("comment") . '


    '; - - if (empty($ewiki_upload_sections[$def_sec])) { - $ewiki_upload_sections[$def_sec] = $def_sec; - } - if (count($ewiki_upload_sections) > 1) { - if (empty($def_sec)) { - $def_sec = optional_param('section', '', PARAM_CLEAN); - } - $o .= ''.ewiki_t("UPL_INSECT").'


    '; - } - - $o .= ''.ewiki_t("UPL_NEWNAM").'


    '; - - $o .= '
    '; - - } - elseif ($upload_file["size"] > EWIKI_UPLOAD_MAXSIZE) { - - $o .= ewiki_t("UPL_TOOLARGE"); - - } - else { - - $meta = array( - "X-Content-Type" => $upload_file["type"], - #"X-Content-Length" => $upload_file["size"], - ); - if (($s = $upload_file["name"]) && (strlen($s) >= 3) - || ($s = substr(md5(time()+microtime()),0,8) . ".dat")) - { - if (strlen($uu = trim(optional_param("new_filename",'', PARAM_FILE))) >= 3) { - if ($uu != $s) { - $meta["Original-Filename"] = $s; - } - $s = $uu; - } - $meta["Content-Location"] = $s; - ($p = 0) or - ($p = strrpos($s, "/")) and ($p++) or - ($p = strrpos($s, '\\')) and ($p++); - $meta["Content-Disposition"] = 'attachment; filename="'.urlencode(substr($s, $p)).'"'; - } - if (strlen($sect = optional_param("section",'', PARAM_CLEAN))) { - if ($ewiki_upload_sections[$sect] - || ($action==EWIKI_ACTION_ATTACHMENTS) && ($data["content"]) - && strlen($ewiki_plugins["action"][EWIKI_ACTION_ATTACHMENTS])) { - $meta["section"] = $sect; - } - else { - $o .= ewiki_t("UPL_REJSECT", array('sect' => $sect)); - - return($o); - } - } - if (strlen($s = trim(optional_param("comment",'', PARAM_CLEAN)))) { - $meta["comment"] = $s; - } - - $result = ewiki_binary_save_image($upload_file["tmp_name"], "", "RETURN", $meta, "ACCEPT_ALL", $care_for_images=0); - - if ($result) { - $o .= ewiki_t("UPL_OK", array('$script'=>ewiki_script())); - } - else { - $o .= ewiki_t("UPL_ERROR"); - } - - } - - return($o); -} - - - - -function ewiki_page_filedownload($id, $data, $action, $def_sec="") { - - global $ewiki_binary_icons, $ewiki_upload_sections; - - $o = ewiki_make_title($id, $id, 2); -## $o .= ewiki_t("DWNL_SEEUPL", '$scr'=>ewiki_script("", "")); - - - #-- params (section, orderby) - $orderby = optional_param('orderby', 'created', PARAM_ALPHA); - - if ($def_sec) { - $section = $def_sec; - } - else { - $section = optional_param('section', '', PARAM_CLEAN); - if (count($ewiki_upload_sections) > 1) { - $oa = array(); - $ewiki_upload_sections["*"] = "*"; - if (empty($ewiki_plugins["action"][EWIKI_ACTION_ATTACHMENTS])) { - $ewiki_upload_sections["**"] = "**"; - } - foreach ($ewiki_upload_sections as $sec=>$title) { - $oa[] = '$orderby, "section" => $sec)) . - '">' . $title . ""; - } - $o .= '
    '.implode(" · ", $oa).'

    '; - } - } - - - #-- collect entries - $files = array(); - $sorted = array(); - $result = ewiki_database("GETALL", array("flags", "meta", "created", "hits", "userid")); - - while ($row = $result->get()) { - if (($row["flags"] & EWIKI_DB_F_TYPE) == EWIKI_DB_F_BINARY) { - - $m = &$row["meta"]; - if(!$section) { - $section="**"; - } - if ($m["section"] != $section) { - if ($section == "**") { - } - elseif (($section == "*") && !empty($ewiki_upload_sections[$m["section"]])) { - } - else { - continue; - } - } - else { - } - - $files[$row["id"]] = $row; - $sorted[$row["id"]] = $row[$orderby]; - } - } - - - #-- sort - arsort($sorted); - - - #-- slice - $pnum = optional_param(EWIKI_UP_PAGENUM, 0, PARAM_INT); - if (count($sorted) > EWIKI_LIST_LIMIT) { - $o_nl .= '
    >> '; - for ($n=0; $n < (int)(count($sorted) / EWIKI_LIST_LIMIT); $n++) { - $o_nl .= '$orderby, "section"=>$section, EWIKI_UP_PAGENUM=>$n)) . - '">[' . $n . "] "; - } - $o_nl .= '

    '; - $o .= $o_nl; - } - $sorted = array_slice($sorted, $pnum * EWIKI_LIST_LIMIT, EWIKI_LIST_LIMIT); - - - #-- output - if (empty($sorted)) { - - $o .= ewiki_t("DWNL_NOFILES"); - } - else { - - foreach ($sorted as $id=>$uu) { - $row = $files[$id]; - $o .= ewiki_entry_downloads($row, $section[0]=="*", true); - } - } - - $o .= $o_nl; - - return($o); - -} - - - - -function ewiki_entry_downloads($row, $show_section=0, $fullinfo=false) { - - global $ewiki_binary_icons, $ewiki_upload_sections, $DB, $OUTPUT; - - $meta = &$row["meta"]; - - $id = $row["id"]; - $p_title = basename($meta["Content-Location"]); - $p_time = userdate($row["created"]); - - - $p_hits = ($row["hits"] ? $row["hits"] : "0"); - $p_size = $meta["size"]; - $p_size = isset($p_size) ? (", " . ($p_size>=4096 ? round($p_size/1024)."K" : $p_size." bytes")) : ""; - $p_ct1 = $meta["Content-Type"]; - $p_ct2 = $meta["X-Content-Type"]; - if ($p_ct1==$p_ct2) { unset($p_ct2); } - if ($p_ct1 && !$p_ct2) { $p_ct = "$p_ct1"; } - elseif (!$p_ct1 && $p_ct2) { $p_ct = "$p_ct2"; } - elseif ($p_ct1 && $p_ct2) { $p_ct = "$p_ct1, $p_ct2"; } - else { $p_ct = "application/octet-stream"; } - $p_section = $ewiki_upload_sections[$meta["section"]]; - $p_section = $p_section ? $p_section : $meta["section"]; - $p_comment = strlen($meta["comment"]) ? '
    '. - str_replace('

    ', '', str_replace('

    ', '', - ewiki_format($meta["comment"]))) . '

    ' : "
    "; - - $p_icon = ""; - /*foreach ($ewiki_binary_icons as $str => $i) { - if (empty($str) || strstr($row["Content-Location"], $str) || strstr($p_ct, $str) || strstr($p_ct2, $str)) { - $p_icon = $i; - $p_icon_t = $str; - } - }*/ - - /// Moodle Icon Handling - global $CFG; - $p_icon = $OUTPUT->pix_url(file_extension_icon($id)); - $p_icon_t = ''; - - $info->id = $id; - $info->size = $p_size; - $info->icon = ($p_icon ? '['.$p_icon_t.'] ' : ''); - $info->time = $p_time; - $info->hits = $p_hits; - $info->section = ($show_section ? ewiki_t('dwnl_section') . ": $p_section
    " : ''); - $info->type = $p_ct; - $info->url = ewiki_script_binary("", $row["id"]); - $info->title = $p_title; - $info->comment = format_text($p_comment); - - if ($fullinfo) { - if ($user = $DB->get_record('user', array('id'=>$row['userid']))) { - if (!isset($course->id)) { - $course->id = 1; - } - $picture = $OUTPUT->user_picture($user, array('courseid'=>$course->id)); - $value = $picture . html_writer::link("$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id", fullname($user)); - } - - $o .= ''.$info->icon.$info->title.''.$info->size.'
    '. - $info->comment. - $info->section." ".get_string("fileisoftype","wiki").": ".$info->type.'
    '. - get_string("uploadedon","wiki").": ".$info->time.", ". - ' by '.$value.'
    '. - get_string("downloadtimes","wiki",$info->hits)."
    ". -// '('.$info->id.")
    ". - '

    '; - } - else { -// global $moodle_format; // from wiki/view.php - $o .= ''.$info->icon.$info->title.''.$info->size.'
    '. - $info->comment.'

    '; -// $o = format_text($o, $moodle_format); - } - - - - ewiki_t("DWNL_ENTRY_FORMAT", $info); - - return($o); -} - - - -#------------------------------------------------------- per-page uploads --- - - -function ewiki_action_attachments($id, $data, $action=EWIKI_ACTION_ATTACHMENTS) { - - if (!empty($_FILES[EWIKI_UP_UPLOAD])) { - $o .= ewiki_page_fileupload($id, $data, EWIKI_ACTION_ATTACHMENTS, $id); - } - - $o .= ewiki_page_filedownload(ucwords(EWIKI_ACTION_ATTACHMENTS) . " " . ewiki_t("of") . " $id", $data, "view", $id); - - unset($_FILES[EWIKI_UP_UPLOAD]); - $o .= ewiki_page_fileupload($id, $data, EWIKI_ACTION_ATTACHMENTS, $id); - - return($o); - -} - - - diff --git a/mod/wiki/ewiki/plugins/moodle/f_fixhtml.php b/mod/wiki/ewiki/plugins/moodle/f_fixhtml.php deleted file mode 100644 index a3c779ee382..00000000000 --- a/mod/wiki/ewiki/plugins/moodle/f_fixhtml.php +++ /dev/null @@ -1,177 +0,0 @@ - inside
      or even -

      inside

      problems (this should rather be fixed in the ewiki_format - function). So following code is not meant to fix any possible html file, - and it certainly won't make valid html files out of random binary data. - So for full html spec conformance you should rather utilize w3c tidy (by - using your Webservers "Filter" directive). -*/ - - -define("EWIKI_XHTML", 1); -$ewiki_plugins["page_final"][] = "ewiki_html_tag_balancer"; - - -function ewiki_html_tag_balancer(&$html) { - - #-- vars - $html_standalone = array( - "img", "br", "hr", - "input", "meta", "link", - ); - $html_tags = array( - "a", "abbr", "acronym", "address", "applet", "area", "b", "base", - "basefont", "bdo", "big", "blockquote", "body", "br", "button", - "caption", "center", "cite", "code", "col", "colgroup", "dd", "del", - "dfn", "dir", "div", "dl", "dt", "em", "fieldset", "font", "form", - "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "html", "i", - "iframe", "img", "input", "ins", "kbd", "label", "legend", "li", - "link", "map", "menu", "meta", "noframes", "noscript", "object", "ol", - "optgroup", "option", "p", "param", "pre", "q", "s", "samp", "script", - "select", "small", "span", "strike", "strong", "style", "sub", "sup", - "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "title", - "tr", "tt", "u", "ul", "var", - #-- H2.0 "nextid", "listing", "xmp", "plaintext", - #-- H3.2 "frame", "frameset", - #-- X1.1 "rb", "rbc", "rp", "rt", "rtc", "ruby", - ); - $close_opened_when = array( - "p", "div", "ul", "td", "table", "tr", - ); - if (!EWIKI_XHTML) { - $html_tags = array_merge( (array) $html_tags, array( - "bgsound", "embed", "layer", "multicol", "nobr", "noembed", - )); - } - - #-- walk through all tags - $tree = array(); - $len = strlen($html); - $done = ""; - $pos = 0; - $loop = (int)$len / 3; - while (($pos < $len) && $loop--) { - - #-- search next tag - $l = strpos($html, "<", $pos); - $r = strpos($html, ">", $l); - if (($l===false) or ($r===false)) { - # finish - $done .= substr($html, $pos); - break; - } - - #-- copy plain text part - if ($l >= $pos) { - $done .= substr($html, $pos, $l-$pos); - $pos = $l; - } - - #-- analyze current html tag - if ($r >= $pos) { - $pos = $r + 1; - $tag = substr($html, $l + 1, $r - $l - 1); - - #-- split into name and attributes - $tname = strtolower(strtok($tag, " \t\n>")); // LOWERCASING not needed here really - ($tattr = strtok(">")) && ($tattr = " $tattr"); - - // attribute checking could go here - // (here we just assume good output from ewiki core) - // ... - - #-- html comment - if (substr($tname, 0, 3) == "!--") { - $r = strpos($html, "-->", $l+4); - $pos = $r + 3; - $done .= substr($html, $l, $r-$l+3); - continue; - } - - #-- opening tag? - elseif ($tname[0] != "/") { - - #-- cdata - if($tname=='![cdata[') { - $tname = strtoupper($tname); // Needs to be uppercase for XHTML compliance - // LEAVE THE POOR THING ALONE! - } - #-- standalone tag - else if (in_array($tname, $html_standalone)) { - $tattr = rtrim(rtrim($tattr, "/")); - if (EWIKI_XHTML) { - $tattr .= " /"; - } - } - #-- normal tag - else { - if (in_array($tname, $html_tags)) { - #-- ok - } - else { - #$tattr .= " class=\"$tname\""; - #$tname = "div"; - } - array_push($tree, $tname); - } - - $tag = "$tname$tattr"; - } - #-- closing tag - else { - $tname = substr($tname, 1); - - if (!in_array($tname, $html_tags)) { - $tname= "div"; - } - - #-- check if this is allowed - if (!$tree) { - continue; // ignore closing tag - } - $last = array_pop($tree); - if ($last != $tname) { - - #-- close until last opened block element - if (in_array($tname, $close_opened_when)) { - do { - $done .= ""; - } - while (($last = array_pop($tree)) && ($last!=$tname)); - } - #-- close last, close current, reopen last - else { - array_push($tree, $last); - $done .= "<$last>"; - continue; - } - } - else { - #-- all ok - } - - #-- readd closing-slash to tag name - $tag = "/$tname"; - } - - $done .= "<$tag>"; - } - } - - #-- close still open tags - while ($tree && ($last = array_pop($tree))) { - $done .= ""; - } - - #-- copy back changes - $html = $done; - -} - - - diff --git a/mod/wiki/ewiki/plugins/moodle/moodle_binary_store.php b/mod/wiki/ewiki/plugins/moodle/moodle_binary_store.php deleted file mode 100644 index 1dd8a5aa3f9..00000000000 --- a/mod/wiki/ewiki/plugins/moodle/moodle_binary_store.php +++ /dev/null @@ -1,119 +0,0 @@ -id/$CFG->moddata/wiki/$wiki->id/$entry->id/".$meta["section"]); - if(substr($id, 0, strlen(EWIKI_IDF_INTERNAL))!=EWIKI_IDF_INTERNAL) { - print_error('cannotstartwith', 'wiki', '', EWIKI_IDF_INTERNAL.substr($id, 0, strlen(EWIKI_IDF_INTERNAL))); - } - $id = substr($id,strlen(EWIKI_IDF_INTERNAL)); - $id = clean_filename($id); - - return "$dir/$id"; -} - - -#-- upload -function moodle_binary_store_file(&$filename, &$id, &$meta, $ext=".bin") { - # READ-Only - global $_FILES, $CFG, $course, $wiki, $groupid, $userid, $ewiki_title, $cm; - if(!$wiki->ewikiacceptbinary) { - print_error('cannotacceptbin', 'wiki'); - return 0; - } - - - $entry=wiki_get_entry($wiki, $course, $userid, $groupid); - if(!$entry->id) { - print_error('cannotgetentry', 'wiki'); - } - - require_once($CFG->dirroot.'/lib/uploadlib.php'); - $um = new upload_manager('upload',false,false,$course,false,0,true,true); - if ($um->process_file_uploads("$course->id/$CFG->moddata/wiki/$wiki->id/$entry->id/$ewiki_title")) { - $filename = ''; // this to make sure we don't keep processing in the parent function - if(!$id) { - $newfilename = $um->get_new_filename(); - $id = EWIKI_IDF_INTERNAL.$newfilename; - } - return true; - } - print_error('uploaderror', 'wiki', '', $um->print_upload_log(true)); - return false; - -} - - -#-- download -function moodle_binary_store_get_file($id, &$meta) { - # READ-Only - global $CFG, $cm, $course, $wiki, $groupid, $userid; - - #-- check for file - if(!$wiki->ewikiacceptbinary) { - print_error('cannotacceptbin', 'wiki'); - return 0; - } - - - $filepath=moodle_binary_get_path($id, $meta, $course, $wiki, $userid, $groupid); - if (file_exists($filepath)) { - readfile($filepath); - return(true); - } else { - return(false); - } - //$dbfname = EWIKI_DB_STORE_DIRECTORY."/".rawurlencode($id); - //if (file_exists($dbfname)) { - // readfile($dbfname); - // return(true); - //} - //else { - // return(false); - //} - -} - diff --git a/mod/wiki/ewiki/plugins/moodle/moodle_highlight.php b/mod/wiki/ewiki/plugins/moodle/moodle_highlight.php deleted file mode 100644 index 22642e53069..00000000000 --- a/mod/wiki/ewiki/plugins/moodle/moodle_highlight.php +++ /dev/null @@ -1,79 +0,0 @@ -", $l); - if ((!$t0) || ($t0 < $t1)) { - - $repl = '' . $word . ''; - $o = substr($o, 0, $l) - . $repl - . substr($o, 1 + $l + strlen($word)-1); - - $l += strlen($repl); - } - - $l++; // advance strpos - } - - } // foreach(word) - - } - - } // if(q) - -} // func - - - diff --git a/mod/wiki/ewiki/plugins/moodle/moodle_wikidump.php b/mod/wiki/ewiki/plugins/moodle/moodle_wikidump.php deleted file mode 100644 index 48b57f8fa6c..00000000000 --- a/mod/wiki/ewiki/plugins/moodle/moodle_wikidump.php +++ /dev/null @@ -1,456 +0,0 @@ - - - - '; - - -function moodle_ewiki_page_wiki_dump($id=0, $data=0, $action=0) { - global $userid, $groupid, $cm, $wikipage, $wiki, $course, $CFG, $OUTPUT; - #-- return legacy page - $cont = true; - $wikiexport = optional_param('wikiexport', '', PARAM_BOOL); - $binaries = optional_param("exportbinaries", null); - $exportformatval = optional_param("exportformats", null); - $withvirtualpages = optional_param("withvirtualpages", null); - $exportdestinationsval = optional_param('exportdestinations', null); - - if (!empty($wikiexport)) { - if(!$wiki->ewikiacceptbinary) { - $binaries=0; - } - if($wiki->htmlmode==2) { - $exportformatval=1; - } - $cont=ewiki_page_wiki_dump_send($binaries, - $exportformatval, - $withvirtualpages, - optional_param("exportdestinations", null,PARAM_CLEAN)); - } - if($cont===false) { - die; - } - - $url = ewiki_script("", "WikiExport"); - $ret = ewiki_make_title($id, ewiki_t($id), 2); - $ret .= ($cont&&$cont!==true)?$cont."

      \n":""; - $ret .= get_string("wikiexportcomment","wiki"); - // removing name="form" from the following form as it does not validate - // and is not referenced. MDL-7861 - $ret .= "

      \n". - '

      '."\n". - "
      \n". - ''."\n". - ''."\n". - ''."\n". - ''."\n". - ''."\n"; - - - // Export binaries too ? - if(!$wiki->ewikiacceptbinary) { - $ret.=''.$exportdestinations[0]."\n"; - } else { - $ret.=''."\n"; - } - $ret.="\n"; - if($wiki->ewikiacceptbinary) { - $ret.=" \n". - ' \n". - " \n". - " \n"; - } - $ret.=" \n". - ' \n". - " \n". - " \n"; - $exportformats=array( "0" => get_string("plaintext","wiki") , "1" => get_string("html","wiki")); - /// Formats - $ret.=" \n". - ' \n". - " \n". - " \n"; - /// Destination - $exportdestinations=array("0" => get_string("downloadaszip","wiki")); - if(wiki_is_teacher($wiki)) { - // Get Directory List - $rawdirs = get_directory_list("$CFG->dataroot/$course->id", 'moddata', true, true, false); - - foreach ($rawdirs as $rawdir) { - $exportdestinations[$rawdir] = get_string("moduledirectory","wiki").": ".$rawdir; - } - } - - $ret.=" \n". - ' \n". - " \n". - " \n". - "
      '.get_string("withbinaries","wiki").":\n". - ' \n". - "
      '.get_string("withvirtualpages","wiki").":\n". - ' \n". - "
      '.get_string("exportformats","wiki").":\n"; - if($wiki->htmlmode!=2) { - $ret.= html_writer::select($exportformats, "exportformats", $exportformatval, false)."\n"; - } else { - $ret.= ''. - get_string("html","wiki"); - } - $ret.="
      '.get_string("exportto","wiki").":\n"; - if(count($exportdestinations)==1) { - $ret.=''.$exportdestinations[0]."\n"; - } else { - $ret.= html_writer::select($exportdestinations, "exportdestinations", $exportdestinationsval, false)."\n"; - } - $ret.="
      \n". - ' '."\n". - "
      \n"; - "
      \n"; - return $ret; -} - -function ewiki_page_wiki_dump_send($exportbinaries=0, $exportformats=0, $withvirtualpages=0, $exportdestinations=0) { - global $ewiki_config, $wiki, $ewiki_plugins, $wiki_entry, $course, $CFG, $ewiki_t, $userid, $groupid, $OUTPUT; - - $filestozip=array(); - #-- disable protected email - if (is_array($ewiki_plugins["link_url"])) { - foreach($ewiki_plugins["link_url"] as $key => $linkplugin){ - if($linkplugin == "ewiki_email_protect_link"){ - unset($ewiki_plugins["link_url"][$key]); - } - } - } - - /// HTML-Export - if($exportformats==1) { - #-- if exportformats is html - $HTML_TEMPLATE = ' - '.$ewiki_t["c"]["EWIKIDUMPCSS"].' - $title - - -
      -

      $title

      - $content -
      - - '; - - #-- reconfigure ewiki_format() to generate offline pages and files - $html_ext = ".html"; - $ewiki_config["script"] = "%s$html_ext"; - $ewiki_config["script_binary"] = "%s"; - } - - // Export Virtual pages special - $a_virtual = array_keys($ewiki_plugins["page"]); - - #-- get all pages / binary files - $a_validpages = ewiki_valid_pages(1, $withvirtualpages); - $a_pagelist = ewiki_sitemap_create($wiki_entry->pagename, $a_validpages, 100, 1); - - # Add linked binary files to pagelist - foreach($a_pagelist as $key => $value) { - if(is_array($a_validpages[$value]["refs"])){ - foreach($a_validpages[$value]["refs"] as $refs){ - if($a_validpages[$refs]["type"]=="image" || $a_validpages[$refs]["type"]=="file"){ - $a_pagelist[]=$refs; - } - } - } - } - - # Adjust links to binary files - foreach($a_pagelist as $key => $value){ - if($a_validpages[$value]["type"]=="image"){ - $a_images[]=urlencode($value); - $a_rimages[]=urlencode(preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $value)); - unset($a_validpages[$value]); - } - if($a_validpages[$value]["type"]=="file") { - $a_images[]=urlencode($value); - $a_rimages[]=clean_filename(substr($value,strlen(EWIKI_IDF_INTERNAL))); - $a_images[]=$value; - $a_rimages[]=clean_filename(substr($value,strlen(EWIKI_IDF_INTERNAL))); - unset($a_validpages[$value]); - } - } - - # Remove binaries from a_validpages and add to a_pagelist - foreach($a_validpages as $key => $value){ - if($a_validpages[$key]["type"]=="image" || $a_validpages[$key]["type"]=="file"){ - $a_pagelist[]=$key; - unset($a_validpages[$key]); - } - } - - #print "
      "; print_r($a_validpages); print "
      "; - #print "
      "; print_r($a_pagelist); print "
      "; - - $a_sitemap = ewiki_sitemap_create($wiki_entry->pagename, $a_validpages, 99, 0); - if ($a_pagelist) { - #-- create new zip file - #if($arctype == "ZIP"){ - # $archivename=EWIKI_WIKIDUMP_ARCNAME."$rootid.zip"; - # $archive = new ewiki_virtual_zip(); - #} elseif ($arctype == "TAR") { - # $archivename=EWIKI_WIKIDUMP_ARCNAME."$rootid.tar"; - # $archive = new ewiki_virtual_tarball(); - #} else { - # die(); - #} - - /// Create/Set Directory - $wname=clean_filename(strip_tags(format_string($wiki->name,true))); - if($exportdestinations) { - if(wiki_is_teacher($wiki)) { - $exportdir=$CFG->dataroot."/".$course->id."/".$exportdestinations; - } else { - add_to_log($course->id, "wiki", "hack", "", format_string($wiki->name,true).": Tried to export a wiki as non-teacher into $exportdestinations."); - print_error('younotteacher'); - } - } else { - $exportbasedir=tempnam("/tmp","WIKIEXPORT"); - @unlink($exportbasedir); - @mkdir($exportbasedir); - /// maybe we need to check the name here...? - $exportdir=$exportbasedir."/".$wname; - @mkdir($exportdir); - if(!is_dir($exportdir)) { - print_error("cannotcreatetempdir"); - } - } - - $a_pagelist = array_unique($a_pagelist); - - - #-- convert all pages - foreach($a_pagelist as $pagename){ - if ((!in_array($pagename, $a_virtual))) { - $id = $pagename; - #-- not a virtual page - $row = ewiki_database("GET", array("id"=>$pagename)); - $content = ""; - } elseif($withvirtualpages) { - $id = $pagename; - #-- is a virtual page - $pf = $ewiki_plugins["page"][$id]; - $content = $pf($id, $content, "view"); - if ($exportformats==1) { - $content = str_replace('$content', $content, str_replace('$title', $id, $HTML_TEMPLATE)); - } - $fn = urlencode($id); - $fn = preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $fn); - $fn = $fn.$html_ext; - } else { - continue; - } - - if (empty($content)){ - switch ($row["flags"] & EWIKI_DB_F_TYPE) { - // Text Page - case (EWIKI_DB_F_TEXT): - #print "
      "; print_r($row[content]); print "\n-------------
      "; - - if($exportformats==1) {/// HTML-Export - $content = ewiki_format($row["content"]); - } else { - $content = $row["content"]; - } - - # Binary files link adjustment when html - if($exportformats==1) { - $content = str_replace($a_images, $a_rimages, $content); - } - - $fn = preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", urlencode($id)); - $fn = $fn.$html_ext; - if($exportformats==1) {/// HTML-Export - $content = str_replace('$content', $content, str_replace('$title', $id, $HTML_TEMPLATE)); - } - break; - case (EWIKI_DB_F_BINARY): - #print "Binary: $row[id]
      "; - if (($row["meta"]["class"]=="image" || $row["meta"]["class"]=="file") && ($exportbinaries)) { - # Copy files to the appropriate directory - $fn= moodle_binary_get_path($id, $row["meta"], $course, $wiki, $userid, $groupid); - $destfn=clean_filename(substr($id,strlen(EWIKI_IDF_INTERNAL))); - $dest="$exportdir/".$destfn; - if(!copy($fn,$dest)) { - echo $OUTPUT->notification("Cannot copy $fn to $dest."); - } - - #$fn = urlencode(preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $id)); - #$content = &$row["content"]; - $filestozip[]=$exportdir."/".$destfn; - continue (2); - } - else { - #-- php considers switch statements as loops so continue 2 is needed to - #-- hit the end of the for loop - continue(2); - } - break; - - default: - # don't want it - continue(2); - } - } - - # Do not translate links when wiki already in pure html - mode - if($wiki->htmlmode!=2) { - $content=preg_replace_callback( - '/()/', - create_function( - // single quotes are essential here, - // or alternative escape all $ as \$ - '$matches', - 'return($matches[1].preg_replace(EWIKI_DUMP_FILENAME_REGEX,"",$matches[2]).$matches[3]);' - ), - $content - ); - } - #-- add file - // Let's make sure the file exists and is writable first. - if (!$handle = fopen($exportdir."/".$fn, 'w')) { - print_error('cannotopenfile', '', '', $exportdir/$fn); - } - - // Write $content to our opened file. - if (fwrite($handle, $content) === FALSE) { - print_error('cannotwritefile', '', '', $exportdir/$fn); - } - - fclose($handle); - $filestozip[]=$exportdir."/".$fn; - #$archive->add($content, $fn, array( - # "mtime" => $row["lastmodified"], - # "uname" => "ewiki", - # "mode" => 0664 | (($row["flags"]&EWIKI_DB_F_WRITEABLE)?0002:0000), - # ), $complevel); - } - - #-- create index page - /// HTML-Export - if($exportformats==1) { - $timer=array(); - $level=-1; - $fordump=1; - $str_formatted="".str_pad("", $fin_level*6, "

    \n"); - $str_formatted=preg_replace_callback( - '/()/', - create_function( - // single quotes are essential here, - // or alternative escape all $ as \$ - '$matches', - 'return($matches[1].preg_replace(EWIKI_DUMP_FILENAME_REGEX,"",$matches[2]).$matches[3]);' - ), - $str_formatted - ); - $str_formatted = str_replace('$content', $str_formatted, str_replace('$title', get_string("index","wiki"), $HTML_TEMPLATE)); - #-- add file - // Let's make sure the file exists and is writable first. - $indexname="index".$html_ext; - if (!$handle = fopen($exportdir."/".$indexname, 'w')) { - print_error('cannnotopenfile', '', '', $exportdir/$indexname); - } - - // Write $somecontent to our opened file. - if (fwrite($handle, $str_formatted) === FALSE) { - print_error('cannnotwritefile', '', '', $exportdir/$indexname); - } - - fclose($handle); - $filestozip[]=$exportdir."/".$indexname; - - #-- add index page -# $archive->add($str_formatted, "Index_$rootid".$html_ext, array( -# "mtime" => $row["lastmodified"], -# "uname" => "ewiki", -# "mode" => 0664 | (($row["flags"]&EWIKI_DB_F_WRITEABLE)?0002:0000), -# ), $complevel); - } - - if(!$exportdestinations) { - $archivename=$wname.".zip"; - zip_files($filestozip, "$exportbasedir/$archivename"); - - #-- Headers - Header("Content-type: application/zip"); - Header("Content-disposition: attachment; filename=\"$archivename\""); - Header("Cache-control: private"); - Header("Original-Filename: $archivename"); - Header("X-Content-Type: application/zip"); - Header("Content-Location: $archivename"); - if(!@readfile("$exportbasedir/$archivename")) { - print_error("cannotreadfile", '', '', $exportbasedir/$archivename); - } - if(!deldir($exportbasedir)) { - print_error('cannotdeletedir', '', '', $exportbasedir); - } - #exit(); - return false; - } else { - return get_string("exportsuccessful","wiki")."
    "; - } - } -} - -function deldir($dir) -{ - $handle = opendir($dir); - while (false!==($FolderOrFile = readdir($handle))) - { - if($FolderOrFile != "." && $FolderOrFile != "..") - { - if(is_dir("$dir/$FolderOrFile")) - { deldir("$dir/$FolderOrFile"); } // recursive - else - { unlink("$dir/$FolderOrFile"); } - } - } - closedir($handle); - if(rmdir($dir)) - { $success = true; } - return $success; -} - diff --git a/mod/wiki/ewiki/plugins/moodle/sitemap.php b/mod/wiki/ewiki/plugins/moodle/sitemap.php deleted file mode 100644 index 436c32a8251..00000000000 --- a/mod/wiki/ewiki/plugins/moodle/sitemap.php +++ /dev/null @@ -1,242 +0,0 @@ -".ewiki_t("VIEWSMFOR")." "; - - foreach($ewiki_config["SiteMap"]["RootList"] as $root){ - if(isset($a_validpages[$root])){ - $o.='
    '.$root.' '; - } - } - - $o.="

    "; - - //checks to see if the user is allowed to view the root page - if(!isset($a_validpages[$str_rootid])){ - $o .= ewiki_t("INVALIDROOT"); - return $o; - } - - //$timesitemap=getmicrotime(); - $a_sitemap=ewiki_sitemap_create($str_rootid, $a_validpages, EWIKI_SITEMAP_DEPTH); - - $timer=array(); - $level=-1; - $fordump=0; - $str_formatted="
      \n
    • ".$str_rootid."
    • "; - $fin_level=format_sitemap($a_sitemap, $str_rootid, $str_formatted, $level, $timer, $fordump); - $str_formatted.="
    ".str_pad("", $fin_level*6, "\n"); - $o.=$str_formatted; - - //$timesitemap_end=getmicrotime(); - - //$o.="GetAll: ".($time_end-$time)."\n"; - //$o.="SiteMap: ".($timesitemap_end-$timesitemap)."\n"; - //$o.="Total: ".($timesitemap_end-$time); - - - return($o); - -} - -function ewiki_valid_pages($bool_allowimages=0, $virtual_pages=0){ - //$time=getmicrotime(); - global $ewiki_plugins; - $result = ewiki_database("GETALL", array("flags", "refs", "meta")); - while ($row = $result->get()) { - if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($row["id"], $str_null, "view")) { - continue; - } - - $isbinary= ($row["meta"]["class"]=="image"||$row["meta"]["class"]=="file")?true:false; - - if (($row["flags"] & EWIKI_DB_F_TYPE) == EWIKI_DB_F_TEXT || ($bool_allowimages ? $isbinary : 0)) { - $temp_refs=explode("\n",$row["refs"]); - foreach($temp_refs as $key => $value) { - if(empty($value)) { - unset($temp_refs[$key]); - } - } - if($isbinary){ - $a_validpages[$row["id"]]=$temp_array=array("refs" => $temp_refs, "type" => $row["meta"]["class"], "touched" => FALSE); - } else { - $a_validpages[$row["id"]]=$temp_array=array("refs" => $temp_refs, "type" => "page", "touched" => FALSE); - } - unset($temp_refs); - } - } - - if($virtual_pages){ - #-- include virtual pages to the sitemap. - $virtual = array_keys($ewiki_plugins["page"]); - foreach($virtual as $vp){ - if(!EWIKI_PROTECTED_MODE || !EWIKI_PROTECTED_MODE_HIDING || ewiki_auth($vp, $str_null, "view")){ - $a_validpages[$vp]=array("refs" => array(), "type" => "page", "touched" => FALSE); - } - } - } - return $a_validpages; -} - -/* - Adds each of the pages in the sitemap to an HTML list. Each site is a clickable link. -*/ -function format_sitemap($a_sitemap, $str_rootpage, &$str_formatted, &$prevlevel, &$timer, &$fordump){ - - //get all children of the root format them and store in $str_formatted array - $a_sitemap[$str_rootpage]["child"]= is_array($a_sitemap[$str_rootpage]["child"])?$a_sitemap[$str_rootpage]["child"]:array(); - if($a_sitemap[$str_rootpage]["child"]){ - while($str_child = current($a_sitemap[$str_rootpage]["child"])){ - $str_mark=""; - if($a_sitemap[$str_rootpage]["level"]>$prevlevel){ - $str_mark="
      \n"; - } - elseif ($a_sitemap[$str_rootpage]["level"]<$prevlevel){ - //markup length is 6 characters - $str_mark=str_pad("", ($prevlevel-$a_sitemap[$str_rootpage]["level"])*6, "
    \n"); - } - $prevlevel=$a_sitemap[$str_rootpage]["level"]; - if($fordump){ - $str_formatted.=($str_mark."
  • ".$str_child."
  • \n"); - } else { - $str_formatted.=($str_mark."
  • ".$str_child."
  • \n"); - } - array_shift($a_sitemap[$str_rootpage]["child"]); - format_sitemap($a_sitemap, $str_child, $str_formatted, $prevlevel, $timer, $fordump); - } - return ($prevlevel+1); - } -} - - -/* - gets all children of the given root and stores them in the $a_children array -*/ -function ewiki_page_listallchildren($str_root, &$a_children, &$a_sitemap, &$a_validpages, $i_level, $i_maxdepth, $i_flatmap){ - if(($i_level<$i_maxdepth) && is_array($a_validpages[$str_root]["refs"])){ //controls depth the sitemap will recurse into - foreach($a_validpages[$str_root]["refs"] as $str_refs){ - if($str_refs){ //make sure $str_refs contains a value before doing anything - if(isset($a_validpages[$str_refs])){ //test page validity - if(!$a_validpages[$str_refs]["touched"]){ //check to see if page already exists - if($i_flatmap){ - $a_sitemap[]=$str_refs; - } - $a_validpages[$str_refs]["touched"]=TRUE; //mark page as displayed - $a_children[$str_refs]=""; - $a_currchildren[]=$str_refs; - } - } - } - } - if(!$i_flatmap){ - if($a_currchildren){ - $a_sitemap[$str_root]=array("level" => $i_level, "child" => $a_currchildren); - } else { - $a_sitemap[$str_root]=array("level" => $i_level); - } - } - } -} - - -/* - Creates the sitemap. And sends the data to the format_sitemap function. - Returns the HTML formatted sitemap. -*/ -function ewiki_sitemap_create($str_rootid, $a_validpages, $i_maxdepth, $i_flatmap=0){ - //map starts out with a depth of 0 - $i_depth=0; - $forcelevel=FALSE; - - //create entry for root in the sitemap array - if(!$i_flatmap){ - $a_sitemap[$str_rootid]=array("parent" => "", "level" => $i_depth, "child" => $str_rootid); - } else { - $a_sitemap[]=$str_rootid; - } - //mark the root page as touched - $a_validpages[$str_rootid]["touched"]=TRUE; - //list all of the children of the root - ewiki_page_listallchildren($str_rootid, $a_children, $a_sitemap, $a_validpages, $i_depth, $i_maxdepth, $i_flatmap); - $i_depth++; - - if($a_children){ - end($a_children); - $str_nextlevel=key($a_children); - reset($a_children); - - while($str_child = key($a_children)){ - //list all children of the current child - ewiki_page_listallchildren($str_child, $a_children, $a_sitemap, $a_validpages, $i_depth, $i_maxdepth, $i_flatmap); - - //if the child is the next level marker... - if($str_child==$str_nextlevel){ - //increment the level counter - $i_depth++; - //determine which child marks the end of this level - end($a_children); - $str_nextlevel=key($a_children); - //reset the array counter to the beginning of the array - reset($a_children); - //we are done with this child...get rid of it - } - array_shift($a_children); - } - } - - return $a_sitemap; -} - diff --git a/mod/wiki/ewiki/plugins/moodle/wantedpages.php b/mod/wiki/ewiki/plugins/moodle/wantedpages.php deleted file mode 100644 index 235e676a6aa..00000000000 --- a/mod/wiki/ewiki/plugins/moodle/wantedpages.php +++ /dev/null @@ -1,65 +0,0 @@ -# $ewiki_plugins["page"]["DanglingSymlinks"] = "ewiki_page_wantedpages"; - - -function ewiki_page_wantedpages($id, $data, $action) { - $wanted=array(); - #-- collect referenced pages - $result = ewiki_database("GETALL", array("refs")); - while ($row = $result->get()) { - if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($row["id"], $uu, "view")) { - continue; - } - $refs .= $row["refs"]; - } - - #-- build array - $refs = array_unique(explode("\n", $refs)); - - #-- strip existing pages from array - $refs = ewiki_database("FIND", $refs); - foreach ($refs as $id=>$exists) { - if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($row["id"], $uu, "view")) { - continue; - } - if (!$exists && !strstr($id, "://") && strlen(trim($id))) { - $wanted[] = $id; - } - } - - // to prevent empty
      getting printed out, we have to interate twice. - // once to make sure the
        is needed at all. - // MDL-7861,
          does not validate. - - $printul = false; - foreach ($wanted as $page) { - $link = ewiki_link_regex_callback(array($page, $page)); - if (strstr($link, "?")) { - $printul = true; - } - } - #-- print out - - if ($printul) { - $o .= "
            "; - foreach ($wanted as $page) { - - $link = ewiki_link_regex_callback(array($page, $page)); - - if (strstr($link, "?")) { - $o .= "
          • " . $link . "
          • "; - } - - } - $o .= "
          "; - } - return($o); -} - - diff --git a/mod/wiki/ewiki/plugins/notify.php b/mod/wiki/ewiki/plugins/notify.php deleted file mode 100644 index ffe19903887..00000000000 --- a/mod/wiki/ewiki/plugins/notify.php +++ /dev/null @@ -1,232 +0,0 @@ -&1 ", "r")) { - - $diff .= fread($f, 16<<10); - pclose($f); - - $diff_failed = !strlen($diff) - || (strpos($diff, "Files ") === 0); - - #-- do not [notify:] if changes were minimal - if ((!$diff_failed) && (strlen($diff) < EWIKI_NOTIFY_WITH_DIFF)) { -#echo("WikiNotice: no notify, because too few changes (" .strlen($diff)." byte)\n"); - $ret_err = 1; - } - - $diff = "\n\n-----------------------------------------------------------------------------\n\n" - . $diff; - } - else { - $diff = ""; -#echo("WikiWarning: diff failed in notify module\n"); - } - - unlink($fn1); - unlink($fn2); - - if ($ret_err) { - return(false); - } - } - - #-- separate addresses into (TLD) groups - $mailto_lang = array( - ); - foreach ($mailto as $m) { - - $lang = ""; - - #-- remove lang selection trailer - $m = strtok($m, ","); - if ($uu = strtok(",")) { - $lang = $uu; - } - $m = strtok($m, ";"); - if ($uu = strtok(";")) { - $lang = $uu; - } - - #-- else use TLD as language code - if (empty($lang)) { - $r = strrpos($m, "."); - $lang = substr($m, $r+1); - } - $lang = trim($lang); - - #-- address mangling - $m = trim($m); - if (substr($m, 0, 4) == "icq:") { - $m = substr($m, 4) . "@pager.icq.com"; - } - - $mailto_lang[$lang][] = $m; - } - - #-- go thru email address groups - foreach ($mailto_lang as $lang=>$a_mailto) { - - $pref_langs = array_merge(array( - "$lang", "en" - ), $ewiki_t["languages"]); - - ($server = $_SERVER["HTTP_HOST"]) or - ($server = $_SERVER["SERVER_NAME"]); - $s_4 = "http".($_SERVER['HTTPS'] == "on" ? 's':'')."://" . $server . $_SERVER["REQUEST_URI"]; - $link = str_replace("edit/$id", "$id", $s_4); - - $m_text = ewiki_t("NOTIFY_BODY", array( - "id" => $id, - "link" => $link, - "edit_link" => $s_4, - "server_admin" => $_SERVER["SERVER_ADMIN"], - "server" => $server, - "wiki_title" => EWIKI_PAGE_INDEX, - ), $pref_langs); - $m_text .= $diff; - - $m_from = EWIKI_NOTIFY_SENDER."@$server"; - $m_subject = ewiki_t("NOTIFY_SUBJECT", array( - "id" => $id, - ), $pref_langs); - - $m_to = implode(", ", $a_mailto); - - mail($m_to, $m_subject, $m_text, "From: \"$s_2\" <$m_from>\nX-Mailer: ErfurtWiki/".EWIKI_VERSION); - - } -} - - - -function ewiki_notify_links(&$source, $strip=1) { - $links = array(); - $l = 0; - if (strlen($source) > 10) - while (($l = @strpos($source, "[notify:", $l)) !== false) { - $r = strpos($source, "]", $l); - $str = substr($source, $l, $r + 1 - $l); - if (!strpos("\n", $str)) { - $links[] = trim(substr($str, 8, -1)); - if ($strip) { - $source = substr($source, 0, $l) . substr($source, $r + 1); - } - } - $l++; - } - return($links); -} - - - -function ewiki_format_remove_notify(&$source) { - ewiki_notify_links($source, 1); -} - - - diff --git a/mod/wiki/ewiki/plugins/page/orphanedpages.php b/mod/wiki/ewiki/plugins/page/orphanedpages.php deleted file mode 100755 index 20acd93a823..00000000000 --- a/mod/wiki/ewiki/plugins/page/orphanedpages.php +++ /dev/null @@ -1,62 +0,0 @@ -get()) { - - $p = $row["id"]; - - #-- remove self-reference - $row["refs"] = str_replace("\n$p\n", "\n", $row["refs"]); - - #-- add to list of referenced pages - $rf = explode("\n", trim($row["refs"])); - $refs = array_merge($refs, $rf); - if ($n++ > 299) { - $refs = array_unique($refs); - $n=0; - } // (clean-up only every 300th loop) - - #-- add page name - if (($row["flags"] & EWIKI_DB_F_TYPE) == EWIKI_DB_F_TEXT) { - $pages[] = $row["id"]; - } - } - $refs = array_unique($refs); - - #-- check pages to be referenced from somewhere - foreach ($pages as $p) { - if (!ewiki_in_array($p, $refs)) { - if (!EWIKI_PROTECTED_MODE || EWIKI_PROTECTED_MODE_HIDING || ewiki_auth($p, $uu, "view")) { - $orphaned[] = $p; - } - } - } - - #-- output - $o .= ewiki_list_pages($orphaned, 0); - - return($o); -} - - - diff --git a/mod/wiki/ewiki/plugins/page/pageindex.php b/mod/wiki/ewiki/plugins/page/pageindex.php deleted file mode 100755 index 1bbbe0b793d..00000000000 --- a/mod/wiki/ewiki/plugins/page/pageindex.php +++ /dev/null @@ -1,44 +0,0 @@ -get()) { - if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($row["id"], $uu, "view")) { - continue; - } - if (($row["flags"] & EWIKI_DB_F_TYPE) == EWIKI_DB_F_TEXT) { - if (!stristr($exclude, "\n".$row["id"]."\n")) { - $sorted[] = $row["id"]; - } - } - } - - natcasesort($sorted); - - $o .= ewiki_list_pages($sorted, 0, 0, $ewiki_plugins["list_dict"][0]); - - return($o); -} - - - diff --git a/mod/wiki/ewiki/plugins/patchsaving.php b/mod/wiki/ewiki/plugins/patchsaving.php deleted file mode 100644 index c3b9a2f4b97..00000000000 --- a/mod/wiki/ewiki/plugins/patchsaving.php +++ /dev/null @@ -1,89 +0,0 @@ -$id, "version"=>$version) - ); - if (!$base) { - return(false); - } - - $fn_base = EWIKI_TMP."/ewiki.base.".md5($base["content"]); - $fn_requ = EWIKI_TMP."/ewiki..requ.".md5($content); - $fn_patch = EWIKI_TMP."/ewiki.patch.".md5($base["content"])."-".md5($content); - $fn_curr = EWIKI_TMP."/ewiki.curr.".md5($data["content"]); - - if ($f = fopen($fn_base, "w")) { - fwrite($f, $base["content"]); - fclose($f); - } - else { - return(false); - } - - if ($f = fopen($fn_requ, "w")) { - fwrite($f, $content); - fclose($f); - } - else { - unlink($fn_base); - return(false); - } - - if ($f = fopen($fn_curr, "w")) { - fwrite($f, $data["content"]); - fclose($f); - } - else { - unlink($fn_base); - unlink($fn_requ); - return(false); - } - - exec("diff -c $fn_base $fn_requ > $fn_patch", $output, $retval); - if ($retval) { - - exec("patch $fn_curr $fn_patch", $output, $retval); - if (!$retval) { - - /// mrc - ?? what is $curr supposed to be ?? - $_REQUEST["version"] = $_POST["version"] = $_GET["version"] = $curr["version"]; - $_REQUEST["content"] = $_POST["content"] = $_GET["content"] = implode("", file($fn_curr)); - $r = true; - - } - } - - unlink($fn_base); - unlink($fn_requ); - unlink($fn_patch); - unlink($fn_curr); - - return($r); -} - - diff --git a/mod/wiki/ewiki/plugins/pluginloader.php b/mod/wiki/ewiki/plugins/pluginloader.php deleted file mode 100644 index 95f19389324..00000000000 --- a/mod/wiki/ewiki/plugins/pluginloader.php +++ /dev/null @@ -1,126 +0,0 @@ - array("", "", 0), - "links" => array("", "", 0), - "info" => array("", "", 0), -# "edit" => array("spellcheck.php", "", 0), -# "calendar" => array("calendar.php", "ewiki_page_calendar", 0), -# "addpost" => array("contrib/aview_posts.php", "ewiki_add_post", 0), -# "imageappend" => array("contrib/aview_imgappend.php", "ewiki_action_image_append", 0), -# "extodo" => array("contrib/action_extracttodo.php", "ewiki_extract_todo", 0), -# "addthread" => array("contrib/aview_threads.php", "ewiki_add_thread", 0), -# "control" => array("admin/control.php", "ewiki_action_control_page", 0), -# "pdf" => array("pdf.php", "ewiki_send_page_as_pdf", 0), - "diff" => array("diff.php", "ewiki_page_stupid_diff", 0), -# "diff" => array("diff_gnu.php", "ewiki_page_gnu_diff", 0), -# "binary" => array("downloads.php", "ewiki_binary", 0), -# "attachments" => array("downloads.php", "ewiki_action_attachments", 0), - "like" => array("like_pages.php", "ewiki_page_like", 0), -# "verdiff" => array("action_verdiff.php", "ewiki_action_verdiff", 0), -); - -$ewiki_plugins["dl"]["page"] = array( -# "PageCalendar" => array("calendar.php", "ewiki_page_calendar", 0), -# "PageYearCalendar" => array("calendar.php", "ewiki_page_year_calendar", 0), -# "WikiNews" => array("contrib/page_wikinews.php", "ewiki_page_wikinews", 0), -# "WikiDump" => array("contrib/page_wikidump.php", "ewiki_page_wiki_dump_tarball", 0), -# "README" => array("contrib/page_README.php", "ewiki_page_README", 0), -# "README.de" => array("contrib/page_README.php", "ewiki_page_README", 0), -# "plugins/auth/README.auth" => array("contrib/page_README.php", "ewiki_page_README", 0), -# "Fortune" => array("contrib/page_fortune.php", "ewiki_page_fortune", 0), -# "ScanDisk" => array("contrib/page_scandisk.php", "ewiki_page_scandisk", 0), - "InterWikiMap" => array("contrib/page_interwikimap.php", "ewiki_page_interwikimap", 0), -# "WikiUserLogin" => array("contrib/page_wikiuserlogin.php", "ewiki_page_wikiuserlogin", 0), -# "PhpInfo" => array("contrib/page_phpinfo.php", "ewiki_page_phpinfo", 0), -# "ImageGallery" => array("contrib/page_imagegallery.php", "ewiki_page_image_gallery", 0), -# "SinceUpdatedPages" => array("contrib/page_since_updates.php", "ewiki_page_since_updates", 0), -# "TextUpload" => array("contrib/page_textupload.php", "ewiki_page_textupload", 0), - "HitCounter" => array("contrib/page_hitcounter.php", "ewiki_page_hitcounter", 0), -# "SearchCache" => array("admin/page_searchcache.php", "ewiki_cache_generated_pages", 0), -# "SearchAndReplace" => array("admin/page_searchandreplace.php", "ewiki_page_searchandreplace", 0), -# "FileUpload" => array("downloads.php", "ewiki_page_fileupload", 0), -# "FileDownload" => array("downloads.php", "ewiki_page_filedownload", 0), - "PowerSearch" => array("page_powersearch.php", "ewiki_page_powersearch", 0), -# "AboutPlugins" => array("page_aboutplugins.php", "ewiki_page_aboutplugins", 0), - "OrphanedPages" => array("page_orphanedpages.php", "ewiki_page_orphanedpages", 0), - "PageIndex" => array("page_pageindex.php", "ewiki_page_index", 0), - "RandomPage" => array("page_randompage.php", "ewiki_page_random", 0), - "WantedPages" => array("page_wantedpages.php", "ewiki_page_wantedpages", 0), - "WordIndex" => array("page_wordindex.php", "ewiki_page_wordindex", 0), -); - - -#-- plugin glue -$ewiki_plugins["view_init"][] = "ewiki_dynamic_plugin_loader"; - - -function ewiki_dynamic_plugin_loader(&$id, &$data, &$action) { - - global $ewiki_plugins, $ewiki_id, $ewiki_title, $ewiki_t, - $ewiki_ring, $ewiki_author, $ewiki_config, $ewiki_auth_user, - $ewiki_action; - - #-- check for entry - if (empty($ewiki_plugins["page"][$id])) { - $load = $ewiki_plugins["dl"]["page"][$id]; - } - elseif (empty($ewiki_plugins["action"][$action])) { - $load = $ewiki_plugins["dl"]["action"][$action]; - } - - #-- load plugin - if ($load) { - if (!is_array($load)) { - $load = array($load, ""); - } - if (!($pf=$load[1]) || !function_exists($pf)) { - include(dirname(__FILE__)."/".$load[0]); - } - } - - #-- fake static pages - foreach ($ewiki_plugins["dl"]["page"] as $name) { - if (empty($ewiki_plugins["page"][$name])) { - $ewiki_plugins["page"][$name] = "ewiki_dynamic_plugin_loader"; - } - } - - #-- show action links - foreach ($ewiki_plugins["dl"]["action"] as $action=>$uu) { - foreach ($ewiki_config["dl"]["action_links"] as $where) { - if ($title = $ewiki_config["dl"]["action_links"][$where][$action]) { - $ewiki_config["action_links"][$where][$action] = $title; - } - } - } - - return(NULL); -} - - diff --git a/mod/wiki/ewiki/plugins/spages.php b/mod/wiki/ewiki/plugins/spages.php deleted file mode 100644 index 078a4798acb..00000000000 --- a/mod/wiki/ewiki/plugins/spages.php +++ /dev/null @@ -1,182 +0,0 @@ - and parts (if any) - if (($l = strpos(strtolower($r), "", $l+1) + 1; - $w = $w - $l; - $r = substr($r, $l, $w); - } - - #-- return body (means successful handled) - return($r); - -} - - - -#-- return page -## $ewiki_plugins["handler"][] = "ewiki_handler_spages"; -function ewiki_handler_spages($id, $data, $action) { - - global $ewiki_spages; - - #-- compare requested page $id with spages` $id values - $i0 = strtolower($id); - foreach ($ewiki_spages as $i1 => $fn) { - if (strtolower($i1)==$i0) { - - return(ewiki_spage($id)); - - } - } - -} - - -#-- init -function ewiki_init_spages($dirs, $idprep="") { - - global $ewiki_spages, $ewiki_plugins; - - if (!is_array($dirs)) { - $dirs = array($dirs); - } - - #-- go through list of directories - foreach ($dirs as $dir) { - - if (empty($dir)) { - continue; - } - - #-- read in one directory - $dh = opendir($dir); - while (false !== ($fn = readdir($dh))) { - - #-- skip over . and .. - if ($fn[0] == ".") { continue; } - - #-- be recursive - if ($fn && is_dir("$dir/$fn")) { - if ($fn != trim($fn, ".")) { - $fnadd = trim($fn, ".") . "."; - } - else { - $fnadd = "$fn/"; - } - - ewiki_init_spages(array("$dir/$fn"), "$idprep$fnadd"); - - continue; - } - - #-- strip filename extensions - $id = str_replace( - array(".html", ".htm", ".php", ".txt", ".wiki", ".src"), - "", - basename($fn) - ); - - #-- register spage file and as page plugin (one for every spage) - $ewiki_spages[strtolower("$idprep$id")] = "$dir/$fn"; - $ewiki_plugins["page"]["$idprep$id"] = "ewiki_spage"; - - } - closedir($dh); - } - -} - - - - diff --git a/mod/wiki/filter.php b/mod/wiki/filter.php deleted file mode 100755 index 999af1f87ac..00000000000 --- a/mod/wiki/filter.php +++ /dev/null @@ -1,73 +0,0 @@ -dirroot.'/mod/wiki/lib.php'); - - function wiki_filter($courseid, $text) { - global $CFG, $DB; - - // Trivial-cache - keyed on $cachedcourseid - static $nothingtodo; - static $wikipagelist; - static $cachedcourseid; - - if (empty($courseid)) { - $courseid = SITEID; - } - - // Initialise/invalidate our trivial cache if dealing with a different course - if (!isset($cachedcourseid) || $cachedcourseid !== (int)$courseid) { - $wikipagelist = array(); - $nothingtodo = false; - } - $cachedcourseid = (int)$courseid; - - if (!empty($nothingtodo)) { // We've been here in this page already - return $text; - } - -/// Create a list of all the wikis to search for. It may be cached already. - - if (empty($wikipagelist)) { - - /// Get all wikis for this course. - if (!$wikis = wiki_get_course_wikis($courseid)) { - $nothingtodo = true; - return $text; - } - - $wikipagelist = array(); - - /// Walk through each wiki, and get entries. - foreach ($wikis as $wiki) { - if ($wiki_entries = wiki_get_entries($wiki)) { - - /// Walk through each entry and get the pages. - foreach ($wiki_entries as $wiki_entry) { - if ($wiki_pages = $DB->get_records('wiki_pages', array('wiki'=>$wiki_entry->id), 'pagename, version DESC')) { - /// Walk through each page and filter. - $wikientries = array(); - foreach ($wiki_pages as $wiki_page) { - if (!in_array($wiki_page->pagename, $wikientries)) { - $startlink = ''; - $wikipagelist[] = new filterobject($wiki_page->pagename, $startlink, '', false, true); - $wikientries[] = $wiki_page->pagename; - } - } - } - } - } - } - } - - return filter_phrases($text, $wikipagelist); - } - - diff --git a/mod/wiki/history.php b/mod/wiki/history.php new file mode 100644 index 00000000000..f4929082888 --- /dev/null +++ b/mod/wiki/history.php @@ -0,0 +1,76 @@ +. + +/** + * This file contains all necessary code to view the history page + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +require_once('../../config.php'); + +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$pageid = required_param('pageid', PARAM_TEXT); +$paging = optional_param('page', 0, PARAM_INT); +$allversion = optional_param('allversion', 0, PARAM_INT); + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} + +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} + +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +if (!$cm = get_coursemodule_from_instance('wiki', $wiki->id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} + +require_course_login($course->id, true, $cm); +add_to_log($course->id, 'wiki', 'history', 'history.php?id='.$cm->id, $wiki->id); + +/// Print the page header +$wikipage = new page_wiki_history($wiki, $subwiki, $cm); + +$wikipage->set_page($page); +$wikipage->set_paging($paging); +$wikipage->set_allversion($allversion); + +$wikipage->print_header(); +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/index.php b/mod/wiki/index.php index c5fdf3c8252..a8653baf2b4 100644 --- a/mod/wiki/index.php +++ b/mod/wiki/index.php @@ -1,110 +1,107 @@ -. - require_once("../../config.php"); - require_once("lib.php"); +/** + * This page lists all the instances of wiki in a particular course + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ - $id = required_param('id', PARAM_INT); // course +require_once('../../config.php'); +require_once('lib.php'); - $PAGE->set_url('/mod/wiki/index.php', array('id'=>$id)); +$id = required_param('id', PARAM_INT); // course - if (!$course = $DB->get_record('course', array('id'=>$id))) { - print_error('invalidcourseid'); - } +if (!$course = $DB->get_record('course', array('id' => $id))) { + print_error('invalidcourseid'); +} - require_course_login($course); - $PAGE->set_pagelayout('incourse'); +require_course_login($course->id, true, $cm); - add_to_log($course->id, "wiki", "view all", "index.php?id=$course->id", ""); +add_to_log($course->id, 'wiki', 'view all', "index.php?id=$course->id", ""); +/// Get all required stringswiki -/// Get all required strings - - $strwikis = get_string("modulenameplural", "wiki"); - $strwiki = get_string("modulename", "wiki"); - +$strwikis = get_string("modulenameplural", "wiki"); +$strwiki = get_string("modulename", "wiki"); /// Print the header - $PAGE->navbar->add($strwikis); - $PAGE->set_title($strwikis); - echo $OUTPUT->header(); + +$navlinks = array(); +$navlinks[] = array('name' => $strwikis, 'link' => '', 'type' => 'activity'); +$navigation = build_navigation($navlinks); + +print_header_simple("$strwikis", "", $navigation, "", "", true, "", navmenu($course)); /// Get all the appropriate data - if (! $wikis = get_all_instances_in_course("wiki", $course)) { - notice(get_string('thereareno', 'moodle', $strwikis), "../../course/view.php?id=$course->id"); - die; - } +if (!$wikis = get_all_instances_in_course("wiki", $course)) { + notice("There are no wikis", "../../course/view.php?id=$course->id"); + die; +} /// Print the list of instances (your module will probably extend this) - $timenow = time(); - $strname = get_string('wikiname', 'wiki'); - $strsummary = get_string('summary'); - $strtype = get_string('wikitype', 'wiki'); - $strlastmodified = get_string('lastmodified'); - $strweek = get_string('week'); - $strtopic = get_string('topic'); +$timenow = time(); +$strname = get_string("name"); +$strweek = get_string("week"); +$strtopic = get_string("topic"); - $table = new html_table(); - if ($course->format == "weeks") { - $table->head = array ($strweek, $strname, $strsummary, $strtype, $strlastmodified); - $table->align = array ('CENTER', 'LEFT', 'LEFT', 'LEFT', 'LEFT'); - } else if ($course->format == "topics") { - $table->head = array ($strtopic, $strname, $strsummary, $strtype, $strlastmodified); - $table->align = array ('CENTER', 'LEFT', 'LEFT', 'LEFT', 'LEFT'); +if ($course->format == "weeks") { + $table->head = array($strweek, $strname); + $table->align = array("center", "left"); +} else if ($course->format == "topics") { + $table->head = array($strtopic, $strname); + $table->align = array("center", "left", "left", "left"); +} else { + $table->head = array($strname); + $table->align = array("left", "left", "left"); +} + +foreach ($wikis as $wiki) { + if (!$wiki->visible) { + //Show dimmed if the mod is hidden + $link = "coursemodule\">$wiki->name"; } else { - $table->head = array ($strname, $strsummary, $strtype, $strlastmodified); - $table->align = array ('LEFT', 'LEFT', 'LEFT', 'LEFT'); + //Show normal if the mod is visible + $link = "coursemodule\">$wiki->name"; } - foreach ($wikis as $wiki) { - if (!$wiki->visible) { - //Show dimmed if the mod is hidden - $link = ''.format_string($wiki->name,true).''; - } else { - //Show normal if the mod is visible - $link = ''.format_string($wiki->name,true).''; - } - - $timmod = ''.userdate($wiki->timemodified).''; - $options = (object)array('noclean'=>true); - $summary = '
          '.format_module_intro('wiki', $wiki, $wiki->coursemodule).'
          '; - - $site = get_site(); - switch ($wiki->wtype) { - - case 'teacher': - $wtype = get_string('defaultcoursestudent'); - break; - - case 'student': - $wtype = get_string('defaultcoursestudent'); - break; - - case 'group': - default: - $wtype = get_string('group'); - break; - } - - $wtype = ''.$wtype.''; - - if ($course->format == "weeks" or $course->format == "topics") { - $table->data[] = array ($wiki->section, $link, $summary, $wtype, $timmod); - } else { - $table->data[] = array ($link, $summary, $wtype, $timmod); - } + if ($course->format == "weeks" or $course->format == "topics") { + $table->data[] = array($wiki->section, $link); + } else { + $table->data[] = array($link); } +} - echo "
          "; +echo "
          "; - echo html_writer::table($table); +print_table($table); /// Finish the page - echo $OUTPUT->footer(); - - +print_footer($course); diff --git a/mod/wiki/instancecomments.php b/mod/wiki/instancecomments.php new file mode 100644 index 00000000000..17456aeedc8 --- /dev/null +++ b/mod/wiki/instancecomments.php @@ -0,0 +1,89 @@ +. + +/** + * @TODO: Doc this file + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Daniel Serrano + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); +require_once($CFG->dirroot . "/mod/wiki/pagelib.php"); +require_once($CFG->dirroot . "/mod/wiki/locallib.php"); +require_once($CFG->dirroot . '/mod/wiki/comments_form.php'); + +$pageid = required_param('pageid', PARAM_TEXT); +$action = optional_param('action', '', PARAM_ACTION); +$id = optional_param('id', PARAM_INT); +$commentid = optional_param('commentid', PARAM_INT); +$newcontent = optional_param('newcontent', '', PARAM_CLEANHTML); + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} + +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} +if (!$cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid)) { + print_error('invalidcoursemodule'); +} +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} +require_course_login($course->id, true, $cm); + +$comm = new page_wiki_handlecomments($wiki, $subwiki, $cm); +$comm->set_page($page); + +if ($action == 'delete') { + $comm->set_action($action, $commentid, 0); +} else { + if (empty($newcontent)) { + $form = new mod_wiki_comments_form(); + $newcomment = $form->get_data(); + $content = $newcomment->entrycomment_editor['text']; + } else { + $content = $newcontent; + } + + if ($action == 'edit') { + $comm->set_action($action, $id, $content); + + } else { + $action = 'add'; + $comm->set_action($action, 0, $content); + } +} + +$comm->print_header(); +$comm->print_content(); +$comm->print_footer(); diff --git a/mod/wiki/lang/en/wiki.php b/mod/wiki/lang/en/wiki.php index 34321b2a482..e5310bd5007 100644 --- a/mod/wiki/lang/en/wiki.php +++ b/mod/wiki/lang/en/wiki.php @@ -1,230 +1,179 @@ . - /** - * Strings for component 'wiki', language 'en', branch 'MOODLE_20_STABLE' * - * @package wiki - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * This file contains en_utf8 translation of Wiki module + * + * @author Jordi Piguillem + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU Public License + * @package wiki */ - -$string['action'] = '-- Action --'; -$string['administration'] = 'Administration'; -$string['allowremovepages'] = 'Allow \'remove pages\''; -$string['allowrevertchanges'] = 'Allow \'revert mass changes\''; -$string['allowsetpage'] = 'Allow \'set page flags\''; -$string['allowstrippages'] = 'Allow \'strip pages\''; -$string['attachments'] = 'This page has attachments'; -$string['author'] = 'Author'; -$string['authorfieldpattern'] = 'Author field pattern'; -$string['authorfieldpatternerror'] = 'Please enter an author.'; -$string['backlinks'] = 'Referring links'; -$string['binimgtoolarge'] = 'Image file is too large!'; -$string['binnoimg'] = 'This is an inacceptable file format!'; -$string['browse'] = 'Browse'; -$string['canceledit'] = 'Cancel'; -$string['cannotacceptbin'] = 'This wiki does not accept binaries'; -$string['cannotaccessgroup'] = 'Cannot access any groups for this wiki'; -$string['cannotaddentry'] = 'Could not add wiki entry.'; -$string['cannotgetentry'] = 'Cannot get entry.'; -$string['cannotchangepage'] = 'This page cannot be changed.'; -$string['cannotstartwith'] = 'Binary entry does not start with ({$a})'; -$string['comment'] = 'Comment'; -$string['contentsize'] = 'Content size'; -$string['created'] = 'Created'; -$string['deletemewikiword'] = 'DeleteMe'; -$string['deletemewikiwordfound'] = '{$a} found on page'; -$string['deletepage'] = 'Delete page'; -$string['deleteversions'] = 'Delete how many last versions'; -$string['deleteversionserror'] = 'Please enter a correct version count.'; +$string['addcomment'] = 'Add comment'; +$string['attachmentattach'] = 'Add as attachment'; +$string['attachmentimage'] = 'Add as image'; +$string['attachmentlink'] = 'Add as link'; +$string['attachments'] = 'Attachments'; +$string['backcomments'] = 'Back to Comments'; +$string['backhistory'] = 'Back to History'; +$string['backoldversion'] = 'Back to Old Version'; +$string['backpage'] = 'Back to Page'; +$string['backtomapmenu'] = 'Back to Map Menu'; +$string['changerate']='Do you wish to change it?'; +$string['comparesel'] = 'Compare Selected'; +$string['comments'] = 'Comments'; +$string['commentscount'] = 'Comments ({$a})'; +$string['comparewith'] = 'Comparing version {$a->old} with version {$a->new}'; +$string['contributions'] = 'Contributions'; +$string['createcomment'] = 'Creating comment'; +$string['creating'] = 'Creating wiki page'; +$string['createpage'] = 'Create Page'; +$string['createddate'] = 'Created: {$a->date} by {$a->username}'; +$string['creole'] = 'Creole'; +$string['defaultformat'] = 'Default format'; +$string['deletecomment'] = 'Deleting comment'; +$string['deleteupload'] = 'Delete'; +$string['deletedbegins'] = 'Deleted begins'; +$string['deletedends'] = 'Deleted ends'; +$string['addedbegins'] = 'added begins'; +$string['addedends'] = 'added ends'; $string['diff'] = 'Diff'; -$string['differences'] = 'Differences between version {$a->new_ver} and {$a->old_ver} of {$a->pagename}.'; -$string['disablecamel'] = 'Disable CamelCase linking'; -$string['disabledpage'] = 'This page is currently not available.'; -$string['doesnotexist'] = 'This page does not yet exist, please click on the edit Button if you would like to create it.'; -$string['downloadaszip'] = 'Downloadable zip archive'; -$string['downloadtimes'] = 'Downloaded {$a} times'; -$string['dwnlnofiles'] = 'No files uploaded yet.'; -$string['dwnlsection'] = 'Download section'; -$string['editform1'] = 'Try not to worry too much about formatting, it can always be improved later.'; -$string['editform2'] = 'Please write sensibly, and remember that all editing is logged.'; -$string['editthispage'] = 'Edit this page'; -$string['emptypage'] = 'Empty page'; -$string['errorbinandtxt'] = 'Flag error: Page of type BIN and TXT'; -$string['errorhtml'] = 'Page of type HTML'; -$string['errornotype'] = 'Flag error: Neither BIN nor TXT'; -$string['errororreason'] = 'Error or reason'; -$string['errorroandwr'] = 'Flag error: Page is Writeable and Read only'; -$string['errorsize'] = 'Page size bigger than 64k'; -$string['errversionsave'] = 'Sorry, while you edited this page someone else did already save a changed version. Please go back to the previous screen and copy your changes to your computers clipboard to insert it again after you reload the edit screen.'; -$string['ewikiacceptbinary'] = 'Allow binary files'; -$string['ewikiprinttitle'] = 'Print wiki name on every page'; -$string['export'] = 'Export'; -$string['exportformats'] = 'Export formats'; -$string['exportsuccessful'] = 'Export successful.'; -$string['exportto'] = 'Export to'; -$string['fetchback'] = 'Fetch-back'; -$string['file'] = 'File'; -$string['filedownload'] = 'File Download'; -$string['fileisoftype'] = 'File is of type'; -$string['filtername'] = 'Wiki Page Auto-linking'; -$string['flagbin'] = 'BIN'; -$string['flaghtm'] = 'HTM'; -$string['flagoff'] = 'OFF'; -$string['flagro'] = 'RO'; -$string['flags'] = 'Flags'; -$string['flagsset'] = 'Flags changed'; -$string['flagtxt'] = 'TXT'; -$string['flagwr'] = 'WR'; -$string['for'] = 'for'; -$string['forbidden'] = 'You are not authorized to access this page.'; -$string['groupmodeerror'] = 'Can\'t access wiki in group mode when no groups are configured for the course'; -$string['groups'] = 'Groups'; -$string['hits'] = '{$a} hits'; -$string['howtooperate'] = 'How to operate'; -$string['howtowiki'] = 'How to wiki'; -$string['html'] = 'HTML-Format'; -$string['htmlmode'] = 'HTML Mode'; -$string['htmlonly'] = 'HTML only'; -$string['changes'] = '{$a} changes'; -$string['changesfield'] = 'Within how many hours from the last change'; -$string['changesfielderror'] = 'Please enter a correct hour count.'; -$string['checklinks'] = 'Check links'; -$string['checklinkscheck'] = 'Are you sure that you want to check the links on this page:'; -$string['checklinksnotice'] = 'Please be patient when this page is working.'; -$string['chooseadministration'] = '-- Administration --'; -$string['chooseafile'] = 'Choose/upload initial page'; -$string['choosewikilinks'] = '-- Choose Wiki Links --'; -$string['index'] = 'Index'; -$string['infoaboutpage'] = 'History for:'; -$string['initialcontent'] = 'Choose an Initial Page'; -$string['invalidpageval'] = 'Unsupported page value'; -$string['invalidroot'] = 'You are not authorized to access the current root page so no sitemap can be created.'; -$string['lastchanged'] = 'Last changed on {$a}'; -$string['lastmodified'] = 'Last modification'; -$string['linkdead'] = 'DEAD'; -$string['linkok'] = 'OK'; -$string['linkschecked'] = 'Links checked'; -$string['listall'] = 'List all'; -$string['listcandidates'] = 'List candidates'; -$string['lockcancelled'] = 'Your editing lock has been overridden and somebody else is now editing this page. If you wish to keep your changes, please select and copy them before clicking Cancel; then try to edit again.'; -$string['meta'] = 'Meta data'; -$string['moduledirectory'] = 'Module Directory'; +$string['diff_help'] = 'Diff help'; +$string['edit'] = 'Edit'; +$string['editcomment'] = 'Edit comment'; +$string['editblocks'] = 'Turn edit blocks on'; +$string['filenotuploadederror'] = 'File \'{$a}\' could not be uploaded correctly.'; +$string['filtername'] = 'Wiki Auto-linking'; +$string['firstpagetitle'] = 'First page name'; +$string['forceformat'] = 'Force format'; +$string['formathtml'] = 'HTML Format'; +$string['formatcreole'] = 'Creole Format'; +$string['formatnwiki'] = 'NWIKI Format'; +$string['history'] = 'History'; +$string['html'] = 'HTML'; +$string['insertcomment'] = 'Insert comment'; +$string['invalidlock'] = 'This page is already locked by another user.'; +$string['invalidparameters'] = 'Invalid parameters have been given.'; +$string['invalidsesskey'] = 'The given Sesskey is not valid. Please resend data again'; +$string['individualpagedoesnotexist'] = 'Individual wiki page doen\'t exist'; +$string['javascriptdisabledlocks'] = 'Javascript is disabled on your browser and locks are not working. The changes you make may not be saved correctly.'; +$string['lockingajaxtimeout'] = 'Edit page locking refresh time'; +$string['lockingtimeout'] = 'Locking timeout'; +$string['links'] = 'Links'; +$string['map'] = 'Map'; +$string['mapmenu'] = 'Map Menu'; +$string['migrationfinished'] = 'Migration finished successfully'; +$string['migrationfinishednowikis'] = 'Migration finished, no wikis were migrated'; +$string['missingpages'] = 'Pages without content'; +$string['modified'] = 'Modified'; $string['modulename'] = 'Wiki'; $string['modulenameplural'] = 'Wikis'; -$string['mostoftenchangedpages'] = 'Most often changed pages'; -$string['mostvisitedpages'] = 'Most visited pages'; -$string['newestpages'] = 'Newest pages'; -$string['noadministrationaction'] = 'No administration action given.'; -$string['nocandidatestoremove'] = 'No candidate pages to remove, choose \'{$a}\' to show all pages.'; -$string['nohtml'] = 'No HTML'; -$string['nochangestorevert'] = 'No changes to revert.'; -$string['nojslockwarning'] = 'Because Javascript is disabled in your browser, it is possible that somebody else could edit this page. If that happens, you won\'t be able to save your changes. Please try to make your edits quickly, or turn Javascript on and reload this page.'; -$string['nolinksfound'] = 'No links found on page.'; -$string['nopermissiontooverride'] = 'You do not have the capability to override editing locks'; -$string['noregexp'] = 'This must be a fixed string (you cannot use * or regex), at best use the attackers` IP address or host name, but do not include the port number (because it increased with every http access).'; -$string['notadministratewiki'] = 'You are not allowed to administrate this wiki !'; -$string['nothingtostrip'] = 'There are no pages with more than one version.'; -$string['nowikicreated'] = 'No entries have been created for this wiki.'; -$string['of'] = 'of'; -$string['offline'] = 'OFFLINE'; -$string['optional'] = 'Optional'; -$string['orphanedpage'] = 'Orphaned page'; -$string['orphanedpages'] = 'Orphaned pages'; -$string['otherwikis'] = 'Other Wikis'; -$string['overridebutton'] = 'Override lock'; -$string['overrideinfo'] = 'You can override this user\'s lock, but doing so may cause them to lose their changes! Please take care.'; -$string['ownerunknown'] = 'unknown'; -$string['pageactions'] = 'Page actions'; +$string['navigation'] = 'Navigation'; +$string['navigationfrom'] = 'This page comes from'; +$string['navigationto'] = 'This page goes to'; +$string['newpage'] = 'New'; +$string['newpagetitle'] = 'New page title'; +$string['noattachments'] = 'No files attached'; +$string['nocontent'] = 'There is no content for this page'; +$string['nocontribs'] = 'You have no contributions in this wiki'; +$string['nocomments'] = 'There are no comments'; +$string['nocreatepermission'] = 'Create page permission needed'; +$string['noeditcommentpermission'] = 'Edit comment permission needed'; +$string['noeditpermission'] = 'Edit page permission needed'; +$string['nofrompages'] = 'There are no links to this page'; +$string['nohistory'] = 'There is no history for this page'; +$string['nomanagecommentpermission'] = 'Manage comments permission needed'; +$string['nomanagewikipermission'] = 'Manage wiki permission needed'; +$string['noorphanedpages'] = 'There are no orphaned pages'; +$string['nooverridelockpermission'] = 'Override lock permission needed'; +$string['norated']='This page has not been rated yet, be the first!'; +$string['norating'] = 'No rating'; +$string['nosearchresults'] = 'No results'; +$string['noteditblocks'] = 'Turn edit blocks off'; +$string['notopages'] = 'This page does not link to other pages'; +$string['notmigrated'] = 'This wiki has not been migrated yet. Please contact your administrator.'; +$string['noupdatedpages'] = 'There are no updated pages'; +$string['noviewcommentpermission'] = 'View comments permission needed'; +$string['noviewpagepermission'] = 'View page permission needed'; +$string['nwiki'] = 'NWiki'; +$string['oldversion'] = 'Old version'; +$string['orphaned'] = 'Orphaned pages'; +$string['overridelocks'] = 'Override locks'; +$string['overridinglocks'] = 'Overriding locks...'; +$string['pageexists'] = 'This page already exists. Redirecting to it.'; $string['pageindex'] = 'Page Index'; -$string['pageinfo'] = 'Page information'; -$string['pagelocked'] = '

          This page is being edited by {$a->name}. They began editing at {$a->since} and still have the window open as of {$a->seen}.

          You need to wait for them to finish before you can edit this page.

          '; -$string['pagename'] = 'Page name'; -$string['pagenamechoice'] = '- or -'; -$string['pageslinkingto'] = 'Pages linking to this page'; -$string['pagesremoved'] = 'Pages removed.'; -$string['pagesreverted'] = 'Changes reverted'; -$string['pagesstripped'] = 'Pages stripped.'; -$string['plaintext'] = 'Plain Text'; -$string['preview'] = 'Preview'; -$string['readonly'] = 'Read only page'; -$string['refs'] = 'References'; -$string['reloadlinkdescription'] = 'Reloads the page, so that any new content is shown.'; -$string['reloadlinktext'] = 'Reload this page'; -$string['removenotice'] = 'Note that only unreferenced pages will be listed here. And because the ewiki engine itself does only limited testing if a page is referenced it may miss some of them here.
          If you however empty a page first, it will get listed here too. Various other database diagnostics are made as well.'; -$string['removepagecheck'] = 'Are you sure that you want to delete these pages ?'; -$string['removepages'] = 'Remove pages'; -$string['removeselectedpages'] = 'Remove selected pages'; -$string['revertallsince'] = 'Version diving, also delete changes made after'; -$string['revertchanges'] = 'Revert changes'; -$string['revertlastonly'] = 'Only, if it was the last change'; -$string['revertpages'] = 'Revert mass changes'; -$string['revertpagescheck'] = 'Do you really want to revert the following changes:'; -$string['revertthe'] = 'Version diving, but only purge the affected one'; -$string['safehtml'] = 'Safe HTML'; +$string['pageislocked'] = 'Someone is editing this page right now. Try to edit it in a few minutes.'; +$string['pageindex'] = 'Page index'; +$string['pagelist'] = 'Page list'; +$string['peerreview'] = 'Peer review'; +$string['prettyprint'] = 'Printer-friendly version'; +$string['previewwarning'] = 'This is a preview. Changes have not been saved yet.'; +$string['rated']='You rated this page as a {$a}'; +$string['rating']='Rating'; +$string['ratingmode'] = 'Rating mode'; +$string['reparsetimeout'] = 'Reparsing default timeout'; +$string['repeatedsection'] = 'Wiki error: Section name cannot be repeated \'{$a}\''; +$string['restore'] = 'Restore'; +$string['restoreconfirm'] = 'Are you sure you want to restore version #{$a}?'; +$string['restoreerror'] = 'Version #{$a} could not be restored'; +$string['restorethis'] = 'Restore this version'; +$string['restoreversion'] = 'Restore old version'; +$string['restoring'] = 'Restoring version #{$a}'; +$string['return'] = 'Go back'; $string['save'] = 'Save'; -$string['savenolock'] = 'You cannot save the page because you do not have an editing lock. This can happen if your browser has Javascript turned off, or if another user overrides your lock.
          You can return to the previous screen using your browser\'s Back button and copy the text of any changes you made, then try editing again.'; -$string['searchwiki'] = 'Search Wiki'; -$string['setpageflags'] = 'Set page flags'; -$string['showversions'] = 'Show versions:'; -$string['sitemap'] = 'Sitemap'; -$string['smfor'] = 'Sitemap for'; -$string['status'] = 'Status'; -$string['strippagecheck'] = 'Are you sure that you want to strip old versions from these pages:'; -$string['strippages'] = 'Strip pages'; -$string['studentadminoptions'] = 'Student admin options'; -$string['submit'] = 'Submit'; -$string['tabattachments'] = 'Attachments'; -$string['tabedit'] = 'Edit'; -$string['tabinfo'] = 'History'; -$string['tablinks'] = 'Links'; -$string['tabview'] = 'View'; -$string['thanksforcontribution'] = 'Thank you for your contribution.'; -$string['thispageisntlinkedfromanywhereelse'] = 'This page isn\'t linked from anywhere else.'; -$string['updatedpages'] = 'Updated pages'; -$string['updatedwikipages'] = 'Updated wiki pages'; -$string['uplerror'] = 'We are sorry, but something went wrong during the file upload.'; -$string['uplinsect'] = 'Upload into'; -$string['uplnewnam'] = 'Save with different filename'; -$string['uploadedon'] = 'Uploaded on'; -$string['uploaderror'] = 'Error occur during uploading ({$a})'; -$string['uploadpicturebutton'] = 'Upload'; -$string['upload0'] = 'Use this form to upload an arbitrary binary file into the wiki:'; -$string['uplok'] = 'Your file was uploaded correctly.'; +$string['saving'] = 'Saving wiki page'; +$string['savingerror'] = 'Saving error'; +$string['searchcontent'] = 'Search in page content'; +$string['searchresult'] = 'Search results:'; +$string['searchwikis'] = 'Search wikis'; +$string['special'] = 'Special'; +$string['teacherrating'] = 'Teacher rating'; +$string['timesrating']='This page has been rated {$a->c} times with an average of: {$a->s}'; +$string['updatedpages'] = "Updated pages"; +$string['updatedwikipages'] = "Updated wiki pages"; +$string['upload'] = "Upload & Delete"; +$string['uploadname'] = "Filename"; +$string['uploadactions'] = "Actions"; +$string['uploadtitle'] = 'Attach files'; +$string['uploadfiletitle'] = 'Attachments'; +$string['versionerror'] = 'Version ID does not exist'; +$string['versionnum'] = 'Version #{$a}'; $string['version'] = 'Version'; -$string['versionrangetoobig'] = 'You cannot delete all versions of a page! The last version should remain.'; -$string['versions'] = 'Versions'; -$string['versionstodelete'] = 'Version(s) to delete'; -$string['viewpage'] = 'View Page'; -$string['viewsmfor'] = 'View sitemap for'; -$string['wantedpages'] = 'Wanted pages'; -$string['wikidefaultpagename'] = 'WikiIndex'; -$string['wikiexport'] = 'Export pages'; -$string['wikiexportcomment'] = 'Here you can configure the export to your needs.'; -$string['wikilinkoptions'] = 'Wiki auto-linking options'; -$string['wikilinks'] = 'Wiki Links'; -$string['wiki:manage'] = 'Manage wiki settings'; -$string['wikiname'] = 'Page Name'; -$string['wiki:overridelock'] = 'Override locked pages'; -$string['wiki:participate'] = 'Edit wiki pages'; -$string['wikistartederror'] = 'Wiki already has entries - can\'t change.'; -$string['wikitype'] = 'Type'; -$string['wikiusage'] = 'Wiki usage'; -$string['withbinaries'] = 'Include binary content'; -$string['withvirtualpages'] = 'Include Wiki-Links'; -$string['wrongversionrange'] = '{$a} is not a correct range!'; +$string['view'] = 'View'; +$string['viewallhistory'] = 'View all history'; +$string['viewperpage'] = 'Show {$a} versions per page'; +$string['viewversion'] = 'Viewing page version #{$a}'; +$string['viewcurrent'] = 'Current Version'; +$string['wiki'] = 'Wiki'; +$string['wikiadministration'] = 'Wiki Administration'; +$string['wikiattachments'] = 'Wiki attachments'; +$string['wikiboldtext'] = 'Bold Text'; +$string['wikiexternalurl'] = 'External URL'; +$string['wikifiletable'] = 'Uploaded file list'; +$string['wikiheader'] = 'Level {$a} Header'; +$string['wikihr'] = 'Horizontal Rule'; +$string['wikiimage'] = 'Image'; +$string['wikiinternalurl'] = 'Internal link'; +$string['wikiintro'] = 'Wiki description'; +$string['wikiitalictext'] = 'Italic Text'; +$string['wikilockingsettings'] = 'Locking and reparsing timeouts'; +$string['wikimode'] = 'Wiki Mode'; +$string['wikimodecollaborative'] = 'Collaborative Wiki'; +$string['wikimodeindividual'] = 'Individual Wiki'; +$string['wikiname'] = 'Wiki name'; +$string['wikinowikitext'] = 'No Wiki Text'; +$string['wikiorderedlist'] = 'Ordered List'; +$string['wikisettings'] = 'Wiki settings'; +$string['wikiunorderedlist'] = 'Unordered List'; +$string['wiki:createpage'] = 'Create new wiki pages'; +$string['wiki:editcomment'] = 'Add comments to pages'; +$string['wiki:editpage'] = 'Save wiki pages'; +$string['wiki:managecomments'] = 'Manage wiki comments'; +$string['wiki:managewiki'] = 'Manage wiki settings'; +$string['wiki:overridelock'] = 'Override wiki locks'; +$string['wiki:viewcomment'] = 'View page comments'; +$string['wiki:viewpage'] = 'View wiki pages'; +$string['wikipages'] = 'Wiki pages'; +$string['wrongversionlock'] = 'Another user has edited this page while you were editing and your content is obsolete.'; +$string['wrongversionsave'] = 'Another user has created a version while you were editing and you have overwritten his changes, check the page history.'; + diff --git a/mod/wiki/lib.php b/mod/wiki/lib.php index a81f9145dc7..ec1cb17533c 100644 --- a/mod/wiki/lib.php +++ b/mod/wiki/lib.php @@ -9,154 +9,71 @@ // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License -// along with Moodle. If not, see . +// along with Moodle. If not, see . /** * Library of functions and constants for module wiki - * (replace wiki with the name of your module and delete this line) * - * @package mod-wiki - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * It contains the great majority of functions defined by Moodle + * that are mandatory to develop a module. + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -/** @global array $WIKI_TYPES */ -global $WIKI_TYPES; -$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 - -// How long locks stay around without being confirmed (seconds) -define("WIKI_LOCK_PERSISTENCE",120); - -// How often to confirm that you still want a lock -define("WIKI_LOCK_RECONFIRM",60); - -// Session variable used to store wiki locks -define('SESSION_WIKI_LOCKS','wikilocks'); - -/*** Moodle 1.7 compatibility functions ***** - ********************************************/ - -/** - * @todo add some $cm caching if needed - * @param object $wiki - * @return object - */ -function wiki_context($wiki) { - //TODO: add some $cm caching if needed - if (is_object($wiki)) { - $wiki = $wiki->id; - } - if (! $cm = get_coursemodule_from_instance('wiki', $wiki)) { - print_error('invalidcoursemodule'); - } - - return get_context_instance(CONTEXT_MODULE, $cm->id); -} - -/** - * @param object $wiki - * @param int $userid - * @return bool - */ -function wiki_is_teacher($wiki, $userid=NULL) { - return has_capability('mod/wiki:manage', wiki_context($wiki), $userid); -} -/** - * @param object $wiki - * @param int $userid - * @return bool - */ -function wiki_is_teacheredit($wiki, $userid=NULL) { - return has_capability('mod/wiki:manage', wiki_context($wiki), $userid) - and has_capability('moodle/site:accessallgroups', wiki_context($wiki), $userid); -} -/** - * @param object $wiki - * @param int $userid - * @return bool - */ -function wiki_is_student($wiki, $userid=NULL) { - return has_capability('mod/wiki:participate', wiki_context($wiki), $userid); -} -/** - * @param object $wiki - * @param string $groups - * @param string $sort - * @param string $fields - * @return array - */ -function wiki_get_students($wiki, $groups='', $sort='u.lastaccess', $fields='u.*') { - return $users = get_users_by_capability(wiki_context($wiki), 'mod/wiki:participate', $fields, $sort, '', '', $groups); -} - -/* end of compatibility functions */ +require_once ($CFG->dirroot . '/mod/wiki/locallib.php'); /** * Given an object containing all the necessary data, - * (defined by the form in mod_form.php) this function + * (defined by the form in mod.html) this function * will create a new instance and return the id number * of the new instance. * - * @global object - * @param object $wiki - * @return bool|int - */ + * @param object $instance An object from the form in mod.html + * @return int The id of the newly inserted wiki record + **/ function wiki_add_instance($wiki) { global $DB; $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); - - return $DB->insert_record("wiki", $wiki); + return $DB->insert_record('wiki', $wiki); } /** * Given an object containing all the necessary data, - * (defined by the form in mod_form.php) this function + * (defined by the form in mod.html) this function * will update an existing instance with new data. * - * @global object - * @param object @wiki - * @return bool - */ + * @param object $instance An object from the form in mod.html + * @return boolean Success/Fail + **/ function wiki_update_instance($wiki) { global $DB; - /// Determine the pagename for this wiki. - $wiki->pagename = wiki_page_name($wiki); - $wiki->timemodified = time(); $wiki->id = $wiki->instance; - return $DB->update_record("wiki", $wiki); -} - -/** - * Delete all Directories recursively - * - * @param string $basedir - */ -function wiki_rmdir($basedir) { - $handle = @opendir($basedir); - if($handle) { - while (false!==($folder = readdir($handle))) { - if($folder != "." && $folder != ".." && $folder != "CVS") { - wiki_rmdir("$basedir/$folder"); // recursive - } + if (empty($wiki->forceformat)) { + $wiki->forceformat = 0; } - closedir($handle); - } - @rmdir($basedir); + + # May have to add extra stuff in here # + + return $DB->update_record('wiki', $wiki); } /** @@ -164,57 +81,61 @@ function wiki_rmdir($basedir) { * this function will permanently delete the instance * and any data that depends on it. * - * @global stdObject - * @global object - * @param int $id - * @return bool - */ + * @param int $id Id of the module instance + * @return boolean Success/Failure + **/ function wiki_delete_instance($id) { - global $CFG, $DB, $OUTPUT; + global $DB; - if (! $wiki = $DB->get_record("wiki", array("id"=>$id))) { + if (!$wiki = $DB->get_record('wiki', array('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"); - echo $OUTPUT->notification("Existing file '$file' has been deleted!"); - #} - } - } - #if (!$exception) { // Delete directory as well, if empty - wiki_rmdir("$basedir"); - #} - } - } + # Get subwiki information # + $subwikis = $DB->get_records('wiki_subwikis', array('wikiid' => $wiki->id)); - # Delete any dependent records here # - if(!$DB->delete_records("wiki_locks", array("wikiid"=>$wiki->id))) { - $result = false; - } + foreach ($subwikis as $subwiki) { + # Get existing links, and delete them # + if (!$DB->delete_records('wiki_links', array('subwikiid' => $subwiki->id), IGNORE_MISSING)) { + $result = false; + } - if (! $DB->delete_records("wiki", array("id"=>$wiki->id))) { - $result = false; - } + # Get existing pages # + if ($pages = $DB->get_records('wiki_pages', array('subwikiid' => $subwiki->id))) { + foreach ($pages as $page) { + # Get locks, and delete them # + if (!$DB->delete_records('wiki_locks', array('pageid' => $page->id), IGNORE_MISSING)) { + $result = false; + } - /// Delete all wiki_entries and wiki_pages. - if (($wiki_entries = wiki_get_entries($wiki)) !== false) { - foreach ($wiki_entries as $wiki_entry) { - if (! $DB->delete_records("wiki_pages", array("wiki"=>$wiki_entry->id))) { - $result = false; + # Get versions, and delete them # + if (!$DB->delete_records('wiki_versions', array('pageid' => $page->id), IGNORE_MISSING)) { + $result = false; + } } - if (! $DB->delete_records("wiki_entries", array("id"=>$wiki_entry->id))) { + + # Delete pages # + if (!$DB->delete_records('wiki_pages', array('subwikiid' => $subwiki->id), IGNORE_MISSING)) { $result = false; } } + + # Get existing synonyms, and delete them # + if (!$DB->delete_records('wiki_synonyms', array('subwikiid' => $subwiki->id), IGNORE_MISSING)) { + $result = false; + } + + # Delete any subwikis # + if (!$DB->delete_records('wiki_subwikis', array('id' => $subwiki->id), IGNORE_MISSING)) { + $result = false; + } + } + + # Delete any dependent records here # + if (!$DB->delete_records('wiki', array('id' => $wiki->id))) { + $result = false; } return $result; @@ -227,1972 +148,336 @@ function wiki_delete_instance($id) { * $return->time = the time they did it * $return->info = a short text description * - * @param object $course - * @param object $user - * @param object $mod - * @param object $wiki * @return null - */ + * @todo Finish documenting this function + **/ function wiki_user_outline($course, $user, $mod, $wiki) { - - $return = NULL; return $return; } /** - * Print a detailed representation of what a user has done with + * Print a detailed representation of what a user has done with * a given particular instance of this module, for user activity reports. * - * @param object $course - * @param object $user - * @param object $mod - * @param object $wiki - * @return bool true - */ + * @return boolean + * @todo Finish documenting this function + **/ function wiki_user_complete($course, $user, $mod, $wiki) { return true; } +/** + * Indicates API features that the wiki supports. + * + * @uses FEATURE_GROUPS + * @uses FEATURE_GROUPINGS + * @uses FEATURE_GROUPMEMBERSONLY + * @uses FEATURE_MOD_INTRO + * @uses FEATURE_COMPLETION_TRACKS_VIEWS + * @uses FEATURE_COMPLETION_HAS_RULES + * @uses FEATURE_GRADE_HAS_GRADE + * @uses FEATURE_GRADE_OUTCOMES + * @param string $feature + * @return mixed True if yes (some features may use other values) + */ +function wiki_supports($feature) { + switch ($feature) { + case FEATURE_GROUPS: + return true; + case FEATURE_GROUPINGS: + return true; + case FEATURE_GROUPMEMBERSONLY: + return true; + case FEATURE_MOD_INTRO: + return true; + case FEATURE_COMPLETION_TRACKS_VIEWS: + return true; + case FEATURE_COMPLETION_HAS_RULES: + return true; + case FEATURE_GRADE_HAS_GRADE: + return true; + case FEATURE_GRADE_OUTCOMES: + return true; + case FEATURE_RATE: + return false; + + default: + return null; + } +} + /** * 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 stdClass - * @global object + * @global $CFG + * @global $DB + * @uses CONTEXT_MODULE + * @uses VISIBLEGROUPS * @param object $course - * @param bool $isteacher + * @param bool $viewfullnames capability * @param int $timestart - * @return bool - */ -function wiki_print_recent_activity($course, $isteacher, $timestart) { + * @return boolean + **/ +function wiki_print_recent_activity($course, $viewfullnames, $timestart) { global $CFG, $DB, $OUTPUT; - $sql = "SELECT l.*, cm.instance - FROM {log} l JOIN {course_modules} cm ON l.cmid = cm.id - WHERE l.time > ? AND l.course = ? - AND l.module = 'wiki' AND action LIKE 'edit%' - ORDER BY l.time ASC"; - - if (!$logs = $DB->get_records_sql($sql, array($timestart, $course->id))){ + if (!$pages = $DB->get_records_sql("SELECT p.*, w.id as wikiid, sw.groupid + FROM {wiki_pages} p + JOIN {wiki_subwikis} sw ON sw.id = p.subwikiid + JOIN {wiki} w ON w.id = sw.wikiid + WHERE p.timemodified > ? AND w.course = ? + ORDER BY p.timemodified ASC", array($timestart, $course->id))) { return false; } + $modinfo =& get_fast_modinfo($course); - $modinfo = get_fast_modinfo($course); $wikis = array(); - foreach ($logs as $log) { - $cm = $modinfo->instances['wiki'][$log->instance]; + $modinfo = get_fast_modinfo($course); + + foreach ($pages as $page) { + if (!isset($modinfo->instances['wiki'][$page->wikiid])) { + // not visible + continue; + } + $cm = $modinfo->instances['wiki'][$page->wikiid]; if (!$cm->uservisible) { continue; } + $context = get_context_instance(CONTEXT_MODULE, $cm->id); - /// Process log->url and rebuild it here to properly clean the pagename - MDL-15896 - $extractedpage = preg_replace('/^.*&page=/', '', $log->url); - $log->url = preg_replace('/page=.*$/', 'page='.urlencode($extractedpage), $log->url); + if (!has_capability('mod/wiki:viewpage', $context)) { + continue; + } - $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('&', '&', $log->url); + $groupmode = groups_get_activity_groupmode($cm, $course); + + if ($groupmode) { + if ($groupmode == SEPARATEGROUPS and !has_capability('mod/wiki:managewiki', $context)) { + // separate mode + if (isguestuser()) { + // shortcut + continue; + } + + if (is_null($modinfo->groups)) { + $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo + } + + if (!in_array($page->groupid, $modinfo->groups[0])) { + continue; + } + } + } + $wikis[] = $page; } + unset($pages); if (!$wikis) { return false; } - echo $OUTPUT->heading(get_string("updatedwikipages", 'wiki').':', 3); + echo $OUTPUT->heading(get_string("updatedwikipages", 'wiki') . ':', 3); foreach ($wikis as $wiki) { - print_recent_activity_note($wiki->time, $wiki, $wiki->pagename, - $CFG->wwwroot.'/mod/wiki/'.$wiki->url); + $cm = $modinfo->instances['wiki'][$wiki->wikiid]; + $link = $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $wiki->id; + print_recent_activity_note($wiki->timemodified, $wiki, $cm->name, $link, false, $viewfullnames); } - return false; + return true; // True if anything was printed, otherwise false } - -/** - * @global stdClass - * @global object - * @param string $log - * @return array - */ -function wiki_log_info($log) { - global $CFG, $DB; - return $DB->get_record_sql("SELECT u.firstname, u.lastname - FROM {user} u - WHERE u.id = ?", array($log->userid)); -} - /** * 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 object - * @return bool - */ -function wiki_cron () { - global $DB; - - // Delete expired locks - $result = $DB->delete_records_select('wiki_locks','lockedseen < '.(time()-WIKI_LOCK_PERSISTENCE)); - - return $result; -} - -/** - * Returns the users with data in one wiki - * (users with records in wiki_pages and wiki_entries) - * - * @global stdClass - * @global object - * @param int $wikiid - * @return array - */ -function wiki_get_participants($wikiid) { - - global $CFG, $DB; - - //Get users from wiki_pages - $st_pages = $DB->get_records_sql("SELECT DISTINCT u.id, u.id - FROM {user} u, {wiki_entries} e, {wiki_pages} p - WHERE e.wikiid = ? and - p.wiki = e.id and - u.id = p.userid", array($wikiid)); - - //Get users from wiki_entries - $st_entries = $DB->get_records_sql("SELECT DISTINCT u.id, u.id - FROM {user} u, {wiki_entries} e - WHERE e.wikiid = ? and - u.id = e.userid", array($wikiid)); - - //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_ - -/** - * 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. - * - * @param string $wikinane - * @return string - */ -function wiki_wiki_name($wikiname) { - - 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'); - } - } -} - -/** - * Check for correct wikiname syntax and return true or false. - * - * @param string $wikiname - * @return bool - */ -function wiki_is_wiki_name($wikiname) { - - /// 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; - } -} - -/** - * Determines the wiki's page name and returns it. - * @param object $wiki - * @return string - */ -function wiki_page_name(&$wiki) { - 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; -} - -/** - * @global stdClass - * @param object $wiki - * @return string - */ -function wiki_content_dir(&$wiki) { -/// Determines the wiki's default content directory (if there is one). + * @uses $CFG + * @return boolean + * @todo Finish documenting this function + **/ +function wiki_cron() { 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; + return true; } /** - * Returns all wikis for the specified course and optionally of the specified type. + * Must return an array of grades for a given instance of this module, + * indexed by user. It also returns a maximum allowed grade. * - * @global object - * @param int $courseid - * @param string $wtype - * @return array - */ -function wiki_get_course_wikis($courseid, $wtype='*') { - global $DB; - - $select = 'course = ?'; - $params = array($courseid); - if ($wtype != '*') { - $select .= ' AND wtype = ?'; - $params[] = $wtype; - } - return $DB->get_records_select('wiki', $select, $params, 'id'); + * Example: + * $return->grades = array of grades; + * $return->maxgrade = maximum allowed grade; + * + * return $return; + * + * @param int $wikiid ID of an instance of this module + * @return mixed Null or object with an array of grades and with the maximum grade + **/ +function wiki_grades($wikiid) { + return null; } /** - * Returns true if wiki already has wiki entries; otherwise false. - * @global object - * @param object $wiki - * @return bool - */ -function wiki_has_entries(&$wiki) { - global $DB; - - return $DB->record_exists('wiki_entries', array('wikiid'=>$wiki->id)); -} - -/** - * 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'. + * Must return an array of user records (all data) who are participants + * for a given instance of wiki. Must include every user involved + * in the instance, independient of his role (student, teacher, admin...) + * See other modules as example. * - * @global stdClass - * @global object - * @param object $wiki - * @param string $byindex - */ -function wiki_get_entries(&$wiki, $byindex=NULL) { - global $CFG, $DB; - - if ($byindex == 'student') { - return $DB->get_records('wiki_entries', array('wikiid'=>$wiki->id), '', - 'userid,id,wikiid,course,groupid,pagename,timemodified'); - } - else if ($byindex == 'group') { - return $DB->get_records('wiki_entries', array('wikiid'=>$wiki->id), '', - 'groupid,id,wikiid,course,userid,pagename,timemodified'); - } - else { - return $DB->get_records('wiki_entries', array('wikiid'=>$wiki->id)); - } -} - -/** - * 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 object - * @param object $wiki By reference - * @param object $course By reference - * @param int $userid - * @param int $groupid - * @return object - */ -function wiki_get_default_entry(&$wiki, &$course, $userid=0, $groupid=0) { - global $USER; - /// If there is a groupmode, get the user's group id. - $groupmode = groups_get_activity_groupmode($wiki); - // if groups mode is in use and no group supplied, use the first one found - if ($groupmode && !$groupid) { - $mygroupids = groups_get_all_groups($course->id, $USER->id); - if ($mygroupids) { - $mygroupids = array_keys($mygroupids); - } - if($mygroupids && count($mygroupids)>0) { - // Use first group. They ought to be able to change later - $groupid=$mygroupids[0]; - } else { - // Whatever groups are in the course, pick one - $coursegroups = groups_get_all_groups($course->id); - if(!$coursegroups || count($coursegroups)==0) { - print_error('groupmodeerror', 'wiki'); - } - $unkeyed=array_values($coursegroups); // Make sure first item is index 0 - $groupid=$unkeyed[0]->id; - } - } - - /// 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) { - print_error('cannotaddentry', 'wiki'); - } - } - } - //print_object($wiki_entry); - return $wiki_entry; -} - -/** - * 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 object - * @param object $wiki By reference - * @param object $course By reference - * @param int $userid - * @param int $groupid - * @return object - */ -function wiki_get_entry(&$wiki, &$course, $userid=0, $groupid=0) { - 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 (wiki_is_teacher($wiki, $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 = groups_get_activity_groupmode($wiki); - if($groupmode) { - if(!$groupid) { - $mygroupids = groups_get_all_groups($course->id, $USER->id); - if ($mygroupids) { - $mygroupids = array_keys($mygroupids); - } - if($mygroupids && count($mygroupids)>0) { - // Use first group. They ought to be able to change later - $groupid=$mygroupids[0]; - } else { - // Whatever groups are in the course, pick one - $coursegroups = groups_get_all_groups($course->id); - if(!$coursegroups || count($coursegroups)==0) { - print_error('groupmodeerror', 'wiki'); - } - $unkeyed=array_values($coursegroups); // Make sure first item is index 0 - $groupid=$unkeyed[0]->id; - } - } - - //echo "groupid is in wiki_get_entry ".$groupid."
          "; - /// 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 { - print_error('cannotaccessgroup', 'wiki'); - } - } - /// 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 (isset($cm->groupmode) && empty($course->groupmodeforce)) { - $groupmode = $cm->groupmode; - } else { - $groupmode = $course->groupmode; - } - - if ($groupmode) { - $mygroupids = groups_get_all_groups($course->id, $USER->id); - if ($mygroupids) { - $mygroupids = array_keys($mygroupids); - } - $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; -} - -/** - * Returns the wiki entry for the wiki teacher type. - * - * @global object - * @param object $wiki - * @param int $groupid - * @return object - */ -function wiki_get_teacher_entry(&$wiki, $groupid=0) { - global $DB; - return $DB->get_record('wiki_entries', array('wikiid'=>$wiki->id, 'course'=>$wiki->course, 'groupid'=>$groupid)); -} - -/** - * Returns the wiki entry for the given group. - * - * @global object - * @param object $wiki - * @param int $groupid - * @return object - */ -function wiki_get_group_entry(&$wiki, $groupid=null) { - global $DB; - return $DB->get_record('wiki_entries', array('wikiid'=>$wiki->id, 'groupid'=>$groupid)); -} - -/** - * Returns the wiki entry for the given student. - * - * @global object - * @global object - * @param object $wiki - * @param int $userid - * @return object - */ -function wiki_get_student_entry(&$wiki, $userid=null) { - global $USER, $DB; - - if (is_null($userid)) { - $userid = $USER->id; - } - return $DB->get_record('wiki_entries', array('wikiid'=>$wiki->id, 'userid'=>$userid)); -} - -/** - * 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 stdClass - * @global int - * @global object - * @param object $wiki - * @param object $user - * @param object $course - * @param int $currentid - * @return array - */ -function wiki_get_other_wikis(&$wiki, &$user, &$course, $currentid=0) { - global $CFG, $id, $DB, $USER; - - $wikis = false; - - $groupmode = groups_get_activity_groupmode($wiki); - $mygroupid = groups_get_all_groups($course->id, $USER->id); - if ($mygroupid) { - $mygroupid = array_keys($mygroupid); - } - $isteacher = wiki_is_teacher($wiki, $user->id); - $isteacheredit = wiki_is_teacheredit($wiki, $user->id); - - $groupingid = null; - $cm = new stdClass; - $cm->id = $wiki->cmid; - $cm->groupmode = $wiki->groupmode; - $cm->groupingid = $wiki->groupingid; - $cm->groupmembersonly = $wiki->groupmembersonly; - if (!empty($cm->groupingid)) { - $groupingid = $wiki->groupingid; - } - - - switch ($wiki->wtype) { - - case 'student': - /// Get all the existing entries for this wiki. - $wiki_entries = wiki_get_entries($wiki, 'student'); - - if (!empty($wiki->groupingid)) { - $sql = "SELECT gm.userid FROM {groups_members} gm " . - "INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid " . - "WHERE gg.groupingid = ? "; - - $groupingmembers = $DB->get_records_sql($sql, array($wiki->groupingid)); - } - - 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_users_by_capability(get_context_instance(CONTEXT_COURSE, $course->id), 'moodle/course:participate', '', '', '', '', '', '', false)) { - /// Default pagename is dependent on the wiki settings. - $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename; - - foreach ($students as $student) { - if (!empty($wiki->groupingid) && empty($groupingmembers[$student->id])) { - continue; - } - /// 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 = wiki_get_students($wiki, $mygroupid)) { - $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename; - foreach ($students as $student) { - if (!empty($wiki->groupingid) && empty($groupingmembers[$student->id])) { - continue; - } - /// 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 = wiki_get_students($wiki, $mygroupid)) { - $defpagename = empty($wiki->pagename) ? get_string('wikidefaultpagename', 'wiki') : $wiki->pagename; - foreach ($students as $student) { - if (!empty($wiki->groupingid) && empty($groupingmembers[$student->id])) { - continue; - } - /// 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. - if (!empty($wiki->groupingid)) { - $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname ' - .' FROM {wiki_entries} w ' - .' INNER JOIN {user} u ON w.userid = u.id ' - .' INNER JOIN {groups_members} gm ON gm.userid = u.id ' - .' INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid ' - .' WHERE w.wikiid = ? AND gg.groupingid = ?' - .' ORDER BY w.id'; - $params = array($wiki->id, $wiki->groupingid); - } else { - $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname ' - .' FROM {wiki_entries} w, {user} u ' - .' WHERE w.wikiid = ? AND u.id = w.userid ' - .' ORDER BY w.id'; - $params = array($wiki->id); - } - $wiki_entries = $DB->get_records_sql($sql, $params); - $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 wiki_is_teacheredit($wiki)) { - $viewall = true; - } - else if ($groupmode == SEPARATEGROUPS) { - $viewall = groups_get_all_groups($course->id, $USER->id); - if ($viewall) { - $viewall = array_keys($viewall); - } - } - else { - $viewall = false; - } - - if ($viewall !== false) { - if (!empty($wiki->groupingid)) { - $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname ' - .' FROM {wiki_entries} w ' - .' INNER JOIN {user} u ON w.userid = u.id ' - .' INNER JOIN {groups_members} gm ON gm.userid = u.id ' - .' INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid ' - .' WHERE w.wikiid = ? AND gg.groupingid = ?' - .' ORDER BY w.id'; - $params = array($wiki->id, $wiki->groupingid); - } else { - $sql = 'SELECT w.id, w.userid, w.pagename, u.firstname, u.lastname ' - .' FROM {wiki_entries} w, {user} u ' - .' WHERE w.wikiid = ? AND u.id = w.userid ' - .' ORDER BY w.id'; - $params = array($wiki->id); - } - $wiki_entries = $DB->get_records_sql($sql, $params); - $wiki_entries=is_array($wiki_entries)?$wiki_entries:array(); - foreach ($wiki_entries as $wiki_entry) { - if (!empty($wiki->groupingid) && empty($groupingmembers[$wiki_entry->userid])) { - continue; - } - - if (($viewall === true) or groups_is_member($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 = groups_get_all_groups($course->id, null, $groupingid)) { - $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 = groups_get_all_groups($course->id, $user->id, $groupingid)){ - - $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) { - if (!empty($wiki->groupingid)) { - $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname ' - .' FROM {wiki_entries} w ' - .' INNER JOIN {groups} g ON g.id = w.groupid ' - .' INNER JOIN {groupings_groups} gg ON g.id = gg.groupid ' - .' WHERE w.wikiid = ? AND gg.groupingid = ?' - .' ORDER BY w.groupid'; - $params = array($wiki->id, $wiki->groupingid); - } else { - $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname ' - .' FROM {wiki_entries} w, {groups} g ' - .' WHERE w.wikiid = ? AND g.id = w.groupid ' - .' ORDER BY w.groupid'; - $params = array($wiki->id); - } - $wiki_entries = $DB->get_records_sql($sql, $params); - $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 = groups_get_all_groups($course->id, null, $groupingid)) { - $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) { - if (!empty($wiki->groupingid)) { - $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname ' - .' FROM {wiki_entries} w ' - .' INNER JOIN {groups} g ON g.id = w.groupid ' - .' INNER JOIN {groupings_groups} gg ON g.id = gg.groupid ' - .' WHERE w.wikiid = ? AND gg.groupingid = ?' - .' ORDER BY w.groupid'; - $params = array($wiki->id, $wiki->groupingid); - } else { - $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname ' - .' FROM {wiki_entries} w, {groups} g ' - .' WHERE w.wikiid = ? AND g.id = w.groupid ' - .' ORDER BY w.groupid'; - $params = array($wiki->id); - } - $wiki_entries = $DB->get_records_sql($sql, $params); - $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) { - if (!empty($wiki->groupingid)) { - $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname ' - .' FROM {wiki_entries} w ' - .' INNER JOIN {groups} g ON g.id = w.groupid ' - .' INNER JOIN {groupings_groups} gg ON g.id = gg.groupid ' - .' WHERE w.wikiid = ? AND gg.groupingid = ?' - .' ORDER BY w.groupid'; - $params = array($wiki->id, $wiki->groupingid); - } else { - $sql = 'SELECT w.id, w.groupid, w.pagename, g.name as gname ' - .' FROM {wiki_entries} w, {groups} g ' - .' WHERE w.wikiid = ? AND g.id = w.groupid ' - .' ORDER BY w.groupid'; - $params = array($wiki->id); - } - $wiki_entries = $DB->get_records_sql($sql, $params); - $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; -} - -/** - * 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 object - * @global object - * @param object $wiki - * @param object $course - * @param int $userid - * @param int $groupid - * @return bool - */ -function wiki_add_entry(&$wiki, &$course, $userid=0, $groupid=0) { - global $USER, $DB; - - /// If this wiki already has a wiki_type entry, return false. - if (wiki_get_entry($wiki, $course, $userid, $groupid) !== false) { - return false; - } - - $wiki_entry = new Object(); - - 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 = groups_get_activity_groupmode($wiki); - - ///give the first groupid by default and try - $mygroups = groups_get_all_groups($course->id, $USER->id); - if ($mygroups) { - $mygroups = array_keys($mygroups); - } - - /// 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 = groups_get_activity_groupmode($wiki); - - /// If there is a groupmode, get the user's group id. - if ($groupmode and $groupid == 0) { - $mygroupid = groups_get_all_groups($course->id, $USER->id); - if ($mygroupid) { - $mygroupid = array_keys($mygroupid); - } - $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 = $wiki_entry->pagename; - - return $DB->insert_record("wiki_entries", $wiki_entry, true); -} - -/** - * Returns true or false if the user can add a wiki entry for this wiki. - * - * @param object $wiki By reference - * @param object $user By reference - * @param object $course By reference - * @param int $userid - * @param int $groupid - * @return bool - */ -function wiki_can_add_entry(&$wiki, &$user, &$course, $userid=0, $groupid=0) { - global $USER; - /// Get the groupmode. It's been added to the wiki object. - $groupmode = groups_get_activity_groupmode($wiki); - $mygroupid = groups_get_all_groups($course->id, $USER->id); - if ($mygroupid) { - $mygroupid = array_keys($mygroupid); - } - - 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 (wiki_is_student($wiki, $user->id) or wiki_is_student($wiki, $user->id)); - } -/// 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 wiki_is_student($wiki, $user->id)) or wiki_is_teacheredit($wiki) or - (wiki_is_teacher($wiki) and (!$groupmode or $mygroupid == 0 or (groups_is_member($mygroupid, $userid))))); - } - break; - - case 'group': - /// If mode is 'nogroups', then all participants can add wikis. - if (wiki_is_teacheredit($wiki, $user->id)) { - return true; - } - - if (!$groupmode) { - return (wiki_is_student($wiki, $user->id) or wiki_is_teacher($wiki, $user->id)); - } - /// 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 (wiki_is_teacheredit($wiki) or - (wiki_is_teacher($wiki) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))) or - (wiki_is_student($wiki, $user->id) and @in_array($groupid, $mygroupid)) - ); - } - break; - - case 'teacher': - /// If mode is 'nogroups', then all teachers can add wikis. - if (!$groupmode) { - return wiki_is_teacher($wiki, $user->id); - } - /// If not requesting a group, must be a member of a group. - else if ($groupid == 0) { - return ($mygroupid != 0 and wiki_is_teacher($wiki)); - } - /// 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 (wiki_is_teacheredit($wiki) or - (wiki_is_teacher($wiki) and ($mygroupid == 0 or @in_array($groupid, $mygroupid))) or - (wiki_is_student($wiki, $user->id) and @in_array($groupid, $mygroupid)) - ); - } - break; - } - + * @param int $wikiid ID of an instance of this module + * @return mixed boolean/array of students + **/ +function wiki_get_participants($wikiid) { return false; } /** - * Returns true or false if the user can edit this wiki entry. + * This function returns if a scale is being used by one wiki + * it it has support for grading and scales. Commented code should be + * modified if necessary. See forum, glossary or journal modules + * as reference. * - * @param object $wiki_entry by reference - * @param object $wiki by reference - * @param object $user by reference - * @param object $course by reference - * @return bool - */ -function wiki_can_edit_entry(&$wiki_entry, &$wiki, &$user, &$course) { + * @param int $wikiid ID of an instance of this module + * @return mixed + * @todo Finish documenting this function + **/ +function wiki_scale_used($wikiid, $scaleid) { + $return = false; - $can_edit = false; - $groupmode = groups_get_activity_groupmode($wiki); - $mygroupid = groups_get_all_groups($course->id, $USER->id); - if ($mygroupid) { - $mygroupid = array_keys($mygroupid); - } + //$rec = get_record("wiki","id","$wikiid","scale","-$scaleid"); + // + //if (!empty($rec) && !empty($scaleid)) { + // $return = true; + //} - /// 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 (wiki_is_teacheredit($wiki, $user->id) or - ((!$groupmode or $mygroupid == 0) and wiki_is_teacher($wiki, $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 wiki_is_teacher($wiki, $user->id) and - groups_is_member($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 = groups_is_member($wiki_entry->groupid, $user->id); - } - /// If mode is 'nogroups', then all participants can edit the wiki. - else { - $can_edit = (wiki_is_student($wiki, $user->id) or wiki_is_teacher($wiki, $user->id)); - } - 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 = (wiki_is_teacher($wiki, $user->id) and groups_is_member($wiki_entry->groupid, $user->id)); - } - else { - $can_edit = wiki_is_teacher($wiki, $user->id); - } - break; - } - } - return $can_edit; + return $return; } /** - * @global object - * @param object $wiki by reference - * @param int $userid - * @param object $course - * @return bool + * Checks if scale is being used by any instance of wiki. + * This function was added in 1.9 + * + * This is used to find out if scale used anywhere + * @param $scaleid int + * @return boolean True if the scale is used by any wiki */ -function wiki_user_can_access_student_wiki(&$wiki, $userid, &$course) { - global $USER; - - /// Get the groupmode. It's been added to the wiki object. - $groupmode = groups_get_activity_groupmode($wiki); - $usersgroup = groups_get_all_groups($course->id, $USER->id); - if ($usersgroup) { - $usersgroup = array_keys($usersgroup); - } - $isteacher = wiki_is_teacher($wiki, $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 groups_is_member($usersgroup, $userid)) or - (wiki_is_teacheredit($wiki, $USER->id)) or - (wiki_is_teacher($wiki, $USER->id) and (!$usersgroup or $groupmode == NOGROUPS))) { - $can_access = true; - } - else { - $can_access = false; - } - return $can_access; -} - -/** - * @global object - * @param object $wiki by reference - * @param int $groupid - * @param object $course - * @return bool - */ -function wiki_user_can_access_group_wiki(&$wiki, $groupid, &$course) { - global $USER; - - /// Get the groupmode. It's been added to the wiki object. - $groupmode = groups_get_activity_groupmode($wiki); - $usersgroup = groups_get_all_groups($course->id, $USER->id); - if ($usersgroup) { - $usersgroup = array_keys($usersgroup); - } - $isteacher = wiki_is_teacher($wiki, $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 - (wiki_is_teacheredit($wiki, $USER->id)) or - (wiki_is_teacher($wiki, $USER->id) and !$usersgroup)) { - $can_access = true; - } - else { - $can_access = false; - } - return $can_access; -} - -/** - * @global object - * @param object $wiki by reference - * @param int $groupid - * @param object $course by reference - * @return bool - */ -function wiki_user_can_access_teacher_wiki(&$wiki, $groupid, &$course) { - global $USER; - - /// Get the groupmode. It's been added to the wiki object. - $groupmode = groups_get_activity_groupmode($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, - - $mygroupids = groups_get_all_groups($course->id, $USER->id); - if ($mygroupids) { - $mygroupids = array_keys($mygroupids); - } - - if (($groupmode == NOGROUPS) or ($groupmode == VISIBLEGROUPS) or - (($groupmode == SEPARATEGROUPS) and (@in_array($groupid, $mygroupids)/*mygroupid($course->id) == $groupid*/)) or - (wiki_is_teacher($wiki, $USER->id))){ - $can_access = true; - } - else { - $can_access = false; - } - return $can_access; -} - -/** - * @global object - * @param object $wiki_entry by reference - * @return string - */ -function wiki_get_owner(&$wiki_entry) { +function wiki_scale_used_anywhere($scaleid) { global $DB; - if ($wiki_entry->userid > 0) { - $user = $DB->get_record('user', array('id'=>$wiki_entry->userid)); - $owner = fullname($user); + if ($scaleid and $DB->record_exists('wiki', array('grade', $scaleid))) { + return true; + } else { + return false; } - else if ($wiki_entry->groupid > 0) { - $owner = groups_get_group_name($wiki_entry->groupid); //TODO:check. - } - else if ($wiki_entry->course > 0) { - $course = $DB->get_record('course', array('id'=>$wiki_entry->course)); - $owner = $course->shortname; - } - else { - $owner = '- '.get_string("ownerunknown","wiki").' -'; - } - return $owner; } /** - * @todo Add Group and User !!! + * Pluginfile hook * - * @global stdClass - * @param int $cmid - * @param string $search - * @param int $userid - * @param int $groupid - * @param bool $return - * @return string + * @author Josep Arus */ -function wiki_print_search_form($cmid, $search="", $userid, $groupid, $return=false) { +function wiki_pluginfile($course, $cminfo, $context, $filearea, $args, $forcedownload) { global $CFG; - # TODO: Add Group and User !!! - $output = "
          wwwroot/mod/wiki/view.php\">"; - $output .="
          "; - $output .= ""; - $output .= ""; - $output .= ""; - $output = $output.($groupid?"":""); - $output = $output.($userid?"":""); - $output .= "".' '; - $output .= ""; - $output .= ""; - $output .= "
          "; - $output .= "
          "; - if ($return) { - return $output; + require_once($CFG->dirroot . "/mod/wiki/locallib.php"); + + if ($filearea == "wiki_attachments") { + $pageid = (int) array_shift($args); + + // Checking page instance + if (!$page = wiki_get_page($pageid)) { + return false; + } + + require_course_login($course->id, true, $cm); + + require_capability('mod/wiki:viewpage', $context); + + $relativepath = '/' . implode('/', $args); + + $fullpath = $context->id . 'wiki_attachments' . $pageid . $relativepath; + + $fs = get_file_storage(); + if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) { + return false; + } + + $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400; + + send_stored_file($file, $lifetime, 0); } - echo $output; } +function wiki_search_form($cm, $search='') { + global $CFG, $OUTPUT; -/** - * Prints a link-list of special wiki-pages - * - * @global object - * @global string - * @param int $cmid - * @param bool $binary - * @param bool $return - */ -function wiki_print_wikilinks_block($cmid, $binary=false, $return=false) { - global $CFG, $ewiki_title, $OUTPUT; + $output = '
          '; + $output .= '
          '; + $output .= '
          '; + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ' '; + $output .= '
          '; + $output .= '
          '; + $output .= '
          '; - $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"); - } - - $name = null; - if (preg_match('/([a-zA-Z0-9\-_]*)=$/', EWIKI_SCRIPT, $matches)) { - $name = $matches[1]; - } - - echo $OUTPUT->single_select(new moodle_url(EWIKI_SCRIPT), $name, $links, null, array(''=>get_string("choosewikilinks", "wiki")), 'wikilinks'); + return $output; } - -/** - * Displays actions which can be performed on the page - * @param int $cmit - * @param array $specialpages - * @param array $page - * @param string $action - * @param bool $binary - * @param bool $canedit - */ -function wiki_print_page_actions($cmid, $specialpages, $page, $action, $binary=false, $canedit=true) { - - $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"); - } - - $name = null; - if (preg_match('/([a-zA-Z0-9\-_]*)=$/', EWIKI_SCRIPT, $matches)) { - $name = $matches[1]; +function wiki_extend_navigation(navigation_node $navref, $course, $module, $cm) { + global $PAGE, $USER; + $url = $PAGE->url; + $userid = 0; + if ($module->wikimode == 'individual') { + $userid = $USER->id; } - echo $OUTPUT->single_select(new moodle_url(EWIKI_SCRIPT), $name, $page, null, array(''=>get_string("action", "wiki")), 'wikiactions'); -} - -/** - * Displays actions which can be performed on the page - * - * @param object $wiki - * @param int $cmid - * @param int $userid - * @param int $groupid - * @param object $page - * @param bool $noeditor - * @param object $course - */ -function wiki_print_administration_actions($wiki, $cmid, $userid, $groupid, $page, $noeditor, $course) { - global $OUTPUT; - /// Create the URL - $ewscript = 'admin.php?id='.$cmid; - if (isset($userid) && $userid!=0) $ewscript .= '&userid='.$userid; - if (isset($groupid) && $groupid!=0) $ewscript .= '&groupid='.$groupid; - if (isset($page)) $ewscript .= '&page='.$page; - - - /// Build that action array according to wiki flags. - $action = array(); - $isteacher = wiki_is_teacher($wiki); - - 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(!$wiki = wiki_get_wiki($cm->instance)) { + return false; } - if($noeditor) { - $action["checklinks"]=get_string("checklinks", "wiki"); - } - echo $OUTPUT->single_select(new moodle_url($ewscript), 'action', $action, null, array(''=>get_string("chooseadministration", "wiki")), 'wikiadministration'); -} - -/** - * @uses EWIKI_DB_F_TEXT - * @uses EWIKI_DB_F_BINARY - * @uses EWIKI_DB_F_DISABLED - * @uses EWIKI_DB_F_HTML - * @uses EWIKI_DB_F_READONLY - * @uses EWIKI_DB_F_WRITEABLE - * @return array - */ -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 - -/** - * @param bool $pageflagstatus - * @return object - */ -function wiki_admin_setpageflags_list($pageflagstatus) { - $FD = wiki_admin_get_flagarray(); - $table = new html_table(); - $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 .= ''; + $gid = groups_get_activity_group($cm); + if (!$subwiki = wiki_get_subwiki_by_group($cm->instance, $gid, $userid)){ + return null; } else { - $cell_pagename .= ''; + $swid = $subwiki->id; } - $cell_pagename .= s($id) . ' / '.get_string("version","wiki").": ".$row["version"]; - foreach ($FD as $n=>$str) { - $cell_flags .=''.$str. ' '; + $pageid = $url->param('pageid'); + $cmid = $url->param('id'); + if (empty($pageid) && !empty($cmid)) { + // wiki main page + $page = wiki_get_page_by_title($swid, $wiki->firstpagetitle); + $pageid = $page->id; } - if($pageflagstatus) { - $table->data[]=array($cell_pagename, $cell_flags, $pageflagstatus[$id]); - } else { - $table->data[]=array($cell_pagename, $cell_flags); - } - } - return $table; -} + $link = new moodle_url('/mod/wiki/create.php', array('action'=>'new', 'swid'=>$swid)); + $node = $navref->add(get_string('newpage', 'wiki'), $link, navigation_node::TYPE_SETTING); -/** - * @param array $pageflags - * @return array Status array - */ -function wiki_admin_setpageflags($pageflags) { - $FD = wiki_admin_get_flagarray(); + if (is_numeric($pageid)) { - $status=array(); - if($pageflags) { - foreach($pageflags as $page=>$fa) { + $link = new moodle_url('/mod/wiki/view.php', array('pageid'=>$pageid)); + $node = $navref->add(get_string('view', 'wiki'), $link, navigation_node::TYPE_SETTING); - $page = rawurldecode($page); + $link = new moodle_url('/mod/wiki/edit.php', array('pageid'=>$pageid)); + $node = $navref->add(get_string('edit', 'wiki'), $link, navigation_node::TYPE_SETTING); - $flags = 0; - $fstr = ""; - foreach($fa as $num=>$isset) { - if ($isset) { - $flags += $num; - $fstr .= ($fstr?",":""). $FD[$num]; - } - } + $link = new moodle_url('/mod/wiki/comments.php', array('pageid'=>$pageid)); + $node = $navref->add(get_string('comments', 'wiki'), $link, navigation_node::TYPE_SETTING); - #$status[$page] .= "{$flags}=[{$fstr}]"; + $link = new moodle_url('/mod/wiki/history.php', array('pageid'=>$pageid)); + $node = $navref->add(get_string('history', 'wiki'), $link, navigation_node::TYPE_SETTING); - $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] = "".get_string("flagsset","wiki")." ".$status[$page]; - } - } - } - return $status; -} - -/** - * @param bool $listall - * @return object - */ -function wiki_admin_remove_list($listall="") { - /// Table header - $table = new html_table(); - $table->head = array(" ", 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")."
          "; - } - } - while ($page = $result->get()) { - $id = $page["id"]; - $page = ewiki_database("GET", array("id"=>$id)); - $flags = $page["flags"]; - #print "$id ".strlen(trim(($page["content"])))."
          "; - - if (!strlen(trim(($page["content"]))) && !($flags & EWIKI_DB_F_BINARY)) { - @$selected[$id] .= get_string("emptypage","wiki")."
          "; - } - - // 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
          "; - } - } - - /// Some more reasons for Deletion... - if ($orphanedpage && $id!=EWIKI_PAGE_INDEX &&!($flags & EWIKI_DB_F_BINARY)) { - @$selected[$id] .= get_string("orphanedpage","wiki")."
          "; - } - - if ($flags & EWIKI_DB_F_DISABLED) { - @$selected[$id] .= get_string("disabledpage","wiki")."
          "; - } - - if (($flags & 3) == 3) { - @$selected[$id] .= get_string("errorbinandtxt","wiki")."
          "; - } - - if (!($flags & 3)) { - @$selected[$id] .= get_string("errornotype","wiki")."
          "; - } - - if ($flags & EWIKI_DB_F_HTML) { - @$selected[$id] .= get_string("errorhtml","wiki")."
          "; - } - - if (($flags & EWIKI_DB_F_READONLY) && !($flags & EWIKI_DB_F_BINARY)) { - @$selected[$id] .= get_string("readonly","wiki")."
          "; - } - - if (($flags & EWIKI_DB_F_READONLY) && ($flags & EWIKI_DB_F_WRITEABLE)) { - @$selected[$id] .= get_string("errorroandwr","wiki")."
          "; - } - - if (strlen($page["content"]) >= 65536) { - @$selected[$id] .= get_string("errorsize","wiki")."
          "; - } - - if (strpos($page["refs"], "\n".get_string("deletemewikiword","wiki")."\n")!==false) { - @$selected[$id] .= get_string("deletemewikiwordfound","wiki",get_string("deletemewikiword","wiki"))."
          "; - } - } - - foreach ($selected as $id => $reason) { - $table_checkbox=''; - - #-- link & id - if (strpos($id, EWIKI_IDF_INTERNAL) === false) { - $table_page=''; - } else { - $table_page=''; - } - $table_page .= s($id) . ''; - - #-- print reason - $table_reason=$reason; - - $table->data[]=array($table_checkbox, $table_page, $table_reason); - } - - return $table; -} - -/** - * This function actually removes the pages - * @param array $pagestodelete - * @param object $course - * @param object $wiki - * @param int $userid - * @param int $groupid - * @return string - */ -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; -} - -/** - * @param array $pagestostrip - * @param string $version - * @param string $err - * @return object - */ -function wiki_admin_strip_list($pagestostrip="",$version="",$err="") { - /// Table header - $table = new html_table(); - $table->head = array(" ", 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=\"checked\""; - } - if($version=="") { - $versiondefault="1-".($row["version"]-1); - } else { - $versiondefault=$version[$i]; - } - $table->data[]=array('', - ''.s($id).' / '.get_string("version","wiki").": ".$row["version"], - ''.$error); - - } - $i++; - } - return $table; -} - -/** - * @param array $pagestostrip - * @param string $version - * @param string $err - * @return array - */ -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; -} - -/** - * @param array $pagestostrip - */ -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)); - } - } -} - -/** - * @return array - */ -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; -} - -/** - * Checks http:// Links - * @return string - */ -function wiki_admin_checklinks($pagetocheck) { - $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")."

          "; - } 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
          \n"; - $badlinks[] = $href; - } else { - $ret.="[".get_string("linkok","wiki")."] $href
          \n"; - } - } - } - - /// Remove old Notices - $content = preg_replace('/ µµ__~\['.get_string("offline","wiki").'\]__µµ /i','', $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; -} - -/** - * @param bool $proceed - * @param string $authorfieldpattern - * @param int $changesfield - * @param string $howtooperate - * @param int $deleteversions - * @return string - */ -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 .= ")
          "; - break; - } - } #-- for($ver) - } #-- while($row) - return $ret; -} - - -/** - * @return array - */ -function wiki_get_view_actions() { - return array('view','view all'); -} - -/** - * @return array - */ -function wiki_get_post_actions() { - return array('hack'); -} - - -/** - * Obtains an editing lock on a wiki page. - * - * @global object - * @global object - * @param int $wikiid ID of wiki object. - * @param string $pagename Name of page. - * @return array Two-element array with a boolean true (if lock has been obtained) - * or false (if lock was held by somebody else). If lock was held by someone else, - * the values of the wiki_locks entry are held in the second element; if lock was - * held by current user then the the second element has a member ->id only. - */ -function wiki_obtain_lock($wikiid,$pagename) { - global $USER, $DB; - - // Check for lock - $alreadyownlock=false; - if($lock=$DB->get_record('wiki_locks', array('pagename'=>$pagename,'wikiid'=>$wikiid))) { - // Consider the page locked if the lock has been confirmed within WIKI_LOCK_PERSISTENCE seconds - if($lock->lockedby==$USER->id) { - // Cool, it's our lock, do nothing except remember it in session - $lockid=$lock->id; - $alreadyownlock=true; - } else if(time()-$lock->lockedseen < WIKI_LOCK_PERSISTENCE) { - return array(false,$lock); - } else { - // Not locked any more. Get rid of the old lock record. - $DB->delete_records('wiki_locks', array('pagename'=>$pagename,'wikiid'=>$wikiid)); - } - } - - // Add lock - if(!$alreadyownlock) { - // Lock page - $newlock=new stdClass; - $newlock->lockedby=$USER->id; - $newlock->lockedsince=time(); - $newlock->lockedseen=$newlock->lockedsince; - $newlock->wikiid=$wikiid; - $newlock->pagename=$pagename; - $lockid = $DB->insert_record('wiki_locks',$newlock); - } - - // Store lock information in session so we can clear it later - if(!array_key_exists(SESSION_WIKI_LOCKS,$_SESSION)) { - $_SESSION[SESSION_WIKI_LOCKS]=array(); - } - $_SESSION[SESSION_WIKI_LOCKS][$wikiid.'_'.$pagename]=$lockid; - $lockdata=new StdClass; - $lockdata->id=$lockid; - return array(true,$lockdata); -} - -/** - * If the user has an editing lock, releases it. Has no effect otherwise. - * Note that it doesn't matter if this isn't called (as happens if their - * browser crashes or something) since locks time out anyway. This is just - * to avoid confusion of the 'what? it says I'm editing that page but I'm - * not, I just saved it!' variety. - * - * @global object - * @param int $wikiid ID of wiki object. - * @param string $pagename Name of page. - */ -function wiki_release_lock($wikiid,$pagename) { - global $DB; - - if(!array_key_exists(SESSION_WIKI_LOCKS,$_SESSION)) { - // No locks at all in session - return; - } - - $key=$wikiid.'_'.$pagename; - - if(array_key_exists($key,$_SESSION[SESSION_WIKI_LOCKS])) { - $lockid=$_SESSION[SESSION_WIKI_LOCKS][$key]; - unset($_SESSION[SESSION_WIKI_LOCKS][$key]); - $DB->delete_records('wiki_locks', array('id'=>$lockid)); - } -} - -/** - * Returns all other caps used in module - * - * @return array - */ -function wiki_get_extra_capabilities() { - return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames'); -} - -/** - * @uses FEATURE_GROUPS - * @uses FEATURE_GROUPINGS - * @uses FEATURE_GROUPMEMBERSONLY - * @uses FEATURE_MOD_INTRO - * @uses FEATURE_COMPLETION_TRACKS_VIEWS - * @uses FEATURE_GRADE_HAS_GRADE - * @uses FEATURE_GRADE_OUTCOMES - * @param string $feature FEATURE_xx constant for requested feature - * @return mixed True if module supports feature, null if doesn't know - */ -function wiki_supports($feature) { - switch($feature) { - case FEATURE_GROUPS: return true; - case FEATURE_GROUPINGS: return true; - case FEATURE_GROUPMEMBERSONLY: return true; - case FEATURE_MOD_INTRO: return true; - case FEATURE_COMPLETION_TRACKS_VIEWS: return true; - case FEATURE_GRADE_HAS_GRADE: return false; - case FEATURE_GRADE_OUTCOMES: return true; - - default: return null; + $link = new moodle_url('/mod/wiki/map.php', array('pageid'=>$pageid)); + $node = $navref->add(get_string('map', 'wiki'), $link, navigation_node::TYPE_SETTING); } + + //if ($page = wiki_get_first_page($swid, $module)) { + //$node = $navref->add(get_string('pageindex', 'wiki')); + //$link = new moodle_url('/mod/wiki/view.php', array('pageid'=>$page->id)); + //$icon = new pix_icon('f/odt', ''); + //$parent = $node->add($page->title, $link, null, null, "index_$page->id", $icon); + //$keys = array(); + //wiki_build_tree($page, $parent, $keys); + //} } diff --git a/mod/wiki/locallib.php b/mod/wiki/locallib.php new file mode 100644 index 00000000000..ebb53d472bc --- /dev/null +++ b/mod/wiki/locallib.php @@ -0,0 +1,1378 @@ +. + +/** + * This contains functions and classes that will be used by scripts in wiki module + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Daniel Serrano + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/parser/parser.php'); + +define('WIKI_REFRESH_CACHE_TIME', 30); // @TODO: To be deleted. +define('FORMAT_CREOLE', '37'); +define('FORMAT_NWIKI', '38'); +define('NO_VALID_RATE', '-999'); +define('IMPROVEMENT', '+'); +define('EQUAL', '='); +define('WORST', '-'); + +define('LOCK_TIMEOUT', 30); + +/** + * Get a wiki instance + * @param int $wikiid the instance id of wiki + */ +function wiki_get_wiki($wikiid) { + global $DB; + + return $DB->get_record('wiki', array('id' => $wikiid)); +} + +/** + * Get sub wiki instances with same wiki id + * @param int $wikiid + */ +function wiki_get_subwikis($wikiid) { + global $DB; + return $DB->get_records('wiki_subwikis', array('wikiid' => $wikiid)); +} + +/** + * Get a sub wiki instance by wiki id and group id + * @param int $wikiid + * @param int $groupid + * @return object + */ +function wiki_get_subwiki_by_group($wikiid, $groupid, $userid = 0) { + global $DB; + return $DB->get_record('wiki_subwikis', array('wikiid' => $wikiid, 'groupid' => $groupid, 'userid' => $userid)); +} + +/** + * Get a sub wiki instace by instance id + * @param int $subwikiid + * @return object + */ +function wiki_get_subwiki($subwikiid) { + global $DB; + return $DB->get_record('wiki_subwikis', array('id' => $subwikiid)); + +} + +/** + * Add a new sub wiki instance + * @param int $wikiid + * @param int $groupid + * @return int $insertid + */ +function wiki_add_subwiki($wikiid, $groupid, $userid = 0) { + global $DB; + + $record = new StdClass(); + $record->wikiid = $wikiid; + $record->groupid = $groupid; + $record->userid = $userid; + + $insertid = $DB->insert_record('wiki_subwikis', $record); + return $insertid; +} + +/** + * Get a wiki instance by pageid + * @param int $pageid + * @return object + */ +function wiki_get_wiki_from_pageid($pageid) { + global $DB; + + $sql = 'SELECT w.* ' . + 'FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p ' . + 'WHERE p.id = ? AND ' . + 'p.subwikiid = s.id AND ' . + 's.wikiid = w.id'; + + return $DB->get_record_sql($sql, array($pageid)); +} + +/** + * Get a wiki page by pageid + * @param int $pageid + * @return object + */ +function wiki_get_page($pageid) { + global $DB; + return $DB->get_record('wiki_pages', array('id' => $pageid)); +} + +/** + * Get latest version of wiki page + * @param int $pageid + * @return object + */ +function wiki_get_current_version($pageid) { + global $DB; + + $sql = 'SELECT * ' . + 'FROM {wiki_versions} ' . + 'WHERE pageid = ? ' . + 'ORDER BY version DESC ' . + 'LIMIT 1'; + return $DB->get_record_sql($sql, array($pageid)); + +} + +/** + * Alias of wiki_get_current_version + * @TODO, does the exactly same thing as wiki_get_current_version, should be removed + * @param int $pageid + * @return object + */ +function wiki_get_last_version($pageid) { + return wiki_get_current_version($pageid); +} + +/** + * Get page section + * @param int $pageid + * @param string $section + */ +function wiki_get_section_page($page, $section) { + + $version = wiki_get_current_version($page->id); + return wiki_parser_proxy::get_section($version->content, $version->contentformat, $section); +} + +/** + * Get a wiki page by page title + * @param int $swid, sub wiki id + * @param string $title + * @return object + */ +function wiki_get_page_by_title($swid, $title) { + global $DB; + return $DB->get_record('wiki_pages', array('subwikiid' => $swid, 'title' => $title)); +} + +/** + * Get a version record by record id + * @param int $versionid, the version id + * @return object + */ +function wiki_get_version($versionid) { + global $DB; + return $DB->get_record('wiki_versions', array('id' => $versionid)); +} + +/** + * Get first page of wiki instace + * @param int $subwikiid + * @param int $module, wiki instance object + */ +function wiki_get_first_page($subwikid, $module=null) { + global $DB, $USER; + // TODO: + // not sure if we should use current userid + + $extra = ''; + if ($module && $module->wikimode == 'individual') { + $extra = ' AND p.userid='.$USER->id; + } + + $sql = 'SELECT p.* ' . + 'FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p ' . + 'WHERE s.id = ? AND ' . + 's.wikiid = w.id AND ' . + 'w.firstpagetitle = p.title AND ' . + 'p.subwikiid = s.id'; + $sql .= $extra; + + return $DB->get_record_sql($sql, array($subwikid)); +} + +function wiki_save_section($wikipage, $sectiontitle, $sectioncontent, $userid) { + + $wiki = wiki_get_wiki_from_pageid($wikipage->id); + $cm = get_coursemodule_from_instance('wiki', $wiki->id); + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + if (has_capability('mod/wiki:editpage', $context)) { + $version = wiki_get_current_version($wikipage->id); + $content = wiki_parser_proxy::get_section($version->content, $version->contentformat, $sectiontitle, true); + + $newcontent = $content[0] . $sectioncontent . $content[2]; + + return wiki_save_page($wikipage, $newcontent, $userid); + } else { + return false; + } +} + +/** + * Save page content + * @param object $wikipage + * @param string $newcontent + * @param int $userid + */ +function wiki_save_page($wikipage, $newcontent, $userid) { + global $DB; + + $wiki = wiki_get_wiki_from_pageid($wikipage->id); + $cm = get_coursemodule_from_instance('wiki', $wiki->id); + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + if (has_capability('mod/wiki:editpage', $context)) { + $version = wiki_get_current_version($wikipage->id); + + $version->content = $newcontent; + $version->userid = $userid; + $version->version++; + $version->timecreated = time(); + if (!$versionid = $DB->insert_record('wiki_versions', $version)) { + return false; + } + + $wikipage->timemodified = $version->timecreated; + $wikipage->userid = $userid; + $return = wiki_refresh_cachedcontent($wikipage, $newcontent); + + return $return; + } else { + return false; + } +} + +function wiki_refresh_cachedcontent($page, $newcontent = null) { + global $DB; + + $version = wiki_get_current_version($page->id); + if (!isset($newcontent)) { + $newcontent = $version->content; + } + + $options = array('swid' => $page->subwikiid, 'pageid' => $page->id); + $parseroutput = wiki_parse_content($version->contentformat, $newcontent, $options); + $page->cachedcontent = $parseroutput['toc'] . $parseroutput['parsed_text']; + $page->timerendered = time(); + $DB->update_record('wiki_pages', $page); + + wiki_refresh_page_links($page, $parseroutput['link_count']); + + return array('page' => $page, 'sections' => $parseroutput['repeated_sections'], 'version' => $version->version); +} +/** + * Restore a page + */ +function wiki_restore_page($wikipage, $newcontent, $userid) { + $return = wiki_save_page($wikipage, $newcontent, $userid); + return $return['page']; +} + +function wiki_refresh_page_links($page, $links) { + global $DB; + + $DB->delete_records('wiki_links', array('frompageid' => $page->id)); + foreach ($links as $linkname => $linkinfo) { + + $newlink = new stdClass(); + $newlink->subwikiid = $page->subwikiid; + $newlink->frompageid = $page->id; + + if ($linkinfo['new']) { + $newlink->tomissingpage = $linkname; + } else { + $newlink->topageid = $linkinfo['pageid']; + } + + $DB->insert_record('wiki_links', $newlink); + + } +} + +/** + * Create a new wiki page, if the page exists, return existing pageid + * @param int $swid + * @param string $title + * @param string $format + * @param int $userid + */ +function wiki_create_page($swid, $title, $format, $userid) { + global $DB; + // if page exists + if ($page = wiki_get_page_by_title($swid, $title)) { + return $page->id; + } + + // Creating a new empty version + $version = new stdClass(); + $version->content = ''; + $version->contentformat = $format; + $version->version = 0; + $version->timecreated = time(); + $version->userid = $userid; + + $versionid = null; + if (!$versionid = $DB->insert_record('wiki_versions', $version)) { + return false; + } + + // Createing a new empty page + $page = new stdClass(); + $page->subwikiid = $swid; + $page->title = $title; + $page->cachedcontent = ''; + $page->timecreated = $version->timecreated; + $page->timemodified = $version->timecreated; + $page->timerendered = $version->timecreated; + $page->userid = $userid; + $page->pageviews = 0; + $page->readonly = 0; + + $pageid = $DB->insert_record('wiki_pages', $page); + + // Setting the pageid + $version->id = $versionid; + $version->pageid = $pageid; + $DB->update_record('wiki_versions', $version); + + wiki_make_cache_expire($page->title); + return $pageid; +} + +function wiki_make_cache_expire($pagename) { + global $DB; + + $sql = 'UPDATE {wiki_pages} ' . + 'SET timerendered = 0 ' . + 'WHERE id IN ( SELECT l.frompageid ' . + ' FROM {wiki_links} l ' . + ' WHERE l.tomissingpage = ?' . + ')'; + $DB->execute ($sql, array($pagename)); +} + +/** + * Get a specific version of page + * @param int $pageid + * @param int $version + */ +function wiki_get_wiki_page_version($pageid, $version) { + global $DB; + return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'version' => $version)); +} + +/** + * Get version list + * @param int $pageid + * @param int $limitfrom + * @param int $limitnum + */ +function wiki_get_wiki_page_versions($pageid, $limitfrom, $limitnum) { + global $DB; + return $DB->get_records('wiki_versions', array('pageid' => $pageid), 'version DESC', '*', $limitfrom, $limitnum); +} + +/** + * Count the number of page version + * @param int $pageid + */ +function wiki_count_wiki_page_versions($pageid) { + global $DB; + return $DB->count_records('wiki_versions', array('pageid' => $pageid)); +} + +/** + * Get linked from page + * @param int $pageid + */ +function wiki_get_linked_to_pages($pageid) { + global $DB; + return $DB->get_records('wiki_links', array('frompageid' => $pageid)); +} + +/** + * Get linked from page + * @param int $pageid + */ +function wiki_get_linked_from_pages($pageid) { + global $DB; + return $DB->get_records('wiki_links', array('topageid' => $pageid)); +} + +/** + * Get pages which user have been edited + * @param int $swid + * @param int $userid + */ +function wiki_get_contributions($swid, $userid) { + global $DB; + + $sql = 'SELECT v.* ' . + 'FROM {wiki_versions} v, {wiki_pages} p ' . + 'WHERE p.subwikiid = ? AND ' . + 'v.pageid = p.id AND ' . + 'v.userid = ?'; + + return $DB->get_records_sql($sql, array($swid, $userid)); +} + +/** + * Get missing or empty pages in wiki + * @param int $swid sub wiki id + */ +function wiki_get_missing_or_empty_pages($swid) { + global $DB; + + $sql = 'SELECT DISTINCT p.title, p.id, p.subwikiid ' . + 'FROM {wiki} w, {wiki_subwikis} s, {wiki_pages} p ' . + 'WHERE s.wikiid = w.id and ' . + 's.id = ? and ' . + 'w.firstpagetitle != p.title and ' . + 'p.subwikiid = ? and ' . + '1 = (SELECT count(*) ' . + ' FROM {wiki_versions} v ' . + ' WHERE v.pageid = p.id) ' . + 'UNION ' . + 'SELECT DISTINCT l.tomissingpage as title, 0 as id, l.subwikiid ' . + 'FROM {wiki_links} l ' . + 'WHERE l.subwikiid = ? and ' . + 'l.topageid = 0'; + + return $DB->get_records_sql($sql, array($swid, $swid, $swid)); +} + +/** + * Get pages list in wiki + * @param int $swid sub wiki id + */ +function wiki_get_page_list($swid) { + global $DB; + $records = $DB->get_records('wiki_pages', array('subwikiid' => $swid), 'title ASC'); + return $records; +} + +/** + * Return a list of orphaned wikis for one specific subwiki + * @global object + * @param int $swid sub wiki id + */ +function wiki_get_orphaned_pages($swid) { + global $DB; + + // @TODO: FIX this query + $sql = 'SELECT p.id, p.title ' . + 'FROM {wiki_pages} p, {wiki} w , {wiki_subwikis} s ' . + 'WHERE p.subwikiid = ? ' . + 'AND s.id = ' . $swid . ' ' . + 'AND w.id = s.wikiid ' . + 'AND p.title != w.firstpagetitle ' . + 'AND p.id NOT IN (SELECT topageid FROM {wiki_links} WHERE subwikiid = ?);'; + + return $DB->get_records_sql($sql, array($swid, $swid)); +} + +/** + * Search wiki title + * @param int $swid sub wiki id + * @param string $search + */ +function wiki_search_title($swid, $search) { + global $DB; + return $DB->get_records_select('wiki_pages', "subwikiid=$swid AND title LIKE '%$search%'"); +} + +/** + * Search wiki content + * @param int $swid sub wiki id + * @param string $search + */ +function wiki_search_content($swid, $search) { + global $DB; + return $DB->get_records_select('wiki_pages', "subwikiid=$swid AND cachedcontent LIKE '%$search%'"); +} + +/** + * Search wiki title and content + * @param int $swid sub wiki id + * @param string $search + */ +function wiki_search_all($swid, $search) { + global $DB; + return $DB->get_records_select('wiki_pages', "subwikiid=$swid AND (cachedcontent LIKE '%$search%' OR title LIKE '%$search%')"); +} + +/** + * Get complete set of user data + */ +function wiki_get_user_info($userid) { + return get_complete_user_data('id', $userid); +} + +/** + * Increase page view nubmer + * @param int $page, database record + */ +function wiki_increment_pageviews($page) { + global $DB; + + $page->pageviews++; + $DB->update_record('wiki_pages', $page); +} + +//---------------------------------------------------------- +//---------------------------------------------------------- + +/** + * Text format supported by wiki module + */ +function wiki_get_formats() { + // TODO: disable creole and nwiki format until moodle core text format lib added + return array('html'); + //return array('html', 'creole', 'nwiki'); +} + +/** + * Parses a string with the wiki markup language in $markup. + * + * @return Array or false when something wrong has happened. + * + * Returned array contains the following fields: + * 'parsed_text' => String. Contains the parsed wiki content. + * 'unparsed_text' => String. Constains the original wiki content. + * 'link_count' => Array of array('destination' => ..., 'new' => "is new?"). Contains the internal wiki links found in the wiki content. + * 'deleted_sections' => the list of deleted sections. + * '' => + * + * @author Josep Arús Pous + **/ +function wiki_parse_content($markup, $pagecontent, $options = array()) { + global $PAGE; + + $subwiki = wiki_get_subwiki($options['swid']); + $cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid); + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + $parser_options = array('link_callback' => '/mod/wiki/locallib.php:wiki_parser_link', 'link_callback_args' => array('swid' => $options['swid']), 'table_callback' => '/mod/wiki/locallib.php:wiki_parser_table', 'real_path_callback' => '/mod/wiki/locallib.php:wiki_parser_real_path', 'real_path_callback_args' => array('context' => $context, 'filearea' => 'wiki_attachments', 'pageid' => $options['pageid']), 'pageid' => $options['pageid'], 'pretty_print' => (isset($options['pretty_print']) && $options['pretty_print']), 'printable' => (isset($options['printable']) && $options['printable'])); + + return wiki_parser_proxy::parse($pagecontent, $markup, $parser_options); +} + +/** + * This function is the parser callback to parse wiki links. + * + * It returns the necesary information to print a link. + * + * NOTE: Empty pages and non-existent pages must be print in red color. + * + * @param link name of a page + * @param $options + * + * @return + * + * @TODO Doc return and options + */ +function wiki_parser_link($link, $options = null) { + global $CFG; + + if (is_object($link)) { + $parsedlink = array('content' => $link->title, 'url' => $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $link->id, 'new' => false, 'link_info' => array('link' => $link->title, 'pageid' => $link->id, 'new' => false)); + + $version = wiki_get_current_version($link->id); + if ($version->version == 0) { + $parsedlink['new'] = true; + } + return $parsedlink; + } else { + $swid = $options['swid']; + + if ($page = wiki_get_page_by_title($swid, $link)) { + $parsedlink = array('content' => $link, 'url' => $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $page->id, 'new' => false, 'link_info' => array('link' => $link, 'pageid' => $page->id, 'new' => false)); + + $version = wiki_get_current_version($page->id); + if ($version->version == 0) { + $parsedlink['new'] = true; + } + + return $parsedlink; + + } else { + return array('content' => $link, 'url' => $CFG->wwwroot . '/mod/wiki/create.php?swid=' . $swid . '&title=' . urlencode($link) . '&action=new', 'new' => true, 'link_info' => array('link' => $link, 'new' => true, 'pageid' => 0)); + } + } +} + +/** + * Returns the table fully parsed (HTML) + * + * @return HTML for the table $table + * @author Josep Arús Pous + * + **/ +function wiki_parser_table($table) { + global $OUTPUT; + + $htmltable = new html_table(); + + $headers = $table[0]; + $htmltable->head = array(); + foreach ($headers as $h) { + $htmltable->head[] = $h[1]; + } + + array_shift($table); + $htmltable->data = array(); + foreach ($table as $row) { + $row_data = array(); + foreach ($row as $r) { + $row_data[] = $r[1]; + } + $htmltable->data[] = $row_data; + } + + return html_writer::table($htmltable); +} + +/** + * Returns an absolute path link, unless there is no such link. + * + * @param url Link's URL + * @param context filearea params + * @param filearea + * @param fileareaid + * + * @return File full path + */ + +function wiki_parser_real_path($url, $context, $filearea, $fileareaid) { + global $CFG; + + if (preg_match("/^(?:http|ftp)s?\:\/\//", $url)) { + return $url; + } else { + return "{$CFG->wwwroot}/pluginfile.php/{$context->id}/$filearea/$fileareaid/$url"; + } +} + +/** + * Returns the token used by a wiki language to represent a given tag or "object" (bold -> **) + * + * @return A string when it has only one token at the beginning (f. ex. lists). An array composed by 2 strings when it has 2 tokens, one at the beginning and one at the end (f. ex. italics). Returns false otherwise. + * @author Josep Arús Pous + **/ +function wiki_parser_get_token($markup, $name) { + + return wiki_parser_proxy::get_token($name, $markup); +} + +/** + * Checks if current user can view a subwiki + * + * @param $subwiki + */ +function wiki_user_can_view($subwiki) { + global $USER; + + $wiki = wiki_get_wiki($subwiki->wikiid); + $cm = get_coursemodule_from_instance('wiki', $wiki->id); + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + // Working depending on activity groupmode + switch (groups_get_activity_groupmode($cm)) { + case NOGROUPS: + + if ($wiki->wikimode == 'collaborative') { + // Collaborative Mode: + // There is one wiki for all the class. + // + // Only view capbility needed + return has_capability('mod/wiki:viewpage', $context, $USER); + } else if ($wiki->wikimode == 'individual') { + // Individual Mode: + // Each person owns a wiki. + if ($subwiki->userid == $USER->id) { + // Only the owner of the wiki can view it + return has_capability('mod/wiki:viewpage', $context, $USER); + } else { // User has special capabilities + // User must have: + // mod/wiki:viewpage capability + // and + // mod/wiki:managewiki capability + $view = has_capability('mod/wiki:viewpage', $context, $USER); + $manage = has_capability('mod/wiki:managewiki', $context, $USER); + + return $view && $manage; + } + } else { + //Error + return false; + } + case SEPARATEGROUPS: + // Collaborative and Individual Mode + // + // Collaborative Mode: + // There is one wiki per group. + // Individual Mode: + // Each person owns a wiki. + if ($wiki->wikimode == 'collaborative' || $wiki->wikimode == 'individual') { + // Only members of subwiki group could view that wiki + if ($subwiki->groupid == groups_get_activity_group($cm)) { + // Only view capability needed + return has_capability('mod/wiki:viewpage', $context, $USER); + + } else { // User is not part of that group + // User must have: + // mod/wiki:managewiki capability + // or + // moodle/site:accessallgroups capability + // and + // mod/wiki:viewpage capability + $view = has_capability('mod/wiki:viewpage', $context, $USER); + $manage = has_capability('mod/wiki:managewiki', $context, $USER); + $access = has_capability('moodle/site:accessallgroups', $context, $USER); + return ($manage || $access) && $view; + } + } else { + //Error + return false; + } + case VISIBLEGROUPS: + // Collaborative and Individual Mode + // + // Collaborative Mode: + // There is one wiki per group. + // Individual Mode: + // Each person owns a wiki. + if ($wiki->wikimode == 'collaborative' || $wiki->wikimode == 'individual') { + // Everybody can read all wikis + // + // Only view capability needed + return has_capability('mod/wiki:viewpage', $context, $USER); + } else { + //Error + return false; + } + default: // Error + return false; + } +} + +/** + * Checks if current user can edit a subwiki + * + * @param $subwiki + */ +function wiki_user_can_edit($subwiki) { + global $USER; + + $wiki = wiki_get_wiki($subwiki->wikiid); + $cm = get_coursemodule_from_instance('wiki', $wiki->id); + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + // Working depending on activity groupmode + switch (groups_get_activity_groupmode($cm)) { + case NOGROUPS: + + if ($wiki->wikimode == 'collaborative') { + // Collaborative Mode: + // There is a wiki for all the class. + // + // Only edit capbility needed + return has_capability('mod/wiki:editpage', $context, $USER); + } else if ($wiki->wikimode == 'individual') { + // Individual Mode + // There is a wiki per user + + // Only the owner of that wiki can edit it + if ($subwiki->userid == $USER->id) { + return has_capability('mod/wiki:editpage', $context, $USER); + } else { // Current user is not the owner of that wiki. + + // User must have: + // mod/wiki:editpage capability + // and + // mod/wiki:managewiki capability + $edit = has_capability('mod/wiki:editpage', $context, $USER); + $manage = has_capability('mod/wiki:managewiki', $context, $USER); + + return $edit && $manage; + } + } else { + //Error + return false; + } + case SEPARATEGROUPS: + if ($wiki->wikimode == 'collaborative') { + // Collaborative Mode: + // There is one wiki per group. + // + // Only members of subwiki group could edit that wiki + if ($subwiki->groupid == groups_get_activity_group($cm)) { + // Only edit capability needed + return has_capability('mod/wiki:editpage', $context, $USER); + } else { // User is not part of that group + // User must have: + // mod/wiki:managewiki capability + // and + // moodle/site:accessallgroups capability + // and + // mod/wiki:editpage capability + $manage = has_capability('mod/wiki:managewiki', $context, $USER); + $access = has_capability('moodle/site:accessallgroups', $context, $USER); + $edit = has_capability('mod/wiki:editpage', $context, $USER); + return $manage && $access && $edit; + } + } else if ($wiki->wikimode == 'individual') { + // Individual Mode: + // Each person owns a wiki. + // + // Only the owner of that wiki can edit it + if ($subwiki->userid == $USER->id) { + return has_capability('mod/wiki:editpage', $context, $USER); + } else { // Current user is not the owner of that wiki. + // User must have: + // mod/wiki:managewiki capability + // and + // moodle/site:accessallgroups capability + // and + // mod/wiki:editpage capability + $manage = has_capability('mod/wiki:managewiki', $context, $USER); + $access = has_capability('moodle/site:accessallgroups', $context, $USER); + $edit = has_capability('mod/wiki:editpage', $context, $USER); + return $manage && $access && $edit; + } + } else { + //Error + return false; + } + case VISIBLEGROUPS: + if ($wiki->wikimode == 'collaborative') { + // Collaborative Mode: + // There is one wiki per group. + // + // Only members of subwiki group could edit that wiki + if ($subwiki->groupid == groups_get_activity_group($cm)) { + // Only edit capability needed + return has_capability('mod/wiki:editpage', $context, $USER); + } else { // User is not part of that group + // User must have: + // mod/wiki:managewiki capability + // and + // mod/wiki:editpage capability + $manage = has_capability('mod/wiki:managewiki', $context, $USER); + $edit = has_capability('mod/wiki:editpage', $context, $USER); + return $manage && $edit; + } + } else if ($wiki->wikimode == 'individual') { + // Individual Mode: + // Each person owns a wiki. + // + // Only the owner of that wiki can edit it + if ($subwiki->userid == $USER->id) { + return has_capability('mod/wiki:editpage', $context, $USER); + } else { // Current user is not the owner of that wiki. + // User must have: + // mod/wiki:managewiki capability + // and + // mod/wiki:editpage capability + $manage = has_capability('mod/wiki:managewiki', $context, $USER); + $edit = has_capability('mod/wiki:editpage', $context, $USER); + return $manage && $edit; + } + } else { + //Error + return false; + } + default: // Error + return false; + } +} + +//---------------- +// Locks +//---------------- + +/** + * Checks if a page-section is locked. + * + * @return true if the combination of section and page is locked, FALSE otherwise. + */ +function wiki_is_page_section_locked($pageid, $userid, $section = null) { + global $DB; + + $sql = "pageid = ? AND lockedat > ? AND userid != ?"; + $params = array($pageid, time(), $userid); + + if (!empty($section)) { + $sql .= " AND (sectionname = ? OR sectionname IS null)"; + $params[] = $section; + } + + return $DB->record_exists_select('wiki_locks', $sql, $params); +} + +/** + * Inserts or updates a wiki_locks record. + */ +function wiki_set_lock($pageid, $userid, $section = null, $insert = false) { + global $DB; + + if (wiki_is_page_section_locked($pageid, $userid, $section)) { + return false; + } + + $params = array('pageid' => $pageid, 'userid' => $userid, 'sectionname' => $section); + + $lock = $DB->get_record('wiki_locks', $params); + + if (!empty($lock)) { + $DB->update_record('wiki_locks', array('id' => $lock->id, 'lockedat' => time() + LOCK_TIMEOUT)); + } else if ($insert) { + $DB->insert_record('wiki_locks', array('pageid' => $pageid, 'sectionname' => $section, 'userid' => $userid, 'lockedat' => time() + 30)); + } + + return true; +} + +/** + * Deletes wiki_locks that are not in use. (F.Ex. after submitting the changes). If no userid is present, it deletes ALL the wiki_locks of a specific page. + */ +function wiki_delete_locks($pageid, $userid = null, $section = null, $delete_from_db = true, $delete_section_and_page = false) { + global $DB; + + $params = array('pageid' => $pageid); + + if (!empty($userid)) { + $params['userid'] = $userid; + } + + if (!empty($section)) { + $params['sectionname'] = $section; + } + + if ($delete_from_db) { + $DB->delete_records('wiki_locks', $params); + if ($delete_section_and_page && !empty($section)) { + $params['sectionname'] = null; + $DB->delete_records('wiki_locks', $params); + } + } else { + $DB->set_field('wiki_locks', 'lockedat', time(), $params); + } +} + +/** + * Deletes wiki_locks that expired 1 hour ago. + */ +function wiki_delete_old_locks() { + global $DB; + + $DB->delete_records_select('wiki_locks', "lockedat < ?", array(time() - 3600)); +} + +/** + * File processing + */ + +/** + * Uploads files to permanent disk space. + * + * @param draftitemid Draft space ID + * @param contextid + * + * @return array of files that have not been inserted. + */ + +function wiki_process_attachments($draftitemid, $deleteuploads, $contextid, $filearea, $itemid, $options = null) { + global $CFG, $USER; + + if (empty($options)) { + $options = page_wiki_edit::$attachmentoptions; + } + + $errors = array(); + + $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $fs = get_file_storage(); + + $oldfiles = $fs->get_area_files($contextid, $filearea, $itemid, 'id'); + + foreach ($oldfiles as $file) { + if (in_array($file->get_pathnamehash(), $deleteuploads)) { + $file->delete(); + } + } + + $draftfiles = $fs->get_area_files($usercontext->id, 'user_draft', $draftitemid, 'id'); + $oldfiles = $fs->get_area_files($contextid, $filearea, $itemid, 'id'); + + $file_record = array('contextid' => $contextid, 'filearea' => $filearea, 'itemid' => $itemid); + //more or less a merge... + $newhashes = array(); + foreach ($draftfiles as $file) { + $newhash = sha1($contextid . $filearea . $itemid . $file->get_filepath() . $file->get_filename()); + $newhashes[$newhash] = $file; + } + + $filecount = 0; + foreach ($oldfiles as $file) { + $oldhash = $file->get_pathnamehash(); + if (!$file->is_directory() && isset($newhashes[$oldhash])) { + //repeated file: ERROR!!! + unset($newhashes[$oldhash]); + $errors[] = $file; + } + + if (!$file->is_directory()) { + $filecount++; + } + } + + foreach ($newhashes as $file) { + if ($file->get_filepath() !== '/' or $file->is_directory()) { + continue; + } + + if ($options['maxfiles'] and $options['maxfiles'] <= $filecount) { + break; + } + + if (!$file->is_directory()) { + $filecount++; + $fs->create_file_from_storedfile($file_record, $file); + } + } + + //delete all draft files + $fs->delete_area_files($usercontext->id, 'user_draft', $draftitemid); + + return $errors; +} + +/** + * Returns all comments by context and pageid + * + * @param $context. Current context + * @param $pageid. Current pageid + **/ +function wiki_get_comments($context, $pageid) { + global $CFG; + require_once($CFG->dirroot . '/comment/lib.php'); + list($context, $course, $cm) = get_context_info_array($context->id); + + $cmt = new stdclass(); + $cmt->context = $context; + $cmt->itemid = $pageid; + $cmt->pluginname = 'wiki'; + $cmt->area = 'wiki_comment_section'; + $cmt->course = $course; + $manager = new comment($cmt); + + return ($manager->get_comments()); + +} + +/** + * Returns all comments from wiki comments section by user + * + * @param $userid. User whose we want get the comments + **/ +function wiki_get_comments_by_user($userid) { + global $DB; + + $area = 'wiki_comment_section'; + $sql = 'SELECT c.* ' . + 'FROM {comments} c ' . + 'WHERE c.userid = ? and c.commentarea= ?'; + + return $DB->get_records_sql($sql, array($userid, $area)); + +} + +/** + * Add comments ro database + * + * @param object $context. Current context + * @param int $pageid. Current pageid + * @param string $content. Content of the comment + * @param string editor. Version of editor we are using. + **/ +function wiki_add_comment($context, $pageid, $content, $editor) { + global $CFG; + require_once($CFG->dirroot . '/comment/lib.php'); + + list($context, $course, $cm) = get_context_info_array($context->id); + $cmt = new stdclass(); + $cmt->context = $context; + $cmt->itemid = $pageid; + $cmt->area = 'wiki_comment_section'; + $cmt->course = $course; + $cmt->pluginname = 'wiki'; + + $manager = new comment($cmt); + + if ($editor == 'creole') { + $manager->add($content, FORMAT_CREOLE); + } else if ($editor == 'html') { + $manager->add($content, FORMAT_HTML); + } else if ($editor == 'nwiki') { + $manager->add($content, FORMAT_NWIKI); + } + +} + +/** + * Delete comments from database + * + * @param $idcomment. Id of comment which will be deleted + * @param $context. Current context + * @param $pageid. Current pageid + **/ +function wiki_delete_comment($idcomment, $context, $pageid) { + global $CFG; + require_once($CFG->dirroot . '/comment/lib.php'); + + list($context, $course, $cm) = get_context_info_array($context->id); + $cmt = new stdclass; + $cmt->context = $context; + $cmt->itemid = $pageid; + $cmt->area = 'wiki_comment_section'; + $cmt->pluginname = 'wiki'; + $cmt->course = $course; + + $manager = new comment($cmt); + $manager->delete($idcomment); + +} + +/** + * Delete al comments from wiki + * + **/ +function wiki_delete_comments_wiki() { + global $PAGE, $DB; + + $cm = $PAGE->cm; + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + $table = 'comments'; + $select = 'contextid = ?'; + + $DB->delete_records_select($table, $select, array($context->id)); + +} + +function wiki_add_progress($pageid, $oldversionid, $versionid, $progress) { + global $DB; + for ($v = $oldversionid + 1; $v <= $versionid; $v++) { + $user = wiki_get_wiki_page_id($pageid, $v); + + $DB->insert_record('wiki_progress', array('userid' => $user->userid, 'pageid' => $pageid, 'versionid' => $v, 'progress' => $progress)); + } +} + +function wiki_get_wiki_page_id($pageid, $id) { + global $DB; + return $DB->get_record('wiki_versions', array('pageid' => $pageid, 'id' => $id)); +} + +function wiki_print_page_content($page, $context, $subwikiid) { + global $OUTPUT, $CFG; + + if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { + $content = wiki_refresh_cachedcontent($page); + $page = $content['page']; + } + + if (isset($content)) { + $box = ''; + foreach ($content['sections'] as $s) { + $box .= '

          ' . get_string('repeatedsection', 'wiki', $s) . '

          '; + } + + if (!empty($box)) { + echo $OUTPUT->box($box); + } + } + $html = file_rewrite_pluginfile_urls($page->cachedcontent, 'pluginfile.php', $context->id, 'wiki_attachments', $subwikiid); + echo $OUTPUT->box($html); + + if (!empty($CFG->usetags)) { + $tags = tag_get_tags_array('wiki', $page->id); + echo '

          Tags: ' . join($tags, ", ") . '

          '; + } + + wiki_increment_pageviews($page); +} + +/** + * This function trims any given text and returns it with some dots at the end + * + * @param string $text + * @param string $limit + * + * @return string + */ +function wiki_trim_string($text, $limit = 25) { + + if (strlen($text) > $limit) { + $text = substr($text, 0, $limit) . '...'; + } + + return $text; +} + +/** + * Prints default edit form fields and buttons + * + * @param string $format Edit form format (html, creole...) + * @param integer $version Version number. A negative number means no versioning. + */ + +function wiki_print_edit_form_default_fields($format, $pageid, $version = -1, $upload = false, $deleteuploads = array()) { + global $CFG, $PAGE, $OUTPUT; + + echo ''; + + if ($version >= 0) { + echo ''; + } + + echo ''; + + //attachments + require_once($CFG->dirroot . '/lib/form/filemanager.php'); + + $filemanager = new MoodleQuickForm_filemanager('attachments', get_string('wikiattachments', 'wiki'), array('id' => 'attachments'), array('subdirs' => false, 'maxfiles' => 99, 'maxbytes' => $CFG->maxbytes)); + + $value = file_get_submitted_draft_itemid('attachments'); + if (!empty($value) && !$upload) { + $filemanager->setValue($value); + } + + echo "
          " . get_string("uploadtitle", 'wiki') . ""; + + echo $OUTPUT->container_start('mdl-align wiki-form-center aaaaa'); + print $filemanager->toHtml(); + echo $OUTPUT->container_end(); + + $cm = $PAGE->cm; + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + echo $OUTPUT->container_start('mdl-align wiki-form-center wiki-upload-table'); + wiki_print_upload_table($context, 'wiki_upload', $pageid, $deleteuploads); + echo $OUTPUT->container_end(); + + echo "
          "; + + echo ''; + echo ''; + echo ''; + echo ''; +} + +/** + * Prints a table with the files attached to a wiki page + * @param object $context + * @param string $filearea + * @param int $fileitemid + * @param array deleteuploads + */ +function wiki_print_upload_table($context, $filearea, $fileitemid, $deleteuploads = array()) { + global $CFG, $OUTPUT; + + $htmltable = new html_table(); + + $htmltable->head = array(get_string('deleteupload', 'wiki'), get_string('uploadname', 'wiki'), get_string('uploadactions', 'wiki')); + + $fs = get_file_storage(); + $browser = get_file_browser(); + $files = $fs->get_area_files($context->id, $filearea, $fileitemid); + + foreach ($files as $file) { + if (!$file->is_directory()) { + $checkbox = 'get_pathnamehash(), $deleteuploads)) { + $checkbox .= ' checked="checked"'; + } + + $checkbox .= " />"; + + $htmltable->data[] = array($checkbox, '' . $file->get_filename() . '', ""); + } + } + + print '

          ' . get_string('uploadfiletitle', 'wiki') . "

          "; + print html_writer::table($htmltable); +} + +/** + * Generate wiki's page tree + * + * @param $page. A wiki page object + * @param $node. Starting navigation_node + * @param $keys. An array to store keys + * @return an array with all tree nodes + */ +function wiki_build_tree($page, $node, &$keys) { + $content = array(); + static $icon; + $icon = new pix_icon('f/odt', ''); + $pages = wiki_get_linked_pages($page->id); + foreach ($pages as $p) { + $key = $page->id . ':' . $p->id; + if (in_array($key, $keys)) { + break; + } + array_push($keys, $key); + $l = wiki_parser_link($p); + $link = new moodle_url('/mod/wiki/view.php', array('pageid' => $p->id)); + $nodeaux = $node->add($p->title, $link, null, null, null, $icon); + if ($l['new']) { + $nodeaux->add_class('wiki_newentry'); + } + wiki_build_tree($p, $nodeaux, $keys); + } + $content[] = $node; + return $content; +} + +/** + * Get linked pages from page + * @param int $pageid + */ +function wiki_get_linked_pages($pageid) { + global $DB; + + return $DB->get_records_sql("SELECT p.id, p.title + FROM mdl_wiki_pages p + JOIN mdl_wiki_links l ON l.topageid = p.id + WHERE l.frompageid = ? + ORDER BY p.title ASC", array($pageid)); +} diff --git a/mod/wiki/lock.php b/mod/wiki/lock.php new file mode 100644 index 00000000000..5c982897f58 --- /dev/null +++ b/mod/wiki/lock.php @@ -0,0 +1,85 @@ +. + +/** + * This file contains all necessary code to execute a lock renewal based on an ajax call + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); + +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$pageid = required_param('pageid', PARAM_INT); +$section = optional_param('section', "", PARAM_TEXT); + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} + +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} + +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +if (!$cm = get_coursemodule_from_instance('wiki', $wiki->id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} + +if (!empty($section) && !$sectioncontent = wiki_get_section_page($page, $section)) { + print_error('invalidsection', 'wiki'); +} + +require_course_login($course->id); + +$context = get_context_instance(CONTEXT_MODULE, $cm->id); +require_capability('mod/wiki:editpage', $context); + +//add_to_log($course->id, "wiki", "lock", "lock.php?id=$cm->id", "$wiki->id"); + +$wikipage = new page_wiki_lock($wiki, $subwiki, $cm); +$wikipage->set_page($page); + +if (!empty($section)) { + $wikipage->set_section($sectioncontent, $section); +} + +$wikipage->print_header(); + +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/map.php b/mod/wiki/map.php new file mode 100644 index 00000000000..58cffe0c36d --- /dev/null +++ b/mod/wiki/map.php @@ -0,0 +1,72 @@ +. + +/** + * This file contains all necessary code to view the navigation tab + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$pageid = required_param('pageid', PARAM_INT); // Page ID +$option = optional_param('option', 0, PARAM_INT); // Option ID + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} +if (!$cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid)) { + print_error('invalidcoursemodule'); +} +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +require_course_login($course->id, true, $cm); + +add_to_log($course->id, "wiki", "map", "map.php?id=$cm->id", "$wiki->id"); + +/// Print page header + +/// Finish the page +$wikipage = new page_wiki_map($wiki, $subwiki, $cm); + +$wikipage->set_view($option); +$wikipage->set_page($page); +$wikipage->print_header(); +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/mod_form.php b/mod/wiki/mod_form.php index 8ccb7e7ffb9..2e7ea059dcf 100644 --- a/mod/wiki/mod_form.php +++ b/mod/wiki/mod_form.php @@ -1,90 +1,103 @@ dirroot.'/course/moodleform_mod.php'); + +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . + +/** + * This file defines de main wiki configuration form + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('moodleform_mod.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/lib/datalib.php'); class mod_wiki_mod_form extends moodleform_mod { function definition() { - global $CFG, $COURSE, $WIKI_TYPES; - $mform =& $this->_form; + global $COURSE; + $mform =& $this->_form; - if (!empty($this->_instance)) { - $queryobject = new stdClass(); - $queryobject->id = $this->_instance; - $wikihasentries = wiki_has_entries($queryobject); - } else { - $wikihasentries=false; - } -//------------------------------------------------------------------------------- + //------------------------------------------------------------------------------- + /// Adding the "general" fieldset, where all the common settings are showed $mform->addElement('header', 'general', get_string('general', 'form')); - $mform->addElement('text', 'name', get_string('name'), array('size'=>'64')); - $mform->setType('name', PARAM_NOTAGS); + /// Adding the standard "name" field + $mform->addElement('text', 'name', get_string('wikiname', 'wiki'), array('size' => '64')); + $mform->setType('name', PARAM_TEXT); $mform->addRule('name', null, 'required', null, 'client'); + /// Adding the optional "intro" and "introformat" pair of fields + // $mform->addElement('htmleditor', 'intro', get_string('wikiintro', 'wiki')); + // $mform->setType('intro', PARAM_RAW); + // $mform->addRule('intro', get_string('required'), 'required', null, 'client'); + // $mform->setHelpButton('intro', array('writing', 'richtext2'), false, 'editorhelpbutton'); + // + // $mform->addElement('format', 'introformat', get_string('format')); + $this->add_intro_editor(true, get_string('wikiintro', 'wiki')); + //------------------------------------------------------------------------------- + /// Adding the rest of wiki settings, spreeading all them into this fieldset + /// or adding more fieldsets ('header' elements) if needed for better logic - $this->add_intro_editor(true); + $mform->addElement('header', 'wikifieldset', get_string('wikisettings', 'wiki')); - if (!$wikihasentries){ - asort($WIKI_TYPES); - $mform->addElement('select', 'wtype', get_string('wikitype', 'wiki'), $WIKI_TYPES); - $mform->setHelpButton('wtype', array('wikitype', get_string('wikitype', 'wiki'), 'wiki')); - $mform->setDefault('wtype', 'group'); + $attr = array('size' => '20'); + if (!empty($this->_instance)) { + $attr['disabled'] = 'disabled'; } else { - $mform->addElement('static', 'wtype', get_string('wikitype', 'wiki')); + $attr['value'] = get_string('firstpagetitle', 'wiki'); } - $mform->addElement('selectyesno', 'ewikiprinttitle', get_string('ewikiprinttitle', 'wiki')); - $mform->setDefault('ewikiprinttitle', 1); - $mform->setAdvanced('ewikiprinttitle'); + $mform->addElement('text', 'firstpagetitle', get_string('firstpagetitle', 'wiki'), $attr); - $htmlmodes = array(0 => get_string('nohtml', 'wiki'), - 1 => get_string('safehtml', 'wiki'), - 2 => get_string('htmlonly', 'wiki')); - $mform->addElement('select', 'htmlmode', get_string('htmlmode', 'wiki'), $htmlmodes); - $mform->setDefault('htmlmode', 2); - $mform->setAdvanced('htmlmode'); - - $mform->addElement('selectyesno', 'ewikiacceptbinary', get_string('ewikiacceptbinary', 'wiki')); - $mform->setDefault('ewikiacceptbinary', 0); - $mform->setHelpButton('ewikiacceptbinary', array('ewikiacceptbinary', get_string('ewikiacceptbinary', 'wiki'), 'wiki')); - $mform->setAdvanced('ewikiacceptbinary'); - - $mform->addElement('advcheckbox', 'disablecamelcase', get_string('wikilinkoptions', 'wiki'), get_string('disablecamel', 'wiki')); - $mform->setDefault('disablecamelcase', 0); - $mform->setHelpButton('disablecamelcase', array('wikilinkoptions', get_string('wikilinkoptions', 'wiki'), 'wiki')); - $mform->setAdvanced('disablecamelcase'); - - $studentadminoptionsgrp = array(); - $studentadminoptionsgrp[] =& $mform->createElement('advcheckbox', 'setpageflags', '', get_string('allowsetpage', 'wiki')); - $mform->setDefault('setpageflags', 0); - $studentadminoptionsgrp[] =& $mform->createElement('advcheckbox', 'strippages', '', get_string('allowstrippages', 'wiki')); - $mform->setDefault('strippages', 0); - $studentadminoptionsgrp[] =& $mform->createElement('advcheckbox', 'removepages', '', get_string('allowremovepages', 'wiki')); - $mform->setDefault('removepages', 0); - $studentadminoptionsgrp[] =& $mform->createElement('advcheckbox', 'revertchanges', '', get_string('allowrevertchanges', 'wiki')); - $mform->setDefault('revertchanges', 0); - $mform->addGroup($studentadminoptionsgrp, 'studentadminoptions', get_string('studentadminoptions', 'wiki'), null, false); - $mform->setAdvanced('studentadminoptions'); - -//------------------------------------------------------------------------------- - $mform->addElement('header', 'optional', get_string('optional', 'form')); - $mform->addElement('text', 'pagename', get_string('wikiname', 'wiki')); - if ($wikihasentries) { - $mform->hardFreeze('pagename'); + if (empty($this->_instance)) { + $mform->addRule('firstpagetitle', null, 'required', null, 'client'); } - $mform->setHelpButton('pagename', array('wikiname', get_string('wikiname', 'wiki'), 'wiki')); - $mform->setType('pagename', PARAM_NOTAGS); - $mform->setAdvanced('pagename'); - $mform->addElement('choosecoursefile', 'initialcontent', get_string('initialcontent', 'wiki')); - $mform->setHelpButton('initialcontent', array('initialcontent', get_string('initialcontent', 'wiki'), 'wiki')); - $mform->setAdvanced('initialcontent'); + $wikimodeoptions = array ('collaborative' => get_string('wikimodecollaborative', 'wiki'), 'individual' => get_string('wikimodeindividual', 'wiki')); + // don't allow to change wiki type once is set + $wikitype_attr = array(); + if (!empty($this->_instance)) { + $wikitype_attr['disabled'] = 'disabled'; + } + $mform->addElement('select', 'wikimode', get_string('wikimode', 'wiki'), $wikimodeoptions, $wikitype_attr); -//------------------------------------------------------------------------------- + $formats = wiki_get_formats(); + $editoroptions = array(); + foreach ($formats as $format) { + $editoroptions[$format] = get_string($format, 'wiki'); + } + $mform->addElement('select', 'defaultformat', get_string('defaultformat', 'wiki'), $editoroptions); + $mform->addElement('checkbox', 'forceformat', get_string('forceformat', 'wiki')); + + //------------------------------------------------------------------------------- + // add standard elements, common to all modules $this->standard_coursemodule_elements(); -//------------------------------------------------------------------------------- -// buttons + //------------------------------------------------------------------------------- + // add standard buttons, common to all modules $this->add_action_buttons(); } } - diff --git a/mod/wiki/module.js b/mod/wiki/module.js new file mode 100644 index 00000000000..e4c0ed38820 --- /dev/null +++ b/mod/wiki/module.js @@ -0,0 +1,76 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . + +/** + * Javascript helper function for wiki + * + * @package mod-wiki + * @copyright 2010 Dongsheng Cai + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +M.mod_wiki = {}; + +M.mod_wiki.init = function(Y, args) { + var WikiHelper = function(args) { + WikiHelper.superclass.constructor.apply(this, arguments); + } + WikiHelper.NAME = "WIKI"; + WikiHelper.ATTRS = { + options: {}, + lang: {} + }; + Y.extend(WikiHelper, Y.Base, { + initializer: function(args) { + } + }); + new WikiHelper(args); +}; +M.mod_wiki.renew_lock = function(Y, args) { + function renewLock() { + var args = 'pageid=' + wiki.pageid; + if (wiki.section) { + args += '§ion=' + wiki.section; + } + var callback = {}; + YAHOO.util.Connect.asyncRequest('GET', 'lock.php?' + args, callback); + } + setInterval(renewLock, wiki.renew_lock_timeout * 1000); +} +M.mod_wiki.history = function(Y, args) { + var compare = false; + var comparewith = false; + var radio = document.getElementsByName('compare'); + var radio2 = document.getElementsByName('comparewith'); + for(var i=0; iset_url('/mod/wiki/overridelock.php', array('id'=>$id, 'page'=>$page)); - -if (! $cm = get_coursemodule_from_id('wiki', $id)) { - print_error('invalidcoursemodule'); -} -if (! $course = $DB->get_record("course", array("id"=>$cm->course))) { - print_error('coursemisconf'); -} -if (! $wiki = $DB->get_record("wiki", array("id"=>$cm->instance))) { - print_error('invalidcoursemodule'); -} - -if(!confirm_sesskey()) { - print_error('confirmsesskeybad'); -} -if(!data_submitted()) { - print_error('invalidformdata'); -} - -require_course_login($course, true, $cm); - -$modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); -if(!has_capability('mod/wiki:overridelock', $modcontext)) { - print_error('nopermissiontooverride', 'wiki'); -} - -$actions = explode('/', $page,2); -if(count($actions)!=2) { - print_error('invalidpageval', 'wiki'); -} -$pagename=$actions[1]; -$DB->delete_records('wiki_locks', array('pagename'=>$pagename, 'wikiid'=>$wiki->id)); - -redirect("view.php?id=$id&page=".urlencode($page)); - diff --git a/mod/wiki/overridelocks.php b/mod/wiki/overridelocks.php new file mode 100644 index 00000000000..b40a233a23d --- /dev/null +++ b/mod/wiki/overridelocks.php @@ -0,0 +1,89 @@ +. + +/** + * This file contains all necessary code to edit a wiki page + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); + +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$pageid = required_param('pageid', PARAM_INT); +$section = optional_param('section', '', PARAM_TEXT); + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} + +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} + +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +if (!$cm = get_coursemodule_from_instance('wiki', $wiki->id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} + +if (!empty($section) && !$sectioncontent = wiki_get_section_page($page, $section)) { + print_error('invalidsection', 'wiki'); +} + +require_course_login($course->id, true, $cm); + +$context = get_context_instance(CONTEXT_MODULE, $cm->id); +require_capability('mod/wiki:overridelock', $context); + +add_to_log($course->id, "wiki", "overridelocks", "overridelocks.php?id=$cm->id", "$wiki->id"); + +if (!confirm_sesskey()) { + print_error(get_string('invalidsesskey', 'wiki')); +} + +$wikipage = new page_wiki_overridelocks($wiki, $subwiki, $cm); +$wikipage->set_page($page); + +if (!empty($section)) { + $wikipage->set_section($sectioncontent, $section); +} + +$wikipage->print_header(); + +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/pagelib.php b/mod/wiki/pagelib.php new file mode 100644 index 00000000000..ef3e21ac55e --- /dev/null +++ b/mod/wiki/pagelib.php @@ -0,0 +1,2260 @@ +. + +/** + * This file contains several classes uses to render the diferent pages + * of the wiki module + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Daniel Serrano + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once($CFG->dirroot . '/mod/wiki/edit_form.php'); +require_once($CFG->dirroot . '/tag/lib.php'); + +/** + * Class page_wiki contains the common code between all pages + * + * @package mod-wiki + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class page_wiki { + + /** + * @var object Current subwiki + */ + protected $subwiki; + + /** + * @var int Current page + */ + protected $page; + + /** + * @var string Current page title + */ + protected $title; + + /** + * @var int Current group ID + */ + protected $gid; + + /** + * @var array The tabs set used in wiki module + */ + protected $tabs = array('view', 'edit', 'comments', 'history', 'map'); + /** + * @var array tabs options + */ + protected $tabs_options = array(); + /** + * @var object wiki renderer + */ + protected $wikioutput; + + /** + * page_wiki constructor + * + * @param $wiki. Current wiki + * @param $subwiki. Current subwiki. + * @param $cm. Current course_module. + */ + function __construct($wiki, $subwiki, $cm) { + global $PAGE, $CFG; + $this->subwiki = $subwiki; + + // initialise wiki renderer + $this->wikioutput = $PAGE->get_renderer('mod_wiki'); + + $PAGE->set_focuscontrol(''); + $PAGE->set_cacheable(true); + $PAGE->set_cm($cm); + $PAGE->set_activity_record($wiki); + // the search box + $PAGE->set_button(wiki_search_form($cm)); + } + + /** + * This method prints the top of the page. + */ + function print_header() { + global $OUTPUT, $PAGE, $CFG, $USER, $SESSION; + + $PAGE->set_heading($PAGE->course->fullname); + + $this->set_url(); + + if (isset($SESSION->wikipreviousurl) && is_array($SESSION->wikipreviousurl)) { + $this->process_session_url(); + } + $this->set_session_url(); + + $this->create_navbar(); + $this->setup_tabs(); + + echo $OUTPUT->header(); + + echo $this->wikioutput->wiki_info(); + + // tabs are associated with pageid, so if page is empty, tabs should be disabled + if (!empty($this->page) && !empty($this->tabs)) { + echo $this->wikioutput->tabs($this->page, $this->tabs, $this->tabs_options); + } + } + + /** + * Protected method to print current page title. + */ + protected function print_pagetitle() { + global $OUTPUT; + $html = ''; + + $html .= $OUTPUT->container_start(); + $html .= $OUTPUT->heading($this->title, 2, 'wiki_headingtitle'); + $html .= $OUTPUT->container_end(); + echo $html; + } + + /** + * Setup page tabs, if options is empty, will set up active tab automatically + * @param array $options, tabs options + */ + protected function setup_tabs($options = array()) { + if (empty($options)) { + $this->tabs_options = array('activetab' => substr(get_class($this), 10)); + } else { + $this->tabs_options = $options; + } + + } + + /** + * This method must be overwritten to print the page content. + */ + function print_content() { + throw new coding_exception('Page wiki class does not implement method print_content()'); + } + + /** + * Method to set the current page + * + * @param object $page Current page + */ + function set_page($page) { + global $PAGE; + + $this->page = $page; + $this->title = $page->title; + $PAGE->set_title($this->title); + } + + /** + * Method to set the current page title. + * This method must be called when the current page is not created yet. + * @param string $title Current page title. + */ + function set_title($title) { + global $PAGE; + + $this->page = null; + $this->title = $title; + $PAGE->set_title($this->title); + } + + /** + * Method to set current group id + * @param int $gid Current group id + */ + function set_gid($gid) { + $this->gid = $gid; + } + + /** + * Method to set the URL of the page. + * This method must be overwritten by every type of page. + */ + protected function set_url() { + throw new coding_exception('Page wiki class does not implement method set_url()'); + } + + /** + * Protected method to create the common items of the navbar in every page type. + */ + protected function create_navbar() { + global $PAGE, $CFG; + + $PAGE->navbar->add($this->title, $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $this->page->id); + } + + /** + * This method print the footer of the page. + */ + function print_footer() { + global $OUTPUT; + echo $OUTPUT->footer(); + } + + protected function process_session_url() { + global $USER, $SESSION; + + //delete locks if edit + $url = $SESSION->wikipreviousurl; + switch ($url['page']) { + case 'edit': + wiki_delete_locks($url['params']['pageid'], $USER->id, $url['params']['section'], false); + break; + } + } + + protected function set_session_url() { + global $SESSION; + unset($SESSION->wikipreviousurl); + } + +} + +/** + * View a wiki page + * + * @package mod-wiki + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class page_wiki_view extends page_wiki { + /** + * @var int the coursemodule id + */ + private $coursemodule; + + function print_header() { + global $PAGE; + + parent::print_header(); + + $this->wikioutput->wiki_print_subwiki_selector($PAGE->activityrecord, $this->subwiki, $this->page); + + if (!empty($this->page)) { + echo $this->wikioutput->prettyview_link($this->page); + } + + //echo $this->wikioutput->page_index(); + + $this->print_pagetitle(); + } + + function print_content() { + global $PAGE, $CFG; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + if (wiki_user_can_view($this->subwiki)) { + + if (!empty($this->page)) { + wiki_print_page_content($this->page, $context, $this->subwiki->id); + $wiki = $PAGE->activityrecord; + } else { + print_string('nocontent', 'wiki'); + // TODO: fix this part + $swid = 0; + if (!empty($this->subwiki)) { + $swid = $this->subwiki->id; + } + } + } else { + // @TODO: Tranlate it + echo "You can not view this page"; + } + } + + function set_url() { + global $PAGE, $CFG; + $params = array(); + + if (isset($this->coursemodule)) { + $params['id'] = $this->coursemodule; + } else if (!empty($this->page) and $this->page != null) { + $params['pageid'] = $this->page->id; + } else if (!empty($this->gid)) { + $params['wid'] = $PAGE->cm->instance; + $params['group'] = $this->gid; + } else if (!empty($this->title)) { + $params['swid'] = $this->subwiki->id; + $params['title'] = $this->title; + } else { + print_error(get_string('invalidparameters', 'wiki')); + } + + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/view.php', $params); + } + + function set_coursemodule($id) { + $this->coursemodule = $id; + } + + protected function create_navbar() { + global $PAGE, $CFG; + + $PAGE->navbar->add($this->title); + $PAGE->navbar->add(get_string('view', 'wiki')); + } +} + +/** + * Wiki page editing page + * + * @package mod-wiki + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class page_wiki_edit extends page_wiki { + + public static $attachmentoptions; + + protected $sectioncontent; + /** @var string the section name needed to be edited */ + protected $section; + protected $overridelock = false; + protected $versionnumber = -1; + protected $upload = false; + protected $attachments = 0; + protected $deleteuploads = array(); + protected $format; + + function __construct($wiki, $subwiki, $cm) { + global $CFG, $PAGE; + parent::__construct($wiki, $subwiki, $cm); + self::$attachmentoptions = array( + 'subdirs' => false, + 'maxfiles' => -1, + 'maxbytes' => $CFG->maxbytes, + 'accepted_types'=>'*' + ); + $PAGE->requires->js_init_call('M.mod_wiki.renew_lock', null, true); + $PAGE->requires->yui2_lib('connection'); + } + + protected function print_pagetitle() { + global $OUTPUT; + + $title = $this->title; + if (isset($this->section)) { + $title .= ' : ' . $this->section; + } + echo $OUTPUT->container_start('wiki_clear'); + echo $OUTPUT->heading($title, 2, 'wiki_headingtitle'); + echo $OUTPUT->container_end(); + } + + function print_header() { + global $OUTPUT, $PAGE; + $PAGE->requires->data_for_js('wiki', array('renew_lock_timeout' => LOCK_TIMEOUT - 5, 'pageid' => $this->page->id, 'section' => $this->section)); + + parent::print_header(); + + $this->print_pagetitle(); + + print ''; + } + + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + if (wiki_user_can_edit($this->subwiki)) { + $this->print_edit(); + } else { + // @TODO: Translate it + echo "You can not edit this page"; + } + } + + protected function set_url() { + global $PAGE, $CFG; + + $params = array('pageid' => $this->page->id); + + if (isset($this->section)) { + $params['section'] = $this->section; + } + + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/edit.php', $params); + } + + protected function set_session_url() { + global $SESSION; + + $SESSION->wikipreviousurl = array('page' => 'edit', 'params' => array('pageid' => $this->page->id, 'section' => $this->section)); + } + + protected function process_session_url() { + } + + function set_section($sectioncontent, $section) { + $this->sectioncontent = $sectioncontent; + $this->section = $section; + } + + public function set_versionnumber($versionnumber) { + $this->versionnumber = $versionnumber; + } + + public function set_overridelock($override) { + $this->overridelock = $override; + } + + function set_format($format) { + $this->format = $format; + } + + public function set_upload($upload) { + $this->upload = $upload; + } + + public function set_attachments($attachments) { + $this->attachments = $attachments; + } + + public function set_deleteuploads($deleteuploads) { + $this->deleteuploads = $deleteuploads; + } + + protected function create_navbar() { + global $PAGE, $CFG; + + parent::create_navbar(); + + $PAGE->navbar->add(get_string('edit', 'wiki')); + } + + protected function check_locks() { + global $OUTPUT, $USER, $CFG; + + if (!wiki_set_lock($this->page->id, $USER->id, $this->section, true)) { + print $OUTPUT->box(get_string('pageislocked', 'wiki'), 'generalbox boxwidthnormal boxaligncenter'); + + if ($this->overridelock) { + $params = 'pageid=' . $this->page->id; + + if ($this->section) { + $params .= '§ion=' . $this->section; + } + + $form = '
          '; + $form .= ''; + $form .= ''; + $form .= '
          '; + + print $OUTPUT->box($form, 'generalbox boxwidthnormal boxaligncenter'); + } + return false; + } + return true; + } + + protected function print_edit($content = null) { + global $CFG, $OUTPUT, $USER, $PAGE; + + if (!$this->check_locks()) { + return; + } + + //delete old locks (> 1 hour) + wiki_delete_old_locks(); + + $version = wiki_get_current_version($this->page->id); + $format = $version->contentformat; + + if ($content == null) { + if (empty($this->section)) { + $content = $version->content; + } else { + $content = $this->sectioncontent; + } + } + + $versionnumber = $version->version; + if ($this->versionnumber >= 0) { + if ($version->version != $this->versionnumber) { + print $OUTPUT->box(get_string('wrongversionlock', 'wiki'), 'errorbox'); + $versionnumber = $this->versionnumber; + } + } + + $cm = $PAGE->cm; + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + $url = $CFG->wwwroot . '/mod/wiki/edit.php?pageid=' . $this->page->id; + if (!empty($this->section)) { + $url .= "§ion=" . $this->section; + } + + $params = array('attachmentoptions' => page_wiki_edit::$attachmentoptions, 'format' => $version->contentformat, 'version' => $versionnumber); + + $data = new StdClass(); + $data->newcontent = $content; + $data->version = $versionnumber; + $data->format = $format; + + switch ($format) { + case 'html': + $data->newcontentformat = FORMAT_HTML; + $data = file_prepare_standard_editor($data, 'newcontent', page_wiki_edit::$attachmentoptions, $context, 'wiki_attachments', $this->subwiki->id); + break; + default: + //$draftitemid = file_get_submitted_draft_itemid('attachments'); + //file_prepare_draft_area($draftitemid, $context->id, 'wiki_attachments', $this->subwiki->id); + //$data->attachments = $draftitemid; + } + + if ($version->contentformat != 'html') { + $params['contextid'] = $context->id; + $params['filearea'] = 'wiki_attachments'; + $params['fileitemid'] = $this->subwiki->id; + } + + $form = new mod_wiki_edit_form($url, $params); + + + if ($formdata = $form->get_data()) { + if ($format != 'html') { + $errors = $this->process_uploads($context); + if (!empty($errors)) { + $contenterror = ""; + foreach ($errors as $e) { + $contenterror .= "

          " . get_string('filenotuploadederror', 'wiki', $e->get_filename()) . "

          "; + } + print $OUTPUT->box($contenterror, 'errorbox'); + } + } + if (!empty($CFG->usetags)) { + $data->tags = $formdata->tags; + } + } else { + if (!empty($CFG->usetags)) { + $data->tags = tag_get_tags_array('wiki', $this->page->id); + } + } + + $form->set_data($data); + $form->display(); + } + + protected function process_uploads($context) { + global $PAGE, $OUTPUT; + + if ($this->upload) { + file_save_draft_area_files($this->attachments, $context->id, 'wiki_attachments', $this->subwiki->id); + return null; + //return wiki_process_attachments($this->attachments, $this->deleteuploads, $context->id, 'wiki_attachments', $this->subwiki->id); + } + } +} + +/** + * Class that models the behavior of wiki's view comments page + * + * @package mod-wiki + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class page_wiki_comments extends page_wiki { + + function print_header() { + + parent::print_header(); + + $this->print_pagetitle(); + + } + + function print_content() { + global $CFG, $OUTPUT, $USER, $PAGE, $COURSE; + require_once($CFG->dirroot . '/mod/wiki/locallib.php'); + + $page = $this->page; + $subwiki = $this->subwiki; + $wiki = $PAGE->activityrecord; + $cm = $PAGE->cm; + $course = $COURSE; + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + require_capability('mod/wiki:viewcomment', $context, NULL, true, 'noviewcommentpermission', 'wiki'); + + $comments = wiki_get_comments($context, $page->id); + + if (has_capability('mod/wiki:editcomment', $context)) { + echo ''; + } + + $options = array('swid' => $this->page->subwikiid, 'pageid' => $page->id); + $version = wiki_get_current_version($this->page->id); + $format = $version->contentformat; + + if (empty($comments)) { + echo $OUTPUT->heading(get_string('nocomments', 'wiki')); + } + + foreach ($comments as $num) { + + $user = wiki_get_user_info($num->userid); + + $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id))); + $by = new stdclass(); + $by->name = '' . $fullname . ''; + $by->date = userdate($num->timecreated); + + $t = new html_table(); + $cell1 = new html_table_cell($OUTPUT->user_picture($user, array('popup' => true))); + $cell2 = new html_table_cell(get_string('bynameondate', 'forum', $by)); + $cell3 = new html_table_cell(); + $cell3->atributtes ['width'] = "80%"; + $cell4 = new html_table_cell(); + $cell5 = new html_table_cell(); + + $row1 = new html_table_row(); + $row1->cells[] = $cell1; + $row1->cells[] = $cell2; + $row2 = new html_table_row(); + $row2->cells[] = $cell3; + + if ($format != 'html') { + if ($format == 'creole') { + $parsedcontent = wiki_parse_content('creole', $num->content, $options); + } else if ($format == 'nwiki') { + $parsedcontent = wiki_parse_content('nwiki', $num->content, $options); + } + + $cell4->text = html_entity_decode($parsedcontent['parsed_text']); + } else { + $cell4->text = $num->content; + } + + $row2->cells[] = $cell4; + + if ((has_capability('mod/wiki:managecomment', $context)) and ($USER->id == $num->userid)) { + + $urledit = new moodle_url('/mod/wiki/editcomments.php', array('commentid' => $num->id, 'pageid' => $page->id, 'action' => 'edit')); + $urldelet = new moodle_url('/mod/wiki/instancecomments.php', array('commentid' => $num->id, 'pageid' => $page->id, 'action' => 'delete')); + $cell6 = new html_table_cell($OUTPUT->action_icon($urledit, new pix_icon('t/edit', get_string('edit'))) . $OUTPUT->action_icon($urldelet, new pix_icon('t/delete', get_string('delete')))); + $row3 = new html_table_row(); + $row3->cells[] = $cell5; + $row3->cells[] = $cell6; + $t->data = array($row1, $row2, $row3); + + } else { + $t->data = array($row1, $row2); + } + + echo html_writer::table($t); + + } + } + + function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/comments.php', array('pageid' => $this->page->id)); + } + + protected function create_navbar() { + global $PAGE, $CFG; + + parent::create_navbar(); + $PAGE->navbar->add(get_string('comments', 'wiki')); + } + +} + +/** + * Class that models the behavior of wiki's edit comment + * + * @package mod-wiki + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class page_wiki_editcomment extends page_wiki { + private $comment; + private $action; + private $form; + private $format; + + function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/comments.php', array('pageid' => $this->page->id)); + } + + function print_header() { + parent::print_header(); + $this->print_pagetitle(); + } + + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:editcomment', $context, NULL, true, 'noeditcommentpermission', 'wiki'); + + if ($this->action == 'add') { + $this->add_comment_form(); + } else if ($this->action == 'edit') { + $this->edit_comment_form($this->comment); + } + } + + function set_action($action, $comment) { + global $CFG; + require_once($CFG->dirroot . '/mod/wiki/comments_form.php'); + + $this->action = $action; + $this->comment = $comment; + $version = wiki_get_current_version($this->page->id); + $this->format = $version->contentformat; + + if ($this->format == 'html') { + $destination = $CFG->wwwroot . '/mod/wiki/instancecomments.php?pageid=' . $this->page->id; + $this->form = new mod_wiki_comments_form($destination); + } + } + + protected function create_navbar() { + global $PAGE, $CFG; + + $PAGE->navbar->add(get_string('comments', 'wiki'), $CFG->wwwroot . '/mod/wiki/comments.php?pageid=' . $this->page->id); + + if ($this->action == 'add') { + $PAGE->navbar->add(get_string('insertcomment', 'wiki')); + } else { + $PAGE->navbar->add(get_string('editcomment', 'wiki')); + } + } + + protected function setup_tabs() { + parent::setup_tabs(array('linkedwhenactive' => 'comments', 'activetab' => 'comments')); + } + + private function add_comment_form() { + global $CFG; + require_once($CFG->dirroot . '/mod/wiki/editors/wiki_editor.php'); + + $pageid = $this->page->id; + + if ($this->format == 'html') { + $this->form->display(); + } else { + wiki_print_editor_wiki($this->page->id, null, $this->format, -1, null, false, null, 'fromcomments'); + } + } + + private function edit_comment_form($com) { + global $CFG; + require_once($CFG->dirroot . '/mod/wiki/comments_form.php'); + require_once($CFG->dirroot . '/mod/wiki/editors/wiki_editor.php'); + + if ($this->format == 'html') { + $commentoptions = array('trusttext' => true, 'maxfiles' => 0); + $com->action = 'edit'; + $com->entrycomment_editor['text'] = $com->content; + + $this->form->set_data($com, $commentoptions); + $this->form->display(); + } else { + $action = 'edit'; + $commentid = $com->id; + $pageid = $this->page->id; + $destination = $CFG->wwwroot . '/mod/wiki/instancecomments.php?pageid=' . $pageid . '&id=' . $commentid . '&action=' . $action; + wiki_print_editor_wiki($this->page->id, $com->content, $this->format, -1, null, false, array(), 'fromcomments', $commentid); + } + + } + +} + +/** + * Wiki page search page + * + * @package mod-wiki + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class page_wiki_search extends page_wiki { + private $search_result; + + protected function create_navbar() { + global $PAGE, $CFG; + + $PAGE->navbar->add($PAGE->activityrecord->name, $CFG->wwwroot . '/mod/wiki/view.php?id=' . $PAGE->cm->id); + } + + function set_search_string($search, $searchcontent) { + $swid = $this->subwiki->id; + if ($searchcontent) { + $this->search_result = wiki_search_all($swid, $search); + } else { + $this->search_result = wiki_search_title($swid, $search); + } + + } + + function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/search.php'); + } + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:viewpage', $context, NULL, true, 'noviewpagepermission', 'wiki'); + + echo $this->wikioutput->search_result($this->search_result); + } +} + +/** + * + * Class that models the behavior of wiki's + * create page + * + */ +class page_wiki_create extends page_wiki { + + private $format; + private $swid; + private $action; + private $mform; + + function print_header() { + $this->set_url(); + parent::print_header(); + } + + function set_url() { + global $PAGE, $CFG; + + $params = array(); + if ($this->action == 'new') { + $params['action'] = 'new'; + $params['swid'] = $this->swid; + if ($this->title != get_string('newpage', 'wiki')) { + $params['title'] = $this->title; + } + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/create.php', $params); + } else { + $params['action'] = 'create'; + $params['swid'] = $this->swid; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/create.php', $params); + } + } + + function set_format($format) { + $this->format = $format; + } + + function set_swid($swid) { + $this->swid = $swid; + } + + function set_action($action) { + $this->action = $action; + + require_once(dirname(__FILE__) . '/create_form.php'); + $url = new moodle_url('/mod/wiki/create.php', array('action' => 'create', 'swid' => $this->swid)); + $formats = wiki_get_formats(); + $options = array('formats' => $formats); + if ($this->title != get_string('newpage', 'wiki')) { + $options['disable_pagetitle'] = true; + } + $this->mform = new mod_wiki_create_form($url->out(false), $options); + } + + protected function create_navbar() { + global $PAGE; + + $PAGE->navbar->add($this->title); + } + + function print_content($pagetitle = '') { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + $wiki = wiki_get_wiki($this->swid); + + // @TODO: Change this to has_capability and show an alternative interface. + require_capability('mod/wiki:createpage', $context, NULL, true, 'nocreatepermission', 'wiki'); + $data = new stdclass; + if (!empty($pagetitle)) { + $data->pagetitle = $pagetitle; + } + $data->pageformat = $PAGE->activityrecord->defaultformat; + + $this->mform->set_data($data); + $this->mform->display(); + } + + function create_page() { + global $USER, $CFG; + $data = $this->mform->get_data(); + $id = wiki_create_page($this->subwiki->id, $data->pagetitle, $data->pageformat, $USER->id); + redirect($CFG->wwwroot . '/mod/wiki/edit.php?pageid=' . $id); + } +} + +class page_wiki_preview extends page_wiki_edit { + + private $newcontent; + + function __construct($wiki, $subwiki, $cm) { + global $PAGE, $CFG, $OUTPUT; + parent::__construct($wiki, $subwiki, $cm); + $buttons = $OUTPUT->update_module_button($cm->id, 'wiki'); + $PAGE->set_button($buttons); + } + + function print_header() { + global $PAGE, $CFG; + + parent::print_header(); + + } + + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:editpage', $context, NULL, true, 'noeditpermission', 'wiki'); + + $this->print_preview(); + } + + function set_newcontent($newcontent) { + $this->newcontent = $newcontent; + } + + function set_url() { + global $PAGE, $CFG; + + $params = array('pageid' => $this->page->id + ); + + if (isset($this->section)) { + $params['section'] = $this->section; + } + + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/edit.php', $params); + } + + protected function setup_tabs() { + parent::setup_tabs(array('linkedwhenactive' => 'view', 'activetab' => 'view')); + } + + protected function check_locks() { + return true; + } + + protected function print_preview() { + global $CFG, $OUTPUT; + + $version = wiki_get_current_version($this->page->id); + $format = $version->contentformat; + $content = $version->content; + + $options = array('swid' => $this->page->subwikiid, 'pageid' => $this->page->id, 'pretty_print' => true); + + $parseroutput = wiki_parse_content($format, $this->newcontent, $options); + echo $OUTPUT->notification(get_string('previewwarning', 'wiki'), 'notifyproblem wiki_info'); + echo $OUTPUT->box($parseroutput['parsed_text'], 'generalbox wiki_previewbox'); + $content = $this->newcontent; + + $this->print_edit($content); + } + +} + +/** + * + * Class that models the behavior of wiki's + * view differences + * + */ +class page_wiki_diff extends page_wiki { + + private $compare; + private $comparewith; + + function print_header() { + global $OUTPUT; + + parent::print_header(); + + $this->print_pagetitle(); + $vstring = new stdclass; + $vstring->old = $this->compare; + $vstring->new = $this->comparewith; + echo $OUTPUT->heading(get_string('comparewith', 'wiki', $vstring)); + } + + /** + * Print the diff view + */ + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:viewpage', $context, NULL, true, 'noviewpagepermission', 'wiki'); + + $this->print_diff_content(); + } + + function set_url() { + global $PAGE, $CFG; + + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/diff.php', array('pageid' => $this->page->id, 'comparewith' => $this->comparewith, 'compare' => $this->compare)); + } + + function set_comparison($compare, $comparewith) { + $this->compare = $compare; + $this->comparewith = $comparewith; + } + + protected function create_navbar() { + global $PAGE, $CFG; + + parent::create_navbar(); + $PAGE->navbar->add(get_string('history', 'wiki'), $CFG->wwwroot . '/mod/wiki/history.php?pageid' . $this->page->id); + $PAGE->navbar->add(get_string('diff', 'wiki')); + } + + protected function setup_tabs() { + parent::setup_tabs(array('linkedwhenactive' => 'history', 'activetab' => 'history')); + } + + /** + * Given two versions of a page, prints a page displaying the differences between them. + * + * @uses $CFG + * + * @param int $pageid The page id whose versions will be displayed. + * @param int $cm The course id, needed to print user images. + * @param int $compare The first version number to be compared. + * @param int $comparewith The second version number to be compared. + */ + private function print_diff_content() { + global $CFG, $OUTPUT, $PAGE; + + $pageid = $this->page->id; + $total = wiki_count_wiki_page_versions($pageid) - 1; + + $oldversion = wiki_get_wiki_page_version($pageid, $this->compare); + $newversion = wiki_get_wiki_page_version($pageid, $this->comparewith); + + if ($oldversion && $newversion) { + + $oldtext = format_text($oldversion->content); + $newtext = format_text($newversion->content); + list($diff1, $diff2) = ouwiki_diff_html($oldtext, $newtext); + $oldversion->diff = $diff1; + $oldversion->user = wiki_get_user_info($oldversion->userid); + $newversion->diff = $diff2; + $newversion->user = wiki_get_user_info($newversion->userid); + + echo $this->wikioutput->diff($pageid, $oldversion, $newversion, array('total' => $total)); + } else { + print_error('versionerror', 'wiki'); + } + } +} + +/** + * + * Class that models the behavior of wiki's history page + * + */ +class page_wiki_history extends page_wiki { + /** + * @var int $paging current page + */ + private $paging; + + /** + * @var int @rowsperpage Items per page + */ + private $rowsperpage = 10; + + /** + * @var int $allversion if $allversion != 0, all versions will be printed in a signle table + */ + private $allversion; + + function __construct($wiki, $subwiki, $cm) { + global $PAGE; + parent::__construct($wiki, $subwiki, $cm); + $PAGE->requires->js_init_call('M.mod_wiki.history', null, true); + } + + function print_header() { + parent::print_header(); + $this->print_pagetitle(); + } + + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:viewpage', $context, NULL, true, 'noviewpagepermission', 'wiki'); + + $this->print_history_content(); + } + + function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/history.php', array('pageid' => $this->page->id)); + } + + function set_paging($paging) { + $this->paging = $paging; + } + + function set_allversion($allversion) { + $this->allversion = $allversion; + } + + protected function create_navbar() { + global $PAGE, $CFG; + + parent::create_navbar(); + $PAGE->navbar->add(get_string('history', 'wiki')); + } + + /** + * Prints the history for a given wiki page + * + * @uses $CFG + * + * @param int $pageid The page id whose history should be displayed. + * @param int $cm The course id, needed to print user images. + * @param wikipage $wikipage + * @param int $allversion This tells how results should be displayed. + * If $allversion == 0 : Only $rowsperpage will be displayed at a time, and $paging is the page being displayed. + * If $allversion != 0 : All versions will be printed in a single table. + * @param int $paging Desired page to be displayed, this is ignored if $allversion!=0. + * @param int $rowsperpage How many rows to be displayed in each page, this is ignored if $allversion!=0. + */ + private function print_history_content() { + global $CFG, $OUTPUT, $PAGE; + + $pageid = $this->page->id; + $offset = $this->paging * $this->rowsperpage; + // vcount is the latest version + $vcount = wiki_count_wiki_page_versions($pageid) - 1; + if ($this->allversion) { + $versions = wiki_get_wiki_page_versions($pageid, 0, $vcount); + } else { + $versions = wiki_get_wiki_page_versions($pageid, $offset, $this->rowsperpage); + } + // We don't want version 0 to be displayed + // version 0 is blank page + if (end($versions)->version == 0) { + array_pop($versions); + } + + $contents = array(); + + $version0page = wiki_get_wiki_page_version($this->page->id, 0); + $creator = wiki_get_user_info($version0page->userid); + $a = new StdClass; + $a->date = userdate($this->page->timecreated, get_string('strftimedaydatetime', 'langconfig')); + $a->username = $creator->username; + echo $OUTPUT->heading(get_string('createddate', 'wiki', $a), 4, 'wiki_headingtime'); + if ($vcount > 0) { + + /// If there is only one version, we don't need radios nor forms + if (count($versions) == 1) { + + $row = array_shift($versions); + + $username = wiki_get_user_info($row->userid); + $picture = $OUTPUT->user_picture($username); + $date = userdate($row->timecreated, get_string('strftimedate', 'langconfig')); + $time = userdate($row->timecreated, get_string('strftimetime', 'langconfig')); + $versionid = wiki_get_version($row->id); + $versionlink = new moodle_url('/mod/wiki/viewversion.php', array('pageid' => $pageid, 'versionid' => $versionid->id)); + $userlink = new moodle_url('/user/view.php', array('id' => $username->id)); + $contents[] = array('', html_writer::link($versionlink->out(false), $row->version), $picture . html_writer::link($userlink->out(false), fullname($username)), $time, print_container($date, false, 'wiki_histdate', '', true)); + + $table = new html_table(); + $table->head = array('', get_string('version'), get_string('user'), get_string('modified'), ''); + $table->data = $contents; + $table->attributes['class'] = 'mdl-align'; + + echo html_writer::table($table); + + } else { + + $checked = $vcount - $offset; + $lastdate = ''; + $rowclass = array(); + + foreach ($versions as $version) { + $user = wiki_get_user_info($version->userid); + $picture = $OUTPUT->user_picture($user, array('popup' => true)); + $date = userdate($version->timecreated, get_string('strftimedate')); + if ($date == $lastdate) { + $date = ''; + $rowclass[] = ''; + } else { + $lastdate = $date; + $rowclass[] = 'wiki_histnewdate'; + } + $time = userdate($version->timecreated, get_string('strftimetime', 'langconfig')); + $versionid = wiki_get_version($version->id); + if ($versionid) { + $url = new moodle_url('/mod/wiki/viewversion.php', array('pageid' => $pageid, 'versionid' => $versionid->id)); + $viewlink = html_writer::link($url->out(false), $version->version); + } else { + $viewlink = $version->version; + } + $userlink = new moodle_url('/user/view.php', array('id' => $version->userid)); + $contents[] = array($this->choose_from_radio(array($version->version => null), 'compare', 'M.mod_wiki.history()', $checked - 1, true) . $this->choose_from_radio(array($version->version => null), 'comparewith', 'M.mod_wiki.history()', $checked, true), $viewlink, $picture . html_writer::link($userlink->out(false), fullname($user)), $time, print_container($date, false, 'wiki_histdate', '', true)); + } + + $table = new html_table(); + $icon = $OUTPUT->help_icon('diff', 'wiki', get_string('diff', 'wiki')); + + $table->head = array($icon, get_string('version'), get_string('user'), get_string('modified'), ''); + $table->data = $contents; + $table->attributes['class'] = 'mdl-align'; + $table->rowclasses = $rowclass; + + /*$table = new StdClass(); + $table->head = array(helpbutton('diff', 'diff', 'wiki', true, false, '', true, ''), + get_string('version'), + get_string('user'), + get_string('modified'), + ''); + $table->data = $contents; + $table->class = 'mdl-align'; + $table->rowclass = $rowclass;*/ + + ///Print the form + echo '
          '; + echo '
          '; + echo html_writer::table($table); + echo '
          '; + echo '
          '; + } + } else { + print_string('nohistory', 'wiki'); + } + if (!$this->allversion) { + //$pagingbar = moodle_paging_bar::make($vcount, $this->paging, $this->rowsperpage, $CFG->wwwroot.'/mod/wiki/history.php?pageid='.$pageid.'&'); + // $pagingbar->pagevar = $pagevar; + echo $OUTPUT->paging_bar($vcount, $this->paging, $this->rowsperpage, $CFG->wwwroot . '/mod/wiki/history.php?pageid=' . $pageid . '&'); + //print_paging_bar($vcount, $paging, $rowsperpage,$CFG->wwwroot.'/mod/wiki/history.php?pageid='.$pageid.'&','paging'); + } else { + $link = new moodle_url('/mod/wiki/history.php', array('pageid' => $pageid)); + $OUTPUT->container(html_writer::link($link->out(false), get_string('viewperpage', 'wiki', $this->rowsperpage)), 'mdl-align'); + } + if ($vcount > $this->rowsperpage && !$this->allversion) { + $link = new moodle_url('/mod/wiki/history.php', array('pageid' => $pageid, 'allversion' => 1)); + $OUTPUT->container(html_writer::link($link->out(false), get_string('viewallhistory', 'wiki')), 'mdl-align'); + } + } + + /** + * Given an array of values, creates a group of radio buttons to be part of a form + * + * @param array $options An array of value-label pairs for the radio group (values as keys). + * @param string $name Name of the radiogroup (unique in the form). + * @param string $onclick Function to be executed when the radios are clicked. + * @param string $checked The value that is already checked. + * @param bool $return If true, return the HTML as a string, otherwise print it. + * + * @return mixed If $return is false, returns nothing, otherwise returns a string of HTML. + */ + private function choose_from_radio($options, $name, $onclick = '', $checked = '', $return = false) { + + static $idcounter = 0; + + if (!$name) { + $name = 'unnamed'; + } + + $output = '\n"; + + if (!empty($options)) { + $currentradio = 0; + foreach ($options as $value => $label) { + $htmlid = 'auto-rb' . sprintf('%04d', ++$idcounter); + $output .= ' "; + $output .= '' . $value . '' . "\n"; + } else { + $output .= ' /> ' . "\n"; + } + $currentradio = ($currentradio + 1) % 2; + } + } + + $output .= '' . "\n"; + + if ($return) { + return $output; + } else { + echo $output; + } + } +} + +/** + * Class that models the behavior of wiki's map page + * + */ +class page_wiki_map extends page_wiki { + + /** + * @var int wiki view option + */ + private $view; + + function print_header() { + parent::print_header(); + $this->print_pagetitle(); + } + + function print_content() { + global $CFG, $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:viewpage', $context, NULL, true, 'noviewpagepermission', 'wiki'); + + if ($this->view > 0) { + //echo ''; + } + + switch ($this->view) { + case 1: + echo $this->wikioutput->menu_map($this->page->id, $this->view); + $this->print_contributions_content(); + break; + case 2: + echo $this->wikioutput->menu_map($this->page->id, $this->view); + $this->print_navigation_content(); + break; + case 3: + echo $this->wikioutput->menu_map($this->page->id, $this->view); + $this->print_orphaned_content(); + break; + case 4: + echo $this->wikioutput->menu_map($this->page->id, $this->view); + $this->print_index_content(); + break; + case 5: + echo $this->wikioutput->menu_map($this->page->id, $this->view); + $this->print_page_list_content(); + break; + case 6: + echo $this->wikioutput->menu_map($this->page->id, $this->view); + $this->print_updated_content(); + break; + default: + echo $this->wikioutput->menu_map($this->page->id, $this->view); + $this->print_page_list_content(); + } + } + + function set_view($option) { + $this->view = $option; + } + + function print_menu_map() { + $options = array('contributions', 'links', 'orphaned', 'pageindex', 'pagelist', 'updatedpages'); + $items = array(); + foreach ($options as $opt) { + $items[] = get_string($opt, 'wiki'); + } + $table = new html_table(); + $table->head = array(get_string('mapmenu', 'wiki')); + $table->attributes['class'] = 'wiki_editor generalbox'; + $table->data = array(); + $table->rowclasses = array(); + foreach ($items as $key => $item) { + $link = new moodle_url('/mod/wiki/map.php', array('pageid' => $this->page->id, 'option' => $key + 1)); + $table->data[] = array(html_writer::link($link, $item)); + } + echo html_writer::table($table); + } + + function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/map.php', array('pageid' => $this->page->id)); + } + + protected function create_navbar() { + global $PAGE; + + parent::create_navbar(); + $PAGE->navbar->add(get_string('map', 'wiki')); + } + + /** + * Prints the contributions tab content + * + * @uses $OUTPUT, $USER + * + */ + private function print_contributions_content() { + global $CFG, $OUTPUT, $USER; + $page = $this->page; + + if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { + $fresh = wiki_refresh_cachedcontent($page); + $page = $fresh['page']; + } + + $swid = $this->subwiki->id; + + $table = new html_table(); + $table->head = array(get_string('contributions', 'wiki')); + $table->attributes['class'] = 'wiki_editor generalbox'; + $table->data = array(); + $table->rowclasses = array(); + + $lastversions = array(); + $pages = array(); + $users = array(); + + if ($contribs = wiki_get_contributions($swid, $USER->id)) { + foreach ($contribs as $contrib) { + if (!array_key_exists($contrib->pageid, $pages)) { + $page = wiki_get_page($contrib->pageid); + $pages[$contrib->pageid] = $page; + } else { + continue; + } + + if (!array_key_exists($page->id, $lastversions)) { + $version = wiki_get_last_version($page->id); + $lastversions[$page->id] = $version; + } else { + $version = $lastversions[$page->id]; + } + + if (!array_key_exists($version->userid, $users)) { + $user = wiki_get_user_info($version->userid); + $users[$version->userid] = $user; + } else { + $user = $users[$version->userid]; + } + + $link = wiki_parser_link(wiki_trim_string($page->title), array('swid' => $swid)); + $class = ($link['new']) ? 'class="wiki_newentry"' : ''; + + $linkpage = '' . $link['content'] . ''; + $icon = $OUTPUT->user_picture($user, array('popup' => true)); + + $table->data[] = array("$icon $linkpage"); + } + } else { + $table->data[] = array(get_string('nocontribs', 'wiki')); + } + echo html_writer::table($table); + } + + /** + * Prints the navigation tab content + * + * @uses $OUTPUT + * + */ + private function print_navigation_content() { + global $OUTPUT; + $page = $this->page; + + if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { + $fresh = wiki_refresh_cachedcontent($page); + $page = $fresh['page']; + } + + $tolinks = wiki_get_linked_to_pages($page->id); + $fromlinks = wiki_get_linked_from_pages($page->id); + + $table = new html_table(); + $table->attributes['class'] = 'wiki_navigation_from'; + $table->head = array(get_string('navigationfrom', 'wiki') . ':'); + $table->data = array(); + $table->rowclasses = array(); + foreach ($fromlinks as $link) { + $lpage = wiki_get_page($link->frompageid); + $link = new moodle_url('/mod/wiki/view.php', array('pageid' => $lpage->id)); + $table->data[] = array(html_writer::link($link->out(false), $lpage->title)); + $table->rowclasses[] = 'mdl-align'; + } + + $table_left = html_writer::table($table); + + $table = new html_table(); + $table->attributes['class'] = 'wiki_navigation_to'; + $table->head = array(get_string('navigationto', 'wiki') . ':'); + $table->data = array(); + $table->rowclasses = array(); + foreach ($tolinks as $link) { + if ($link->tomissingpage) { + $viewlink = new moodle_url('/mod/wiki/create.php', array('swid' => $page->subwikiid, 'title' => $link->tomissingpage, 'action' => 'new')); + $table->data[] = array(html_writer::link($viewlink->out(false), $link->tomissingpage, array('class' => 'wiki_newentry'))); + } else { + $lpage = wiki_get_page($link->topageid); + $viewlink = new moodle_url('/mod/wiki/view.php', array('pageid' => $lpage->id)); + $table->data[] = array(html_writer::link($viewlink->out(false), $lpage->title)); + } + $table->rowclasses[] = 'mdl-align'; + } + $table_right = html_writer::table($table); + echo $OUTPUT->container($table_left . $table_right, 'wiki_navigation_container'); + } + + /** + * Prints the index page tab content + * + * + */ + private function print_index_content() { + $page = $this->page; + + if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { + $fresh = wiki_refresh_cachedcontent($page); + $page = $fresh['page']; + } + + $node = new navigation_node($page->title); + + $keys = array(); + $tree = array(); + $tree = wiki_build_tree($page, $node, $keys); + + $table = new html_table(); + $table->head = array(get_string('pageindex', 'wiki')); + $table->attributes['class'] = 'wiki_editor generalbox'; + $table->data[] = array($this->render_navigation_node($tree)); + + echo html_writer::table($table); + } + + /** + * Prints the page list tab content + * + * + */ + private function print_page_list_content() { + $page = $this->page; + + if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { + $fresh = wiki_refresh_cachedcontent($page); + $page = $fresh['page']; + } + + $pages = wiki_get_page_list($this->subwiki->id); + + $stdaux = new stdClass(); + $strspecial = get_string('special', 'wiki'); + + foreach ($pages as $page) { + $letter = strtoupper(substr($page->title, 0, 1)); + if (preg_match('/[A-Z]/', $letter)) { + $stdaux->{ + $letter} + [] = wiki_parser_link($page); + } else { + $stdaux->{ + $strspecial} + [] = wiki_parser_link($page); + } + } + + $table = new html_table(); + $table->head = array(get_string('pagelist', 'wiki')); + $table->attributes['class'] = 'wiki_editor generalbox'; + $table->align = array('center'); + foreach ($stdaux as $key => $elem) { + $table->data[] = array($key); + foreach ($elem as $e) { + $table->data[] = array(html_writer::link($e['url'], $e['content'])); + } + } + echo html_writer::table($table); + } + + /** + * Prints the orphaned tab content + * + * + */ + private function print_orphaned_content() { + $page = $this->page; + + if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { + $fresh = wiki_refresh_cachedcontent($page); + $page = $fresh['page']; + } + + $swid = $this->subwiki->id; + + $table = new html_table(); + $table->head = array(get_string('orphaned', 'wiki')); + $table->attributes['class'] = 'wiki_editor generalbox'; + $table->data = array(); + $table->rowclasses = array(); + + if ($orphanedpages = wiki_get_orphaned_pages($swid)) { + foreach ($orphanedpages as $page) { + $link = wiki_parser_link(wiki_trim_string($page->title), array('swid' => $swid)); + $class = ($link['new']) ? 'class="wiki_newentry"' : ''; + $table->data[] = array('' . $link['content'] . ''); + } + } else { + $table->data[] = array(get_string('noorphanedpages', 'wiki')); + } + + echo html_writer::table($table); + } + + /** + * Prints the updated tab content + * + * @uses $COURSE, $OUTPUT + * + */ + private function print_updated_content() { + global $COURSE, $OUTPUT; + $page = $this->page; + + if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { + $fresh = wiki_refresh_cachedcontent($page); + $page = $fresh['page']; + } + + $swid = $this->subwiki->id; + + $table = new html_table(); + $table->head = array(get_string('updatedpages', 'wiki')); + $table->attributes['class'] = 'wiki_editor generalbox'; + $table->data = array(); + $table->rowclasses = array(); + + if ($pages = wiki_get_updated_pages_by_subwiki($swid)) { + $strdataux = ''; + foreach ($pages as $page) { + $user = wiki_get_user_info($page->userid); + $strdata = strftime('%d %b %Y', $page->timemodified); + if ($strdata != $strdataux) { + $table->data[] = array($OUTPUT->heading($strdata, 4)); + $strdataux = $strdata; + } + $link = wiki_parser_link(wiki_trim_string($page->title), array('swid' => $swid)); + $class = ($link['new']) ? 'class="wiki_newentry"' : ''; + + $linkpage = '' . $link['content'] . ''; + $icon = $OUTPUT->user_picture($user, array($COURSE->id)); + $table->data[] = array("$icon $linkpage"); + } + } else { + $table->data[] = array(get_string('noupdatedpages', 'wiki')); + } + + echo html_writer::table($table); + } + + protected function render_navigation_node($items, $attrs = array(), $expansionlimit = null, $depth = 1) { + + // exit if empty, we don't want an empty ul element + if (count($items) == 0) { + return ''; + } + + // array of nested li elements + $lis = array(); + foreach ($items as $item) { + if (!$item->display) { + continue; + } + $content = $item->get_content(); + $title = $item->get_title(); + if ($item->icon instanceof renderable) { + $icon = $this->wikioutput->render($item->icon); + $content = $icon . ' ' . $content; // use CSS for spacing of icons + } + if ($item->helpbutton !== null) { + $content = trim($item->helpbutton) . html_writer::tag('span', $content, array('class' => 'clearhelpbutton')); + } + + if ($content === '') { + continue; + } + + if ($item->action instanceof action_link) { + //TODO: to be replaced with something else + $link = $item->action; + if ($item->hidden) { + $link->add_class('dimmed'); + } + $content = $this->output->render($link); + } else if ($item->action instanceof moodle_url) { + $attributes = array(); + if ($title !== '') { + $attributes['title'] = $title; + } + if ($item->hidden) { + $attributes['class'] = 'dimmed_text'; + } + $content = html_writer::link($item->action, $content, $attributes); + + } else if (is_string($item->action) || empty($item->action)) { + $attributes = array(); + if ($title !== '') { + $attributes['title'] = $title; + } + if ($item->hidden) { + $attributes['class'] = 'dimmed_text'; + } + $content = html_writer::tag('span', $content, $attributes); + } + + // this applies to the li item which contains all child lists too + $liclasses = array($item->get_css_type(), 'depth_' . $depth); + if ($item->has_children() && (!$item->forceopen || $item->collapse)) { + $liclasses[] = 'collapsed'; + } + if ($item->isactive === true) { + $liclasses[] = 'current_branch'; + } + $liattr = array('class' => join(' ', $liclasses)); + // class attribute on the div item which only contains the item content + $divclasses = array('tree_item'); + if ((empty($expansionlimit) || $item->type != $expansionlimit) && ($item->children->count() > 0 || ($item->nodetype == navigation_node::NODETYPE_BRANCH && $item->children->count() == 0 && isloggedin()))) { + $divclasses[] = 'branch'; + } else { + $divclasses[] = 'leaf'; + } + if (!empty($item->classes) && count($item->classes) > 0) { + $divclasses[] = join(' ', $item->classes); + } + $divattr = array('class' => join(' ', $divclasses)); + if (!empty($item->id)) { + $divattr['id'] = $item->id; + } + $content = html_writer::tag('p', $content, $divattr) . $this->render_navigation_node($item->children, array(), $expansionlimit, $depth + 1); + if (!empty($item->preceedwithhr) && $item->preceedwithhr === true) { + $content = html_writer::empty_tag('hr') . $content; + } + $content = html_writer::tag('li', $content, $liattr); + $lis[] = $content; + } + + if (count($lis)) { + return html_writer::tag('ul', implode("\n", $lis), $attrs); + } else { + return ''; + } + } + +} + +/** + * Class that models the behavior of wiki's restore version page + * + */ +class page_wiki_restoreversion extends page_wiki { + private $version; + + function print_header() { + parent::print_header(); + $this->print_pagetitle(); + } + + function print_content() { + global $CFG, $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:managewiki', $context, NULL, true, 'nomanagewikipermission', 'wiki'); + + $this->print_restoreversion(); + } + + function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/viewversion.php', array('pageid' => $this->page->id, 'versionid' => $this->version->id)); + } + + function set_versionid($versionid) { + $this->version = wiki_get_version($versionid); + } + + protected function create_navbar() { + global $PAGE, $CFG; + + parent::create_navbar(); + $PAGE->navbar->add(get_string('restoreversion', 'wiki')); + } + + protected function setup_tabs() { + parent::setup_tabs(array('linkedwhenactive' => 'history', 'activetab' => 'history')); + } + + /** + * Prints the restore version content + * + * @uses $CFG + * + * @param page $page The page whose version will be restored + * @param int $versionid The version to be restored + * @param bool $confirm If false, shows a yes/no confirmation page. + * If true, restores the old version and redirects the user to the 'view' tab. + */ + private function print_restoreversion() { + global $CFG, $OUTPUT; + + $version = wiki_get_version($this->version->id); + + echo $OUTPUT->heading(get_string('restoreconfirm', 'wiki', $version->version), 2); + print_container_start(false, 'wiki_restoreform'); + echo '
          '; + echo '
          '; + echo '
          '; + echo '
          '; + echo '
          '; + echo '
          '; + print_container_end(); + } +} + +/** + * + * Class that models the behavior of wiki's + * save page + * + */ +class page_wiki_save extends page_wiki_edit { + + private $newcontent; + + function print_header() { + } + + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:editpage', $context, NULL, true, 'noeditpermission', 'wiki'); + + $this->print_save(); + } + + function set_newcontent($newcontent) { + $this->newcontent = $newcontent; + } + + protected function set_session_url() { + } + + protected function print_save() { + global $CFG, $USER, $OUTPUT, $PAGE; + + $cm = $PAGE->cm; + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + $url = $CFG->wwwroot . '/mod/wiki/edit.php?pageid=' . $this->page->id; + if (!empty($this->section)) { + $url .= "§ion=" . $this->section; + } + + $params = array('attachmentoptions' => page_wiki_edit::$attachmentoptions, 'format' => $this->format, 'version' => $this->versionnumber); + + if ($this->format != 'html') { + $params['contextid'] = $context->id; + $params['filearea'] = 'wiki_attachments'; + $params['fileitemid'] = $this->page->id; + } + + $form = new mod_wiki_edit_form($url, $params); + + $save = false; + $data = false; + if ($data = $form->get_data()) { + if ($this->format == 'html') { + $data = file_postupdate_standard_editor($data, 'newcontent', page_wiki_edit::$attachmentoptions, $context, 'wiki_attachments', $this->subwiki->id); + } + + if (isset($this->section)) { + $save = wiki_save_section($this->page, $this->section, $data->newcontent, $USER->id); + } else { + $save = wiki_save_page($this->page, $data->newcontent, $USER->id); + } + } + + if ($save && $data) { + if ($this->format != 'html') { + $errors = $this->process_uploads($context); + } + if (!empty($CFG->usetags)) { + tag_set('wiki', $this->page->id, $data->tags); + } + + $message = '

          ' . get_string('saving', 'wiki') . '

          '; + + if (!empty($save['sections'])) { + foreach ($save['sections'] as $s) { + $message .= '

          ' . get_string('repeatedsection', 'wiki', $s) . '

          '; + } + } + + if ($this->versionnumber + 1 != $save['version']) { + $message .= '

          ' . get_string('wrongversionsave', 'wiki') . '

          '; + } + + if (isset($errors) && !empty($errors)) { + foreach ($errors as $e) { + $message .= "

          " . get_string('filenotuploadederror', 'wiki', $e->get_filename()) . "

          "; + } + } + + //deleting old locks + wiki_delete_locks($this->page->id, $USER->id, $this->section); + + redirect($CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $this->page->id); + } else { + print_error('savingerror', 'wiki'); + } + } +} + +/** + * Class that models the behavior of wiki's view an old version of a page + * + */ +class page_wiki_viewversion extends page_wiki { + + private $version; + + function print_header() { + parent::print_header(); + $this->print_pagetitle(); + } + + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:viewpage', $context, NULL, true, 'noviewpagepermission', 'wiki'); + + $this->print_version_view(); + } + + function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/viewversion.php', array('pageid' => $this->page->id, 'versionid' => $this->version->id)); + } + + function set_versionid($versionid) { + $this->version = wiki_get_version($versionid); + } + + protected function create_navbar() { + global $PAGE, $CFG; + + parent::create_navbar(); + $PAGE->navbar->add(get_string('history', 'wiki'), $CFG->wwwroot . '/mod/wiki/history.php?pageid' . $this->page->id); + $PAGE->navbar->add(get_string('versionnum', 'wiki', $this->version->version)); + } + + protected function setup_tabs() { + parent::setup_tabs(array('linkedwhenactive' => 'history', 'activetab' => 'history', 'inactivetabs' => array('edit'))); + } + + /** + * Given an old page version, output the version content + * + * @uses $CFG + * + * @param page $page The page whose version will be displayed. + * @param int $cm The course id, needed to print user images. + * @param int $version The version number to be displayed. + */ + private function print_version_view() { + global $CFG, $OUTPUT, $PAGE; + $cm = $PAGE->cm; + $pageversion = wiki_get_version($this->version->id); + + if ($pageversion) { + $restorelink = new moodle_url('/mod/wiki/restoreversion.php', array('pageid' => $this->page->id, 'versionid' => $this->version->id)); + echo $OUTPUT->heading(get_string('viewversion', 'wiki', $pageversion->version) . '
          ' . html_writer::link($restorelink->out(false), '(' . get_string('restorethis', 'wiki') . ')', array('class' => 'wiki_restore')) . ' ', 4); + $userinfo = wiki_get_user_info($pageversion->userid); + $heading = '

          ' . get_string('modified', 'wiki') . ': ' . userdate($pageversion->timecreated, get_string('strftimedatetime', 'langconfig')); + $viewlink = new moodle_url('/user/view.php', array('id' => $userinfo->id)); + $heading .= '   ' . get_string('user') . ': ' . html_writer::link($viewlink->out(false), fullname($userinfo)); + $heading .= '  → ' . $OUTPUT->user_picture(wiki_get_user_info($pageversion->userid), array('popup' => true)) . '

          '; + print_container($heading, false, 'mdl-align wiki_modifieduser wiki_headingtime'); + $options = array('swid' => $this->subwiki->id, 'pretty_print' => true, 'pageid' => $this->page->id); + $parseroutput = wiki_parse_content($pageversion->contentformat, $pageversion->content, $options); + $content = print_container($parseroutput['parsed_text'], false, '', '', true); + echo $OUTPUT->box($content, 'generalbox wiki_contentbox'); + + } else { + print_error('versionerror', 'wiki'); + } + } +} + +class page_wiki_confirmrestore extends page_wiki_save { + + private $version; + + function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/viewversion.php', array('pageid' => $this->page->id, 'versionid' => $this->version->id)); + } + + function print_content() { + global $CFG, $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:managewiki', $context, NULL, true, 'nomanagewikipermission', 'wiki'); + + $version = wiki_get_version($this->version->id); + if (wiki_restore_page($this->page, $version->content, $version->userid)) { + redirect($CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $this->page->id, get_string('restoring', 'wiki', $version->version), 3); + } else { + print_error('restoreerror', 'wiki', $version->version); + } + } + + function set_versionid($versionid) { + $this->version = wiki_get_version($versionid); + } +} + +class page_wiki_prettyview extends page_wiki { + + function print_header() { + global $CFG, $OUTPUT; + + echo $OUTPUT->doctype(); + echo ''; + echo ''; + echo $OUTPUT->standard_head_html(); + echo ''; + echo ''; + + echo '

          ' . $this->title . '

          '; + } + + function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:viewpage', $context, NULL, true, 'noviewpagepermission', 'wiki'); + + $this->print_pretty_view(); + } + + function set_url() { + global $PAGE, $CFG; + + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/prettyview.php', array('pageid' => $this->page->id)); + } + + function print_footer() { + echo ''; + echo ''; + } + + private function print_pretty_view() { + $version = wiki_get_current_version($this->page->id); + + $content = wiki_parse_content($version->contentformat, $version->content, array('printable' => true, 'swid' => $this->subwiki->id, 'pageid' => $this->page->id, 'pretty_print' => true)); + + echo '
          '; + echo $content['parsed_text']; + echo '
          '; + } +} + +class page_wiki_handlecomments extends page_wiki { + private $action; + private $content; + private $commentid; + private $format; + + function print_header() { + $this->set_url(); + } + + public function print_content() { + global $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:managecomment', $context, NULL, true, 'nomanagecommentpermission', 'wiki'); + + if ($this->action == 'add' or $this->action == 'edit') { + $this->add_comment($this->content, $this->commentid); + } else if ($this->action == 'delete') { + $this->delete_comment($this->commentid); + } + + } + + public function set_url() { + global $PAGE, $CFG; + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/comments.php', array('pageid' => $this->page->id)); + } + + public function set_action($action, $commentid, $content) { + $this->action = $action; + $this->commentid = $commentid; + $this->content = $content; + + $version = wiki_get_current_version($this->page->id); + $format = $version->contentformat; + + $this->format = $format; + } + + private function add_comment($content, $idcomment) { + global $CFG, $PAGE; + require_once($CFG->dirroot . "/mod/wiki/locallib.php"); + + $pageid = $this->page->id; + $cm = $PAGE->cm; + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + + wiki_add_comment($context, $pageid, $content, $this->format); + + if (!$idcomment) { + redirect($CFG->wwwroot . '/mod/wiki/comments.php?pageid=' . $pageid, get_string('createcomment', 'wiki'), 2); + } else { + $this->delete_comment($idcomment); + } + } + + private function delete_comment($commentid) { + global $CFG, $PAGE; + + $cm = $PAGE->cm; + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $pageid = $this->page->id; + + wiki_delete_comment($commentid, $context, $pageid); + + redirect($CFG->wwwroot . '/mod/wiki/comments.php?pageid=' . $pageid, get_string('deletecomment', 'wiki'), 2); + } + +} + +class page_wiki_lock extends page_wiki_edit { + + public function print_header() { + $this->set_url(); + } + + protected function set_url() { + global $PAGE, $CFG; + + $params = array('pageid' => $this->page->id); + + if ($this->section) { + $params['section'] = $this->section; + } + + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/lock.php', $params); + } + + protected function set_session_url() { + } + + public function print_content() { + global $USER, $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:editpage', $context, NULL, true, 'noeditpermission', 'wiki'); + + wiki_set_lock($this->page->id, $USER->id, $this->section); + } + + public function print_footer() { + } +} + +class page_wiki_overridelocks extends page_wiki_edit { + function print_header() { + $this->set_url(); + } + + function print_content() { + global $CFG, $PAGE; + + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + require_capability('mod/wiki:overridelock', $context, NULL, true, 'nooverridelockpermission', 'wiki'); + + wiki_delete_locks($this->page->id, null, $this->section, true, true); + + $args = "pageid=" . $this->page->id; + + if (!empty($this->section)) { + $args .= "§ion=" . $this->section; + } + + redirect($CFG->wwwroot . '/mod/wiki/edit.php?' . $args, get_string('overridinglocks', 'wiki'), 2); + } + + function set_url() { + global $PAGE, $CFG; + + $params = array('pageid' => $this->page->id); + + if (!empty($this->section)) { + $params['section'] = $this->section; + } + + $PAGE->set_url($CFG->wwwroot . '/mod/wiki/overridelocks.php', $params); + } + + protected function set_session_url() { + } + + private function print_overridelocks() { + global $CFG; + + wiki_delete_locks($this->page->id, null, $this->section, true, true); + + $args = "pageid=" . $this->page->id; + + if (!empty($this->section)) { + $args .= "§ion=" . $this->section; + } + + redirect($CFG->wwwroot . '/mod/wiki/edit.php?' . $args, get_string('overridinglocks', 'wiki'), 2); + } + +} diff --git a/mod/wiki/parser/markups/creole.php b/mod/wiki/parser/markups/creole.php new file mode 100644 index 00000000000..487a7791b23 --- /dev/null +++ b/mod/wiki/parser/markups/creole.php @@ -0,0 +1,212 @@ + array( + 'expression' => "/^\{\{\{(.*?)\}\}\}/ims", + 'tags' => array(), + 'token' => array('{{{', '}}}') + ), + 'header' => array( + 'expression' => "/^\ *(={1,6})\ *(.+?)=*\ *$/ims", + 'tags' => array(), //none + 'token' => '=' + ), + 'table' => array( + 'expression' => "/^(?:\|.*?\|\ *\n)+/ims" + ), + 'line_break' => array( + 'expression' => "/^----\s*$/im", + 'token' => '----', + 'tags' => array() + ), + 'list' => array( + 'expression' => "/((?:^\ *[\*#][^\*#]\ *.+?)(?:^\ *[\*#]{1,5}\ *.+?)*)(\n\s*(?:\n|<(?:h\d|pre|table|tbody|thead|tr|th|td|ul|li|ol|hr)))/ims", + 'tags' => array(), + 'token' => array('*', '#') + ), + 'paragraph' => array( + 'expression' => "/^\ *((?:<(?!\ *\/?(?:h\d|pre|table|tbody|thead|tr|th|td|ul|li|ol|hr)\ *\/?>)|[^<\s]).+?)\n\s*\n/ims", + //not specified -> all tags (null or unset) + 'tag' => 'p' + ) + ); + + protected $tagrules = array( + 'nowiki' => array( + 'expression' => "/\{\{\{(.*?)\}\}\}/is", + 'token' => array('{{{', '}}}') + ), + 'image' => array( + 'expression' => "/\~?\{\{(.+)\|(.+)\}\}/i", + 'tags' => array(), + 'token' => array('{{', '|Alt}}') + ), + 'link' => array( + 'expression' => "/\~?\[\[(.+?)\]\]/is", + 'tag' => 'a', + 'token' => array('[[', ']]') + ), + 'url' => array( + 'expression' => "/\~?(? 'a', + 'token' => "http://" + ), + 'line_break' => array( + 'expression' => "/\\\\\\\\/", + 'tag' => 'br', + 'simple' => true, + 'token' => '----' + ), + 'bold' => array( + 'expression' => "/\*\*(.*?)(?:\*\*|$)/is", + 'tag' => 'strong', + 'token' => array('**', '**') + ), + 'italic' => array( + 'expression' => "#(? 'em', + 'token' => array('//', '//') + ) + ); + + /** + * Block hooks + */ + + protected function before_parsing() { + $this->string = htmlspecialchars($this->string); + parent::before_parsing(); + } + + protected function header_block_rule($match) { + $num = strlen($match[1]); + + $text = trim($match[2]); + + $text = preg_replace("/\s*={1,$num}$/im", "", $text); + + return $this->generate_header($text, $num); + } + + /** + * Table generation + */ + + protected function table_block_rule($match) { + + $rows = split("\n", $match[0]); + $table = array(); + foreach($rows as $r) { + if(empty($r)) { + continue; + } + $rawcells = split("\|", $r); + $cells = array(); + + array_shift($rawcells); + array_pop($rawcells); + + foreach($rawcells as $c) { + if(!empty($c)) { + if($c[0] == "=") { + $type = 'header'; + $c = substr($c, 1); + } + else { + $type = 'normal'; + } + $this->rules($c); + $cells[] = array($type, $c); + } + } + $table[] = $cells; + } + + return $this->generate_table($table); + } + + protected function paragraph_block_rule($match) { + $text = $match[1]; + foreach($this->tagrules as $tr) { + if(isset($tr['token'])) { + if(is_array($tr['token'])) { + $this->escape_token_string($text, $tr['token'][0]); + $this->escape_token_string($text, $tr['token'][1]); + } + else { + $this->escape_token_string($text, $tr['token']); + } + } + } + $this->escape_token_string($text, "~"); + + return $text; + } + + /** + * Escape token when it is "negated" + */ + private function escape_token_string(&$text, $token) { + $text = str_replace("~".$token, $this->protect($token), $text); + } + + /** + * Tag functions + */ + + protected function url_tag_rule($match) { + if(strpos($match[0], "~") === 0) { + return substr($match[0], 1); + } + else { + $text = trim($match[0]); + $options = array('href' => $text); + + return array($text, $options); + } + } + + protected function link_tag_rule($match) { + $text = trim($match[1]); + + if(strpos($match[0], "~") === 0) { + return substr($match[0], 1); + } + else { + return $this->format_link($text); + } + } + + /** + * Special treatment of // ** // ** // + */ + protected function bold_tag_rule($match) { + $text = $match[1]; + $this->rules($text, array('only' => array('italic'))); + if(strpos($text, "//") !== false) { + $text = str_replace("//", $this->protect("//"), $text); + } + return array($text, array()); + } + + protected function image_tag_rule($match) { + if(strpos($match[0], "~") === 0) { + return substr($match[0], 1); + } + + return $this->format_image($match[1], $match[2]); + } +} diff --git a/mod/wiki/parser/markups/html.php b/mod/wiki/parser/markups/html.php new file mode 100644 index 00000000000..0817a0285b9 --- /dev/null +++ b/mod/wiki/parser/markups/html.php @@ -0,0 +1,80 @@ +tagrules = array('link' => $this->tagrules['link'], 'url' => $this->tagrules['url']); + + //headers are considered tags here... + $h1 = array("<\s*h1\s*>", "<\/h1>"); + $this->tagrules['header1'] = array('expression' => "/{$h1[0]}(.+?){$h1[1]}/is" + ); + } + + protected function before_parsing() { + parent::before_parsing(); + + $this->rules($this->string); + } + + /** + * Header 1 tag rule + */ + protected function header1_tag_rule($match) { + return $this->generate_header($match[1], 1); + } + + /** + * Section editing: Special for HTML Parser (It parses

          ) + */ + + public function get_section($header, $text, $clean = false) { + if ($clean) { + $text = preg_replace('/\r\n/', "\n", $text); + $text = preg_replace('/\r/', "\n", $text); + $text .= "\n\n"; + } + + $h1 = array("<\s*h1\s*>", "<\/h1>"); + + preg_match("/(.*?)({$h1[0]}\s*\Q$header\E\s*{$h1[1]}.*?)((?:\n{$h1[0]}.*)|$)/is", $text, $match); + + if (!empty($match)) { + return array($match[1], $match[2], $match[3]); + } else { + return false; + } + } + + protected function get_repeated_sections(&$text, $repeated = array()) { + $this->repeated_sections = $repeated; + return preg_replace_callback($this->tagrules['header1'], array($this, 'get_repeated_sections_callback'), $text); + } + + protected function get_repeated_sections_callback($match) { + $text = trim($match[1]); + + if (in_array($text, $this->repeated_sections)) { + $this->returnvalues['repeated_sections'][] = $text; + return parser_utils::h('p', $text); + } else { + $this->repeated_sections[] = $text; + } + + return $match[0]; + } +} diff --git a/mod/wiki/parser/markups/nwiki.php b/mod/wiki/parser/markups/nwiki.php new file mode 100644 index 00000000000..a8ec9f8bfd4 --- /dev/null +++ b/mod/wiki/parser/markups/nwiki.php @@ -0,0 +1,282 @@ + array( + 'expression' => "/^(.*?)<\/nowiki>/ims", + 'tags' => array(), + 'token' => array('', '') + ), + 'header' => array( + 'expression' => "/^\ *(={1,6})\ *(.+?)(={1,6})\ *$/ims", + 'tags' => array(), //none + 'token' => '=' + ), + 'line_break' => array( + 'expression' => "/^-{3,4}\s*$/im", + 'tags' => array(), + 'token' => '---' + ), + 'desc_list' => array( + 'expression' => "/(?:^.+?\:.+?\;\n)+/ims", + 'tags' => array(), + 'token' => array(':', ';'), + 'tag' => 'dl' + ), + 'table' => array( + 'expression' => "/\{\|(.+?)\|\}/ims" + ), + 'tab_paragraph' => array( + 'expression' => "/^(\:+)(.+?)$/ims", + 'tag' => 'p' + ), + 'list' => array( + 'expression' => "/^((?:\ *[\*|#]{1,5}\ *.+?)+)(\n\s*(?:\n|<(?:h\d|pre|table|tbody|thead|tr|th|td|ul|li|ol|hr)\ *\/?>))/ims", + 'tags' => array(), + 'token' => array('*', '#') + ), + 'paragraph' => array( + 'expression' => "/^\ *((?:<(?!\ *\/?(?:h\d|pre|table|tbody|thead|tr|th|td|ul|li|ol|hr)\ *\/?>)|[^<\s]).+?)\n\s*\n/ims", + //not specified -> all tags (null or unset) + 'tag' => 'p' + ) + ); + + protected $tagrules = array( + 'nowiki' => array( + 'expression' => "/(.*?)<\/nowiki>/is", + 'token' => array('', '') + ), + 'image' => array( + 'expression' => "/\[\[image:(.+?)\|(.+?)\]\]/is", + 'token' => array("[[image:", "|alt]]") + ), + 'attach' => array( + 'expression' => "/\[\[attach:(.+?)\]\]/is", + 'token' => array("[[attach:", "|name]]") + ), + 'link' => array( + 'expression' => "/\[\[(.+?)\]\]/is", + 'tag' => 'a', + 'token' => array("[[", "]]") + ), + 'url_tag' => array( + 'expression' => "/\[(.+?)\]/is", + 'tag' => 'a', + 'token' => array("[", "]") + ), + 'url' => array( + 'expression' => "/(? 'a', + 'token' => 'http://' + ), + 'italic' => array( + 'expression' => "/\'{3}(.+?)(\'{3}(?:\'{2})?)/is", + 'tag' => 'em', + 'token' => array("'''", "'''") + ), + 'bold' => array( + 'expression' => "/\'{2}(.+?)\'{2}/is", + 'tag' => 'strong', + 'token' => array("''", "''") + ) + ); + + protected function after_parsing() { + if(function_exists('replace_smilies')) { + replace_smilies($this->string); + } + + parent::after_parsing(); + } + + /** + * Block hooks + */ + + protected function header_block_rule($match) { + if($match[1] != $match[3]) { + return $match[0]; + } + + $num = strlen($match[1]); + + return $this->generate_header($match[2], $num); + } + + protected function table_block_rule($match) { + $rows = split("\n\|-", $match[1]); + $table = array(); + foreach($rows as $r) { + $colsendline = split("\n", $r); + $cols = array(); + foreach($colsendline as $ce) { + $cols = array_merge($cols, $this->get_table_cells($ce)); + } + + if(!empty($cols)) { + $table[] = $cols; + } + } + return $this->generate_table($table); + } + + private function get_table_cells($string) { + $string = ltrim($string); + $type = (!empty($string) && $string[0] == "!") ? 'header' : 'normal'; + $string = substr($string, 1); + if(empty($string)) { + $normalcells = array(); + } + else { + $normalcells = split("\|\|", $string); + } + $cells = array(); + foreach($normalcells as $nc) { + $headercells = split("!!", $nc); + for($i = 0; $i < count($headercells); $i++) { + $cells[] = array($type, $headercells[$i]); + $type = 'header'; + } + $type = 'normal'; + } + + return $cells; + } + + protected function tab_paragraph_block_rule($match) { + $num = strlen($match[1]); + $text = $match[2]; + $html = ""; + for($i = 0; $i < $num - 1; $i++) { + $html = parser_utils::h('p', $html, array('class' => 'wiki_tab_paragraph')); + } + + return parser_utils::h('p', $text, array('class' => 'wiki_tab_paragraph')); + } + + protected function desc_list_block_rule($match) { + preg_match_all("/^(.+?)\:(.+?)\;$/ims", $match[0], $listitems, PREG_SET_ORDER); + + $list = ""; + foreach($listitems as $li) { + $term = $li[1]; + $this->rules($term); + + $description = $li[2]; + $this->rules($description); + + $list .= parser_utils::h('dt', $term).parser_utils::h('dd', $description); + } + + return $list; + } + + /** + * Tag functions + */ + + /** + * Bold and italic similar to creole... + */ + protected function italic_tag_rule($match) { + $text = $match[1]; + if(strlen($match[2]) == 5) { + $text .= "''"; + } + + $this->rules($text, array('only' => array('bold'))); + if(strpos($text, "''") !== false) { + $text = str_replace("''", $this->protect("''"), $text); + } + + return array($text, array()); + } + + /** + * Link tag functions + */ + + protected function link_tag_rule($match) { + return $this->format_link($match[1]); + } + + protected function url_tag_tag_rule($match) { + $text = trim($match[1]); + if(preg_match("/(.+?)\|(.+)/is", $text, $matches)) { + $link = $matches[1]; + $text = $matches[2]; + } + else if(preg_match("/(.+?)\ (.+)/is", $text, $matches)) { + $link = $matches[1]; + $text = $matches[2]; + } + else { + $link = $text; + } + return array($this->protect($text), array('href' => $this->protect($link))); + } + + protected function url_tag_rule($match) { + $url = $this->protect($match[1]); + $options = array('href' => $url); + + return array($url, $options); + } + + /** + * Attachments & images + */ + + protected function image_tag_rule($match) { + return $this->format_image($match[1], $match[2]); + } + + protected function attach_tag_rule($match) { + $parts = split("\|", $match[1]); + + $url = array_shift($parts); + + if(count($parts) > 0) { + $text = array_shift($parts); + } + + $extension = substr($url, strrpos($url, ".")); + $text = empty($text) ? $url : $text; + + $imageextensions = array('jpg', 'jpeg', 'png', 'bmp', 'gif', 'tif'); + if(in_array($extension, $imageextensions)) { + $align = 'left'; + if(count($parts) > 0) { + switch(strtolower($text)) { + case 'right': + $align = 'right'; + break; + case 'center': + $align = 'center'; + break; + default: + $align = 'left'; + } + $text = $parts[0]; + } + return $this->format_image($url, $text, $text, $align); + } + else { + $url = $this->real_path($url); + return parser_utils::h('a', $text, array('href' => $url, 'class' => 'wiki-attachment')); + } + } +} diff --git a/mod/wiki/parser/markups/wikimarkup.php b/mod/wiki/parser/markups/wikimarkup.php new file mode 100644 index 00000000000..c0c88cb6395 --- /dev/null +++ b/mod/wiki/parser/markups/wikimarkup.php @@ -0,0 +1,433 @@ + "Inside the link", 'url' => "http://url.com/Wiki/Entry", 'new' => false). + */ + private $linkgeneratorcallback = array('parser_utils', 'wiki_parser_link_callback'); + private $linkgeneratorcallbackargs = array(); + + /** + * Table generator callback + */ + + private $tablegeneratorcallback = array('parser_utils', 'wiki_parser_table_callback'); + + /** + * Get real path from relative path + */ + private $realpathcallback = array('parser_utils', 'wiki_parser_real_path'); + private $realpathcallbackargs = array(); + + /** + * Before and after parsing... + */ + + protected function before_parsing() { + $this->toc = array(); + + $this->string = preg_replace('/\r\n/', "\n", $this->string); + $this->string = preg_replace('/\r/', "\n", $this->string); + + $this->string .= "\n\n"; + + if (!$this->printable && $this->section_editing) { + $this->returnvalues['unparsed_text'] = $this->string; + $this->string = $this->get_repeated_sections($this->string); + } + } + + protected function after_parsing() { + if (!$this->printable) { + $this->returnvalues['repeated_sections'] = array_unique($this->returnvalues['repeated_sections']); + } + + $this->process_toc(); + + $this->string = preg_replace("/\n\s/", "\n", $this->string); + $this->string = preg_replace("/\n{2,}/", "\n", $this->string); + $this->string = trim($this->string); + $this->string .= "\n"; + } + + /** + * Set options + */ + + protected function set_options($options) { + parent::set_options($options); + + $this->returnvalues['link_count'] = array(); + $this->returnvalues['repeated_sections'] = array(); + $this->returnvalues['toc'] = ""; + + foreach ($options as $name => $o) { + switch ($name) { + case 'link_callback': + $callback = split(':', $o); + + global $CFG; + require_once($CFG->dirroot . $callback[0]); + + if (function_exists($callback[1])) { + $this->linkgeneratorcallback = $callback[1]; + } + break; + case 'link_callback_args': + if (is_array($o)) { + $this->linkgeneratorcallbackargs = $o; + } + break; + case 'real_path_callback': + $callback = split(':', $o); + + global $CFG; + require_once($CFG->dirroot . $callback[0]); + + if (function_exists($callback[1])) { + $this->realpathcallback = $callback[1]; + } + break; + case 'real_path_callback_args': + if (is_array($o)) { + $this->realpathcallbackargs = $o; + } + break; + case 'table_callback': + $callback = split(':', $o); + + global $CFG; + require_once($CFG->dirroot . $callback[0]); + + if (function_exists($callback[1])) { + $this->tablegeneratorcallback = $callback[1]; + } + break; + case 'pretty_print': + if ($o) { + $this->pretty_print = true; + } + break; + case 'pageid': + $this->wiki_page_id = $o; + break; + case 'printable': + if ($o) { + $this->printable = true; + } + break; + } + } + } + + /** + * Generic block rules + */ + + protected function line_break_block_rule($match) { + return '
          '; + } + + protected function list_block_rule($match) { + preg_match_all("/^\ *([\*\#]{1,5})\ *((?:[^\n]|\n(?!(?:\ *[\*\#])|\n))+)/im", $match[1], $listitems, PREG_SET_ORDER); + + return $this->process_block_list($listitems) . $match[2]; + } + + protected function nowiki_block_rule($match) { + return parser_utils::h('pre', $this->protect($match[1])); + } + + /** + * Generic tag rules + */ + + protected function nowiki_tag_rule($match) { + return parser_utils::h('tt', $this->protect($match[1])); + } + + /** + * Header generation + */ + + protected function generate_header($text, $level) { + $text = trim($text); + + if (!$this->pretty_print && $level == 1) { + $text .= parser_utils::h('a', $this->section_edit_text, array('href' => "edit.php?pageid={$this->wiki_page_id}§ion=" . urlencode($text), 'class' => 'wiki_edit_section')); + } + + if ($level < 4) { + $this->toc[] = array($level, $text); + $num = count($this->toc); + $text = parser_utils::h('a', "", array('name' => "toc-$num")) . $text; + } + + return parser_utils::h('h' . $level, $text) . "\n\n"; + } + + /** + * Table of contents processing after parsing + */ + protected function process_toc() { + if (empty($this->toc)) { + return; + } + + $toc = ""; + $currentsection = array(0, 0, 0); + $i = 1; + foreach ($this->toc as & $header) { + switch ($header[0]) { + case 1: + $currentsection = array($currentsection[0] + 1, 0, 0); + break; + case 2: + $currentsection[1]++; + $currentsection[2] = 0; + if ($currentsection[0] == 0) { + $currentsection[0]++; + } + break; + case 3: + $currentsection[2]++; + if ($currentsection[1] == 0) { + $currentsection[1]++; + } + if ($currentsection[0] == 0) { + $currentsection[0]++; + } + break; + default: + continue; + } + $number = "$currentsection[0]"; + if (!empty($currentsection[1])) { + $number .= ".$currentsection[1]"; + if (!empty($currentsection[2])) { + $number .= ".$currentsection[2]"; + } + } + $toc .= parser_utils::h('p', $number . ". " . parser_utils::h('a', $header[1], array('href' => "#toc-$i")), array('class' => 'wiki-toc-section-' . $header[0] . " wiki-toc-section")); + $i++; + } + + $this->returnvalues['toc'] = "

          Table of contents

          $toc
          "; + } + + /** + * List helpers + */ + + private function process_block_list($listitems) { + $list = array(); + foreach ($listitems as $li) { + $text = str_replace("\n", "", $li[2]); + $this->rules($text); + + if ($li[1][0] == '*') { + $type = 'ul'; + } else { + $type = 'ol'; + } + + $list[] = array(strlen($li[1]), $text, $type); + } + $type = $list[0][2]; + return "<$type>" . "\n" . $this->generate_list($list) . "\n" . "" . "\n"; + } + + /** + * List generation function from an array of array(level, text) + */ + + protected function generate_list($listitems) { + $list = ""; + $current_depth = 1; + $next_depth = 1; + $liststack = array(); + for ($lc = 0; $lc < count($listitems) && $next_depth; $lc++) { + $cli = $listitems[$lc]; + $nli = isset($listitems[$lc + 1]) ? $listitems[$lc + 1] : null; + + $text = $cli[1]; + + $current_depth = $next_depth; + $next_depth = $nli ? $nli[0] : null; + + if ($next_depth == $current_depth || $next_depth == null) { + $list .= parser_utils::h('li', $text) . "\n"; + } else if ($next_depth > $current_depth) { + $next_depth = $current_depth + 1; + + $list .= "
        • " . $text . "\n"; + $list .= "<" . $nli[2] . ">" . "\n"; + $liststack[] = $nli[2]; + } else { + $list .= parser_utils::h('li', $text) . "\n"; + + for ($lv = $next_depth; $lv < $current_depth; $lv++) { + $type = array_pop($liststack); + $list .= "" . "\n" . "
        • " . "\n"; + } + } + } + + for ($lv = 1; $lv < $current_depth; $lv++) { + $type = array_pop($liststack); + $list .= "" . "\n" . "" . "\n"; + } + + return $list; + } + + /** + * Table generation functions + */ + + protected function generate_table($table) { + $table_html = call_user_func_array($this->tablegeneratorcallback, array($table)); + + return $table_html; + } + + protected function format_image($src, $alt, $caption = "", $align = 'left') { + $src = $this->real_path($src); + return parser_utils::h('div', parser_utils::h('p', $caption) . '' . $alt . '', array('class' => 'wiki_image_' . $align)); + } + + protected function real_path($url) { + $callbackargs = array_merge(array($url), $this->realpathcallbackargs); + return call_user_func_array($this->realpathcallback, $callbackargs); + } + + /** + * Link internal callback + */ + + protected function link($link, $anchor = "") { + $link = trim($link); + if (preg_match("/^(https?|s?ftp):\/\/.+$/i", $link)) { + $link = trim($link, ",.?!"); + return array('content' => $link, 'url' => $link); + } else { + $callbackargs = $this->linkgeneratorcallbackargs; + $callbackargs['anchor'] = $anchor; + $link = call_user_func_array($this->linkgeneratorcallback, array($link, $callbackargs)); + + if (isset($link['link_info'])) { + $l = $link['link_info']['link']; + unset($link['link_info']['link']); + $this->returnvalues['link_count'][$l] = $link['link_info']; + } + return $link; + } + } + + /** + * Format links + */ + + protected function format_link($text) { + $matches = array(); + if (preg_match("/^([^\|]+)\|(.+)$/i", $text, $matches)) { + $link = $matches[1]; + $content = trim($matches[2]); + if (preg_match("/(.+)#(.*)/is", $link, $matches)) { + $link = $this->link($matches[1], $matches[2]); + } else if ($link[0] == '#') { + $link = array('url' => "#" . urlencode(substr($link, 1))); + } else { + $link = $this->link($link); + } + + $link['content'] = $content; + } else { + $link = $this->link($text); + } + + if (isset($link['new']) && $link['new']) { + $options = array('class' => 'wiki_newentry'); + } else { + $options = array(); + } + + $link['content'] = $this->protect($link['content']); + $link['url'] = $this->protect($link['url']); + + $options['href'] = $link['url']; + + if ($this->printable) { + $options['href'] = '#'; //no target for the link + } + return array($link['content'], $options); + } + + /** + * Section editing + */ + + public function get_section($header, $text, $clean = false) { + if ($clean) { + $text = preg_replace('/\r\n/', "\n", $text); + $text = preg_replace('/\r/', "\n", $text); + $text .= "\n\n"; + } + + preg_match("/(.*?)(=\ *\Q$header\E\ *=*\n.*?)((?:\n=[^=]+.*)|$)/is", $text, $match); + + if (!empty($match)) { + return array($match[1], $match[2], $match[3]); + } else { + return false; + } + } + + protected function get_repeated_sections(&$text, $repeated = array()) { + $this->repeated_sections = $repeated; + return preg_replace_callback($this->blockrules['header']['expression'], array($this, 'get_repeated_sections_callback'), $text); + } + + protected function get_repeated_sections_callback($match) { + $num = strlen($match[1]); + $text = trim($match[2]); + if ($num == 1) { + if (in_array($text, $this->repeated_sections)) { + $this->returnvalues['repeated_sections'][] = $text; + return $text . "\n"; + } else { + $this->repeated_sections[] = $text; + } + } + + return $match[0]; + } + +} diff --git a/mod/wiki/parser/parser.php b/mod/wiki/parser/parser.php new file mode 100644 index 00000000000..b8af04df213 --- /dev/null +++ b/mod/wiki/parser/parser.php @@ -0,0 +1,284 @@ +dirroot.'/mod/wiki/parser/'; + } + + $type = strtolower($type); + if(self::create_parser_instance($type)) { + return self::$parsers[$type]->parse($string, $options); + } + else { + return false; + } + } + + public static function get_token($name, $type) { + if(self::create_parser_instance($type)) { + return self::$parsers[$type]->get_token($name); + } + else { + return false; + } + } + + public static function get_section(&$string, $type, $section, $all_content = false) { + if(self::create_parser_instance($type)) { + $content = self::$parsers[$type]->get_section($section, $string, true); + + if($all_content) { + return $content; + } + else { + return $content[1]; + } + } + else { + return false; + } + } + + private static function create_parser_instance($type) { + if(empty(self::$parsers[$type])) { + if(include(self::$basepath."markups/$type.php")) { + $class = strtolower($type)."_parser"; + if(class_exists($class)) { + self::$parsers[$type] = new $class; + return true; + } + else { + return false; + } + } + else { + return false; + } + } + else { + return true; + } + } +} + +require_once('utils.php'); + +abstract class generic_parser { + protected $string; + + protected $blockrules = array(); + protected $tagrules = array(); + + private $rulestack = array(); + + protected $parser_status = 'Before'; + + /** + * Dynamic return values + */ + + protected $returnvalues = array(); + + private $nowikiindex = array(); + + protected $nowikitoken = "%!"; + + public function __construct() {} + + /** + * Parse function + */ + + public function parse(&$string, $options = array()) { + if(!is_string($string)) { + return false; + } + + $this->string =& $string; + + $this->set_options(is_array($options) ? $options : array()); + + $this->initialize_nowiki_index(); + + if(method_exists($this, 'before_parsing')) { + $this->before_parsing(); + } + + $this->parser_status = 'Parsing'; + + foreach($this->blockrules as $name => $block) { + $this->process_block_rule($name, $block); + } + + $this->commit_nowiki_index(); + + $this->parser_status = 'After'; + + if(method_exists($this, 'after_parsing')) { + $this->after_parsing(); + } + + return array('parsed_text' => $this->string) + $this->returnvalues; + } + + /** + * Initialize options + */ + + protected function set_options($options) {} + + /** + * Block processing function & callbacks + */ + + protected function process_block_rule($name, $block) { + $this->rulestack[] = array('callback' => method_exists($this, $name."_block_rule") ? $name."_block_rule" : null, 'rule' => $block); + + $this->string = preg_replace_callback($block['expression'], array($this, 'block_callback'), $this->string); + + array_pop($this->rulestack); + } + + private function block_callback($match) { + $rule = end($this->rulestack); + if(!empty($rule['callback'])) { + $stuff = $this->{$rule['callback']}($match); + } + else { + $stuff = $match[1]; + } + + if(is_array($stuff) && $rule['rule']['tag']) { + $this->rules($stuff[0], $rule['rule']['tags']); + $stuff = "\n".parser_utils::h($rule['rule']['tag'], $stuff[0], $stuff[1])."\n"; + } + else { + if(!isset($rule['rule']['tags'])) { + $rule['rule']['tags'] = null; + } + $this->rules($stuff, $rule['rule']['tags']); + if(isset($rule['rule']['tag']) && is_string($rule['rule']['tag'])) { + $stuff = "\n".parser_utils::h($rule['rule']['tag'], $stuff)."\n"; + } + } + + return $stuff; + } + + /** + * Rules processing function & callback + */ + + protected final function rules(&$text, $rules = null) { + if($rules === null) { + $rules = array('except' => array()); + } + else if(is_array($rules) && count($rules) > 1) { + $rules = array('only' => $rules); + } + + if(isset($rules['only']) && is_array($rules['only'])) { + $rules = $rules['only']; + foreach($rules as $r) { + if(!empty($this->tagrules[$r])) { + $this->process_tag_rule($r, $this->tagrules[$r], $text); + } + } + } + else if(isset($rules['except']) && is_array($rules['except'])) { + $rules = $rules['except']; + foreach($this->tagrules as $r => $tr) { + if(!in_array($r, $rules)) { + $this->process_tag_rule($r, $tr, $text); + } + } + } + } + + private function process_tag_rule($name, $rule, &$text) { + if(method_exists($this, $name."_tag_rule")) { + $this->rulestack[] = array('callback' => $name."_tag_rule", 'rule' => $rule); + $text = preg_replace_callback($rule['expression'], array($this, 'tag_callback'), $text); + array_pop($this->rulestack); + } + else { + if(isset($rule['simple'])) { + $replace = "<{$rule['tag']} />"; + } + else { + $replace = parser_utils::h($rule['tag'], "$1"); + } + + $text = preg_replace($rule['expression'], $replace, $text); + } + } + + private function tag_callback($match) { + $rule = end($this->rulestack); + $stuff = $this->{$rule['callback']}($match); + + if(is_array($stuff)) { + return parser_utils::h($rule['rule']['tag'], $stuff[0], $stuff[1]); + } + else { + return $stuff; + } + } + + /** + * Special nowiki parser index + */ + + private function initialize_nowiki_index() { + $token = "\Q".$this->nowikitoken."\E"; + $this->string = preg_replace_callback("/".$token."\d+".$token."/", array($this, "initialize_nowiki_index_callback"), $this->string); + } + + private function initialize_nowiki_index_callback($match) { + return $this->protect($match[0]); + } + + protected function protect($text) { + $this->nowikiindex[] = $text; + + return $this->nowikitoken.(count($this->nowikiindex)-1).$this->nowikitoken; + } + + private function commit_nowiki_index() { + $token = "\Q".$this->nowikitoken."\E"; + $this->string = preg_replace_callback("/".$token."(\d+)".$token."/", array($this, "commit_nowiki_index_callback"), $this->string); + } + + private function commit_nowiki_index_callback($match) { + return $this->nowikiindex[intval($match[1])]; + } + + /** + * Get token of the parsable element $name. + */ + + public function get_token($name) { + foreach(array_merge($this->blockrules, $this->tagrules) as $n => $v) { + if($name == $n && isset($v['token'])) { + return $v['token'] ? $v['token'] : false; + } + } + + return false; + } +} diff --git a/mod/wiki/parser/utils.php b/mod/wiki/parser/utils.php new file mode 100644 index 00000000000..eb14bc07657 --- /dev/null +++ b/mod/wiki/parser/utils.php @@ -0,0 +1,98 @@ +dirroot . "/lib/outputcomponents.php"); + +class parser_utils { + + public static function h($tag, $text = null, $options = array(), $escape_text = false) { + $tag = htmlentities($tag); + if(!empty($text) && $escape_text) { + $text = htmlentities($text); + } + return html_writer::tag($tag, $text, $options); + } + + /** + * Default link generator + */ + + public static function wiki_parser_link_callback($link, $options) { + $l = urlencode($link); + if(!empty($options['anchor'])) { + $l .= "#".urlencode($options['anchor']); + } + return array('content' => $link, 'url' => "http://".$l); + } + + + /** + * Default table generator + */ + + public static function wiki_parser_table_callback($table) { + $html = ""; + $headers = $table[0]; + $columncount = count($headers); + $headerhtml = ""; + foreach($headers as $h) { + $text = trim($h[1]); + if($h[0] == 'header') { + $headerhtml .= "\n".parser_utils::h('th', $text)."\n"; + $hasheaders = true; + } + else if($h[0] == 'normal'){ + $headerhtml .= "\n".parser_utils::h("td", $text)."\n"; + } + } + $headerhtml = "\n".parser_utils::h('tr', $headerhtml)."\n"; + $bodyhtml = ""; + if(isset($hasheaders)) { + $html = "\n".parser_utils::h('thead', $headerhtml)."\n"; + } + else { + $bodyhtml .= $headerhtml; + } + + array_shift($table); + foreach($table as $row) { + $htmlrow = ""; + for($i = 0; $i < $columncount; $i++) { + $text = ""; + if(!isset($row[$i])) { + $htmlrow .= "\n".parser_utils::h('td', $text)."\n"; + } + else { + $text = trim($row[$i][1]); + if($row[$i][0] == 'header') { + $htmlrow .= "\n".parser_utils::h('th', $text)."\n"; + } + else if($row[$i][0] == 'normal'){ + $htmlrow .= "\n".parser_utils::h('td', $text)."\n"; + } + } + } + $bodyhtml .= "\n".parser_utils::h('tr', $htmlrow)."\n"; + } + + $html .= "\n".parser_utils::h('tbody', $bodyhtml)."\n"; + return "\n".parser_utils::h('table', $html)."\n"; + } + + /** + * Default path converter + */ + + public static function wiki_parser_real_path($url) { + return $url; + } +} + diff --git a/mod/wiki/pix/attachment.png b/mod/wiki/pix/attachment.png new file mode 100644 index 0000000000000000000000000000000000000000..e8219ab61daba4e55e835353de3c4a99e044e890 GIT binary patch literal 309 zcmeAS@N?(olHy`uVBq!ia0vp^AT}2V8<6ZZI=>f4u@pObhHwBu4M$1`kk47*5m^jW z^8thzoz|Gl01AqhxJHyX7o{eaWaj57gkbRT!Nh) s9hTKq;w~&oziMNd8lqmm|FD+5Ts^MwzgO-WpvxFMUHx3vIVCg!0I*AJf&c&j literal 0 HcmV?d00001 diff --git a/mod/wiki/prettyview.php b/mod/wiki/prettyview.php new file mode 100644 index 00000000000..c6a78e84def --- /dev/null +++ b/mod/wiki/prettyview.php @@ -0,0 +1,69 @@ +. + +/** + * This file contains all necessary code to get a printable version of a wiki page + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$pageid = required_param('pageid', PARAM_INT); // Page ID + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} +if (!$cm = get_coursemodule_from_instance("wiki", $subwiki->wikiid)) { + print_error('invalidcoursemodule'); +} +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +require_course_login($course->id, true, $cm); + +$context = get_context_instance(CONTEXT_MODULE, $cm->id); +require_capability('mod/wiki:viewpage', $context); + +add_to_log($course->id, "wiki", "view", "prettyview.php?pageid=$pageid", "$wiki->id"); + +$wikipage = new page_wiki_prettyview($wiki, $subwiki, $cm); + +$wikipage->set_page($page); + +$wikipage->print_header(); +$wikipage->print_content(); +$wikipage->print_footer(); diff --git a/mod/wiki/removepages.html b/mod/wiki/removepages.html deleted file mode 100644 index c76125af040..00000000000 --- a/mod/wiki/removepages.html +++ /dev/null @@ -1,33 +0,0 @@ -
          "; - - -?> -
          -
          - - - - - -listall); - echo html_writer::table($remove_table); -?> -
          -data)) { - print get_string("nocandidatestoremove","wiki",get_string("listall","wiki"))."

          "; - } -?> -listall) { - print ' '."\n"; - } else { - print ' '."\n"; - } -?> - " /> -
          diff --git a/mod/wiki/renderer.php b/mod/wiki/renderer.php new file mode 100644 index 00000000000..f833c7a659f --- /dev/null +++ b/mod/wiki/renderer.php @@ -0,0 +1,401 @@ +. + +/** + * Moodle Wiki 2.0 Renderer + * + * @package mod-wiki + * @copyright 2010 Dongsheng Cai + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +class mod_wiki_renderer extends plugin_renderer_base { + public function page_index() { + global $CFG; + $output = ''; + // Checking wiki instance + if (!$wiki = wiki_get_wiki($this->page->cm->instance)) { + return false; + } + + // @TODO: Fix call to wiki_get_subwiki_by_group + $gid = groups_get_activity_group($this->page->cm); + if (!$subwiki = wiki_get_subwiki_by_group($this->page->cm->instance, $gid)) { + return false; + } + $swid = $subwiki->id; + $pages = wiki_get_page_list($swid); + $selectoptions = array(); + foreach ($pages as $page) { + $selectoptions[$page->id] = $page->title; + } + $label = get_string('pageindex', 'wiki') . ': '; + $select = new single_select(new moodle_url('/mod/wiki/view.php'), 'pageid', $selectoptions); + $select->label = $label; + return $this->output->container($this->output->render($select), 'wiki_index'); + } + + public function search_result($records) { + global $CFG, $PAGE, $OUTPUT; + $table = new html_table(); + $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + $strsearchresults = get_string('searchresult', 'wiki'); + $totalcount = count($records); + $html = $OUTPUT->heading("$strsearchresults $totalcount"); + foreach ($records as $page) { + $table->head = array('title' => $page->title . ' (' . html_writer::link($CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $page->id, get_string('view', 'wiki')) . ')'); + $table->align = array('title' => 'left'); + $table->width = '100%'; + $table->data = array(array(file_rewrite_pluginfile_urls($page->cachedcontent, 'pluginfile.php', $context->id, 'wiki_attachments', $page->id))); + $table->colclasses = array('wikisearchresults'); + $html .= html_writer::table($table); + } + return $this->output->container($html); + } + + public function diff($pageid, $old, $new, $options = array()) { + global $CFG; + if (!empty($options['total'])) { + $total = $options['total']; + } else { + $total = 0; + } + $diff1 = $old->diff; + $diff2 = $new->diff; + + $olduser = $old->user; + $versionlink = new moodle_url('/mod/wiki/viewversion.php', array('pageid' => $pageid, 'versionid' => $old->id)); + $restorelink = new moodle_url('/mod/wiki/restoreversion.php', array('pageid' => $pageid, 'versionid' => $old->id)); + $userlink = new moodle_url('/user/view.php', array('id' => $olduser->id)); + // view version link + $oldversionview = ' '; + $oldversionview .= html_writer::link($versionlink->out(false), get_string('view', 'wiki'), array('class' => 'wiki_diffview')); + $oldversionview .= ' '; + // restore version link + $oldversionview .= html_writer::link($restorelink->out(false), get_string('restore', 'wiki'), array('class' => 'wiki_diffview')); + + // userinfo container + $oldheading = $this->output->container_start('wiki_diffuserleft'); + // username + $oldheading .= html_writer::link($CFG->wwwroot . '/user/view.php?id=' . $olduser->id, fullname($olduser)) . ' '; + // user picture + $oldheading .= html_writer::link($userlink->out(false), $this->output->user_picture($olduser, array('popup' => true)), array('class' => 'notunderlined')); + $oldheading .= $this->output->container_end(); + + // version number container + $oldheading .= $this->output->container_start('wiki_diffversion'); + $oldheading .= get_string('version') . ' ' . $old->version . $oldversionview; + $oldheading .= $this->output->container_end(); + // userdate container + $oldheading .= $this->output->container_start('wiki_difftime'); + $oldheading .= userdate($old->timecreated, get_string('strftimedatetime', 'langconfig')); + $oldheading .= $this->output->container_end(); + + $newuser = $new->user; + $versionlink = new moodle_url('/mod/wiki/viewversion.php', array('pageid' => $pageid, 'versionid' => $new->id)); + $restorelink = new moodle_url('/mod/wiki/restoreversion.php', array('pageid' => $pageid, 'versionid' => $new->id)); + $userlink = new moodle_url('/user/view.php', array('id' => $newuser->id)); + + $newversionview = ' '; + $newversionview .= html_writer::link($versionlink->out(false), get_string('view', 'wiki'), array('class' => 'wiki_diffview')); + // new user info + $newheading = $this->output->container_start('wiki_diffuserright'); + $newheading .= $this->output->user_picture($newuser, array('popup' => true)); + + $newheading .= html_writer::link($userlink->out(false), fullname($newuser), array('class' => 'notunderlined')); + $newheading .= $this->output->container_end(); + + // version + $newheading .= $this->output->container_start('wiki_diffversion'); + $newheading .= get_string('version') . ' ' . $new->version . $newversionview; + $newheading .= $this->output->container_end(); + // userdate + $newheading .= $this->output->container_start('wiki_difftime'); + $newheading .= userdate($new->timecreated, get_string('strftimedatetime', 'langconfig')); + $newheading .= $this->output->container_end(); + + $table1 = new html_table(); + $table1->head = array($oldheading); + $table1->width = '100%'; + $table1->data = array(array($diff1)); + + $table2 = new html_table(); + $table2->head = array($newheading); + $table2->width = '100%'; + $table2->data = array(array($diff2)); + $output = ''; + + $box = new html_table(); + $box->width = '95%'; + $box->data = array(array(html_writer::table($table1), html_writer::table($table2))); + $output .= html_writer::table($box); + + if (!empty($total)) { + $output .= '
          '; + $output .= $this->output->container($this->diff_paging_bar(1, $new->version - 1, $old->version, $CFG->wwwroot . '/mod/wiki/diff.php?pageid=' . $pageid . '&comparewith=' . $new->version . '&', 'compare', false, true), 'wiki_diff_oldpaging'); + $output .= $this->output->container($this->diff_paging_bar($old->version + 1, $total, $new->version, $CFG->wwwroot . '/mod/wiki/diff.php?pageid=' . $pageid . '&compare=' . $old->version . '&', 'comparewith', false, true), 'wiki_diff_newpaging'); + $output .= '
          '; + } + + return $output; + } + + /** + * Prints a single paging bar to provide access to other versions + * + * @param int $minpage First page to be displayed in the bar + * @param int $maxpage Last page to be displayed in the bar + * @param int $page The page you are currently viewing + * @param mixed $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number. + * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page. + * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc) + * @param bool $nocurr do not display the current page as a link + * @param bool $return whether to return an output string or echo now + * @return bool or string + */ + public function diff_paging_bar($minpage, $maxpage, $page, $baseurl, $pagevar = 'page', $nocurr = false) { + $totalcount = $maxpage - $minpage; + $maxdisplay = 2; + $output = ''; + + if ($totalcount > 0) { + $output .= '
          '; + $output .= get_string('version', 'wiki') . ':'; + if ($page - $minpage > 0) { + $pagenum = $page - 1; + if (!is_a($baseurl, 'moodle_url')) { + $output .= ' () '; + } else { + $output .= ' () '; + } + } + + if ($page - $minpage > 4) { + $startpage = $page - 3; + if (!is_a($baseurl, 'moodle_url')) { + $output .= ' ' . $minpage . ' ...'; + } else { + $output .= ' ' . $minpage . ' ...'; + } + } else { + $startpage = $minpage; + } + $currpage = $startpage; + $displaycount = 0; + while ($displaycount < $maxdisplay and $currpage <= $maxpage) { + if ($page == $currpage && empty($nocurr)) { + $output .= '  ' . $currpage; + } else { + if (!is_a($baseurl, 'moodle_url')) { + $output .= '  ' . $currpage . ''; + } else { + $output .= '  ' . $currpage . ''; + } + + } + $displaycount++; + $currpage++; + } + if ($currpage < $maxpage) { + if (!is_a($baseurl, 'moodle_url')) { + $output .= ' ...' . $maxpage . ' '; + } else { + $output .= ' ...' . $maxpage . ' '; + } + } else if ($currpage == $maxpage) { + if (!is_a($baseurl, 'moodle_url')) { + $output .= '  ' . $currpage . ''; + } else { + $output .= '  ' . $currpage . ''; + } + } + $pagenum = $page + 1; + if ($page != $maxpage) { + if (!is_a($baseurl, 'moodle_url')) { + $output .= '  ()'; + } else { + $output .= '  ()'; + } + } + $output .= '
          '; + } + + return $output; + } + public function wiki_info() { + return $this->output->box($this->page->activityrecord->intro, 'generalbox', 'intro'); + } + public function tabs($page, $tabitems, $options) { + global $CFG; + if (empty($page)) { + return null; + } + $tabs = array(); + $baseurl = $CFG->wwwroot . '/mod/wiki/'; + + $pageid = null; + if (isset($page)) { + $pageid = $page->id; + } + + $selected = $options['activetab']; + + // make specific tab linked even it is active + if (!empty($options['linkedwhenactive'])) { + $linked = $options['linkedwhenactive']; + } else { + $linked = ''; + } + + if (!empty($options['inactivetabs'])) { + $inactive = $options['inactivetabs']; + } else { + $inactive = array(); + } + + foreach ($tabitems as $tab) { + $link = $baseurl . $tab . '.php?pageid=' . $pageid; + if ($linked == $tab) { + $tabs[] = new tabobject($tab, $link, get_string($tab, 'wiki'), '', true); + } else { + $tabs[] = new tabobject($tab, $link, get_string($tab, 'wiki')); + } + } + + return print_tabs(array($tabs), $selected, $inactive, null, true); + } + + public function prettyview_link($page) { + $html = ''; + $link = new moodle_url('/mod/wiki/prettyview.php', array('pageid' => $page->id)); + $html .= $this->output->container_start('wiki_right'); + $html .= $this->output->action_link($link, get_string('prettyprint', 'wiki'), new popup_action('click', $link)); + $html .= $this->output->container_end(); + return $html; + } + + public function wiki_print_subwiki_selector($wiki, $subwiki, $page) { + global $CFG, $USER; + require_once($CFG->dirroot . '/user/lib.php'); + + $cm = get_coursemodule_from_instance('wiki', $wiki->id); + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + // @TODO: A plenty of duplicated code below this lines. + // Create private functions. + switch (groups_get_activity_groupmode($cm)) { + case NOGROUPS: + if ($wiki->wikimode == 'collaborative') { + // No need to print anything + return; + } else if ($wiki->wikimode == 'individual') { + // We have private wikis here + + $view = has_capability('mod/wiki:viewpage', $context, $USER); + $manage = has_capability('mod/wiki:managewiki', $context, $USER); + + // Only people with these capabilities can view all wikis + if ($view && $manage) { + // @TODO: Print here a combo that contains all users. + $subwikis = wiki_get_subwikis($wiki->id); + $options = array(); + foreach ($subwikis as $subwiki) { + if ($subwiki->userid == 0) { + continue; + } + $user = user_get_users_by_id(array($subwiki->userid)); + $options[$subwiki->id] = fullname($user[$subwiki->userid]); + } + + echo $this->output->container_start('wiki_right'); + $url = $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $page->id; + $name = 'swid'; + $selected = $page->subwikiid; + echo $this->output->single_select($url, $name, $options, $selected); + echo $this->output->container_end(); + } + return; + } else { + // error + return; + } + case SEPARATEGROUPS: + if ($wiki->wikimode == 'collaborative') { + // We need to print a select to choose a course group + + $params = 'pageid=' . $page->id; + + echo $this->output->container_start('wiki_right'); + groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/wiki/view.php?' . $params); + echo $this->output->container_end(); + return; + } else if ($wiki->wikimode == 'individual') { + // @TODO: Print here a combo that contains all users of that subwiki. + echo $this->output->container_start('wiki_right'); + echo "TODO: Print here a combo to choose user wiki from that subwiki"; + echo $this->output->container_end(); + return; + } else { + // error + return; + } + CASE VISIBLEGROUPS: + if ($wiki->wikimode == 'collaborative') { + // We need to print a select to choose a course group + + $params = 'pageid=' . $page->id; + + echo $this->output->container_start('wiki_right'); + groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/wiki/view.php?' . $params); + echo $this->output->container_end(); + return; + + } else if ($wiki->wikimode == 'individual') { + // @TODO: Print here a combo that contains all users of that wiki grouped by group. + echo $this->output->container_start('wiki_right'); + echo "TODO: Print here a combo to choose user wiki from that wiki"; + echo $this->output->container_end(); + return; + + } else { + // error + return; + } + default: + // error + return; + + } + + } + + function menu_map($pageid, $currentselect) { + $options = array('contributions', 'links', 'orphaned', 'pageindex', 'pagelist', 'updatedpages'); + $items = array(); + foreach ($options as $opt) { + $items[] = get_string($opt, 'wiki'); + } + $selectoptions = array(); + foreach ($items as $key=>$item) { + $selectoptions[$key+1] = $item; + } + $select = new single_select(new moodle_url('/mod/wiki/map.php', array('pageid'=>$pageid)), 'option', $selectoptions, $currentselect); + $select->label = get_string('mapmenu', 'wiki') . ': '; + return $this->output->container($this->output->render($select), 'midpad'); + } +} diff --git a/mod/wiki/restorelib.php b/mod/wiki/restorelib.php index 74878fa4835..94c9002ca2e 100644 --- a/mod/wiki/restorelib.php +++ b/mod/wiki/restorelib.php @@ -1,414 +1,16 @@ id) - // - // wiki_entries - // (pk->id, fk->wikiid) - // - // wiki_pages - // (pk->pagename,version,wiki, fk->wiki) - // - // Meaning: pk->primary key field of the table - // fk->foreign key to link with parent - // nt->nested field (recursive data) - // CL->course level info - // UL->user level info - // files->table may have files) - // - //----------------------------------------------------------- - - function wiki_restore_mods($mod,$restore) { - global $CFG, $DB; - - $status = true; - - //Get record from backup_ids - $data = backup_getid($restore->backup_unique_code,$mod->modtype,$mod->id); - - if ($data) { - //Now get completed xmlized object - $info = $data->info; - //if necessary, write to restorelog and adjust date/time fields - if ($restore->course_startdateoffset) { - restore_log_date_changes('Wiki', $restore, $info['MOD']['#'], array('TIMEMODIFIED')); - } - //traverse_xmlize($info); //Debug - //print_object ($GLOBALS['traverse_array']); //Debug - //$GLOBALS['traverse_array']=""; //Debug - - //Now, build the wiki record structure - $wiki->course = $restore->course_id; - $wiki->name = backup_todb($info['MOD']['#']['NAME']['0']['#']); - $wiki->intro = backup_todb($info['MOD']['#']['SUMMARY']['0']['#']); - $wiki->pagename = backup_todb($info['MOD']['#']['PAGENAME']['0']['#']); - $wiki->wtype = backup_todb($info['MOD']['#']['WTYPE']['0']['#']); - $wiki->ewikiprinttitle = backup_todb($info['MOD']['#']['EWIKIPRINTTITLE']['0']['#']); - $wiki->htmlmode = backup_todb($info['MOD']['#']['HTMLMODE']['0']['#']); - $wiki->ewikiacceptbinary = backup_todb($info['MOD']['#']['EWIKIACCEPTBINARY']['0']['#']); - $wiki->disablecamelcase = backup_todb($info['MOD']['#']['DISABLECAMELCASE']['0']['#']); - $wiki->setpageflags = backup_todb($info['MOD']['#']['SETPAGEFLAGS']['0']['#']); - $wiki->strippages = backup_todb($info['MOD']['#']['STRIPPAGES']['0']['#']); - $wiki->removepages = backup_todb($info['MOD']['#']['REMOVEPAGES']['0']['#']); - $wiki->revertchanges = backup_todb($info['MOD']['#']['REVERTCHANGES']['0']['#']); - $wiki->initialcontent = backup_todb($info['MOD']['#']['INITIALCONTENT']['0']['#']); - $wiki->timemodified = backup_todb($info['MOD']['#']['TIMEMODIFIED']['0']['#']); - - //The structure is equal to the db, so insert the wiki - $newid = $DB->insert_record ("wiki",$wiki); - - //Do some output - if (!defined('RESTORE_SILENTLY')) { - echo "
        • ".get_string("modulename","wiki")." \"".format_string($wiki->name,true)."\"
        • "; - } - backup_flush(300); - - if ($newid) { - //We have the newid, update backup_ids - backup_putid($restore->backup_unique_code,$mod->modtype, - $mod->id, $newid); - //Now check if want to restore user data and do it. - if (restore_userdata_selected($restore,'wiki',$mod->id)) { - //Restore wiki_entries - $status = wiki_entries_restore_mods($mod->id,$newid,$info,$restore); - } - } else { - $status = false; - } - } else { - $status = false; - } - - return $status; - } - - //This function restores the wiki_entries - function wiki_entries_restore_mods($old_wiki_id,$new_wiki_id,$info,$restore) { - global $CFG, $DB; - - $status = true; - - //Get the entries array - $entries = $info['MOD']['#']['ENTRIES']['0']['#']['ENTRY']; - - //Iterate over entries - for($i = 0; $i < sizeof($entries); $i++) { - $ent_info = $entries[$i]; - //traverse_xmlize($ent_info); //Debug - //print_object ($GLOBALS['traverse_array']); //Debug - //$GLOBALS['traverse_array']=""; //Debug - - //We'll need this later!! - $oldid = backup_todb($ent_info['#']['ID']['0']['#']); - - //Now, build the wiki_ENTRIES record structure - $entry = new object(); - $entry->wikiid = $new_wiki_id; - $entry->course = $restore->course_id; - $entry->userid = backup_todb($ent_info['#']['USERID']['0']['#']); - $entry->groupid = backup_todb($ent_info['#']['GROUPID']['0']['#']); - $entry->pagename = backup_todb($ent_info['#']['PAGENAME']['0']['#']); - $entry->timemodified = backup_todb($ent_info['#']['TIMEMODIFIED']['0']['#']); - $entry->timemodified += $restore->course_startdateoffset; - //We have to recode the userid field - $user = backup_getid($restore->backup_unique_code,"user",$entry->userid); - if ($user) { - $entry->userid = $user->new_id; - } - //We have to recode the groupid field - $group = restore_group_getid($restore, $entry->groupid); - if ($group) { - $entry->groupid = $group->new_id; - } - - //The structure is equal to the db, so insert the wiki_entries - $newid = $DB->insert_record ("wiki_entries",$entry); - - //Do some output - if (($i+1) % 50 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if (($i+1) % 1000 == 0) { - echo "
          "; - } - } - backup_flush(300); - } - - if ($newid) { - //We have the newid, update backup_ids - backup_putid($restore->backup_unique_code,"wiki_entries",$oldid,$newid); - - //Restore wiki_pages - $status = wiki_pages_restore_mods($oldid,$newid,$ent_info,$restore); - - //Now copy moddata associated files - $status = wiki_restore_files ($old_wiki_id, $new_wiki_id, $oldid, $newid, $restore); - } else { - $status = false; - } - } - return $status; - } - - //This function restores the wiki_pages - function wiki_pages_restore_mods($old_entry_id,$new_entry_id,$info,$restore) { - global $CFG, $DB; - - $status = true; - - //Get the comments array - $pages = $info['#']['PAGES']['0']['#']['PAGE']; - - //Iterate over pages - for($i = 0; $i < sizeof($pages); $i++) { - $pag_info = $pages[$i]; - //traverse_xmlize($pag_info); //Debug - //print_object ($GLOBALS['traverse_array']); //Debug - //$GLOBALS['traverse_array']=""; //Debug - - //We'll need this later!! - $oldid = backup_todb($pag_info['#']['ID']['0']['#']); - - //Now, build the wiki_page record structure - $page->wiki = $new_entry_id; - $page->pagename = backup_todb($pag_info['#']['PAGENAME']['0']['#']); - $page->version = backup_todb($pag_info['#']['VERSION']['0']['#']); - $page->flags = backup_todb($pag_info['#']['FLAGS']['0']['#']); - $page->content = backup_todb($pag_info['#']['CONTENT']['0']['#']); - $page->author = backup_todb($pag_info['#']['AUTHOR']['0']['#']); - $page->userid = backup_todb($pag_info['#']['USERID']['0']['#']); - $page->created = backup_todb($pag_info['#']['CREATED']['0']['#']); - $page->created += $restore->course_startdateoffset; - $page->lastmodified = backup_todb($pag_info['#']['LASTMODIFIED']['0']['#']); - $page->lastmodified += $restore->course_startdateoffset; - $page->refs = str_replace("$@LINEFEED@$","\n",backup_todb($pag_info['#']['REFS']['0']['#'])); - $page->meta = backup_todb($pag_info['#']['META']['0']['#']); - $page->hits = backup_todb($pag_info['#']['HITS']['0']['#']); - - //We have to recode the userid field - $user = backup_getid($restore->backup_unique_code,"user",$page->userid); - if ($user) { - $page->userid = $user->new_id; - } - //The structure is equal to the db, so insert the wiki_pages - $newid = $DB->insert_record ("wiki_pages",$page); - - //Do some output - if (($i+1) % 50 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if (($i+1) % 1000 == 0) { - echo "
          "; - } - } - backup_flush(300); - } - if ($newid) { - //We have the newid, update backup_ids - backup_putid($restore->backup_unique_code,"wiki_pages",$oldid,$newid); - } else { - $status = false; - } - } - return $status; - } - - function wiki_restore_files ($oldwikiid, $newwikiid, $oldentryid, $newentryid, $restore) { - - global $CFG; - - $status = true; - $todo = false; - $moddata_path = ""; - $forum_path = ""; - $temp_path = ""; - - //First, we check to "course_id" exists and create is as necessary - //in CFG->dataroot - $dest_dir = $CFG->dataroot."/".$restore->course_id; - $status = check_dir_exists($dest_dir,true); - - //First, locate course's moddata directory - $moddata_path = $CFG->dataroot."/".$restore->course_id."/".$CFG->moddata; - - //Check it exists and create it - $status = check_dir_exists($moddata_path,true); - - //Now, locate wiki directory - if ($status) { - $wiki_path = $moddata_path."/wiki"; - //Check it exists and create it - $status = check_dir_exists($wiki_path,true); - } - - //Now locate the temp dir we are restoring from - if ($status) { - $temp_path = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code. - "/moddata/wiki/".$oldwikiid."/".$oldentryid; - //Check it exists - if (is_dir($temp_path)) { - $todo = true; - } - } - - //If todo, we create the neccesary dirs in course moddata/wiki - if ($status and $todo) { - //First this wiki id - $this_wiki_path = $wiki_path."/".$newwikiid; - $status = check_dir_exists($this_wiki_path,true); - //Now this entry id - $entry_wiki_path = $this_wiki_path."/".$newentryid; - //And now, copy temp_path to entry_wiki_path - $status = backup_copy_file($temp_path, $entry_wiki_path); - } - - return $status; - } - - //Return a content decoded to support interactivities linking. Every module - //should have its own. They are called automatically from - //wiki_decode_content_links_caller() function in each module - //in the restore process - function wiki_decode_content_links ($content,$restore) { - - global $CFG; - - $result = $content; - - //Link to the list of wikis - - $searchstring='/\$@(WIKIINDEX)\*([0-9]+)@\$/'; - //We look for it - preg_match_all($searchstring,$content,$foundset); - //If found, then we are going to look for its new id (in backup tables) - if ($foundset[0]) { - //print_object($foundset); //Debug - //Iterate over foundset[2]. They are the old_ids - foreach($foundset[2] as $old_id) { - //We get the needed variables here (course id) - $rec = backup_getid($restore->backup_unique_code,"course",$old_id); - //Personalize the searchstring - $searchstring='/\$@(WIKIINDEX)\*('.$old_id.')@\$/'; - //If it is a link to this course, update the link to its new location - if($rec->new_id) { - //Now replace it - $result= preg_replace($searchstring,$CFG->wwwroot.'/mod/wiki/index.php?id='.$rec->new_id,$result); - } else { - //It's a foreign link so leave it as original - $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/wiki/index.php?id='.$old_id,$result); - } - } - } - - //Link to wiki view by moduleid - - $searchstring='/\$@(WIKIVIEWBYID)\*([0-9]+)@\$/'; - //We look for it - preg_match_all($searchstring,$result,$foundset); - //If found, then we are going to look for its new id (in backup tables) - if ($foundset[0]) { - //print_object($foundset); //Debug - //Iterate over foundset[2]. They are the old_ids - foreach($foundset[2] as $old_id) { - //We get the needed variables here (course_modules id) - $rec = backup_getid($restore->backup_unique_code,"course_modules",$old_id); - //Personalize the searchstring - $searchstring='/\$@(WIKIVIEWBYID)\*('.$old_id.')@\$/'; - //If it is a link to this course, update the link to its new location - if($rec->new_id) { - //Now replace it - $result= preg_replace($searchstring,$CFG->wwwroot.'/mod/wiki/view.php?id='.$rec->new_id,$result); - } else { - //It's a foreign link so leave it as original - $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/wiki/view.php?id='.$old_id,$result); - } - } - } - - return $result; - } - - //This function makes all the necessary calls to xxxx_decode_content_links() - //function in each module, passing them the desired contents to be decoded - //from backup format to destination site/course in order to mantain inter-activities - //working in the backup/restore process. It's called from restore_decode_content_links() - //function in restore process - function wiki_decode_content_links_caller($restore) { - global $CFG, $DB; - $status = true; - - //Process every wiki PAGE in the course - if ($pages = $DB->get_records_sql("SELECT p.id, p.content - FROM {wiki_pages} p, {wiki} w - WHERE w.course = ? AND - p.wiki = w.id", array($restore->course_id))) { - //Iterate over each post->message - $i = 0; //Counter to send some output to the browser to avoid timeouts - foreach ($pages as $page) { - //Increment counter - $i++; - $content = $page->definition; - $result = restore_decode_content_links_worker($content,$restore); - if ($result != $content) { - //Update record - $page->content = $result; - $status = $DB->update_record("wiki_pages",$page); - if (debugging()) { - if (!defined('RESTORE_SILENTLY')) { - echo '

          '.s($content).'
          changed to
          '.s($result).'

          '; - } - } - } - //Do some output - if (($i+1) % 5 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if (($i+1) % 100 == 0) { - echo "
          "; - } - } - backup_flush(300); - } - } - } - - //Process every wiki (summary) in the course - if ($wikis = $DB->get_records('wiki', array('course'=>$restore->course_id), '', "id,summary")) { - //Iterate over each wiki->summary - $i = 0; //Counter to send some output to the browser to avoid timeouts - foreach ($wikis as $wiki) { - //Increment counter - $i++; - $content = $wiki->summary; - $result = restore_decode_content_links_worker($content,$restore); - if ($result != $content) { - //Update record - $wiki->summary = $result; - $status = $DB->update_record("wiki",$wiki); - if (debugging()) { - if (!defined('RESTORE_SILENTLY')) { - echo '

          '.s($content).'
          changed to
          '.s($result).'

          '; - } - } - } - //Do some output - if (($i+1) % 5 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if (($i+1) % 100 == 0) { - echo "
          "; - } - } - backup_flush(300); - } - } - } - - return $status; - } +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . diff --git a/mod/wiki/restoreversion.php b/mod/wiki/restoreversion.php new file mode 100644 index 00000000000..2664fbeb70a --- /dev/null +++ b/mod/wiki/restoreversion.php @@ -0,0 +1,84 @@ +. + +/** + * This file renders the restoring wikipage HTML + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$pageid = required_param('pageid', PARAM_INT); +$versionid = required_param('versionid', PARAM_INT); +$confirm = optional_param('confirm', '', PARAM_ALPHA); + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} + +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} + +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +if (!$cm = get_coursemodule_from_instance('wiki', $wiki->id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} + +require_course_login($course->id, true, $cm); + +add_to_log($course->id, "restore", "restore", "view.php?id=$cm->id", "$wiki->id"); + +if ($confirm) { + + $wikipage = new page_wiki_confirmrestore($wiki, $subwiki, $cm); + $wikipage->set_page($page); + $wikipage->set_versionid($versionid); + +} else { + + $wikipage = new page_wiki_restoreversion($wiki, $subwiki, $cm); + $wikipage->set_page($page); + $wikipage->set_versionid($versionid); + +} + +$wikipage->print_header(); +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/revertpages.html b/mod/wiki/revertpages.html deleted file mode 100644 index 630e77ea93b..00000000000 --- a/mod/wiki/revertpages.html +++ /dev/null @@ -1,63 +0,0 @@ -deleteversions)) { - $form->deleteversions = 1; -} -if (!isset($form->changesfield)) { - $form->changesfield = 72; -} - -?> -
          -
          - - - - - - -
          -remark) { - echo $OUTPUT->error_text($err->remark); -} -?> - - - - - - - - - - - - - - - - - -

          :

          - -old_help_icon('revertauthorfieldpattern', get_string('authorfieldpattern', 'wiki'), 'wiki'); - if (!empty($err->authorfieldpattern)) { echo $OUTPUT->error_text($err->authorfieldpattern); } -?> -

          :

          - - changesfield)) { echo $OUTPUT->error_text($err->changesfield); } ?> -

          :

          - get_string("revertlastonly","wiki"), - "allsince" => get_string("revertallsince","wiki"), - "the" => get_string("revertthe","wiki")); - echo html_writer::select($operations, "howtooperate", $form->howtooperate, false); - ?> -

          :

          - - deleteversions)) { echo $OUTPUT->error_text($err->deleteversions); } ?> -
          - " /> -
          diff --git a/mod/wiki/search.php b/mod/wiki/search.php new file mode 100644 index 00000000000..766e10dd555 --- /dev/null +++ b/mod/wiki/search.php @@ -0,0 +1,62 @@ +. + +/** + * @package mod-wiki + * @copyright 2010 Dongsheng Cai + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$search = optional_param('searchstring', null, PARAM_ALPHANUMEXT); +$courseid = optional_param('courseid', 0, PARAM_INT); +$searchcontent = optional_param('searchwikicontent', 0, PARAM_INT); +$cmid = optional_param('cmid', 0, PARAM_INT); + +if (!$course = $DB->get_record('course', array('id'=>$courseid))) { + print_error('invalidcourseid'); +} +if (! $cm = get_coursemodule_from_id('wiki', $cmid)) { + print_error('invalidcoursemodule'); +} + +require_course_login($course, true, $cm); + +// @TODO: Fix call to wiki_get_subwiki_by_group +$gid = groups_get_activity_group($cm); +if (!$subwiki = wiki_get_subwiki_by_group($cm->instance, $gid)){ + return false; +} +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +$wikipage = new page_wiki_search($wiki, $subwiki, $cm); + +$wikipage->set_search_string($search, $searchcontent); + +$wikipage->set_title(get_string('search')); + +$wikipage->print_header(); + +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/setpageflags.html b/mod/wiki/setpageflags.html deleted file mode 100644 index f26502add71..00000000000 --- a/mod/wiki/setpageflags.html +++ /dev/null @@ -1,19 +0,0 @@ - -
          -
          - - - - - - -
          -
          - " /> -
          diff --git a/mod/wiki/simpletest/input/creole/1 b/mod/wiki/simpletest/input/creole/1 new file mode 100644 index 00000000000..b8104e1065d --- /dev/null +++ b/mod/wiki/simpletest/input/creole/1 @@ -0,0 +1,5 @@ +Donec semper, nunc nec imperdiet lacinia, dui magna gravida odio, ut pretium nisl sapien ut lacus. Pellentesque nec pede. Praesent condimentum. Aliquam porttitor mi ut odio! Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed laoreet mauris vitae tellus. Curabitur dignissim. Duis ac leo. Nam gravida pharetra sapien. Sed feugiat lobortis orci. Cras sed nisl. Curabitur congue mollis erat. Quisque dictum! Praesent a lectus. Pellentesque nulla nisi; tempus eget, tincidunt id; tincidunt vel, nisl. + +Duis consequat vulputate felis. Praesent diam nisi, venenatis vitae; dignissim quis, feugiat ut, pede. Maecenas tincidunt iaculis elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed sed nulla at eros mollis tempor. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam bibendum lorem at sem. Morbi blandit. Nullam volutpat mi. Suspendisse dapibus lacus vel nisl. Ut lacinia adipiscing mi! Maecenas ipsum erat, accumsan quis, cursus ut, ultrices in; metus. Nulla adipiscing rhoncus ante? Nulla hendrerit tortor sit amet mauris. Cras varius dui vel leo. Proin vulputate! Phasellus lacus arcu, eleifend a, accumsan at, vulputate sed, neque. Fusce leo ante, interdum ac, tincidunt non, scelerisque eu, velit. Suspendisse sed nunc. Aenean sodales turpis! + +Suspendisse fringilla fermentum sem. Integer viverra dui id dolor! Mauris ornare eros vel nunc. Phasellus ligula nulla, vestibulum eget, vestibulum vel, aliquam eget, eros. Integer in pede. Fusce ultricies viverra ante. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque eget lorem ut mi vestibulum facilisis. Vestibulum augue. Curabitur arcu pede, fringilla eu, placerat id, condimentum sit amet, lectus. Fusce at diam eu justo semper interdum. Vivamus id turpis at justo tempus tempor. Maecenas eros libero, bibendum non, dictum ut, blandit id, augue. Pellentesque facilisis. Aenean aliquet sem. In tellus! \ No newline at end of file diff --git a/mod/wiki/simpletest/input/creole/2 b/mod/wiki/simpletest/input/creole/2 new file mode 100644 index 00000000000..36bcded2104 --- /dev/null +++ b/mod/wiki/simpletest/input/creole/2 @@ -0,0 +1,19 @@ += Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. +Phasellus odio? Ut ac leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vivamus enim justo, porttitor at, lacinia vitae; consectetuer et, ante? Maecenas eget libero. Duis est. Curabitur tincidunt dictum ligula. Nunc euismod lectus quis mi. Proin et enim sed nunc scelerisque posuere. Suspendisse enim purus, sodales non, tristique vel, sollicitudin ullamcorper, nulla. Aliquam condimentum; tellus eu vulputate facilisis, ante pede rhoncus elit, vel euismod nulla sapien et metus? + +== Praesent tristique facilisis metus. == + +Quisque lectus? Morbi ultrices ultricies neque. In ligula sem; pretium eget, iaculis laoreet, pulvinar sed, dui. Proin mattis luctus diam. Aenean eget risus in mauris sagittis vehicula. Vivamus dapibus enim ac dolor. Pellentesque leo. Praesent tristique facilisis metus. Nulla imperdiet ante et urna? Maecenas leo nisi, lacinia sollicitudin, viverra at, aliquet et, justo. Quisque congue dolor. + +=== Phasellus ut augue ut felis porttitor condimentum. === +Aliquam erat volutpat. Phasellus ut augue ut felis porttitor condimentum. Nam sapien tellus, tempus sed; mattis quis, viverra quis, mauris. Suspendisse venenatis sollicitudin massa. Pellentesque lobortis dolor vitae nisl. Nulla interdum aliquet neque. Duis nisl pede, vestibulum in, tristique eget, viverra vitae, erat. Maecenas justo turpis, convallis sit amet, tristique eu, laoreet et, augue. Fusce sem. Pellentesque ut turpis? Morbi suscipit sollicitudin metus? Morbi pharetra, sem eget ornare tempor, neque erat dapibus lacus, ut tincidunt nisi leo sed nunc. Sed sodales dignissim eros. Duis vitae risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed lobortis consequat sem. Nunc posuere vulputate velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis vestibulum pellentesque neque. + +==== Sed adipiscing dui at massa. Nulla consectetuer tristique lacus? ==== +Maecenas lacus justo, pellentesque vitae, mattis vitae, rutrum sit amet, metus! Etiam aliquam odio vel nulla. Suspendisse ante. Pellentesque viverra leo at lorem! Ut pharetra egestas ante. Aliquam erat volutpat. Sed adipiscing dui at massa. Nulla consectetuer tristique lacus? Donec ante leo, condimentum non, consectetuer vel, sodales placerat, tortor. Etiam at diam at elit adipiscing ultrices. Etiam lectus sapien, congue sed, sodales quis, ultricies a, libero. Pellentesque tincidunt! + +== Curabitur euismod sollicitudin nibh + +Curabitur euismod sollicitudin nibh. Duis nec diam. Sed nunc quam, lobortis nec; tristique et, dignissim eget, massa. Suspendisse sagittis malesuada tortor. Nullam lectus diam, mollis id, malesuada at, gravida ut, nisl. In hac habitasse platea dictumst. Sed a purus. Etiam velit urna, lacinia et, imperdiet quis, varius quis, orci! Sed dolor ante, mollis in, ultrices in, vestibulum vitae; justo. Vestibulum accumsan vehicula risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus sit amet diam lobortis urna tristique pretium. Quisque erat. + +==== Duis nec diam. +Pellentesque lobortis dolor vitae nisl. Nulla interdum aliquet neque. Duis nisl pede, vestibulum in, tristique eget, viverra vitae, erat. Maecenas justo turpis, convallis sit amet, tristique eu, laoreet et, augue. Fusce sem. Pellentesque ut turpis? Morbi suscipit sollicitudin metus? Morbi pharetra, sem eget ornare tempor, neque erat dapibus lacus, ut tincidunt nisi leo sed nunc. Sed sodales dignissim eros. Duis vitae risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed lobortis consequat sem. Nunc posuere vulputate velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis vestibulum pellentesque neque. diff --git a/mod/wiki/simpletest/input/creole/3 b/mod/wiki/simpletest/input/creole/3 new file mode 100644 index 00000000000..8080cb003ba --- /dev/null +++ b/mod/wiki/simpletest/input/creole/3 @@ -0,0 +1,8 @@ += In nisi purus, varius in, mollis eget, interdum in, ipsum. +Vivamus lobortis. **Mauris dui dui, rutrum in, egestas nec, porttitor vehicula, risus!** Vivamus aliquam ultrices metus. //Donec ultricies, metus eget volutpat condimentum;// neque orci mattis dolor, non posuere eros dui et orci. Duis aliquam. Fusce sit amet nisl. Duis tempor dapibus diam? In venenatis congue mi? Aliquam metus erat; facilisis a, suscipit a, pretium vitae; ligula? Ut id metus a pede adipiscing commodo! **Praesent ultricies urna et sapien.** //Donec adipiscing.// Donec sit amet lacus. + +== **In nisi purus**, //varius in,// mollis eget, interdum in, ipsum. + +Duis feugiat ligula ac elit. %!34%!Nulla sed arcu a risus sodales mattis. Etiam magna arcu, accumsan vitae, sodales non, faucibus quis, nunc. Aenean ut elit. Pellentesque malesuada lacus a orci. Suspendisse in erat sed mi porta faucibus. Nullam a nibh. Suspendisse potenti. Nam malesuada lobortis nibh. Ut venenatis, nibh ac convallis iaculis, justo pede tristique sapien, vel ultricies massa diam id leo. Pellentesque ullamcorper condimentum urna. //Proin dui lacus; scelerisque nec, condimentum non, **lobortis ac, felis. + +//Nullam ac neque. %!4%!**Praesent quis tellus. **Maecenas** et felis vitae lectus porttitor dignissim. Etiam at dui id nibh molestie semper. Sed vulputate nunc et neque. Fusce consectetur elit id leo. //Nulla facilisi. //Donec vitae nulla ac nisl mollis blandit. //Nulla adipiscing.** Phasellus quis odio sed eros viverra sodales. Suspendisse eget mauris id urna convallis fringilla. Aliquam dolor. Sed commodo. Quisque vestibulum, eros in mollis rutrum, odio risus aliquam turpis; nec convallis ante justo in dui? Pellentesque pharetra venenatis odio. Nulla placerat, libero at lacinia pellentesque; nisi massa sodales risus, at tincidunt orci pede sed ipsum. Etiam massa! Nullam aliquet justo at erat placerat convallis. diff --git a/mod/wiki/simpletest/input/creole/4 b/mod/wiki/simpletest/input/creole/4 new file mode 100644 index 00000000000..9ae482ad6ec --- /dev/null +++ b/mod/wiki/simpletest/input/creole/4 @@ -0,0 +1,10 @@ +== Donec ultricies neque eu libero scelerisque feugiat. + + +**Donec ultricies //neque eu [[libero]] scelerisque //feugiat. //Cras sed ante.// Sed volutpat urna eu diam. Curabitur fringilla lacinia mi.** Quisque lorem. Etiam fringilla consequat dui. Nunc est est; aliquet eu, porttitor auctor; malesuada id, massa. [[Nullam|Nullam feugiat]], nulla eget vulputate facilisis, erat odio vestibulum mi, eget volutpat lorem enim vitae eros. Vestibulum convallis. Maecenas posuere pellentesque mi? Donec consectetur volutpat dolor. [[**Curabitur**]] non **[[//Tellus**|tellus nec ligula bibendum pulvinar.]]** + +http://www.google.com +[[http://www.google.com]] + +~http://www.apple.com +~[[Link que no va]] diff --git a/mod/wiki/simpletest/input/creole/5 b/mod/wiki/simpletest/input/creole/5 new file mode 100644 index 00000000000..c5367a7d16a --- /dev/null +++ b/mod/wiki/simpletest/input/creole/5 @@ -0,0 +1,6 @@ += Integer eu leo? \\ Quisque posuere. +Nunc commodo nisi vitae quam. Etiam tincidunt; lectus eu tempus molestie, elit enim auctor tortor, in varius leo mi ac risus. Sed iaculis magna vel libero. Pellentesque iaculis, tellus in ullamcorper tempus, justo sapien scelerisque enim, eu ornare dui neque sed ligula. \\Vestibulum porta justo a dolor. Duis mollis quam vel sem. Quisque vel arcu. Pellentesque sem. Aliquam adipiscing neque quis turpis. Mauris placerat, elit quis iaculis vehicula, sem nulla imperdiet nunc, in elementum felis lectus non magna. Mauris cursus; odio eu sagittis sodales, nisi nibh pellentesque tortor, ut ultricies lacus tellus non odio. In semper, ligula eu condimentum posuere, sapien tellus blandit quam, dapibus iaculis lacus erat eget ipsum. Duis pulvinar molestie magna. Aliquam bibendum quam ac nulla! + +== Fusce justo. Aliquam felis tellus, tempor vel, congue quis, tempus eu, ipsum. \\ + +\\Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi sed erat! Vivamus condimentum. Praesent euismod; nibh sed mollis feugiat, erat lorem commodo lectus, vitae tristique erat massa semper diam. Morbi vitae elit. \\Quisque sagittis leo non odio auctor faucibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque mi pede, lacinia id, commodo faucibus, rhoncus in, nibh. Praesent vestibulum aliquet quam! \ No newline at end of file diff --git a/mod/wiki/simpletest/input/creole/6 b/mod/wiki/simpletest/input/creole/6 new file mode 100644 index 00000000000..ab9171bd98f --- /dev/null +++ b/mod/wiki/simpletest/input/creole/6 @@ -0,0 +1,18 @@ +Donec sem est, dictum ac, blandit ut, commodo vitae, pede. Proin auctor egestas est. Aliquam fermentum, dui ac malesuada facilisis, mauris felis porttitor turpis, non adipiscing odio mi sit amet felis. Duis dignissim posuere sem. Fusce consequat convallis lectus. Ut suscipit neque sed massa. Etiam suscipit. Sed vitae elit. Nulla non mi. Aliquam risus erat, varius eget, eleifend eget, scelerisque sit amet, enim. Proin venenatis. + +* Donec ligula enim +* viverra at +* ultricies rutrum + +* volutpat sed +** ligula +** Aenean laoreet tortor at lorem +* Fusce varius nunc quis lacus sodales posuere + +** Integer laoreet congue ligula** + +* Vestibulum condimentum + +**dui ac porta imperdiet** + +**Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam accumsan lectus vel sapien. Quisque laoreet lorem non dolor. Ut diam dolor, facilisis non, tempus eu, varius id, nunc. Aliquam sit amet lorem. Cras congue ultricies enim. Nunc vehicula, odio eget volutpat pharetra, leo pede commodo tellus, eu scelerisque erat purus non felis. Sed sed sem eget massa convallis eleifend? Nam tristique. Aliquam justo. Sed risus mi, egestas in, viverra a; tincidunt ac, mauris! Nulla magna. Aenean mauris velit, facilisis ut, condimentum eget, hendrerit ac, sem. Phasellus lorem. Curabitur augue mi; iaculis sit amet, suscipit eget, commodo nec; nibh. Cras pellentesque hendrerit quam. Praesent arcu dui, rhoncus non, feugiat ut, laoreet vitae, velit.** diff --git a/mod/wiki/simpletest/input/creole/7 b/mod/wiki/simpletest/input/creole/7 new file mode 100644 index 00000000000..062b079a6a8 --- /dev/null +++ b/mod/wiki/simpletest/input/creole/7 @@ -0,0 +1,4 @@ += In nisi purus, varius in, mollis eget, interdum in, ipsum. +Vivamus lobortis. **Mauris dui dui, rutrum in, egestas nec, porttitor vehicula, risus!** Vivamus aliquam ultrices metus. //Donec ultricies, metus eget volutpat condimentum;// neque orci mattis dolor, non posuere eros dui et orci. Duis aliquam. Fusce sit amet nisl. Duis tempor dapibus diam? In venenatis congue mi? Aliquam metus erat; facilisis a, suscipit a, pretium vitae; ligula? Ut id metus a pede adipiscing commodo! {{{**Praesent ultricies urna et sapien.** //Donec adipiscing.//}}} Donec sit amet lacus. + +{{{ lkdsjflsdjflsdkjflskdjlfk }}} \ No newline at end of file diff --git a/mod/wiki/simpletest/input/creole/8 b/mod/wiki/simpletest/input/creole/8 new file mode 100644 index 00000000000..06dfb9c8718 --- /dev/null +++ b/mod/wiki/simpletest/input/creole/8 @@ -0,0 +1,28 @@ +== Testing some tables + +Phasellus urna erat; venenatis ac, iaculis sed, pretium ut, pede. Suspendisse mauris tellus, rhoncus a, tempor id, mattis non, nibh. Aliquam magna odio; hendrerit at, eleifend sed, dignissim quis, orci. Donec mollis, ante sit amet convallis porta, augue nibh viverra magna, ac scelerisque dui ligula eu felis. Sed eget magna. Proin eget ligula. Vestibulum ornare; sem molestie congue sollicitudin, mi velit porta est, pellentesque dignissim libero est at velit. Donec congue adipiscing massa? Nunc eget nisi eget elit facilisis ornare. Vestibulum et felis id leo feugiat sagittis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed tellus velit, luctus et, tempor non, tempor vitae, magna. Aliquam viverra tortor sit amet tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nibh risus, dictum eu, tempor sit amet, posuere et, nulla. + +Well formed table... + +|= Name |= Surname | +| George | Washington | +| Abraham | Lincoln | + +Not so well formed table + +|= Name |= Surname |= Erroneous stuff | +| George | Washington | +| Abraham | Lincoln | Error error | + +Bad headers: + +| Name |= Surname | +|= George | Washington | +| Abraham |= Lincoln | + +Two tables (treated as such) with some format: + +|= Name |= Surname | +| **George** | //Washington// | + +| Abraham | Lincoln | \ No newline at end of file diff --git a/mod/wiki/simpletest/input/creole/9 b/mod/wiki/simpletest/input/creole/9 new file mode 100644 index 00000000000..de007c1a09f --- /dev/null +++ b/mod/wiki/simpletest/input/creole/9 @@ -0,0 +1,133 @@ += Top-level heading (1) +== This a test for creole 0.1 (2) +=== This is a Subheading (3) +==== Subsub (4) +===== Subsubsub (5) + +The ending equal signs should not be displayed: + += Top-level heading (1) = +== This a test for creole 0.1 (2) == +=== This is a Subheading (3) === +==== Subsub (4) ==== +===== Subsubsub (5) ===== + + +You can make things **bold** or //italic// or **//both//** or //**both**//. + +Character formatting extends across line breaks: **bold, +this is still bold. This line deliberately does not end in star-star. + +Not bold. Character formatting does not cross paragraph boundaries. + +You can use [[internal links]] or [[http://www.wikicreole.org|external links]], +give the link a [[internal links|different]] name. + +Here's another sentence: This wisdom is taken from [[Ward Cunningham's]] +[[http://www.c2.com/doc/wikisym/WikiSym2006.pdf|Presentation at the Wikisym 06]]. + +Here's a external link without a description: [[http://www.wikicreole.org]] + +Be careful that italic links are rendered properly: //[[http://my.book.example/|My Book Title]]// + +Free links without braces should be rendered as well, like http://www.wikicreole.org/ and http://www.wikicreole.org/users/~example. + +Creole1.0 specifies that http://bar and ftp://bar should not render italic, something like foo://bar should render as italic.// + +You can use this to draw a line to separate the page: + + +---- + +You can use lists, start it at the first column for now, please... + +unnumbered lists are like + +* item a +* item b +* **bold item c** + +blank space is also permitted before lists like: + + * item a + * item b +* item c + ** item c.a + +or you can number them + +# [[item 1]] +# item 2 +# // italic item 3 // + ## item 3.1 + ## item 3.2 + +up to five levels + +* 1 +** 2 +*** 3 +**** 4 +***** 5 + +* You can have +multiline list items +* this is a second multiline +list item + +You can use nowiki syntax if you would like do stuff like this: + +{{{ +Guitar Chord C: + +||---|---|---| +||-0-|---|---| +||---|---|---| +||---|-0-|---| +||---|---|-0-| +||---|---|---| +}}} + +You can also use it inline nowiki {{{ in a sentence }}} like this. + += Escapes = +Normal Link: http://wikicreole.org/ - now same link, but escaped: ~http://wikicreole.org/ + +Normal asterisks: ~**not bold~** + +a tilde alone: ~ + +a tilde escapes itself: ~~xxx + +=== Creole 0.2 === + +This should be a flower with the ALT text "this is a flower" if your wiki supports ALT text on images: + +{{Red-Flower.jpg|here is a red flower}} + +=== Creole 0.4 === + +Tables are done like this: + +|=header col1|=header col2| +|col1|col2| +|you |can | +|also |align\\ it. | + +You can format an address by simply forcing linebreaks: + +My contact dates:\\ +Pone: xyz\\ +Fax: +45\\ +Mobile: abc + +=== Creole 0.5 === + +|= Header title |= Another header title | +| {{{ //not italic text// }}} | {{{ **not bold text** }}} | +| //italic text// | ** bold text ** | + +=== Creole 1.0 === + +If interwiki links are setup in your wiki, this links to the WikiCreole page about Creole 1.0 test cases: [[WikiCreole:Creole1.0TestCases]]. + diff --git a/mod/wiki/simpletest/input/html/1 b/mod/wiki/simpletest/input/html/1 new file mode 100644 index 00000000000..7a1f4a28e1d --- /dev/null +++ b/mod/wiki/simpletest/input/html/1 @@ -0,0 +1,20 @@ +

          Header1

          +

          +Etiam eget nibh leo. In luctus orci quis tellus sagittis egestas. Praesent et turpis augue, ac accumsan orci? Pellentesque porttitor sodales tortor; vitae faucibus dui auctor vel. Phasellus sit amet sem leo; eu adipiscing ipsum. Aliquam vehicula ipsum at diam imperdiet a condimentum urna commodo? Nunc ac lacus non lorem porttitor malesuada et sit amet diam! Aenean pulvinar lectus et dolor dignissim viverra placerat nisl mattis! Nunc non leo a massa imperdiet porta vel eu tellus. Sed ac est quis orci viverra cursus. Nam tellus mauris, facilisis nec faucibus sit amet, consequat in felis. Ut volutpat lacinia est ut fringilla. Pellentesque augue dui, aliquet et ornare euismod, egestas nec arcu! Vivamus gravida, lorem vitae suscipit condimentum, turpis arcu iaculis tortor; vel ullamcorper lorem ante id nisi. Ut sit amet sem tempor quam dignissim interdum. Nam aliquam, odio vitae volutpat semper; sapien turpis feugiat neque, ac ullamcorper felis enim vitae arcu. Morbi viverra feugiat justo, at ullamcorper ipsum posuere non. +

          +

          +Proin ultricies gravida dui a mattis. Integer nec nisl ante. Mauris euismod, tortor et fermentum semper; est mi adipiscing erat, non pellentesque orci dui ac arcu. Nam vitae metus augue. Integer magna nibh, elementum nec molestie eget; commodo sed turpis. Duis neque mi, vehicula sed aliquet id, ultricies sed tortor. Aliquam pharetra ante sapien. Etiam accumsan ipsum sed dolor bibendum congue sollicitudin enim fringilla. Nulla eros risus, auctor placerat vestibulum eget, tincidunt ac eros. Duis ut turpis leo, sit amet ornare arcu. Aliquam eu lorem in arcu accumsan iaculis. Integer placerat lacus in nibh sollicitudin euismod? Sed a urna vel dui sagittis varius cursus sit amet dolor. Nulla ut sem at magna fringilla hendrerit sed nec sapien. Aenean nisi elit, feugiat vel euismod non, laoreet sit amet ligula. Aenean a dui quam. +

          +

          +Curabitur dolor ligula, suscipit et eleifend nec, faucibus varius sapien. Quisque ornare felis ac leo tincidunt quis malesuada elit lobortis? Suspendisse potenti. Vestibulum tempus porta dui, at ullamcorper mauris sollicitudin vel? In convallis risus id elit ultrices pellentesque. Sed id quam lectus. Duis tincidunt egestas urna, in tempor tortor rhoncus ac. Sed commodo, nunc sit amet sodales vulputate, purus nisi malesuada urna, ut cursus nisl nunc vel enim. Mauris ut imperdiet risus. Integer sagittis; odio at laoreet venenatis, purus neque fermentum nisi, non elementum urna libero sed ipsum. +

          +

          Header2

          +

          +Etiam eget nibh leo. In luctus orci quis tellus sagittis egestas. Praesent et turpis augue, ac accumsan orci? Pellentesque porttitor sodales tortor; vitae faucibus dui auctor vel. Phasellus sit amet sem leo; eu adipiscing ipsum. Aliquam vehicula ipsum at diam imperdiet a condimentum urna commodo? Nunc ac lacus non lorem porttitor malesuada et sit amet diam! Aenean pulvinar lectus et dolor dignissim viverra placerat nisl mattis! Nunc non leo a massa imperdiet porta vel eu tellus. Sed ac est quis orci viverra cursus. Nam tellus mauris, facilisis nec faucibus sit amet, consequat in felis. Ut volutpat lacinia est ut fringilla. Pellentesque augue dui, aliquet et ornare euismod, egestas nec arcu! Vivamus gravida, lorem vitae suscipit condimentum, turpis arcu iaculis tortor; vel ullamcorper lorem ante id nisi. Ut sit amet sem tempor quam dignissim interdum. Nam aliquam, odio vitae volutpat semper; sapien turpis feugiat neque, ac ullamcorper felis enim vitae arcu. Morbi viverra feugiat justo, at ullamcorper ipsum posuere non. +

          +

          +Proin ultricies gravida dui a mattis. Integer nec nisl ante. Mauris euismod, tortor et fermentum semper; est mi adipiscing erat, non pellentesque orci dui ac arcu. Nam vitae metus augue. Integer magna nibh, elementum nec molestie eget; commodo sed turpis. Duis neque mi, vehicula sed aliquet id, ultricies sed tortor. Aliquam pharetra ante sapien. Etiam accumsan ipsum sed dolor bibendum congue sollicitudin enim fringilla. Nulla eros risus, auctor placerat vestibulum eget, tincidunt ac eros. Duis ut turpis leo, sit amet ornare arcu. Aliquam eu lorem in arcu accumsan iaculis. Integer placerat lacus in nibh sollicitudin euismod? Sed a urna vel dui sagittis varius cursus sit amet dolor. Nulla ut sem at magna fringilla hendrerit sed nec sapien. Aenean nisi elit, feugiat vel euismod non, laoreet sit amet ligula. Aenean a dui quam. +

          +

          +Curabitur dolor ligula, suscipit et eleifend nec, faucibus varius sapien. Quisque ornare felis ac leo tincidunt quis malesuada elit lobortis? Suspendisse potenti. Vestibulum tempus porta dui, at ullamcorper mauris sollicitudin vel? In convallis risus id elit ultrices pellentesque. Sed id quam lectus. Duis tincidunt egestas urna, in tempor tortor rhoncus ac. Sed commodo, nunc sit amet sodales vulputate, purus nisi malesuada urna, ut cursus nisl nunc vel enim. Mauris ut imperdiet risus. Integer sagittis; odio at laoreet venenatis, purus neque fermentum nisi, non elementum urna libero sed ipsum. +

          \ No newline at end of file diff --git a/mod/wiki/simpletest/input/html/2 b/mod/wiki/simpletest/input/html/2 new file mode 100644 index 00000000000..259787783cd --- /dev/null +++ b/mod/wiki/simpletest/input/html/2 @@ -0,0 +1,7 @@ +
          +

          +I Love Validator +[[Donate|Make a donation]] or become a +[[sponsor]] +of the http://validator.w3.org/ .

          +
          \ No newline at end of file diff --git a/mod/wiki/simpletest/input/nwiki/1 b/mod/wiki/simpletest/input/nwiki/1 new file mode 100644 index 00000000000..88a595031eb --- /dev/null +++ b/mod/wiki/simpletest/input/nwiki/1 @@ -0,0 +1,20 @@ += Header 1 = + +First paragraph with no formats. + +''This paragraph has bold text.'' + +== False header = + +'''This part of the paragraph is italicized.''' But not this part. + +==Header 2== + +Some mix of '''italics''' and ''bold'', and some '''''italics & bold'''''. + +And that '''italics and ''both'''''. + +And this: '''italics and''' '''''both'''''. + +--- +---- \ No newline at end of file diff --git a/mod/wiki/simpletest/input/nwiki/2 b/mod/wiki/simpletest/input/nwiki/2 new file mode 100644 index 00000000000..3538a89a14e --- /dev/null +++ b/mod/wiki/simpletest/input/nwiki/2 @@ -0,0 +1,23 @@ += Links = + +== Internal links == + +Some [[links]]. [[link|Another Link]]. + +=== Anchors === + +This is an [[#External links|anchor]] to the external links section. + +And this is an [[link#Section|anchor to another page]]. + +== External links == + +A link to http://www.google.com , and a link to [http://www.apple.com|apple]. + +The same link to [http://www.apple.com Apple Corporation]. + +== Attachments & images == + +That's an [[attach:attachment.png|attachment]]. + +And that's an [[image:image.png|image]]. \ No newline at end of file diff --git a/mod/wiki/simpletest/input/nwiki/3 b/mod/wiki/simpletest/input/nwiki/3 new file mode 100644 index 00000000000..91d3abc5ed3 --- /dev/null +++ b/mod/wiki/simpletest/input/nwiki/3 @@ -0,0 +1,22 @@ += Lists = + +== Unordered lists == + +* 1 +** 2 +* 1 + +** 1 +*** 3 +***** ''bold'' +* '''italic''' + +== Ordered lists == + +# 1 +#### 2 +# 3 + +### 4 +# 5 +### 6 \ No newline at end of file diff --git a/mod/wiki/simpletest/input/nwiki/4 b/mod/wiki/simpletest/input/nwiki/4 new file mode 100644 index 00000000000..f591707b5c1 --- /dev/null +++ b/mod/wiki/simpletest/input/nwiki/4 @@ -0,0 +1,13 @@ +{| +| A +| B +|- +| C +| D +|} + +{| +! A !! B +|- +| C || D +|} diff --git a/mod/wiki/simpletest/input/nwiki/5 b/mod/wiki/simpletest/input/nwiki/5 new file mode 100644 index 00000000000..e69de29bb2d diff --git a/mod/wiki/simpletest/output/creole/1 b/mod/wiki/simpletest/output/creole/1 new file mode 100644 index 00000000000..8225933c860 --- /dev/null +++ b/mod/wiki/simpletest/output/creole/1 @@ -0,0 +1,3 @@ +

          Donec semper, nunc nec imperdiet lacinia, dui magna gravida odio, ut pretium nisl sapien ut lacus. Pellentesque nec pede. Praesent condimentum. Aliquam porttitor mi ut odio! Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed laoreet mauris vitae tellus. Curabitur dignissim. Duis ac leo. Nam gravida pharetra sapien. Sed feugiat lobortis orci. Cras sed nisl. Curabitur congue mollis erat. Quisque dictum! Praesent a lectus. Pellentesque nulla nisi; tempus eget, tincidunt id; tincidunt vel, nisl.

          +

          Duis consequat vulputate felis. Praesent diam nisi, venenatis vitae; dignissim quis, feugiat ut, pede. Maecenas tincidunt iaculis elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed sed nulla at eros mollis tempor. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam bibendum lorem at sem. Morbi blandit. Nullam volutpat mi. Suspendisse dapibus lacus vel nisl. Ut lacinia adipiscing mi! Maecenas ipsum erat, accumsan quis, cursus ut, ultrices in; metus. Nulla adipiscing rhoncus ante? Nulla hendrerit tortor sit amet mauris. Cras varius dui vel leo. Proin vulputate! Phasellus lacus arcu, eleifend a, accumsan at, vulputate sed, neque. Fusce leo ante, interdum ac, tincidunt non, scelerisque eu, velit. Suspendisse sed nunc. Aenean sodales turpis!

          +

          Suspendisse fringilla fermentum sem. Integer viverra dui id dolor! Mauris ornare eros vel nunc. Phasellus ligula nulla, vestibulum eget, vestibulum vel, aliquam eget, eros. Integer in pede. Fusce ultricies viverra ante. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque eget lorem ut mi vestibulum facilisis. Vestibulum augue. Curabitur arcu pede, fringilla eu, placerat id, condimentum sit amet, lectus. Fusce at diam eu justo semper interdum. Vivamus id turpis at justo tempus tempor. Maecenas eros libero, bibendum non, dictum ut, blandit id, augue. Pellentesque facilisis. Aenean aliquet sem. In tellus!

          diff --git a/mod/wiki/simpletest/output/creole/2 b/mod/wiki/simpletest/output/creole/2 new file mode 100644 index 00000000000..0de9e7de5c2 --- /dev/null +++ b/mod/wiki/simpletest/output/creole/2 @@ -0,0 +1,12 @@ +

          Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

          +

          Phasellus odio? Ut ac leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vivamus enim justo, porttitor at, lacinia vitae; consectetuer et, ante? Maecenas eget libero. Duis est. Curabitur tincidunt dictum ligula. Nunc euismod lectus quis mi. Proin et enim sed nunc scelerisque posuere. Suspendisse enim purus, sodales non, tristique vel, sollicitudin ullamcorper, nulla. Aliquam condimentum; tellus eu vulputate facilisis, ante pede rhoncus elit, vel euismod nulla sapien et metus?

          +

          Praesent tristique facilisis metus.

          +

          Quisque lectus? Morbi ultrices ultricies neque. In ligula sem; pretium eget, iaculis laoreet, pulvinar sed, dui. Proin mattis luctus diam. Aenean eget risus in mauris sagittis vehicula. Vivamus dapibus enim ac dolor. Pellentesque leo. Praesent tristique facilisis metus. Nulla imperdiet ante et urna? Maecenas leo nisi, lacinia sollicitudin, viverra at, aliquet et, justo. Quisque congue dolor.

          +

          Phasellus ut augue ut felis porttitor condimentum.

          +

          Aliquam erat volutpat. Phasellus ut augue ut felis porttitor condimentum. Nam sapien tellus, tempus sed; mattis quis, viverra quis, mauris. Suspendisse venenatis sollicitudin massa. Pellentesque lobortis dolor vitae nisl. Nulla interdum aliquet neque. Duis nisl pede, vestibulum in, tristique eget, viverra vitae, erat. Maecenas justo turpis, convallis sit amet, tristique eu, laoreet et, augue. Fusce sem. Pellentesque ut turpis? Morbi suscipit sollicitudin metus? Morbi pharetra, sem eget ornare tempor, neque erat dapibus lacus, ut tincidunt nisi leo sed nunc. Sed sodales dignissim eros. Duis vitae risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed lobortis consequat sem. Nunc posuere vulputate velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis vestibulum pellentesque neque.

          +

          Sed adipiscing dui at massa. Nulla consectetuer tristique lacus?

          +

          Maecenas lacus justo, pellentesque vitae, mattis vitae, rutrum sit amet, metus! Etiam aliquam odio vel nulla. Suspendisse ante. Pellentesque viverra leo at lorem! Ut pharetra egestas ante. Aliquam erat volutpat. Sed adipiscing dui at massa. Nulla consectetuer tristique lacus? Donec ante leo, condimentum non, consectetuer vel, sodales placerat, tortor. Etiam at diam at elit adipiscing ultrices. Etiam lectus sapien, congue sed, sodales quis, ultricies a, libero. Pellentesque tincidunt!

          +

          Curabitur euismod sollicitudin nibh

          +

          Curabitur euismod sollicitudin nibh. Duis nec diam. Sed nunc quam, lobortis nec; tristique et, dignissim eget, massa. Suspendisse sagittis malesuada tortor. Nullam lectus diam, mollis id, malesuada at, gravida ut, nisl. In hac habitasse platea dictumst. Sed a purus. Etiam velit urna, lacinia et, imperdiet quis, varius quis, orci! Sed dolor ante, mollis in, ultrices in, vestibulum vitae; justo. Vestibulum accumsan vehicula risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus sit amet diam lobortis urna tristique pretium. Quisque erat.

          +

          Duis nec diam.

          +

          Pellentesque lobortis dolor vitae nisl. Nulla interdum aliquet neque. Duis nisl pede, vestibulum in, tristique eget, viverra vitae, erat. Maecenas justo turpis, convallis sit amet, tristique eu, laoreet et, augue. Fusce sem. Pellentesque ut turpis? Morbi suscipit sollicitudin metus? Morbi pharetra, sem eget ornare tempor, neque erat dapibus lacus, ut tincidunt nisi leo sed nunc. Sed sodales dignissim eros. Duis vitae risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed lobortis consequat sem. Nunc posuere vulputate velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis vestibulum pellentesque neque.

          diff --git a/mod/wiki/simpletest/output/creole/3 b/mod/wiki/simpletest/output/creole/3 new file mode 100644 index 00000000000..7311db5173c --- /dev/null +++ b/mod/wiki/simpletest/output/creole/3 @@ -0,0 +1,5 @@ +

          In nisi purus, varius in, mollis eget, interdum in, ipsum.

          +

          Vivamus lobortis. Mauris dui dui, rutrum in, egestas nec, porttitor vehicula, risus! Vivamus aliquam ultrices metus. Donec ultricies, metus eget volutpat condimentum; neque orci mattis dolor, non posuere eros dui et orci. Duis aliquam. Fusce sit amet nisl. Duis tempor dapibus diam? In venenatis congue mi? Aliquam metus erat; facilisis a, suscipit a, pretium vitae; ligula? Ut id metus a pede adipiscing commodo! Praesent ultricies urna et sapien. Donec adipiscing. Donec sit amet lacus.

          +

          **In nisi purus**, //varius in,// mollis eget, interdum in, ipsum.

          +

          Duis feugiat ligula ac elit. %!34%!Nulla sed arcu a risus sodales mattis. Etiam magna arcu, accumsan vitae, sodales non, faucibus quis, nunc. Aenean ut elit. Pellentesque malesuada lacus a orci. Suspendisse in erat sed mi porta faucibus. Nullam a nibh. Suspendisse potenti. Nam malesuada lobortis nibh. Ut venenatis, nibh ac convallis iaculis, justo pede tristique sapien, vel ultricies massa diam id leo. Pellentesque ullamcorper condimentum urna. //Proin dui lacus; scelerisque nec, condimentum non, lobortis ac, felis.

          +

          //Nullam ac neque. %!4%!Praesent quis tellus. Maecenas et felis vitae lectus porttitor dignissim. Etiam at dui id nibh molestie semper. Sed vulputate nunc et neque. Fusce consectetur elit id leo. Nulla facilisi. Donec vitae nulla ac nisl mollis blandit. //Nulla adipiscing. Phasellus quis odio sed eros viverra sodales. Suspendisse eget mauris id urna convallis fringilla. Aliquam dolor. Sed commodo. Quisque vestibulum, eros in mollis rutrum, odio risus aliquam turpis; nec convallis ante justo in dui? Pellentesque pharetra venenatis odio. Nulla placerat, libero at lacinia pellentesque; nisi massa sodales risus, at tincidunt orci pede sed ipsum. Etiam massa! Nullam aliquet justo at erat placerat convallis.

          diff --git a/mod/wiki/simpletest/output/creole/4 b/mod/wiki/simpletest/output/creole/4 new file mode 100644 index 00000000000..965d91def52 --- /dev/null +++ b/mod/wiki/simpletest/output/creole/4 @@ -0,0 +1,6 @@ +

          Donec ultricies neque eu libero scelerisque feugiat.

          +

          Donec ultricies neque eu libero scelerisque feugiat. Cras sed ante. Sed volutpat urna eu diam. Curabitur fringilla lacinia mi. Quisque lorem. Etiam fringilla consequat dui. Nunc est est; aliquet eu, porttitor auctor; malesuada id, massa. Nullam feugiat, nulla eget vulputate facilisis, erat odio vestibulum mi, eget volutpat lorem enim vitae eros. Vestibulum convallis. Maecenas posuere pellentesque mi? Donec consectetur volutpat dolor. **Curabitur** non tellus nec ligula bibendum pulvinar.

          +

          http://www.google.com +http://www.google.com

          +

          http://www.apple.com +[[Link que no va]]

          diff --git a/mod/wiki/simpletest/output/creole/5 b/mod/wiki/simpletest/output/creole/5 new file mode 100644 index 00000000000..fec622c8782 --- /dev/null +++ b/mod/wiki/simpletest/output/creole/5 @@ -0,0 +1,4 @@ +

          Integer eu leo? \\ Quisque posuere.

          +

          Nunc commodo nisi vitae quam. Etiam tincidunt; lectus eu tempus molestie, elit enim auctor tortor, in varius leo mi ac risus. Sed iaculis magna vel libero. Pellentesque iaculis, tellus in ullamcorper tempus, justo sapien scelerisque enim, eu ornare dui neque sed ligula.
          Vestibulum porta justo a dolor. Duis mollis quam vel sem. Quisque vel arcu. Pellentesque sem. Aliquam adipiscing neque quis turpis. Mauris placerat, elit quis iaculis vehicula, sem nulla imperdiet nunc, in elementum felis lectus non magna. Mauris cursus; odio eu sagittis sodales, nisi nibh pellentesque tortor, ut ultricies lacus tellus non odio. In semper, ligula eu condimentum posuere, sapien tellus blandit quam, dapibus iaculis lacus erat eget ipsum. Duis pulvinar molestie magna. Aliquam bibendum quam ac nulla!

          +

          Fusce justo. Aliquam felis tellus, tempor vel, congue quis, tempus eu, ipsum. \\

          +


          Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi sed erat! Vivamus condimentum. Praesent euismod; nibh sed mollis feugiat, erat lorem commodo lectus, vitae tristique erat massa semper diam. Morbi vitae elit.
          Quisque sagittis leo non odio auctor faucibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque mi pede, lacinia id, commodo faucibus, rhoncus in, nibh. Praesent vestibulum aliquet quam!

          diff --git a/mod/wiki/simpletest/output/creole/6 b/mod/wiki/simpletest/output/creole/6 new file mode 100644 index 00000000000..dcddf4f1fb5 --- /dev/null +++ b/mod/wiki/simpletest/output/creole/6 @@ -0,0 +1,21 @@ +

          Donec sem est, dictum ac, blandit ut, commodo vitae, pede. Proin auctor egestas est. Aliquam fermentum, dui ac malesuada facilisis, mauris felis porttitor turpis, non adipiscing odio mi sit amet felis. Duis dignissim posuere sem. Fusce consequat convallis lectus. Ut suscipit neque sed massa. Etiam suscipit. Sed vitae elit. Nulla non mi. Aliquam risus erat, varius eget, eleifend eget, scelerisque sit amet, enim. Proin venenatis.

          +
            +
          • Donec ligula enim
          • +
          • viverra at
          • +
          • ultricies rutrum
          • +
          +
            +
          • volutpat sed +
              +
            • ligula
            • +
            • Aenean laoreet tortor at lorem
            • +
            +
          • +
          • Fusce varius nunc quis lacus sodales posuere
          • +
          +

          Integer laoreet congue ligula

          +
            +
          • Vestibulum condimentum
          • +
          +

          dui ac porta imperdiet

          +

          Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam accumsan lectus vel sapien. Quisque laoreet lorem non dolor. Ut diam dolor, facilisis non, tempus eu, varius id, nunc. Aliquam sit amet lorem. Cras congue ultricies enim. Nunc vehicula, odio eget volutpat pharetra, leo pede commodo tellus, eu scelerisque erat purus non felis. Sed sed sem eget massa convallis eleifend? Nam tristique. Aliquam justo. Sed risus mi, egestas in, viverra a; tincidunt ac, mauris! Nulla magna. Aenean mauris velit, facilisis ut, condimentum eget, hendrerit ac, sem. Phasellus lorem. Curabitur augue mi; iaculis sit amet, suscipit eget, commodo nec; nibh. Cras pellentesque hendrerit quam. Praesent arcu dui, rhoncus non, feugiat ut, laoreet vitae, velit.

          diff --git a/mod/wiki/simpletest/output/creole/7 b/mod/wiki/simpletest/output/creole/7 new file mode 100644 index 00000000000..72d2f9aa853 --- /dev/null +++ b/mod/wiki/simpletest/output/creole/7 @@ -0,0 +1,3 @@ +

          In nisi purus, varius in, mollis eget, interdum in, ipsum.

          +

          Vivamus lobortis. Mauris dui dui, rutrum in, egestas nec, porttitor vehicula, risus! Vivamus aliquam ultrices metus. Donec ultricies, metus eget volutpat condimentum; neque orci mattis dolor, non posuere eros dui et orci. Duis aliquam. Fusce sit amet nisl. Duis tempor dapibus diam? In venenatis congue mi? Aliquam metus erat; facilisis a, suscipit a, pretium vitae; ligula? Ut id metus a pede adipiscing commodo! **Praesent ultricies urna et sapien.** //Donec adipiscing.// Donec sit amet lacus.

          +
           lkdsjflsdjflsdkjflskdjlfk 
          diff --git a/mod/wiki/simpletest/output/creole/8 b/mod/wiki/simpletest/output/creole/8 new file mode 100644 index 00000000000..50f01068013 --- /dev/null +++ b/mod/wiki/simpletest/output/creole/8 @@ -0,0 +1,85 @@ +

          Testing some tables

          +

          Phasellus urna erat; venenatis ac, iaculis sed, pretium ut, pede. Suspendisse mauris tellus, rhoncus a, tempor id, mattis non, nibh. Aliquam magna odio; hendrerit at, eleifend sed, dignissim quis, orci. Donec mollis, ante sit amet convallis porta, augue nibh viverra magna, ac scelerisque dui ligula eu felis. Sed eget magna. Proin eget ligula. Vestibulum ornare; sem molestie congue sollicitudin, mi velit porta est, pellentesque dignissim libero est at velit. Donec congue adipiscing massa? Nunc eget nisi eget elit facilisis ornare. Vestibulum et felis id leo feugiat sagittis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed tellus velit, luctus et, tempor non, tempor vitae, magna. Aliquam viverra tortor sit amet tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nibh risus, dictum eu, tempor sit amet, posuere et, nulla.

          +

          Well formed table...

          + + + + + + + + + + + + + + + + + +
          NameSurname
          GeorgeWashington
          AbrahamLincoln
          +

          Not so well formed table

          + + + + + + + + + + + + + + + + + + + + +
          NameSurnameErroneous stuff
          GeorgeWashington
          AbrahamLincolnError error
          +

          Bad headers:

          + + + + + + + + + + + + + + + + + +
          NameSurname
          GeorgeWashington
          AbrahamLincoln
          +

          Two tables (treated as such) with some format:

          + + + + + + + + + + + + + +
          NameSurname
          GeorgeWashington
          + + + + + + + +
          AbrahamLincoln
          diff --git a/mod/wiki/simpletest/output/creole/9 b/mod/wiki/simpletest/output/creole/9 new file mode 100644 index 00000000000..80b93039bfe --- /dev/null +++ b/mod/wiki/simpletest/output/creole/9 @@ -0,0 +1,146 @@ +

          Top-level heading (1)

          +

          This a test for creole 0.1 (2)

          +

          This is a Subheading (3)

          +

          Subsub (4)

          +
          Subsubsub (5)
          +

          The ending equal signs should not be displayed:

          +

          Top-level heading (1)

          +

          This a test for creole 0.1 (2)

          +

          This is a Subheading (3)

          +

          Subsub (4)

          +
          Subsubsub (5)
          +

          You can make things bold or italic or both or both.

          +

          Character formatting extends across line breaks: bold, +this is still bold. This line deliberately does not end in star-star.

          +

          Not bold. Character formatting does not cross paragraph boundaries.

          +

          You can use internal links or external links, +give the link a different name.

          +

          Here's another sentence: This wisdom is taken from Ward Cunningham's +Presentation at the Wikisym 06.

          +

          Here's a external link without a description: http://www.wikicreole.org

          +

          Be careful that italic links are rendered properly: My Book Title

          +

          Free links without braces should be rendered as well, like http://www.wikicreole.org/ and http://www.wikicreole.org/users/~example.

          +

          Creole1.0 specifies that http://bar and ftp://bar should not render italic, something like foo:bar should render as italic.

          +

          You can use this to draw a line to separate the page:

          +
          +

          You can use lists, start it at the first column for now, please...

          +

          unnumbered lists are like

          +
            +
          • item a
          • +
          • item b
          • +
          • bold item c
          • +
          +

          blank space is also permitted before lists like:

          +
            +
          • item a
          • +
          • item b
          • +
          • item c +
              +
            • item c.a
            • +
            +
          • +
          +

          or you can number them

          +
            +
          1. item 1
          2. +
          3. item 2
          4. +
          5. italic item 3 +
              +
            1. item 3.1
            2. +
            3. item 3.2
            4. +
            +
          6. +
          +

          up to five levels

          +
            +
          • 1 +
              +
            • 2 +
                +
              • 3 +
                  +
                • 4 +
                    +
                  • 5
                  • +
                  +
                • +
                +
              • +
              +
            • +
            +
          • +
          +
            +
          • You can havemultiline list items
          • +
          • this is a second multilinelist item
          • +
          +

          You can use nowiki syntax if you would like do stuff like this:

          +
          +Guitar Chord C:
          +||---|---|---|
          +||-0-|---|---|
          +||---|---|---|
          +||---|-0-|---|
          +||---|---|-0-|
          +||---|---|---|
          +
          +

          You can also use it inline nowiki in a sentence like this.

          +

          Escapes

          +

          Normal Link: http://wikicreole.org/ - now same link, but escaped: http://wikicreole.org/

          +

          Normal asterisks: **not bold**

          +

          a tilde alone: ~

          +

          a tilde escapes itself: ~xxx

          +

          Creole 0.2

          +

          This should be a flower with the ALT text "this is a flower" if your wiki supports ALT text on images:

          +

          here is a red flower

          +

          Creole 0.4

          +

          Tables are done like this:

          + + + + + + + + + + + + + + + + + + + + + +
          header col1header col2
          col1col2
          youcan
          alsoalign
          it.
          +

          You can format an address by simply forcing linebreaks:

          +

          My contact dates:
          +Pone: xyz
          +Fax: +45
          +Mobile: abc

          +

          Creole 0.5

          + + + + + + + + + + + + + + + + + +
          Header titleAnother header title
          //not italic text// **not bold text**
          italic text bold text
          +

          Creole 1.0

          +

          If interwiki links are setup in your wiki, this links to the WikiCreole page about Creole 1.0 test cases: WikiCreole:Creole1.0TestCases.

          diff --git a/mod/wiki/simpletest/output/html/1 b/mod/wiki/simpletest/output/html/1 new file mode 100644 index 00000000000..bbfcab16ad9 --- /dev/null +++ b/mod/wiki/simpletest/output/html/1 @@ -0,0 +1,20 @@ +

          Header1

          +

          +Etiam eget nibh leo. In luctus orci quis tellus sagittis egestas. Praesent et turpis augue, ac accumsan orci? Pellentesque porttitor sodales tortor; vitae faucibus dui auctor vel. Phasellus sit amet sem leo; eu adipiscing ipsum. Aliquam vehicula ipsum at diam imperdiet a condimentum urna commodo? Nunc ac lacus non lorem porttitor malesuada et sit amet diam! Aenean pulvinar lectus et dolor dignissim viverra placerat nisl mattis! Nunc non leo a massa imperdiet porta vel eu tellus. Sed ac est quis orci viverra cursus. Nam tellus mauris, facilisis nec faucibus sit amet, consequat in felis. Ut volutpat lacinia est ut fringilla. Pellentesque augue dui, aliquet et ornare euismod, egestas nec arcu! Vivamus gravida, lorem vitae suscipit condimentum, turpis arcu iaculis tortor; vel ullamcorper lorem ante id nisi. Ut sit amet sem tempor quam dignissim interdum. Nam aliquam, odio vitae volutpat semper; sapien turpis feugiat neque, ac ullamcorper felis enim vitae arcu. Morbi viverra feugiat justo, at ullamcorper ipsum posuere non. +

          +

          +Proin ultricies gravida dui a mattis. Integer nec nisl ante. Mauris euismod, tortor et fermentum semper; est mi adipiscing erat, non pellentesque orci dui ac arcu. Nam vitae metus augue. Integer magna nibh, elementum nec molestie eget; commodo sed turpis. Duis neque mi, vehicula sed aliquet id, ultricies sed tortor. Aliquam pharetra ante sapien. Etiam accumsan ipsum sed dolor bibendum congue sollicitudin enim fringilla. Nulla eros risus, auctor placerat vestibulum eget, tincidunt ac eros. Duis ut turpis leo, sit amet ornare arcu. Aliquam eu lorem in arcu accumsan iaculis. Integer placerat lacus in nibh sollicitudin euismod? Sed a urna vel dui sagittis varius cursus sit amet dolor. Nulla ut sem at magna fringilla hendrerit sed nec sapien. Aenean nisi elit, feugiat vel euismod non, laoreet sit amet ligula. Aenean a dui quam. +

          +

          +Curabitur dolor ligula, suscipit et eleifend nec, faucibus varius sapien. Quisque ornare felis ac leo tincidunt quis malesuada elit lobortis? Suspendisse potenti. Vestibulum tempus porta dui, at ullamcorper mauris sollicitudin vel? In convallis risus id elit ultrices pellentesque. Sed id quam lectus. Duis tincidunt egestas urna, in tempor tortor rhoncus ac. Sed commodo, nunc sit amet sodales vulputate, purus nisi malesuada urna, ut cursus nisl nunc vel enim. Mauris ut imperdiet risus. Integer sagittis; odio at laoreet venenatis, purus neque fermentum nisi, non elementum urna libero sed ipsum. +

          +

          Header2

          +

          +Etiam eget nibh leo. In luctus orci quis tellus sagittis egestas. Praesent et turpis augue, ac accumsan orci? Pellentesque porttitor sodales tortor; vitae faucibus dui auctor vel. Phasellus sit amet sem leo; eu adipiscing ipsum. Aliquam vehicula ipsum at diam imperdiet a condimentum urna commodo? Nunc ac lacus non lorem porttitor malesuada et sit amet diam! Aenean pulvinar lectus et dolor dignissim viverra placerat nisl mattis! Nunc non leo a massa imperdiet porta vel eu tellus. Sed ac est quis orci viverra cursus. Nam tellus mauris, facilisis nec faucibus sit amet, consequat in felis. Ut volutpat lacinia est ut fringilla. Pellentesque augue dui, aliquet et ornare euismod, egestas nec arcu! Vivamus gravida, lorem vitae suscipit condimentum, turpis arcu iaculis tortor; vel ullamcorper lorem ante id nisi. Ut sit amet sem tempor quam dignissim interdum. Nam aliquam, odio vitae volutpat semper; sapien turpis feugiat neque, ac ullamcorper felis enim vitae arcu. Morbi viverra feugiat justo, at ullamcorper ipsum posuere non. +

          +

          +Proin ultricies gravida dui a mattis. Integer nec nisl ante. Mauris euismod, tortor et fermentum semper; est mi adipiscing erat, non pellentesque orci dui ac arcu. Nam vitae metus augue. Integer magna nibh, elementum nec molestie eget; commodo sed turpis. Duis neque mi, vehicula sed aliquet id, ultricies sed tortor. Aliquam pharetra ante sapien. Etiam accumsan ipsum sed dolor bibendum congue sollicitudin enim fringilla. Nulla eros risus, auctor placerat vestibulum eget, tincidunt ac eros. Duis ut turpis leo, sit amet ornare arcu. Aliquam eu lorem in arcu accumsan iaculis. Integer placerat lacus in nibh sollicitudin euismod? Sed a urna vel dui sagittis varius cursus sit amet dolor. Nulla ut sem at magna fringilla hendrerit sed nec sapien. Aenean nisi elit, feugiat vel euismod non, laoreet sit amet ligula. Aenean a dui quam. +

          +

          +Curabitur dolor ligula, suscipit et eleifend nec, faucibus varius sapien. Quisque ornare felis ac leo tincidunt quis malesuada elit lobortis? Suspendisse potenti. Vestibulum tempus porta dui, at ullamcorper mauris sollicitudin vel? In convallis risus id elit ultrices pellentesque. Sed id quam lectus. Duis tincidunt egestas urna, in tempor tortor rhoncus ac. Sed commodo, nunc sit amet sodales vulputate, purus nisi malesuada urna, ut cursus nisl nunc vel enim. Mauris ut imperdiet risus. Integer sagittis; odio at laoreet venenatis, purus neque fermentum nisi, non elementum urna libero sed ipsum. +

          diff --git a/mod/wiki/simpletest/output/html/2 b/mod/wiki/simpletest/output/html/2 new file mode 100644 index 00000000000..318180983cb --- /dev/null +++ b/mod/wiki/simpletest/output/html/2 @@ -0,0 +1,7 @@ +
          +

          +I Love Validator +Make a donation or become a +sponsor +of the http://validator.w3.org/ .

          +
          diff --git a/mod/wiki/simpletest/output/nwiki/1 b/mod/wiki/simpletest/output/nwiki/1 new file mode 100644 index 00000000000..6b1303f0f85 --- /dev/null +++ b/mod/wiki/simpletest/output/nwiki/1 @@ -0,0 +1,11 @@ +

          Header 1

          +

          First paragraph with no formats.

          +

          This paragraph has bold text.

          +

          == False header =

          +

          This part of the paragraph is italicized. But not this part.

          +

          Header 2

          +

          Some mix of italics and bold, and some italics & bold.

          +

          And that italics and both.

          +

          And this: italics and both.

          +
          +
          diff --git a/mod/wiki/simpletest/output/nwiki/2 b/mod/wiki/simpletest/output/nwiki/2 new file mode 100644 index 00000000000..5b2c07dd091 --- /dev/null +++ b/mod/wiki/simpletest/output/nwiki/2 @@ -0,0 +1,12 @@ +

          Links

          +

          Internal links

          +

          Some links. Another Link.

          +

          Anchors

          +

          This is an anchor to the external links section.

          +

          And this is an anchor to another page.

          +

          External links

          +

          A link to http://www.google.com , and a link to apple.

          +

          The same link to Apple Corporation.

          +

          Attachments & images

          +

          That's an attachment.

          +

          And that's an

          image
          .

          diff --git a/mod/wiki/simpletest/output/nwiki/3 b/mod/wiki/simpletest/output/nwiki/3 new file mode 100644 index 00000000000..1c38e6893c5 --- /dev/null +++ b/mod/wiki/simpletest/output/nwiki/3 @@ -0,0 +1,39 @@ +

          Lists

          +

          Unordered lists

          +
            +
          • 1 +
              +
            • 2
            • +
            +
          • +
          • 1
          • +
          +
            +
          • 1 +
              +
            • 3 +
                +
              • bold
              • +
              +
            • +
            +
          • +
          • italic
          • +
          +

          Ordered lists

          +
            +
          1. 1 +
              +
            1. 2
            2. +
            +
          2. +
          3. 3
          4. +
          +
            +
          1. 4
          2. +
          3. 5 +
              +
            1. 6
            2. +
            +
          4. +
          diff --git a/mod/wiki/simpletest/output/nwiki/4 b/mod/wiki/simpletest/output/nwiki/4 new file mode 100644 index 00000000000..6bff3823b6f --- /dev/null +++ b/mod/wiki/simpletest/output/nwiki/4 @@ -0,0 +1,26 @@ + + + + + + + + + + + +
          AB
          CD
          + + + + + + + + + + + + + +
          AB
          CD
          diff --git a/mod/wiki/simpletest/output/nwiki/5 b/mod/wiki/simpletest/output/nwiki/5 new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/mod/wiki/simpletest/output/nwiki/5 @@ -0,0 +1 @@ + diff --git a/mod/wiki/simpletest/testwikiparser.php b/mod/wiki/simpletest/testwikiparser.php new file mode 100644 index 00000000000..2c043bb3850 --- /dev/null +++ b/mod/wiki/simpletest/testwikiparser.php @@ -0,0 +1,81 @@ +. + +/** + * Unit tests for the wiki parser + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +if (!defined('MOODLE_INTERNAL')) { + die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page +} + +require_once($CFG->dirroot . '/mod/wiki/parser/parser.php'); + +class wikiparser_test extends UnitTestCase { + + private $test_directory; + + function setUp() { + global $CFG; + $this->test_directory = $CFG->dirroot . '/mod/wiki/simpletest/'; + } + + function testCreoleMarkup() { + $this->assertTestFiles('creole'); + } + + function testNwikiMarkup() { + $this->assertTestFiles('nwiki'); + } + + function testHtmlMarkup() { + $this->assertTestFiles('html'); + } + + private function assertTestFile($num, $markup) { + if(!file_exists($this->test_directory."input/$markup/$num") || !file_exists($this->test_directory."output/$markup/$num")) { + return false; + } + + $input = file_get_contents($this->test_directory."input/$markup/$num"); + $output = file_get_contents($this->test_directory."output/$markup/$num"); + + $result = wiki_parser_proxy::parse($input, $markup, array('pretty_print' => true)); + + $this->assertEqual($result['parsed_text'], $output); + return true; + } + + private function assertTestFiles($markup) { + $i = 1; + while($this->assertTestFile($i, $markup)) { + $i++; + } + } +} diff --git a/mod/wiki/strippages.html b/mod/wiki/strippages.html deleted file mode 100644 index 483f58031e7..00000000000 --- a/mod/wiki/strippages.html +++ /dev/null @@ -1,23 +0,0 @@ - -
          -
          - - - - - -pagestostrip, $form->version, $err); - echo html_writer::table($strip_table); -?> -
          -data)) { - print get_string("nothingtostrip","wiki")."

          "; - } -?> - " /> -
          diff --git a/mod/wiki/styles.css b/mod/wiki/styles.css index b29bc4c178d..7890a4c2871 100644 --- a/mod/wiki/styles.css +++ b/mod/wiki/styles.css @@ -1,7 +1,346 @@ -.path-mod-wiki .sideblockheading, -.path-mod-wiki .howtowiki {text-align:right;} -.path-mod-wiki .wikisearchform, -.path-mod-wiki .wikilinksblock, -.path-mod-wiki .wikiadminactions {text-align:center;} -.path-mod-wiki .wikilinkright {text-align:right;padding-bottom: 0.5em;} -.path-mod-wiki .wikiexportbox {margin-left:auto;margin-right:auto;} \ No newline at end of file +/* + This file is part of Moodle - http://moodle.org/ + + Moodle is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Moodle is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Moodle. If not, see . +*/ /** + * Wiki module style sheet + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +.wiki_contentbox { + width: 80%; + margin: auto; + min-width: 200px; + min-height: 100px; +} + +.wiki_editor { + width: 50%; + margin: auto; + margin-top: 10px; + margin-bottom: 10px; +} + +.wiki_previewbox { + width: 50%; + margin: auto; + border: thin solid blue; +} + +.wiki_info { + color: darkred; + text-decoration: underline; +} + +.wiki_button { + margin: 5px; +} + +.wiki_warning { + color: red; +} + +.emptycomments { + color: red; + display: inline; +} + +.wiki-toc { + border: 1px solid #BBB; + background: #EEE; + margin: 16px; + padding: 8px; +} + +.wiki-toc-title { + color: #666; + font-size: 1.1em; + font-variant: small-caps; + text-align: center; +} + +.wiki-toc-section { + padding: 0; + margin: 2px 8px; +} + +.wiki-toc-section-2 { + padding-left: 12px; +} + +.wiki-toc-section-3 { + padding-left: 24px; +} + +.wiki_form-button { + margin-left: 0%; +} + +.wiki-form-center { + text-align: center; + margin: auto; + width: 320px; +} + +.wiki-upload-table { + margin: 8px auto; + clear: both; +} + +.wiki-upload-table table { + margin: auto; +} + +.wiki-upload-table h3 { + margin: 4px 0px; + text-align: center; +} + +.wiki-upload-section { + border: 1px solid #EEE; + width: 400px; + margin: 8px auto; +} + +.wiki-upload-section legend { + font-weight: bold; + font-size: 0.9em; + margin-left: 16px; +} + +.wiki-tags { + text-align: right; +} + +.wiki-tags span { + font-weight: bold; +} + +.filemanager-container { + margin: auto; + width: 320px; +} + +.wiki_modifieduser p { + line-height: 35px; +} + +.wiki_modifieduser img { + border: thin black solid; +} + +.wiki_restore_yes { + float: left; +} + +.wiki_restore_no { + float: right; +} + +.wiki_restoreform { + width: 10%; + margin: auto; +} + +.wiki_versionuser { + float: left; +} + +.wiki_diffuserleft,.wiki_diffuserright { + font-weight: normal; + padding-top: 1%; +} + +.wiki_diffuserleft { + float: right; +} + +.wiki_diffuserright { + float: left; +} + +.wiki_compareheading { + font-weight: normal; +} + +.wiki_restore,.wiki_diffview,.wiki_difftime,.wiki_headingtime { + font-size: 0.8em; + font-weight: normal; +} + +.wiki_difftime,.wiki_headingtime { + font-style: oblique; + text-align: center; +} + +.wiki_diff_oldpaging { + float: left; + width: 40%; + min-width: 200px; + margin-left: 5%; +} + +.wiki_diff_newpaging { + float: right; + width: 40%; + min-width: 200px; + margin-right: 5%; +} + +.wiki_diff_old,.wiki_diff_new { + float: left; + min-width: 200px; + width: 40%; +} + +.wiki_difftable td { + width: 50%; + float: left; +} + +.wiki_histdate { + text-align: left; +} + +.wiki_histnewdate { + border-top: 1px dotted gray; +} + +.ouw_deleted { + background: #FFFFAA; + color: red; + text-decoration: line-through; +} + +.ouw_added { + background: #CCFFCC; + color: red; +} + +a.wiki_newentry:link,a.wiki_newentry:visited { + color: red; +} + +.wiki_newentry a { + color: red; +} + +#intro.generalbox { + margin-top: 10px; + padding: 5px; +} + +.wiki_navigation_container { + margin: 0 auto; +} + +.wiki_navigation_from { + float: left; + width: 40%; + min-width: 200px; + margin-left: 5%; +} + +.wiki_navigation_to { + float: left; + width: 40%; + min-width: 200px; + margin-right: 5%; +} + +.wiki_headingtitle { + text-align: center; +} + +.wiki_clear { + clear: both; +} + +.wiki_right { + text-align: right; +} + +.wiki_index { + text-align: right; +} + +.notunderlined { + text-decoration: none; +} + +a.wiki_edit_section { + font-size: 0.6em; + vertical-align: top; + position: relative; + float: right; +} + +.midpad { + text-align: center; + margin-top: 0.4em; + margin-bottom: 0.4em; +} + +.block_wiki_search ul { + margin-top: 0.5em; + margin-bottom: 3px; +} + +.wiki-attachment:before { + content: url("/mod/wiki/pix/attachment.png"); + padding-right: 2px; +} + +/** Print CSS */ +#wiki_printable_content { + text-align: left; +} + +#wiki_printable_content a { + color: black; +} + +#wiki_printable_title { + font-size: 2.2em; + text-decoration: underline; +} + +.wiki_diff_boxes { + width: 100%; + clear: both; +} + +.wiki_diff_paging { + width: 100%; + clear: both; +} + +.wiki_grayline { + color: gray +} + +.wikisearchresults{ + padding-left: 50px; + padding-top: 20px; +} \ No newline at end of file diff --git a/mod/wiki/test.php b/mod/wiki/test.php deleted file mode 100644 index 94cb063f5da..00000000000 --- a/mod/wiki/test.php +++ /dev/null @@ -1,2 +0,0 @@ -version = 2009042700; // The current module version (Date: YYYYMMDDXX) -$module->requires = 2009041700; // The current module version (Date: YYYYMMDDXX) -$module->cron = 3600; // Period for cron to check this module (secs) +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . +/** + * Code fragment to define the version of wiki + * This fragment is called by moodle_needs_upgrading() and /admin/index.php + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +$module->version = 2010040109; // The current module version (Date: YYYYMMDDXX) +$module->cron = 0; // Period for cron to check this module (secs) diff --git a/mod/wiki/view.php b/mod/wiki/view.php index 3ebed73b16b..0960c402c72 100644 --- a/mod/wiki/view.php +++ b/mod/wiki/view.php @@ -1,516 +1,299 @@ . - require_once("../../config.php"); - require_once("lib.php"); - #require_once("$CFG->dirroot/course/lib.php"); // For side-blocks - $PAGE->requires->yui2_lib('connection'); +/** + * This file contains all necessary code to view a wiki page + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ - $ewiki_action = null; // this is a bloody global which is set up elsewhere - $id = optional_param('id', 0, PARAM_INT); // Course Module ID, or - $wid = optional_param('wid', 0, PARAM_INT); // Wiki ID - $page = optional_param('page', false); // Wiki Page Name - $q = optional_param('q',"", PARAM_PATH); // Search Context - $userid = optional_param('userid', 0, PARAM_INT); // User wiki. - $groupid = optional_param('groupid', 0, PARAM_INT); // Group wiki. - $canceledit = optional_param('canceledit','', PARAM_ALPHA); // Editing has been cancelled - $cacheme = optional_param('allowcache', 1, PARAM_INT); // Set this to 0 to try and disable page caching. +require_once('../../config.php'); +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); - // Only want to add edit log entries if we have made some changes ie submitted a form - $editsave = optional_param('thankyou', '', PARAM_RAW); +$currentgroup = optional_param('group', 0, PARAM_INT); // Group ID +$userid = optional_param('userid', 0, PARAM_INT); // User ID +$title = optional_param('title', '', PARAM_TEXT); // Page Title +$action = optional_param('action', '', PARAM_ALPHA); +$id = optional_param('id', 0, PARAM_INT); // Course Module ID +$swid = optional_param('swid', 0, PARAM_INT); // Subwiki ID +$pageid = optional_param('pageid', 0, PARAM_INT); // Page ID +$wid = optional_param('wid', 0, PARAM_INT); // Wiki ID +$edit = optional_param('edit', -1, PARAM_BOOL); - $url = new moodle_url('/mod/wiki/view.php'); - if ($ewiki_action !== '') { - $url->param('ewiki_action', $ewiki_action); +/* + * Case 0: + * + * User that comes from a course. First wiki page must be shown + * + * URL params: id -> course module id + * + */ +if ($id) { + // Cheacking course module instance + if (!$cm = get_coursemodule_from_id('wiki', $id)) { + print_error('invalidcoursemodule'); } - if ($id !== 0) { - $url->param('id', $id); - } - if ($wid !== 0) { - $url->param('wid', $wid); - } - if ($page !== false) { - $url->param('page', $page); - } - if ($q !== '') { - $url->param('q', $q); - } - if ($userid !== 0) { - $url->param('userid', $userid); - } - if ($groupid !== 0) { - $url->param('groupid', $groupid); - } - if ($canceledit !== '') { - $url->param('canceledit', $canceledit); - } - if ($cacheme !== 1) { - $url->param('allowcache', $cacheme); - } - $PAGE->set_url($url); - if($page) { - // Split page command into action and page - $actions = explode('/', $page,2); - if(count($actions)==2) { - $pagename=$actions[1]; - } else { - $pagename=$actions[0]; + // Checking course instance + if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); + } + + // Checking wiki instance + if (!$wiki = wiki_get_wiki($cm->instance)) { + print_error('incorrectwikiid', 'wiki'); + } + + // Getting the subwiki corresponding to that wiki, group and user. + // + // Also setting the page if it exists or getting the first page title form + // that wiki + + // Getting current group id + $currentgroup = groups_get_activity_group($cm); + // Getting current user id + if ($wiki->wikimode == 'individual'){ + if (empty($userid)){ + $userid = $USER->id; } } else { - $actions=array(''); - $pagename=''; + $userid = 0; } - - if ($id) { - if (! $cm = get_coursemodule_from_id('wiki', $id)) { - print_error('invalidcoursemodule'); - } - - if (! $course = $DB->get_record("course", array("id"=>$cm->course))) { - print_error('coursemisconf'); - } - - if (! $wiki = $DB->get_record("wiki", array("id"=>$cm->instance))) { - print_error('invalidcoursemodule'); - } - + $subwiki = wiki_get_subwiki_by_group($wiki->id, $currentgroup, $userid); + $page = null; + if (!empty($subwiki)){ + $page = wiki_get_first_page($subwiki->id, $wiki); + } + if (!empty($page)){ + $pageid = $page->id; } else { - if (! $wiki = $DB->get_record("wiki", array("id"=>$wid))) { - print_error('invalidcoursemodule'); - } - if (! $course = $DB->get_record("course", array("id"=>$wiki->course))) { - print_error('coursemisconf'); - } - if (! $cm = get_coursemodule_from_instance("wiki", $wiki->id, $course->id)) { - print_error('invalidcoursemodule'); - } - } - - require_course_login($course, true, $cm); - - /// Add the course module info to the wiki object, for easy access. - $wiki->groupmode = $cm->groupmode; - $wiki->groupingid = $cm->groupingid; - $wiki->groupmembersonly = $cm->groupmembersonly; - $wiki->cmid = $cm->id; - - /// Default format: - $moodle_format=FORMAT_MOODLE; - -/// Globally disable CamelCase, if the option is selected for this wiki. - $moodle_disable_camel_case = ($wiki->disablecamelcase == 1); - - if (($wiki_entry = wiki_get_default_entry($wiki, $course, $userid, $groupid))) { - // OK, now we know the entry ID, we can do lock etc. - - // If true, we are 'really' on an editing page, not just on edit/something - $reallyedit=$actions[0]=='edit' && !$canceledit && !$editsave; - - // Remove lock when we go to another wiki page (such as the cancel page) - if(!$reallyedit) { - wiki_release_lock($wiki_entry->id,$pagename); - } else if(array_key_exists('content',$_POST)) { - // Do not allow blank content because it causes problems (the wiki decides - // the page should automatically go into edit mode, but Moodle doesn't realise - // this and filters out the JS) - if($_POST['content']=='') { - $_POST['content']="\n"; - $_REQUEST['content']="\n"; - } - - // We must have the edit lock in order to be permitted to save - list($ok,$lock)=wiki_obtain_lock($wiki_entry->id,$pagename); - if(!$ok) { - print_error('savenolock', 'wiki', $CFG->wwwroot.'/mod/wiki/view.php?id='.$cm->id.'&page=view/'.urlencode($pagename)); - } - } - -/// ################# EWIKI Part ########################### -/// The wiki_entry->pagename is set to the specified value of the wiki, -/// or the default value in the 'lang' file if the specified value was empty. - define("EWIKI_PAGE_INDEX",$wiki_entry->pagename); - - /// If the page has a ' in it, it may have slashes added to it. Remove them if it does. - $page = ($page === false) ? EWIKI_PAGE_INDEX : $page; - -/// # Prevent ewiki getting id as PageID... - unset($_REQUEST["id"]); - unset($_GET["id"]); - unset($_POST["id"]); - unset($_POST["id"]); - unset($_SERVER["QUERY_STRING"]); - if (isset($HTTP_GET_VARS)) { - unset($HTTP_GET_VARS["id"]); - } - if (isset($HTTP_POST_VARS)) { - unset($HTTP_POST_VARS["id"]); - } - global $ewiki_title; - -/// #-- predefine some of the configuration constants - - - /// EWIKI_NAME is defined in ewikimoodlelibs, so that also admin.php can use this - #define("EWIKI_NAME", $wiki_entry->pagename); - - /// Search Hilighting - if($ewiki_title=="SearchPages") { - $qArgument="&q=".urlencode($q); - } - - /// Build the ewsiki script constant - /// ewbase will also be needed by EWIKI_SCRIPT_BINARY - $ewbase = 'view.php?id='.$cm->id; - if (isset($userid) && $userid!=0) $ewbase .= '&userid='.$userid; - if (isset($groupid) && $groupid!=0) $ewbase .= '&groupid='.$groupid; - $ewscript = $ewbase.'&page='; - define("EWIKI_SCRIPT", $ewscript); - define("EWIKI_SCRIPT_URL", $ewscript); - - /// # Settings for this specific Wiki - define("EWIKI_PRINT_TITLE", $wiki->ewikiprinttitle); - - define("EWIKI_INIT_PAGES", wiki_content_dir($wiki)); - - # Database Handler - include_once($CFG->dirroot."/mod/wiki/ewikimoodlelib.php"); - # Plugins - //include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/email_protect.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/patchsaving.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/notify.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/feature/imgresize_gd.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/moodle_highlight.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/f_fixhtml.php"); - #include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/wikinews.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/sitemap.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/moodle_wikidump.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/aview/backlinks.php"); - #include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/markup/css.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/markup/footnotes.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/diff.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/page/pageindex.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/page/orphanedpages.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/wantedpages.php"); - - # Binary Handling - if($wiki->ewikiacceptbinary) { - define("EWIKI_UPLOAD_MAXSIZE", get_max_upload_file_size()); - define("EWIKI_SCRIPT_BINARY", $ewbase."&binary="); - define("EWIKI_ALLOW_BINARY",1); - define("EWIKI_IMAGE_CACHING",1); - #define("EWIKI_AUTOVIEW",1); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/lib/mime_magic.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/aview/downloads.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/downloads.php"); - #include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/db/binary_store.php"); - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/moodle_binary_store.php"); + // the first page doesn't exist, so redirect to create page + $page = null; + $title = $wiki->firstpagetitle; + $default = $wiki->defaultformat; + $params = array(); + $params['action'] = 'new'; + $params['title'] = $title; + if (empty($subwiki)) { + $params['gid'] = $currentgroup; + $params['wid'] = $wiki->id; + $params['uid'] = $userid; } else { - define("EWIKI_SCRIPT_BINARY", 0); - define("EWIKI_ALLOW_BINARY",0); + $params['swid'] = $subwiki->id; } - # The mighty Wiki itself - include_once($CFG->dirroot."/mod/wiki/ewiki/ewiki.php"); - - if($canceledit) { - if ($delim = strpos($page, EWIKI_ACTION_SEP_CHAR)) { - @$page = substr($page, $delim + 1); - } else { - @$page=""; - } - } - # Language-stuff: eWiki gets language from Browser. Lets correct it. Empty arrayelements do no harm - $ewiki_t["languages"]=array(current_language(), $course->lang, $CFG->lang,"en","c"); - - # Check Access Rights - $canedit = wiki_can_edit_entry($wiki_entry, $wiki, $USER, $course); - if (!$canedit) { - # Protected Mode - unset($ewiki_plugins["action"]["edit"]); - unset($ewiki_plugins["action"]["info"]); - } - - # HTML Handling - $ewiki_use_editor=0; - if($wiki->htmlmode == 0) { - # No HTML - $ewiki_config["htmlentities"]=array(); // HTML is managed by moodle - $moodle_format=FORMAT_TEXT; - } - if($wiki->htmlmode == 1) { - # Safe HTML - include_once($CFG->dirroot."/mod/wiki/ewiki/plugins/moodle/moodle_rescue_html.php"); - $moodle_format=FORMAT_HTML; - } - if($wiki->htmlmode == 2) { - # HTML Only - $moodle_format=FORMAT_HTML; - $ewiki_use_editor=1; - $ewiki_config["htmlentities"]=array(); // HTML is allowed - $ewiki_config["wiki_link_regex"] = "\007 [!~]?( - \#?\[[^<>\[\]\n]+\] | - \^[-".EWIKI_CHARS_U.EWIKI_CHARS_L."]{3,} | - \b([\w]{3,}:)*([".EWIKI_CHARS_U."]+[".EWIKI_CHARS_L."]+){2,}\#?[\w\d]* | - \w[-_.+\w]+@(\w[-_\w]+[.])+\w{2,} ) \007x"; - } - - global $ewiki_author, $USER; - $ewiki_author=fullname($USER); - $content=ewiki_page($page); - $content2=''; - -/// ################# EWIKI Part ########################### - } - else { - $content = ''; - $content2 = '
          '.get_string('nowikicreated', 'wiki').'
          '; - + $url = new moodle_url('/mod/wiki/create.php', $params); + redirect($url->out(false)); } - # Group wiki, ...: No page and no ewiki_title - if(!isset($ewiki_title)) { - $ewiki_title=""; + /* + * Case 1: + * + * A user wants to see a page. + * + * If group is set, system must show the page with the same name from another group. + * In this case, is probable that there is no version of that page for the + * given group + * + * URL Params: pageid -> page id + * group -> group id (optional) + * + */ +} elseif ($pageid) { + + // Checking page instance + if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); } - - -/// Moodle Log - if ($editsave != NULL) { /// We've submitted an edit and have been redirected back here - add_to_log($course->id, "wiki", 'edit', - "view.php?id=$cm->id&groupid=$groupid&userid=$userid&page=$ewiki_title", - format_string($wiki->name,true).": ".$ewiki_title, $cm->id, $userid); - } else if ($ewiki_action != 'edit') { - if (!in_array($ewiki_action, array('view', 'links', 'info'))) { - add_to_log($course->id, "wiki", 'bogus', - "view.php?id=$cm->id&groupid=$groupid&userid=$userid&page=$ewiki_title", - format_string($wiki->name,true).": ".$ewiki_title, $cm->id, $userid); - } else { - add_to_log($course->id, "wiki", $ewiki_action, - "view.php?id=$cm->id&groupid=$groupid&userid=$userid&page=$ewiki_title", - format_string($wiki->name,true).": ".$ewiki_title, $cm->id, $userid); - } - } - - -/// Print the page header - - $strwikis = get_string("modulenameplural", "wiki"); - $strwiki = get_string("modulename", "wiki"); - -/// Add page name if not main page - if ($ewiki_title != $wiki->name) { - $PAGE->navbar->add(format_string($ewiki_title)); - } - $PAGE->set_title($ewiki_title?$ewiki_title:format_string($wiki->name)); - $PAGE->set_cacheable($cacheme); - $PAGE->set_button($OUTPUT->update_module_button($cm->id, 'wiki')); - echo $OUTPUT->header(); - /// Print Page - echo '
          - '; - /// The top row contains links to other wikis, if applicable. - if ($wiki_entry && $wiki_list = wiki_get_other_wikis($wiki, $USER, $course, $wiki_entry->id)) { - //echo "wiki list ";print_r($wiki_list); - $selected=""; - - if (isset($wiki_list['selected'])) { - $selected = $wiki_list['selected']; - unset($wiki_list['selected']); - } - echo ''; - - echo '
          '; - echo ''; - echo ''; - - echo ''; - echo '
           ' - .$WIKI_TYPES[$wiki->wtype].' ' - .get_string('modulename', 'wiki')." ".get_string('for',"wiki")." " - .wiki_get_owner($wiki_entry).':' - .get_string('otherwikis', 'wiki').':  '; - $aid = $OUTPUT->add_action_handler(new component_action('change', 'go_to_wiki')); - $attributes = array('id'=>$aid); - echo html_writer::select($wiki_list, 'wikiselect', $selected, array(''=>'choose'), $attributes); - echo '
          '; - echo '
          '; - - echo ''; - echo ''; - } - - if ($wiki_entry) { - $specialpages=array("WikiExport", "SiteMap", "SearchPages", "PageIndex","NewestPages","MostVisitedPages","MostOftenChangedPages","UpdatedPages","FileDownload","FileUpload","OrphanedPages","WantedPages"); - /// Page Actions - echo ''; - echo ''; - - /// Searchform - echo ''; - - /// Internal Wikilinks - echo ''; - - /// Administrative Links - if($canedit) { - echo ''; - } - - /// Formatting Rules - echo ''; - - echo '
          '; - wiki_print_search_form($cm->id, $q, $userid, $groupid, false); - echo ''; - wiki_print_wikilinks_block($cm->id, $wiki->ewikiacceptbinary); - echo ''; - wiki_print_administration_actions($wiki, $cm->id, $userid, $groupid, $ewiki_title, $wiki->htmlmode!=2, $course); - echo ''; - echo $OUTPUT->old_help_icon('howtowiki', get_string('howtowiki', 'wiki'), 'wiki'); - echo '
          '; - } - - echo '
          -
          - '; - - if($wiki_entry && $ewiki_title==$wiki_entry->pagename && !empty($wiki->intro)) { - if (trim(strip_tags($wiki->intro))) { - echo $OUTPUT->box(format_module_intro('wiki', $wiki, $cm->id), 'generalbox', 'intro'); - } - } - - // The wiki Contents - - if (!empty($canedit)) { /// Print tabs with commands for this page - $tabs = array('view', 'edit','links','info'); - if ($wiki->ewikiacceptbinary) { - $tabs[] = 'attachments'; - } - - $tabrows = array(); - $row = array(); - $currenttab = ''; - foreach ($tabs as $tab) { - $tabname = get_string("tab$tab", 'wiki'); - $row[] = new tabobject($tabname, $ewbase.'&page='.$tab.'/'.s($ewiki_id), $tabname); - if ($ewiki_action == "$tab" or in_array($page, $specialpages)) { - $currenttab = $tabname; - } - } - $tabrows[] = $row; - - print_tabs($tabrows, $currenttab); - } - - /// Insert a link to force page refresh if new content isn't showing. - - // build new URL + query string - $queries = preg_split('/[?&]/', me()); - $nqueries = count($queries); - $me = $queries[0] . '?'; - for($i=1; $i < $nqueries; $i++) - { - if( !strstr($queries[$i], 'allowcache') ) - $me .= $queries[$i] . '&'; - } - $me .= 'allowcache=0'; - - // Insert the link - $linkdesc = get_string('reloadlinkdescription', 'wiki'); - $linktext = get_string('reloadlinktext', 'wiki'); - echo "
          "; - - echo $OUTPUT->box_start(); - - /// Don't filter any pages containing wiki actions (except view). A wiki page containing - /// actions will have the form [action]/[pagename]. If the action is 'view' or the '/' - /// isn't there (so the action defaults to 'view'), filter it. - /// If the page does not yet exist, the display will default to 'edit'. - if((count($actions) < 2 || $actions[0] == "view") && $wiki_entry && - $DB->record_exists('wiki_pages', array('pagename'=>$page, 'wiki'=>$wiki_entry->id))) { - print(format_text($content, $moodle_format)); - } else if($actions[0]=='edit' && $reallyedit) { - // Check the page isn't locked before printing out standard wiki content. (Locking - // is implemented as a wrapper over the existing wiki.) - list($gotlock,$lock)=wiki_obtain_lock($wiki_entry->id,$pagename); - if(!$gotlock) { - $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); - $canoverridelock = has_capability('mod/wiki:overridelock', $modcontext); - - $a=new stdClass; - $a->since=userdate($lock->lockedsince); - $a->seen=userdate($lock->lockedseen); - $user=$DB->get_record('user', array('id'=>$lock->lockedby)); - $a->name=fullname($user, - has_capability('moodle/site:viewfullnames', $modcontext)); - - print_string('pagelocked','wiki',$a); - - if($canoverridelock) { - $pageesc=htmlspecialchars($page); - $stroverrideinfo=get_string('overrideinfo','wiki'); - $stroverridebutton=get_string('overridebutton','wiki'); - $sesskey=sesskey(); - print " -
          -
          - - - - $stroverrideinfo - -
          -
          -"; + if (!empty($swid)){ + // User wants to view another subwiki + if ($subwiki = wiki_get_subwiki($swid)){ + if (!$page = wiki_get_page_by_title($swid, $page->title)) { + $url = new moodle_url('/mod/wiki/view.php', array('id'=>$subwiki->id)); + print_error('individualpagedoesnotexist', 'wiki', $url->out()); } } else { - if (ajaxenabled()) { - // OK, the page is now locked to us. Put in the AJAX for keeping the lock - $strlockcancelled=addslashes_js(get_string('lockcancelled','wiki')); - $strnojslockwarning=get_string('nojslockwarning','wiki'); - $intervalms=WIKI_LOCK_RECONFIRM*1000; - print " - - -"; - } - // Print editor etc - print $content; - } - } else { - print $content; - } - print $content2; - echo $OUTPUT->box_end(); - echo "
          "; -/// Finish the page - echo ' -
          - '; +$wikipage = new page_wiki_view($wiki, $subwiki, $cm); - echo $OUTPUT->footer(); +/*The following piece of code is used in order + * to perform set_url correctly. It is necessary in order + * to make page_wiki_view class know that this page + * has been called via its id. + */ +if ($id) { + $wikipage->set_coursemodule($id); +} +$wikipage->set_gid($currentgroup); +$wikipage->set_page($page); + +$wikipage->print_header(); +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/viewversion.php b/mod/wiki/viewversion.php new file mode 100644 index 00000000000..0bffff2ad87 --- /dev/null +++ b/mod/wiki/viewversion.php @@ -0,0 +1,75 @@ +. + +/** + * This file contains all necessary code to view an old version of a page + * + * @package mod-wiki-2.0 + * @copyrigth 2009 Marc Alier, Jordi Piguillem marc.alier@upc.edu + * @copyrigth 2009 Universitat Politecnica de Catalunya http://www.upc.edu + * + * @author Jordi Piguillem + * @author Marc Alier + * @author David Jimenez + * @author Josep Arus + * @author Kenneth Riba + * + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); + +require_once($CFG->dirroot . '/mod/wiki/lib.php'); +require_once($CFG->dirroot . '/mod/wiki/locallib.php'); +require_once($CFG->dirroot . '/mod/wiki/pagelib.php'); + +$pageid = required_param('pageid', PARAM_TEXT); +$versionid = required_param('versionid', PARAM_INT); + +if (!$page = wiki_get_page($pageid)) { + print_error('incorrectpageid', 'wiki'); +} + +if (!$subwiki = wiki_get_subwiki($page->subwikiid)) { + print_error('incorrectsubwikiid', 'wiki'); +} + +if (!$wiki = wiki_get_wiki($subwiki->wikiid)) { + print_error('incorrectwikiid', 'wiki'); +} + +if (!$cm = get_coursemodule_from_instance('wiki', $wiki->id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = get_course_by_id($cm->course)) { + print_error('coursemisconf'); +} + +require_course_login($course->id, true, $cm); +add_to_log($course->id, "wiki", "history", "history.php?id=$cm->id", "$wiki->id"); + +/// Print the page header +$wikipage = new page_wiki_viewversion($wiki, $subwiki, $cm); + +$wikipage->set_page($page); +$wikipage->set_versionid($versionid); + +$wikipage->print_header(); +$wikipage->print_content(); + +$wikipage->print_footer(); diff --git a/mod/wiki/wiki.js b/mod/wiki/wiki.js deleted file mode 100644 index db737d0bcf9..00000000000 --- a/mod/wiki/wiki.js +++ /dev/null @@ -1,3 +0,0 @@ -function go_to_wiki(e, args) { - self.location = e.target.value; -}