Moodle  2.2.1
http://www.collinsharper.com
C:/xampp/htdocs/moodle/mod/wiki/db/migration/wiki/ewiki/ewiki.php
Go to the documentation of this file.
00001 <?php
00002 
00003 defined('MOODLE_INTERNAL') || die();
00004 
00005 @define("EWIKI_VERSION", "R1.01d");
00006 
00007 /*
00008 
00009   ErfurtWiki - an embedable, fast and user-friendly wiki engine
00010   ---------
00011   This is Public Domain (no license, no warranty); but feel free
00012   to redistribute it under GPL or anything else you like.
00013 
00014   http://erfurtwiki.sourceforge.net/
00015   Mario Salzer <mario*erphesfurt·de> and many others(tm)
00016 
00017 
00018   Use it from inside yoursite.php like that:
00019   <html><body>...
00020   <?php
00021      include("ewiki.php");
00022      echo ewiki_page();
00023   ?>
00024 
00025 */
00026 
00027 #-- you could also establish a mysql connection in here, of course:
00028 // mysql_connect(":/var/run/mysqld/mysqld.sock", "user", "pw")
00029 // and mysql_query("USE mydatabase");
00030 
00031 
00032         #-------------------------------------------------------- config ---
00033 
00034         #-- I'm sorry for that, but all the @ annoy me
00035         error_reporting(0x0000377 & error_reporting());
00036 #   error_reporting(E_ALL^E_NOTICE);
00037 
00038     #-- the position of your ewiki-wrapper script
00039     define("EWIKI_SCRIPT", "?id=");     # relative/absolute to docroot
00040 #   define("EWIKI_SCRIPT_URL", "http://...?id=");       # absolute URL
00041 
00042         #-- change to your needs (site lang)
00043     //define("EWIKI_NAME", "ErfurtWiki");
00044     define("EWIKI_PAGE_INDEX", "ErfurtWiki");
00045     define("EWIKI_PAGE_NEWEST", "NewestPages");
00046     define("EWIKI_PAGE_SEARCH", "SearchPages");
00047     define("EWIKI_PAGE_HITS", "MostVisitedPages");
00048     define("EWIKI_PAGE_VERSIONS", "MostOftenChangedPages");
00049     define("EWIKI_PAGE_UPDATES", "UpdatedPages");
00050 
00051     #-- default settings are good settings - most often ;)
00052         #- look & feel
00053     define("EWIKI_PRINT_TITLE", 1);     # <h2>WikiPageName</h2> on top
00054     define("EWIKI_SPLIT_TITLE", 0);     # <h2>Wiki Page Name</h2>
00055     define("EWIKI_CONTROL_LINE", 1);    # EditThisPage-link at bottom
00056     define("EWIKI_LIST_LIMIT", 20);     # listing limit
00057         #- behaviour
00058     define("EWIKI_AUTO_EDIT", 1);       # edit box for non-existent pages
00059     define("EWIKI_EDIT_REDIRECT", 1);   # redirect after edit save
00060     define("EWIKI_DEFAULT_ACTION", "view"); # (keep!)
00061     define("EWIKI_CASE_INSENSITIVE", 1);    # wikilink case sensitivity
00062     define("EWIKI_HIT_COUNTING", 1);
00063     define("UNIX_MILLENNIUM", 1000000000);
00064         #- rendering
00065     define("EWIKI_ALLOW_HTML", 0);      # often a very bad idea
00066     define("EWIKI_HTML_CHARS", 1);      # allows for &#200;
00067     define("EWIKI_ESCAPE_AT", 1);       # "@" -> "&#x40;"
00068         #- http/urls
00069     define("EWIKI_HTTP_HEADERS", 1);    # most often a good thing
00070     define("EWIKI_NO_CACHE", 1);        # browser+proxy shall not cache
00071     define("EWIKI_URLENCODE", 1);       # disable when _USE_PATH_INFO
00072     define("EWIKI_URLDECODE", 1);
00073     define("EWIKI_USE_PATH_INFO", 1  &&!strstr($_SERVER["SERVER_SOFTWARE"],"Apache"));
00074     define("EWIKI_USE_ACTION_PARAM", 1);
00075     define("EWIKI_ACTION_SEP_CHAR", "/");
00076     define("EWIKI_UP_PAGENUM", "n");    # _UP_ means "url parameter"
00077     define("EWIKI_UP_PAGEEND", "e");
00078     define("EWIKI_UP_BINARY", "binary");
00079     define("EWIKI_UP_UPLOAD", "upload");
00080         #- other stuff
00081         //define("EWIKI_DEFAULT_LANG", "en");
00082         define("EWIKI_CHARSET", "UTF-8");
00083     #- user permissions
00084     define("EWIKI_PROTECTED_MODE", 0);  # disable funcs + require auth
00085     define("EWIKI_PROTECTED_MODE_HIDING", 0);  # hides disallowed actions
00086     define("EWIKI_AUTH_DEFAULT_RING", 3);   # 0=root 1=priv 2=user 3=view
00087     define("EWIKI_AUTO_LOGIN", 1);      # [auth_query] on startup
00088 
00089     #-- allowed WikiPageNameCharacters
00090 
00091 #### BEGIN MOODLE CHANGES - to remove auto-camelcase linking.
00092 //    global $moodle_disable_camel_case;
00093 //    if ($moodle_disable_camel_case) {
00094 //        define("EWIKI_CHARS_L", "");
00095 //        define("EWIKI_CHARS_U", "");
00096 //    }
00097 //    else {
00098 //#### END MOODLE CHANGES
00099 //
00100 //    define("EWIKI_CHARS_L", "a-z_µ¤$\337-\377");
00101 //    define("EWIKI_CHARS_U", "A-Z0-9\300-\336");
00102 //
00103 //#### BEGIN MOODLE CHANGES
00104 //    }
00105 //#### END MOODLE CHANGES
00106 //
00107 //    define("EWIKI_CHARS", EWIKI_CHARS_L.EWIKI_CHARS_U);
00108 //
00109 // COMMENTED BY PIGUI BECOUSE OF MIGRATION
00110 
00111         #-- database
00112     define("EWIKI_DB_TABLE_NAME", "ewiki");      # MySQL / ADOdb
00113     define("EWIKI_DBFILES_DIRECTORY", "/tmp");   # see "db_flat_files.php"
00114     define("EWIKI_DBA", "/tmp/ewiki.dba");       # see "db_dba.php"
00115     define("EWIKI_DBQUERY_BUFFER", 512*1024);    # 512K
00116     define("EWIKI_INIT_PAGES", "./init-pages");  # for initialization
00117 
00118     define("EWIKI_DB_F_TEXT", 1<<0);
00119     define("EWIKI_DB_F_BINARY", 1<<1);
00120     define("EWIKI_DB_F_DISABLED", 1<<2);
00121     define("EWIKI_DB_F_HTML", 1<<3);
00122     define("EWIKI_DB_F_READONLY", 1<<4);
00123     define("EWIKI_DB_F_WRITEABLE", 1<<5);
00124     define("EWIKI_DB_F_APPENDONLY", 1<<6);  #nyi
00125     define("EWIKI_DB_F_SYSTEM", 1<<7);
00126     define("EWIKI_DB_F_PART", 1<<8);
00127     define("EWIKI_DB_F_TYPE", EWIKI_DB_F_TEXT | EWIKI_DB_F_BINARY | EWIKI_DB_F_DISABLED | EWIKI_DB_F_SYSTEM | EWIKI_DB_F_PART);
00128     define("EWIKI_DB_F_ACCESS", EWIKI_DB_F_READONLY | EWIKI_DB_F_WRITEABLE | EWIKI_DB_F_APPENDONLY);
00129     define("EWIKI_DB_F_COPYMASK", EWIKI_DB_F_TYPE | EWIKI_DB_F_ACCESS);
00130 
00131     define("EWIKI_DBFILES_NLR", '\\n');
00132     define("EWIKI_DBFILES_ENCODE", 0 || (DIRECTORY_SEPARATOR != "/"));
00133     define("EWIKI_DBFILES_GZLEVEL", "2");
00134 
00135     #-- internal
00136     define("EWIKI_ADDPARAMDELIM", (strstr(EWIKI_SCRIPT,"?") ? "&" : "?"));
00137 
00138     #-- binary content (images)
00139     define("EWIKI_SCRIPT_BINARY", /*"/binary.php?binary="*/  ltrim(strtok(" ".EWIKI_SCRIPT,"?"))."?".EWIKI_UP_BINARY."="  );
00140     define("EWIKI_CACHE_IMAGES", 1  &&!headers_sent());
00141     define("EWIKI_IMAGE_MAXSIZE", 64 *1024);
00142     define("EWIKI_IMAGE_MAXWIDTH", 3072);
00143     define("EWIKI_IMAGE_MAXHEIGHT", 2048);
00144     define("EWIKI_IMAGE_MAXALLOC", 1<<19);
00145     define("EWIKI_IMAGE_RESIZE", 1);
00146     define("EWIKI_IMAGE_ACCEPT", "image/jpeg,image/png,image/gif,application/x-shockwave-flash");
00147     define("EWIKI_IDF_INTERNAL", "internal://");
00148     define("EWIKI_ACCEPT_BINARY", 0);   # for arbitrary binary data files
00149 
00150     #-- misc
00151         define("EWIKI_TMP", $_SERVER["TEMP"] ? $_SERVER["TEMP"] : "/tmp");
00152     define("EWIKI_LOGLEVEL", -1);       # 0=error 1=warn 2=info 3=debug
00153     define("EWIKI_LOGFILE", "/tmp/ewiki.log");
00154 
00155     #-- plugins (tasks mapped to function names)
00156     $ewiki_plugins["database"][] = "ewiki_database_mysql";
00157     $ewiki_plugins["edit_preview"][] = "ewiki_page_edit_preview";
00158     $ewiki_plugins["render"][] = "ewiki_format";
00159     $ewiki_plugins["init"][-5] = "ewiki_localization";
00160     $ewiki_plugins["init"][-1] = "ewiki_binary";
00161         $ewiki_plugins["handler"][-105] = "ewiki_eventually_initialize";
00162         $ewiki_plugins["handler"][] = "ewiki_intermap_walking";
00163     $ewiki_plugins["view_append"][-1] = "ewiki_control_links";
00164         $ewiki_plugins["view_final"][-1] = "ewiki_add_title";
00165         $ewiki_plugins["page_final"][] = "ewiki_http_headers";
00166         $ewiki_plugins["page_final"][99115115] = "ewiki_page_css_container";
00167     $ewiki_plugins["edit_form_final"][] = "ewiki_page_edit_form_final_imgupload";
00168         $ewiki_plugins["format_block"]["pre"][] = "ewiki_format_pre";
00169         $ewiki_plugins["format_block"]["code"][] = "ewiki_format_pre";
00170         $ewiki_plugins["format_block"]["htm"][] = "ewiki_format_html";
00171         $ewiki_plugins["format_block"]["html"][] = "ewiki_format_html";
00172         $ewiki_plugins["format_block"]["comment"][] = "ewiki_format_comment";
00173 
00174 
00175     #-- internal pages
00176     $ewiki_plugins["page"][EWIKI_PAGE_NEWEST] = "ewiki_page_newest";
00177     $ewiki_plugins["page"][EWIKI_PAGE_SEARCH] = "ewiki_page_search";
00178     if (EWIKI_HIT_COUNTING) $ewiki_plugins["page"][EWIKI_PAGE_HITS] = "ewiki_page_hits";
00179     $ewiki_plugins["page"][EWIKI_PAGE_VERSIONS] = "ewiki_page_versions";
00180     $ewiki_plugins["page"][EWIKI_PAGE_UPDATES] = "ewiki_page_updates";
00181 
00182     #-- page actions
00183     $ewiki_plugins["action"]["edit"] = "ewiki_page_edit";
00184     $ewiki_plugins["action_always"]["links"] = "ewiki_page_links";
00185     $ewiki_plugins["action"]["info"] = "ewiki_page_info";
00186     $ewiki_plugins["action"]["view"] = "ewiki_page_view";
00187 
00188     #-- helper vars ---------------------------------------------------
00189     $ewiki_config["idf"]["url"] = array("http://", "mailto:", "internal://", "ftp://", "https://", "irc://", "telnet://", "news://", "chrome://", "file://", "gopher://", "httpz://");
00190     $ewiki_config["idf"]["img"] = array(".jpeg", ".png", ".jpg", ".gif", ".j2k");
00191     $ewiki_config["idf"]["obj"] = array(".swf", ".svg");
00192 
00193     #-- entitle actions
00194     $ewiki_config["action_links"]["view"] = @array_merge(array(
00195         "edit" => "EDITTHISPAGE",   # ewiki_t() is called on these
00196         "links" => "BACKLINKS",
00197         "info" => "PAGEHISTORY",
00198         "like" => "LIKEPAGES",
00199     ), @$ewiki_config["action_links"]["view"]
00200         );
00201     $ewiki_config["action_links"]["info"] = @array_merge(array(
00202         "view" => "browse",
00203         "edit" => "fetchback",
00204     ), @$ewiki_config["action_links"]["info"]
00205         );
00206 
00207         #-- variable configuration settings (go into '$ewiki_config')
00208         $ewiki_config_DEFAULTSTMP = array(
00209            "edit_thank_you" => 1,
00210            "edit_box_size" => "70x15",
00211            "print_title" => EWIKI_PRINT_TITLE,
00212            "split_title" => EWIKI_SPLIT_TITLE,
00213            "control_line" => EWIKI_CONTROL_LINE,
00214            "list_limit" => EWIKI_LIST_LIMIT,
00215            "script" => EWIKI_SCRIPT,
00216            "script_url" => (defined("EWIKI_SCRIPT_URL")?EWIKI_SCRIPT_URL:NULL),
00217            "script_binary" => EWIKI_SCRIPT_BINARY,
00218     #-- heart of the wiki -- don't try to read this! ;)
00219 
00220            "wiki_pre_scan_regex" => '/
00221         (?<![~!])
00222         ((?:(?:\w+:)*['.wiki_get_define('EWIKI_CHARS_U').']+['.wiki_get_define('EWIKI_CHARS_L').']+){2,}[\w\d]*)
00223         |\^([-'.wiki_get_define('EWIKI_CHARS_L').wiki_get_define('EWIKI_CHARS_U').']{3,})
00224         |\[ (?:"[^\]\"]+" | \s+ | [^:\]#]+\|)*  ([^\|\"\[\]\#]+)  (?:\s+ | "[^\]\"]+")* [\]\#]
00225         |(\w{3,9}:\/\/[^?#\s\[\]\'\"\)\,<]+)    /x',
00226 
00227            "wiki_link_regex" => "\007 [!~]?(
00228         \#?\[[^<>\[\]\n]+\] |
00229         \^[-".wiki_get_define('EWIKI_CHARS_U').wiki_get_define('EWIKI_CHARS_L')."]{3,} |
00230         \b([\w]{3,}:)*([".wiki_get_define('EWIKI_CHARS_U')."]+[".wiki_get_define('EWIKI_CHARS_L')."]+){2,}\#?[\w\d]* |
00231         ([a-z]{2,9}://|mailto:)[^\s\[\]\'\"\)\,<]+ |
00232         \w[-_.+\w]+@(\w[-_\w]+[.])+\w{2,}   ) \007x",
00233 
00234     #-- rendering ruleset
00235            "wm_indent" => '',
00236            "wm_table_defaults" => 'cellpadding="2" border="1" cellspacing="0"',
00237            "wm_whole_line" => array(),
00238            "htmlentities" => array(
00239         "&" => "&amp;",
00240         ">" => "&gt;",
00241         "<" => "&lt;",
00242            ),
00243            "wm_source" => array(
00244         "%%%" => "<br />",
00245         "\t" => "        ",
00246         "\n;:" => "\n      ",   # workaround, replaces the old ;:
00247            ),
00248            "wm_list" => array(
00249         "-" => array('ul type="square"', "", "li"),
00250         "*" => array('ul type="circle"', "", "li"),
00251         "#" => array("ol", "", "li"),
00252         ":" => array("dl", "dt", "dd"),
00253     #<out># ";" => array("dl", "dt", "dd"),
00254            ),
00255            "wm_style" => array(
00256         "'''''" => array("<b><i>", "</i></b>"),
00257         "'''" => array("<b>", "</b>"),
00258         "___" => array("<i><b>", "</b></i>"),
00259         "''" => array("<em>", "</em>"),
00260         "__" => array("<strong>", "</strong>"),
00261         "^^" => array("<sup>", "</sup>"),
00262         "==" => array("<tt>", "</tt>"),
00263     #<off># "***" => array("<b><i>", "</i></b>"),
00264     #<off># "###" => array("<big><b>", "</b></big>"),
00265         "**" => array("<b>", "</b>"),
00266         "##" => array("<big>", "</big>"),
00267         "µµ" => array("<small>", "</small>"),
00268            ),
00269            "wm_start_end" => array(
00270            ),
00271     #-- rendering plugins
00272            "format_block" => array(
00273         "html" => array("&lt;html&gt;", "&lt;/html&gt;", "html", 0x0000),
00274         "htm" => array("&lt;htm&gt;", "&lt;/htm&gt;", "html", 0x0003),
00275         "code" => array("&lt;code&gt;", "&lt;/code&gt;", false, 0x0000),
00276         "pre" => array("&lt;pre&gt;", "&lt;/pre&gt;", false, 0x003F),
00277         "comment" => array("\n&lt;!--", "--&gt;", false, 0x0030),
00278         #  "verbatim" => array("&lt;verbatim&gt;", "&lt;/verbatim&gt;", false, 0x0000),
00279            ),
00280            "format_params" => array(
00281         "scan_links" => 1,
00282         "html" => EWIKI_ALLOW_HTML,
00283         "mpi" => 1,
00284            ),
00285         );
00286         foreach ($ewiki_config_DEFAULTSTMP as $set => $val) {
00287            if (!isset($ewiki_config[$set])) {
00288               $ewiki_config[$set] = $val;
00289            }
00290            elseif (is_array($val)) foreach ($val as $vali=>$valv) {
00291               if (is_int($vali)) {
00292                  $ewiki_config[$set][] = $valv;
00293               }
00294               elseif (!isset($ewiki_config[$set][$vali])) {
00295                  $ewiki_config[$set][$vali] = $valv;
00296               }
00297            }
00298         }
00299         $ewiki_config_DEFAULTSTMP = $valv = $vali = $val = NULL;
00300 
00301     #-- init stuff, autostarted parts
00302     ksort($ewiki_plugins["init"]);
00303     if ($pf_a = $ewiki_plugins["init"]) foreach ($pf_a as $pf) {
00304            // Binary Handling starts here
00305            #### MOODLE CHANGE TO BE COMPATIBLE WITH PHP 4.1
00306            #if(headers_sent($file,$line)) {
00307            #  print_error('headersent');
00308            /*if(headers_sent()) {
00309              print_error('headersent');
00310            }*/
00311            $pf($GLOBALS);
00312         }
00313     unset($ewiki_plugins["init"]);
00314 
00315     #-- text  (never remove the "C" or "en" sections!)
00316         #
00317     $ewiki_t["C"] = @array_merge(@$ewiki_t["C"], array(
00318            "DATE" => "%a, %d %b %G %T %Z",
00319        "EDIT_TEXTAREA_RESIZE_JS" => '<a href="javascript:ewiki_enlarge()" style="text-decoration:none">+</a><script type="text/javascript"><!--'."\n".'function ewiki_enlarge() {var ta=document.getElementById("ewiki_content");ta.style.width=((ta.cols*=1.1)*10).toString()+"px";ta.style.height=((ta.rows*=1.1)*30).toString()+"px";}'."\n".'//--></script>',
00320         ));
00321         #
00322     $ewiki_t["en"] = @array_merge(@$ewiki_t["en"], array(
00323        "EDITTHISPAGE" => "EditThisPage",
00324            "APPENDTOPAGE" => "Add to",
00325        "BACKLINKS" => "BackLinks",
00326        "PAGESLINKINGTO" => "Pages linking to \$title",
00327        "PAGEHISTORY" => "PageInfo",
00328        "INFOABOUTPAGE" => "Information about page",
00329        "LIKEPAGES" => "Pages like this",
00330        "NEWESTPAGES" => "Newest Pages",
00331        "LASTCHANGED" => "last changed on %c",
00332        "DOESNOTEXIST" => "This page does not yet exist, please click on EditThisPage if you'd like to create it.",
00333        "DISABLEDPAGE" => "This page is currently not available.",
00334        "ERRVERSIONSAVE" => "Sorry, while you edited this page someone else
00335         did already save a changed version. Please go back to the
00336         previous screen and copy your changes to your computers
00337         clipboard to insert it again after you reload the edit
00338         screen.",
00339        "ERRORSAVING" => "An error occoured while saving your changes. Please try again.",
00340        "THANKSFORCONTRIBUTION" => "Thank you for your contribution!",
00341        "CANNOTCHANGEPAGE" => "This page cannot be changed.",
00342        "OLDVERCOMEBACK" => "Make this old version come back to replace the current one",
00343        "PREVIEW" => "Preview",
00344        "SAVE" => "Save",
00345        "CANCEL_EDIT" => "CancelEditing",
00346        "UPLOAD_PICTURE_BUTTON" => "upload picture &gt;&gt;&gt;",
00347        "EDIT_FORM_1" => "<a href=\"".EWIKI_SCRIPT."GoodStyle\">GoodStyle</a> is to
00348         write what comes to your mind. Don't care about how it
00349         looks too much now. You can add <a href=\"".EWIKI_SCRIPT."WikiMarkup\">WikiMarkup</a>
00350         also later if you think it is necessary.<br />",
00351        "EDIT_FORM_2" => "<br />Please do not write things, which may make other
00352         people angry. And please keep in mind that you are not all that
00353         anonymous in the internet (find out more about your computers
00354         '<a href=\"http://google.com/search?q=my+computers+IP+address\">IP address</a>' at Google).",
00355        "BIN_IMGTOOLARGE" => "Image file is too large!",
00356        "BIN_NOIMG" => "This is no image file (inacceptable file format)!",
00357        "FORBIDDEN" => "You are not authorized to access this page.",
00358     ));
00359         #
00360         $ewiki_t["es"] = @array_merge(@$ewiki_t["es"], array(
00361            "EDITTHISPAGE" => "EditarEstaPágina",
00362            "BACKLINKS" => "EnlacesInversos",
00363            "PAGESLINKINGTO" => "Páginas enlazando \$title",
00364            "PAGEHISTORY" => "InfoPágina",
00365            "INFOABOUTPAGE" => "Información sobre la página",
00366            "LIKEPAGES" => "Páginas como esta",
00367            "NEWESTPAGES" => "Páginas más nuevas",
00368            "LASTCHANGED" => "última modificación %d/%m/%Y a las %H:%M",
00369            "DOESNOTEXIST" => "Esta página aún no existe, por favor eliga EditarEstaPágina si desea crearla.",
00370            "DISABLEDPAGE" => "Esta página no está disponible en este momento.",
00371            "ERRVERSIONSAVE" => "Disculpe, mientras editaba esta página alguién más
00372         salvó una versión modificada. Por favor regrese a
00373         a la pantalla anterior y copie sus cambios a su computador
00374         para insertalos nuevamente después de que cargue
00375         la pantalla de edición.",
00376            "ERRORSAVING" => "Ocurrió un error mientras se salvavan sus cambios. Por favor intente de nuevo.",
00377            "THANKSFORCONTRIBUTION" => "Gracias por su contribución!",
00378            "CANNOTCHANGEPAGE" => "Esta página no puede ser modificada.",
00379            "OLDVERCOMEBACK" => "Hacer que esta versión antigua regrese a remplazar la actual",
00380            "PREVIEW" => "Previsualizar",
00381            "SAVE" => "Salvar",
00382            "CANCEL_EDIT" => "CancelarEdición",
00383            "UPLOAD_PICTURE_BUTTON" => "subir gráfica &gt;&gt;&gt;",
00384            "EDIT_FORM_1" => "<a href=\"".EWIKI_SCRIPT."BuenEstilo\">BuenEstilo</a> es
00385         escribir lo que viene a su mente. No se preocupe mucho
00386         por la apariencia. También puede agregar <a href=\"".EWIKI_SCRIPT."ReglasDeMarcadoWiki\">ReglasDeMarcadoWiki</a>
00387         más adelante si piensa que es necesario.<br />",
00388            "EDIT_FORM_2" => "<br />Por favor no escriba cosas, que puedan
00389         enfadar a otras personas. Y por favor tenga en mente que
00390         usted no es del todo anónimo en Internet
00391         (encuentre más sobre
00392         '<a href=\"http://google.com/search?q=my+computers+IP+address\">IP address</a>' de su computador con Google).",
00393            "BIN_IMGTOOLARGE" => "¡La gráfica es demasiado grande!",
00394            "BIN_NOIMG" => "¡No es un archivo con una gráfica (formato de archivo inaceptable)!",
00395            "FORBIDDEN" => "No está autorizado para acceder a esta página.",
00396         ));
00397         #
00398     $ewiki_t["de"] = @array_merge(@$ewiki_t["de"], array(
00399        "EDITTHISPAGE" => "DieseSeiteÄndern",
00400            "APPENDTOPAGE" => "Ergänze",
00401        "BACKLINKS" => "ZurückLinks",
00402        "PAGESLINKINGTO" => "Verweise zur Seite \$title",
00403        "PAGEHISTORY" => "SeitenInfo",
00404        "INFOABOUTPAGE" => "Informationen über Seite",
00405        "LIKEPAGES" => "Ähnliche Seiten",
00406        "NEWESTPAGES" => "Neueste Seiten",
00407        "LASTCHANGED" => "zuletzt geändert am %d.%m.%Y um %H:%M",
00408        "DISABLEDPAGE" => "Diese Seite kann momentan nicht angezeigt werden.",
00409        "ERRVERSIONSAVE" => "Entschuldige, aber während Du an der Seite
00410         gearbeitet hast, hat bereits jemand anders eine geänderte
00411         Fassung gespeichert. Damit nichts verloren geht, browse bitte
00412         zurück und speichere Deine Änderungen in der Zwischenablage
00413         (Bearbeiten->Kopieren) um sie dann wieder an der richtigen
00414         Stelle einzufügen, nachdem du die EditBoxSeite nocheinmal
00415         geladen hast.<br />
00416         Vielen Dank für Deine Mühe.",
00417        "ERRORSAVING" => "Beim Abspeichern ist ein Fehler aufgetreten. Bitte versuche es erneut.",
00418        "THANKSFORCONTRIBUTION" => "Vielen Dank für Deinen Beitrag!",
00419        "CANNOTCHANGEPAGE" => "Diese Seite kann nicht geändert werden.",
00420        "OLDVERCOMEBACK" => "Diese alte Version der Seite wieder zur Aktuellen machen",
00421        "PREVIEW" => "Vorschau",
00422        "SAVE" => "Speichern",
00423        "CANCEL_EDIT" => "ÄnderungenVerwerfen",
00424        "UPLOAD_PICTURE_BUTTON" => "Bild hochladen &gt;&gt;&gt;",
00425        "EDIT_FORM_1" => "<a href=\"".EWIKI_SCRIPT."GuterStil\">GuterStil</a> ist es,
00426         ganz einfach das zu schreiben, was einem gerade in den
00427         Sinn kommt. Du solltest dich jetzt noch nicht so sehr
00428         darum kümmern, wie die Seite aussieht. Du kannst später
00429         immernoch zurückkommen und den Text mit <a href=\"".EWIKI_SCRIPT."FormatierungsRegeln\">WikiTextFormatierungsRegeln</a>
00430         aufputschen.<br />",
00431        "EDIT_FORM_2" => "<br />Bitte schreib keine Dinge, die andere Leute
00432         verärgern könnten. Und bedenke auch, daß es schnell auf
00433         dich zurückfallen kann wenn du verschiedene andere Dinge sagst (mehr Informationen zur
00434         '<a href=\"http://google.de/search?q=computer+IP+adresse\">IP Adresse</a>'
00435         deines Computers findest du bei Google).",
00436     ));
00437 
00438     #-- InterWiki:Links
00439     $ewiki_config["interwiki"] = @array_merge(
00440     @$ewiki_config["interwiki"],
00441     array(
00442            "javascript" => "",  # this actually protects from javascript: links
00443            "url" => "",
00444 #          "self" => "this",
00445            "this" => EWIKI_SCRIPT,  # better was absolute _URL to ewiki wrapper
00446            "jump" => ""
00447     ));
00448     // BEGIN MOODLE CHANGES - disable interwiki liks by default
00449     // can be enabled with $CFG->wiki_allow_interwiki = true . MDL-19460
00450     global $CFG;
00451     if (!empty($CFG->wiki_allow_interwiki)) {
00452        $ewiki_config["interwiki"] = @array_merge(
00453            $ewiki_config["interwiki"],
00454            array (
00455                "ErfurtWiki" => "http://erfurtwiki.sourceforge.net/?id=",
00456                "InterWiki" => "InterWikiSearch",
00457                "InterWikiSearch" => "http://sunir.org/apps/meta.pl?",
00458                "Wiki" => "WardsWiki",
00459                "WardsWiki" => "http://www.c2.com/cgi/wiki?",
00460                "WikiFind" => "http://c2.com/cgi/wiki?FindPage&amp;value=",
00461                "WikiPedia" => "http://www.wikipedia.com/wiki.cgi?",
00462                "MeatBall" => "MeatballWiki",
00463                "MeatballWiki" => "http://www.usemod.com/cgi-bin/mb.pl?",
00464                "UseMod"       => "http://www.usemod.com/cgi-bin/wiki.pl?",
00465                "PhpWiki" => "http://phpwiki.sourceforge.net/phpwiki/index.php3?",
00466                "LinuxWiki" => "http://linuxwiki.de/",
00467                "OpenWiki" => "http://openwiki.com/?",
00468                "Tavi" => "http://andstuff.org/tavi/",
00469                "TWiki" => "http://twiki.sourceforge.net/cgi-bin/view/",
00470                "MoinMoin" => "http://www.purl.net/wiki/moin/",
00471                "Google" => "http://google.com/search?q=",
00472                "ISBN" => "http://www.amazon.com/exec/obidos/ISBN=",
00473                "icq" => "http://www.icq.com/"
00474     ));
00475     }
00476     // END MOODLE CHANGES
00477 
00478 
00479 
00480 
00481 
00482 #-------------------------------------------------------------------- main ---
00483 
00484 /*  this is the main function, which you should preferrably call to
00485     integrate the ewiki into your web site; it chains to most other
00486     parts and plugins (including the edit box);
00487     if you do not supply the requested pages "$id" we will fetch it
00488     from the pre-defined possible URL parameters.
00489 */
00490 function ewiki_page($id=false) {
00491 
00492    global $ewiki_links, $ewiki_plugins, $ewiki_ring, $ewiki_t, $ewiki_errmsg;
00493    #-- output var
00494    $o = "";
00495 
00496    #-- selected page
00497     $action  = optional_param('action', EWIKI_DEFAULT_ACTION);
00498     $content = optional_param('content', false);
00499     $version = optional_param('version', false);
00500 
00501    if (!strlen($id)) {
00502       $id = ewiki_id();
00503    }
00504    $id = format_string($id,true);
00505    #-- page action
00506    if ($delim = strpos($id, EWIKI_ACTION_SEP_CHAR)) {
00507       $action = substr($id, 0, $delim);
00508       $id = substr($id, $delim + 1);
00509    }
00510    elseif (!EWIKI_USE_ACTION_PARAM) {
00511       $action = EWIKI_DEFAULT_ACTION;
00512    }
00513    $GLOBALS["ewiki_id"] = $id;
00514    $GLOBALS["ewiki_title"] = ewiki_split_title($id);
00515    $GLOBALS["ewiki_action"] = $action;
00516 
00517    #-- fetch from db
00518    $dquery = array(
00519       "id" => $id
00520    );
00521    if (!$content && ($dquery["version"] = $version)) {
00522       $dquery["forced_version"] = $dquery["version"];
00523    }
00524    $data = @array_merge($dquery, ewiki_database("GET", $dquery));
00525 
00526    #-- stop here if page is not marked as _TEXT,
00527    #   perform authentication then, and let only administrators proceed
00528    if (!empty($data["flags"]) && (($data["flags"] & EWIKI_DB_F_TYPE) != EWIKI_DB_F_TEXT)) {
00529       if (($data["flags"] & EWIKI_DB_F_BINARY) && ($pf = $ewiki_plugins["handler_binary"][0])) {
00530          return($pf($id, $data, $action)); //_BINARY entries handled separately
00531       }
00532       elseif (!EWIKI_PROTECTED_MODE || !ewiki_auth($id, $data, $action, 0, 1) && ($ewiki_ring!=0)) {
00533          return(ewiki_t("DISABLEDPAGE"));
00534       }
00535    }
00536 
00537    #-- pre-check if actions exist
00538    $pf_page = ewiki_array($ewiki_plugins["page"], $id);
00539 
00540    #-- edit <form> for non-existent pages
00541    if (($action==EWIKI_DEFAULT_ACTION) && empty($data["content"]) && empty($pf_page)) {
00542       if (EWIKI_AUTO_EDIT) {
00543          $action = "edit";
00544       }
00545       else {
00546          $data["content"] = ewiki_t("DOESNOTEXIST");
00547       }
00548    }
00549    #-- more initialization
00550    if ($pf_a = @$ewiki_plugins["page_init"]) {
00551       ksort($pf_a);
00552       foreach ($pf_a as $pf) {
00553          $o .= $pf($id, $data, $action);
00554       }
00555       unset($ewiki_plugins["page_init"]);
00556    }
00557    $pf_page = ewiki_array($ewiki_plugins["page"], $id);
00558 
00559    #-- require auth
00560    if (EWIKI_PROTECTED_MODE) {
00561       if (!ewiki_auth($id, $data, $action, $ring=false, $force=EWIKI_AUTO_LOGIN)) {
00562          return($o.=$ewiki_errmsg);
00563       }
00564    }
00565 
00566    #-- handlers
00567    $handler_o = "";
00568    if ($pf_a = @$ewiki_plugins["handler"]) {
00569       ksort($pf_a);
00570       foreach ($pf_a as $pf) {
00571          if ($handler_o = $pf($id, $data, $action)) { break; }
00572    }  }
00573 
00574    #-- finished by handler
00575    if ($handler_o) {
00576       $o .= $handler_o;
00577    }
00578    #-- actions that also work for static and internal pages
00579    elseif (($pf = @$ewiki_plugins["action_always"][$action]) && function_exists($pf)) {
00580       $o .= $pf($id, $data, $action);
00581    }
00582    #-- internal pages
00583    elseif ($pf_page && function_exists($pf_page)) {
00584       $o .= $pf_page($id, $data, $action);
00585    }
00586    #-- page actions
00587    else {
00588       $pf = @$ewiki_plugins["action"][$action];
00589 
00590       #-- fallback to "view" action
00591       if (empty($pf) || !function_exists($pf)) {
00592 
00593          $pf = "ewiki_page_view";
00594          $action = "view";     // we could also allow different (this is a
00595          // catch-all) view variants, but this would lead to some problems
00596       }
00597 
00598       $o .= $pf($id, $data, $action);
00599    }
00600 
00601    #-- error instead of page?
00602    if (empty($o) && $ewiki_errmsg) {
00603       $o = $ewiki_errmsg;
00604    }
00605 
00606    #-- html post processing
00607    if ($pf_a = $ewiki_plugins["page_final"]) {
00608       ksort($pf_a);
00609       foreach ($pf_a as $pf) {
00610          if ($action == 'edit' and $pf == 'ewiki_html_tag_balancer') {
00611             continue; // balancer breaks htmlarea buttons
00612          }
00613          $pf($o, $id, $data, $action);
00614       }
00615    }
00616 
00617    (EWIKI_ESCAPE_AT) && ($o = str_replace("@", "&#x40;", $o));
00618 
00619    return($o);
00620 }
00621 
00622 
00623 
00624 #-- HTTP meta headers
00625 function ewiki_http_headers(&$o, $id, &$data, $action) {
00626    global $ewiki_t;
00627    if (EWIKI_HTTP_HEADERS && !headers_sent()) {
00628       if (!empty($data)) {
00629          if ($uu = @$data["id"]) @header('Content-Disposition: inline; filename="' . urlencode($uu) . '.html"');
00630          if ($uu = @$data["version"]) @header('Content-Version: ' . $uu);
00631          if ($uu = @$data["lastmodified"]) @header('Last-Modified: ' . gmstrftime($ewiki_t["C"]["DATE"], $uu));
00632       }
00633       if (EWIKI_NO_CACHE) {
00634          header('Expires: ' . gmstrftime($ewiki_t["C"]["DATE"], UNIX_MILLENNIUM));
00635          header('Pragma: no-cache');
00636          header('Cache-Control: no-cache, private, must-revalidate');
00637          # change to "C-C: cache, must-revalidate" ??
00638          # private only for authenticated users / _PROT_MODE
00639       }
00640       #-- ETag
00641       if ($data["version"] && ($etag=ewiki_etag($data)) || ($etag=md5($o))) {
00642          $weak = "W/" . urlencode($id) . "." . $data["version"];
00643          header("ETag: \"$etag\"");     ###, \"$weak\"");
00644       }
00645    }
00646 }
00647 function ewiki_etag(&$data) {
00648    return(  urlencode($data["id"]) . ":" . dechex($data["version"]) . ":ewiki:" .
00649             dechex(crc32($data["content"]) & 0x7FFFBFFF)  );
00650 }
00651 
00652 
00653 
00654 #-- encloses whole page output with a descriptive <div>
00655 function ewiki_page_css_container(&$o, &$id, &$data, &$action) {
00656    $o = "<div class=\"wiki $action "
00657       . strtr($id, ' ./ --_!"§$%&()=?²³{[]}`+#*;:,<>| @µöäüÖÄÜߤ^°«»\'\\',
00658                    '-  -----------------------------------------------')
00659       . "\">\n"
00660       . $o . "\n</div>\n";
00661 }
00662 
00663 
00664 
00665 function ewiki_split_title ($id='', $split=EWIKI_SPLIT_TITLE, $entities=1) {
00666    strlen($id) or ($id = $GLOBALS["ewiki_id"]);
00667    if ($split) {
00668       $id = preg_replace("/([".wiki_get_define('EWIKI_CHARS_L')."])([".wiki_get_define('EWIKI_CHARS_U')."]+)/", "$1 $2", $id);
00669    }
00670    return($entities ? s($id) : $id);
00671 }
00672 
00673 
00674 
00675 function ewiki_add_title(&$html, $id, &$data, $action, $go_action="links") {
00676    $html = ewiki_make_title($id, '', 1, $action, $go_action) . $html;
00677 }
00678 
00679 
00680 function ewiki_make_title($id='', $title='', $class=3, $action="view", $go_action="links", $may_split=1) {
00681 
00682    global $ewiki_config, $ewiki_plugins, $ewiki_title, $ewiki_id;
00683 
00684    #-- advanced handler
00685    if ($pf = @$ewiki_plugins["make_title"][0]) {
00686       return($pf($title, $class, $action, $go_action, $may_split));
00687    }
00688    #-- disabled
00689    elseif (!$ewiki_config["print_title"]) {
00690       return("");
00691    }
00692 
00693    #-- get id
00694    if (empty($id)) {
00695       $id = $ewiki_id;
00696    }
00697 
00698    #-- get title
00699    if (!strlen($title)) {
00700       $title = $ewiki_title;  // already in &html; format
00701    }
00702    elseif ($ewiki_config["split_title"] && $may_split) {
00703       $title = ewiki_split_title($title, $ewiki_config["split_title"], 0&($title!=$ewiki_title));
00704    }
00705    else {
00706       $title = s($title);
00707    }
00708 
00709    #-- title mangling
00710    if ($pf_a = @$ewiki_plugins["title_transform"]) {
00711       foreach ($pf_a as $pf) { $pf($id, $title, $go_action); }
00712    }
00713 
00714    #-- clickable link or simple headline
00715    if ($class <= $ewiki_config["print_title"]) {
00716       if ($uu = @$ewiki_config["link_title_action"][$action]) {
00717          $go_action = $uu;
00718       }
00719       if ($uu = @$ewiki_config["link_title_url"]) {
00720          $href = $uu;
00721          unset($ewiki_config["link_title_url"]);
00722       }
00723       else {
00724          $href = ewiki_script($go_action, $id);
00725       }
00726       $o = '<a href="' . $href . '">' . ($title) . '</a>';
00727    }
00728    else {
00729       $o = $title;
00730    }
00731 
00732    return('<h2 class="page title">' . $o . '</h2>'."\n");
00733 }
00734 
00735 
00736 
00737 
00738 function ewiki_page_view($id, &$data, $action, $all=1) {
00739 
00740    global $ewiki_plugins, $ewiki_config;
00741    $o = "";
00742 
00743    $thanks = optional_param('thankyou', '', PARAM_CLEAN);
00744 
00745    #-- render requested wiki page  <-- goal !!!
00746    $render_args = array(
00747       "scan_links" => 1,
00748       "html" => (EWIKI_ALLOW_HTML||(@$data["flags"]&EWIKI_DB_F_HTML)),
00749    );
00750    $o .= $ewiki_plugins["render"][0] ($data["content"], $render_args);
00751    if (!$all) {
00752       return($o);
00753    }
00754    #### MOODLE CHANGE
00755 
00756    global $moodle_format;   // from wiki/view.php
00757    $o = format_text($o, $moodle_format);
00758    $o.= "<br /><br />";
00759 
00760    #-- control line + other per-page info stuff
00761    if ($pf_a = $ewiki_plugins["view_append"]) {
00762       ksort($pf_a);
00763       foreach ($pf_a as $n => $pf) { $o .= $pf($id, $data, $action); }
00764    }
00765    if ($pf_a = $ewiki_plugins["view_final"]) {
00766       ksort($pf_a);
00767       foreach ($pf_a as $n => $pf) { $pf($o, $id, $data, $action); }
00768    }
00769 
00770    if (!empty($thanks) && $ewiki_config["edit_thank_you"]) {
00771       $o = ewiki_t("THANKSFORCONTRIBUTION") . $o;
00772    }
00773 
00774 
00775    if (EWIKI_HIT_COUNTING) {
00776       ewiki_database("HIT", $data);
00777    }
00778 
00779    return($o);
00780 }
00781 
00782 
00783 
00784 
00785 #-------------------------------------------------------------------- util ---
00786 
00787 
00788 /*  retrieves "$id/$action" string from URL / QueryString / PathInfo,
00789     change this in conjunction with ewiki_script() to customize your URLs
00790     further whenever desired
00791 */
00792 function ewiki_id() {
00793    ($id = optional_param("id", '', PARAM_CLEAN)) or
00794    ($id = optional_param("name", '', PARAM_CLEAN)) or
00795    ($id = optional_param("page", '', PARAM_CLEAN)) or
00796    ($id = optional_param("file", '', PARAM_CLEAN)) or
00797    (EWIKI_USE_PATH_INFO) and ($id = ltrim(@$_SERVER["PATH_INFO"], "/")) or
00798    (!isset($_REQUEST["id"])) and ($id = trim(strtok($_SERVER["QUERY_STRING"], "&")));
00799    if (!strlen($id) || ($id=="id=")) {
00800       $id = EWIKI_PAGE_INDEX;
00801    }
00802    (EWIKI_URLDECODE) && ($id = urldecode($id));
00803    return($id);
00804 }
00805 
00806 
00807 
00808 
00809 /*  replaces EWIKI_SCRIPT, works more sophisticated, and
00810     bypasses various design flaws
00811     - if only the first parameter is used (old style), it can contain
00812       a complete "action/WikiPage" - but this is ambigutious
00813     - else $asid is the action, and $id contains the WikiPageName
00814     - $ewiki_config["script"] will now be used in favour of the constant
00815     - needs more work on _BINARY, should be a separate function
00816 */
00817 ## MOODLE-CHANGE: $asid="", Knows the devil why....
00818 function ewiki_script($asid="", $id=false, $params="", $bin=0, $html=1, $script=NULL) {
00819    global $ewiki_config, $ewiki_plugins;
00820 
00821    #-- get base script url from config vars
00822    if (empty($script)) {
00823       $script = &$ewiki_config[!$bin?"script":"script_binary"];
00824    }
00825 
00826 
00827    #-- separate $action and $id for old style requests
00828    if ($id === false) {
00829       if (strpos($asid, EWIKI_ACTION_SEP_CHAR) !== false) {
00830          $asid = strtok($asid, EWIKI_ACTION_SEP_CHAR);
00831          $id = strtok("\000");
00832       }
00833       else {
00834          $id = $asid;
00835          $asid = "";
00836       }
00837    }
00838 
00839    #-- prepare params
00840    if (is_array($params)) {
00841       $uu = $params;
00842       $params = "";
00843       if ($uu) foreach ($uu as $k=>$v) {
00844          $params .= (strlen($params)?"&":"") . rawurlencode($k) . "=" . rawurlencode($v);
00845       }
00846    }
00847    #-- action= parameter
00848    if (EWIKI_USE_ACTION_PARAM >= 2) {
00849       $params = "action=$asid" . (strlen($params)?"&":"") . $params;
00850       $asid = "";
00851    }
00852 
00853    #-- workaround slashes in $id
00854    if (empty($asid) && (strpos($id, EWIKI_ACTION_SEP_CHAR) !== false) && !$bin) {
00855       $asid = "view";
00856    }
00857    /*paranoia*/ $asid = trim($asid, EWIKI_ACTION_SEP_CHAR);
00858 
00859    #-- make url
00860    if (EWIKI_URLENCODE) {
00861       $id = urlencode($id);
00862       $asid = urlencode($asid);
00863    }
00864    else {
00865       # only urlencode &, %, ? for example
00866    }
00867    $url = $script;
00868    if ($asid) {
00869       $id = $asid . EWIKI_ACTION_SEP_CHAR . $id;  #= "action/PageName"
00870    }
00871    if (strpos($url, "%s") !== false) {
00872       $url = str_replace("%s", $id, $url);
00873    }
00874    else {
00875       $url .= $id;
00876    }
00877 
00878    #-- add url params
00879    if (strlen($params)) {
00880       $url .= (strpos($url,"?")!==false ? "&":"?") . $params;
00881    }
00882    #-- fin
00883    if ($html) {
00884       //Don't replace & if it's part of encoded character (bug 2209)
00885       $url = preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,5};)/","&amp;", $url);
00886    } else {
00887       //This is going to be used in some header or meta redirect, so It cannot use &amp; (bug 2620)
00888       $url = preg_replace('/&amp;/', '&', $url);
00889    }
00890    return($url);
00891 }
00892 
00893 
00894 /*  this ewiki_script() wrapper is used to generate URLs to binary
00895     content in the ewiki database
00896 */
00897 function ewiki_script_binary($asid, $id=false, $params=array(), $upload=0) {
00898 
00899    $upload |= is_string($params) && strlen($params) || count($params);
00900 
00901    #-- generate URL directly to the plainly saved data file,
00902    #   see also plugins/binary_store
00903 
00904    if (defined("EWIKI_DB_STORE_URL") && !$upload) {
00905       $url = EWIKI_DB_STORE_URL . rawurlencode($id);
00906    }
00907 
00908    #-- else get standard URL (thru ewiki.php) from ewiki_script()
00909    else {
00910       $url = ewiki_script($asid, $id, $params, "_BINARY=1");
00911    }
00912 
00913    return($url);
00914 }
00915 
00916 
00917 /*  this function returns the absolute ewiki_script url, if EWIKI_SCRIPT_URL
00918     is set, else it guesses the value
00919 */
00920 function ewiki_script_url() {
00921 
00922    global $ewiki_action, $ewiki_id, $ewiki_config;
00923 
00924    $scr_template = $ewiki_config["script"];
00925    $scr_current = ewiki_script($ewiki_action, $ewiki_id);
00926    $req_uri = $_SERVER["REQUEST_URI"];
00927 
00928    if ($url = $ewiki_config["script_url"]) {
00929       return($url);
00930    }
00931    elseif (strpos($req_uri, $scr_current) !== false) {
00932       $url = str_replace($req_uri, $scr_current, $scr_template);
00933    }
00934    elseif (strpos($req_uri, "?") && (strpos($scr_template, "?") !== false)) {
00935       $url = substr($req_uri, 0, strpos($req_uri, "?"))
00936            . substr($scr_template, strpos($scr_template, "?"));
00937    }
00938    elseif (strpos($req_uri, $sn = $_SERVER["SCRIPT_NAME"])) {
00939       $url = $sn . "?id=";
00940    }
00941    else {
00942       return(NULL);   #-- could not guess it
00943    }
00944 
00945    #$url = "http://" . $_SERVER["SERVER_NAME"] . $url;
00946    return($url);
00947 }
00948 
00949 
00950 
00951 
00952 #------------------------------------------------------------ page plugins ---
00953 
00954 
00955 
00956 function ewiki_page_links($id, &$data, $action) {
00957    $o = ewiki_make_title($id, ewiki_t("PAGESLINKINGTO", array("title"=>$id)), 1, $action, "", "_MAY_SPLIT=1");
00958    if ($pages = ewiki_get_backlinks($id)) {
00959       $o .= ewiki_list_pages($pages);
00960    } else {
00961       $o .= ewiki_t("This page isn't linked from anywhere else.");
00962    }
00963    return($o);
00964 }
00965 
00966 function ewiki_get_backlinks($id) {
00967    $result = ewiki_database("SEARCH", array("refs" => $id));
00968    $pages = array();
00969    while ($row = $result->get(0, 0x0020)) {
00970       if ( strpos($row["refs"], "\n$id\n") !== false) {
00971          $pages[] = $row["id"];
00972       }
00973    }
00974    return($pages);
00975 }
00976 
00977 function ewiki_get_links($id) {
00978    if ($data = ewiki_database("GET", array("id"=>$id))) {
00979       $refs = explode("\n", trim($data["refs"]));
00980       $r = array();
00981       foreach (ewiki_database("FIND", $refs) as $id=>$exists) {
00982          if ($exists) {
00983             $r[] = $id;
00984          }
00985       }
00986       return($r);
00987    }
00988 }
00989 
00990 
00991 function ewiki_list_pages($pages=array(), $limit=EWIKI_LIST_LIMIT,
00992                           $value_as_title=0, $pf_list=false)
00993 {
00994    global $ewiki_plugins;
00995    $o = "";
00996 
00997    $is_num = !empty($pages[0]);
00998    $lines = array();
00999    $n = 0;
01000 
01001    foreach ($pages as $id=>$add_text) {
01002 
01003       $title = $id;
01004       $params = "";
01005 
01006       if (is_array($add_text)) {
01007          list($id, $params, $title, $add_text) = $add_text;
01008       }
01009       elseif ($is_num) {
01010          $id = $title = $add_text;
01011          $add_text = "";
01012       }
01013       elseif ($value_as_title) {
01014          $title = $add_text;
01015          $add_text = "";
01016       }
01017 
01018       $lines[] = '<a href="' . ewiki_script("", $id, $params) . '">' . s($title) . '</a> ' . $add_text;
01019 
01020       if (($limit > 0)  &&  ($n++ >= $limit)) {
01021          break;
01022       }
01023    }
01024 
01025    if ($pf_a = @$ewiki_plugins["list_transform"])
01026    foreach ($pf_a as $pf_transform) {
01027       $pf_transform($lines);
01028    }
01029 
01030    if (($pf_list) || ($pf_list = @$ewiki_plugins["list_pages"][0])) {
01031       $o = $pf_list($lines);
01032    }
01033    elseif($lines) {
01034       $o = "&middot; " . implode("<br />\n&middot; ", $lines) . "<br />\n";
01035    }
01036 
01037    return($o);
01038 }
01039 
01040 
01041 
01042 
01043 function ewiki_page_ordered_list($orderby="created", $asc=0, $print, $title) {
01044 
01045    $o = ewiki_make_title("", $title, 2, ".list", "links", 0);
01046 
01047    $sorted = array();
01048    $result = ewiki_database("GETALL", array($orderby));
01049 
01050    while ($row = $result->get()) {
01051       $row = ewiki_database("GET", array(
01052          "id" => $row["id"],
01053          ($asc >= 0 ? "version" : "uu") => 1  // version 1 is most accurate for {hits}
01054       ));
01055       #-- text page?
01056       if (EWIKI_DB_F_TEXT == ($row["flags"] & EWIKI_DB_F_TYPE)) {
01057          #-- viewing allowed?
01058          if (!EWIKI_PROTECTED_MODE || !EWIKI_PROTECTED_MODE_HIDING || ewiki_auth($row["id"], $row, "view")) {
01059             $sorted[$row["id"]] = $row[$orderby];
01060          }
01061       }
01062    }
01063 
01064    if ($asc != 0) { arsort($sorted); }
01065    else { asort($sorted); }
01066 
01067    foreach ($sorted as $name => $value) {
01068       if (empty($value)) { $value = "0"; }
01069    ##### BEGIN MOODLE ADDITION #####
01070       #$sorted[$name] = strftime(str_replace('%n', $value, $print), $value);
01071       if($print=="LASTCHANGED") {
01072         $value=strftime("%c",$value);
01073       }
01074       $sorted[$name] = get_string(strtolower($print),"wiki",$value);
01075    ##### BEGIN MOODLE ADDITION #####
01076    }
01077    $o .= ewiki_list_pages($sorted);
01078 
01079    return($o);
01080 }
01081 
01082 
01083 
01084 function ewiki_page_newest($id=0, $data=0) {
01085    return( ewiki_page_ordered_list("created", 1, "LASTCHANGED", ewiki_t(EWIKI_PAGE_NEWEST)) );
01086 }
01087 
01088 function ewiki_page_updates($id=0, $data=0) {
01089    return( ewiki_page_ordered_list("lastmodified", -1, "LASTCHANGED", ewiki_t(EWIKI_PAGE_UPDATES)) );
01090 }
01091 
01092 function ewiki_page_hits($id=0, $data=0) {
01093    ##### BEGIN MOODLE ADDITION #####
01094    return( ewiki_page_ordered_list("hits", 1, "hits", ewiki_t(EWIKI_PAGE_HITS)) );
01095 }
01096 
01097 function ewiki_page_versions($id=0, $data=0) {
01098    return( ewiki_page_ordered_list("version", -1, "changes", ewiki_t(EWIKI_PAGE_VERSIONS)) );
01099    ##### END MOODLE ADDITION #####
01100 }
01101 
01102 
01103 
01104 
01105 
01106 
01107 
01108 function ewiki_page_search($id, &$data, $action) {
01109 
01110    global $CFG;
01111 
01112    $q = optional_param('q', '', PARAM_CLEAN);
01113    $o = ewiki_make_title($id, $id, 2, $action);
01114 
01115    if ($q == '') {
01116 
01117       $o .= '<form action="' . ewiki_script("", $id) . '" method="post">';
01118       $o .= '<fieldset class="invisiblefieldset">';
01119       $o .= '<input name="q" size="30" /><br /><br />';
01120       $o .= '<input type="submit" value="'.$id.'" />';
01121       $o .= '</fieldset>';
01122       $o .= '</form>';
01123    }
01124    else {
01125       $found = array();
01126 
01127       if ($CFG->unicodedb) {
01128           $q = preg_replace('/\s*[\W]+\s*/u', ' ', $q);
01129       } else {
01130           $q = preg_replace('/\s*[^\w]+\s*/', ' ', $q);
01131       }
01132       foreach (explode(" ", $q) as $search) {
01133 
01134          if (empty($search)) { continue; }
01135 
01136          $result = ewiki_database("SEARCH", array("content" => $search));
01137 
01138          while ($row = $result->get()) {
01139 
01140             #-- show this entry in page listings?
01141             if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($row["id"], $row, "view")) {
01142                continue;
01143             }
01144 
01145             $found[] = $row["id"];
01146          }
01147       }
01148 
01149       $o .= ewiki_list_pages($found);
01150    }
01151 
01152    return($o);
01153 }
01154 
01155 
01156 
01157 
01158 
01159 
01160 
01161 
01162 function ewiki_page_info($id, &$data, $action) {
01163 
01164    global $ewiki_plugins, $ewiki_config, $ewiki_links;
01165    global $CFG, $COURSE, $DB, $OUTPUT;  // MOODLE HACK
01166 
01167    $pnum = optional_param(EWIKI_UP_PAGENUM, 0, PARAM_INT);
01168    $pend = optional_param(EWIKI_UP_PAGEEND, 0, PARAM_INT);
01169 
01170    $o = ewiki_make_title($id, ewiki_t("INFOABOUTPAGE")." '{$id}'", 2, $action,"", "_MAY_SPLIT=1");
01171 
01172    $flagnames = array(
01173       "TEXT", "BIN", "DISABLED", "HTML", "READONLY", "WRITEABLE",
01174       "APPENDONLY", "SYSTEM",
01175    );
01176    $show = array(
01177       "version", "author", "userid", "created",
01178       "lastmodified", "refs",
01179       "flags", "meta", "content"
01180    );
01181 
01182    #-- versions to show
01183    $v_start = $data["version"];
01184    if ( $pnum && ($pnum<=$v_start) ) {
01185       $v_start = $pnum;
01186    }
01187    $v_end = $v_start - $ewiki_config["list_limit"] + 1;
01188    if ( $pend && ($pend<=$v_start) ) {
01189       $v_end = $pend;
01190    }
01191    $v_end = max($v_end, 1);
01192 
01193    #-- go
01194    # the very ($first) entry is rendered more verbosely than the others
01195    for ($v=$v_start,$first=1; ($v>=$v_end); $v--,$first=0) {
01196 
01197       $current = ewiki_database("GET", array("id"=>$id, "version"=>$v));
01198 
01199       if (!strlen(trim($current["id"])) || !$current["version"] || !strlen(trim($current["content"]))) {
01200          continue;
01201       }
01202 
01203       $o .= '<table  class="version-info" cellpadding="2" cellspacing="1">' . "\n";
01204 
01205       #-- additional info-actions
01206       $commands = '';
01207       foreach ($ewiki_config["action_links"]["info"] as $thisaction=>$title)
01208       if (@$ewiki_plugins["action"][$thisaction] || @$ewiki_plugins["action_always"][$thisaction]) {
01209    ##### BEGIN MOODLE ADDITION #####
01210          if ($commands) {
01211              $commands .= '&nbsp;&nbsp;';
01212          }
01213          $commands .= '<a href="' .
01214            ewiki_script($thisaction, $id, array("version"=>$current["version"])) .
01215            '">' . get_string($title,"wiki") . '</a>';
01216    ##### END MOODLE ADDITION #####
01217       }
01218 
01219       #-- print page database entry
01220       foreach($show as $i) {
01221 
01222          $value = @$current[$i];
01223 
01224          #-- show database {fields} differently
01225          if ($i == "meta") {
01226             continue;  // MOODLE DOESN'T USE IT
01227             $str = "";
01228             if ($first && $value) { foreach ($value as $n=>$d) {
01229                $str .= s("$n: $d") . "<br />\n";
01230             } }
01231             $value = $str;
01232          }
01233          elseif ($value >= UNIX_MILLENNIUM) {    #-- {lastmodified}, {created}
01234             #### BEGIN MOODLE CHANGE
01235             $value=userdate($value);
01236             #$value = strftime("%c", $value);
01237             #### END MOODLE CHANGE
01238          }
01239          elseif ($i == "content") {
01240             continue;  // MOODLE DOESN'T CARE
01241             $value = strlen(trim($value)) . " bytes";
01242             $i = "content size";
01243          }
01244          elseif ($first && ($i == "refs") && !(EWIKI_PROTECTED_MODE && (EWIKI_PROTECTED_MODE_HIDING>=2))) {
01245             $a = explode("\n", trim($value));
01246             $ewiki_links = ewiki_database("FIND", $a);
01247             ewiki_merge_links($ewiki_links);
01248             foreach ($a as $n=>$link) {
01249                $a[$n] = ewiki_link_regex_callback(array("$link"), "force_noimg");
01250             }
01251             $value = trim(implode(", ", $a));
01252             if (!$value) {
01253                 continue;
01254             }
01255          }
01256          elseif (strpos($value, "\n") !== false) {       #-- also for {refs}
01257             $value = str_replace("\n", ", ", trim($value));
01258             if (!$value) {
01259                 continue;
01260             }
01261          }
01262          elseif ($i == "version") {
01263             $value = '<a href="' .
01264                ewiki_script("", $id, array("version"=>$value)) . '">' .
01265                $value . '</a> '."($commands)";
01266          }
01267          elseif ($i == "flags") {
01268             continue;  // MOODLE DOESN'T USE IT
01269             $fstr = "";
01270             for ($n = 0; $n < 32; $n++) {
01271               if ($value & (1 << $n)) {
01272                  if (! ($s=$flagnames[$n])) { $s = "UU$n"; }
01273                  $fstr .= $s . " ";
01274               }
01275             }
01276             $value = $fstr;
01277          }
01278          elseif ($i == "author") {
01279             continue;
01280             $ewiki_links=1;
01281             $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);
01282          }
01283          elseif ($i == "userid") {
01284              $i = 'author';
01285              if ($user = $DB->get_record('user', array('id'=>$value))) {
01286                  if (!isset($COURSE->id)) {
01287                      $COURSE->id = SITEID;
01288                  }
01289                  $picture = $OUTPUT->user_picture($user);
01290                  $value = $picture . html_writer::link("$CFG->wwwroot/user/view.php?id=$user->id&course=$COURSE->id", fullname($user));
01291              } else {
01292                  continue;
01293                  //$value = @$current['author'];
01294              }
01295          }
01296 
01297    ##### BEGIN MOODLE ADDITION #####
01298          $o .= '<tr class="page-'.$i.'"><td style="vertical-align:top;text-align:right;white-space: nowrap;"><b>' .ewiki_t($i). ':</b></td>' .
01299                '<td>' . $value . "</td></tr>\n";
01300    ##### END MOODLE ADDITION #####
01301 
01302       }
01303 
01304       $o .= "</table><br /><br />\n";
01305 
01306    }
01307 
01308    #-- page result split
01309    if ($v >= 1) {
01310       $o .= "<br />\n".get_string('showversions','wiki').' '.ewiki_chunked_page($action, $id, -1, $v, 1, 0, 0) . "\n <br />";
01311    }
01312 
01313    return($o);
01314 }
01315 
01316 
01317 
01318 
01319 function ewiki_chunked_page($action, $id, $dir=-1, $start=10, $end=1, $limit=0, $overlap=0.25, $collapse_last=0.67) {
01320 
01321    global $ewiki_config;
01322 
01323    if (empty($limit)) {
01324       $limit = $ewiki_config["list_limit"];
01325    }
01326    if ($overlap < 1) {
01327       $overlap = (int) ($limit * $overlap);
01328    }
01329 
01330    $p = "";
01331    $n = $start;
01332 
01333    while ($n) {
01334 
01335       $n -= $dir * $overlap;
01336 
01337       $e = $n + $dir * ($limit + $overlap) + 1;
01338 
01339       if ($dir<0) {
01340          $e = max(1, $e);
01341          if ($e <= $collapse_last * $limit) {
01342             $e = 1;
01343          }
01344       }
01345       else {
01346          $e = min($end, $e);
01347          if ($e >= $collapse_last * $limit) {
01348             $e = $end;
01349          }
01350       }
01351 
01352       $o .= ($o?" &middot; ":"")
01353          . '<a href="'.ewiki_script($action, $id, array(EWIKI_UP_PAGENUM=>$n, EWIKI_UP_PAGEEND=>$e))
01354          . '">'. "$n-$e" . '</a>';
01355 
01356       if (($n=$e-1) < $end) {
01357          $n = false;
01358       }
01359    }
01360 
01361    return('<span class="chunked-result">'. $o .'</span>');
01362 }
01363 
01364 
01365 
01366 
01367 
01368 
01369 function ewiki_page_edit($id, $data, $action) {
01370 
01371    global $ewiki_links, $ewiki_author, $ewiki_plugins, $ewiki_ring, $ewiki_errmsg;
01372 
01373    $content = optional_param('content', '', PARAM_CLEAN);
01374    $version = optional_param('version', '', PARAM_CLEAN);
01375    $preview = optional_param('preview', false, PARAM_BOOL);
01376    $save    = optional_param('save', false, PARAM_BOOL);
01377 
01378    $hidden_postdata = array();
01379 
01380    #-- previous version come back
01381    if (@$data["forced_version"]) {
01382 
01383       $current = ewiki_database("GET", array("id"=>$id));
01384       $data["version"] = $current["version"];
01385       unset($current);
01386 
01388       $_REQUEST['content'] = $_POST['content'] = $_GET['content'] = null;
01389       $_REQUEST['version'] = $_POST['version'] = $_GET['version'] = null;
01390       $content = '';
01391       $version = '';
01392    }
01393 
01394    #-- edit hacks
01395    if ($pf_a = @$ewiki_plugins["edit_hook"]) foreach ($pf_a as $pf) {
01396       if ($output = $pf($id, $data, $hidden_postdata)) {
01397          return($output);
01398       }
01399    }
01400 
01401    #-- permission checks
01402    if (isset($ewiki_ring)) {
01403       $ring = $ewiki_ring;
01404    } else {
01405       $ring = 3;
01406    }
01407    $flags = @$data["flags"];
01408    if (!($flags & EWIKI_DB_F_WRITEABLE)) {
01409 
01410       #-- perform auth
01411       $edit_ring = (EWIKI_PROTECTED_MODE>=2) ? (2) : (NULL);
01412       if (EWIKI_PROTECTED_MODE && !ewiki_auth($id, $data, $action, $edit_ring, "FORCE")) {
01413          return($ewiki_errmsg);
01414       }
01415 
01416       #-- flag checking
01417       if (($flags & EWIKI_DB_F_READONLY) and ($ring >= 2)) {
01418          return(ewiki_t("CANNOTCHANGEPAGE"));
01419       }
01420       if (($flags) and (($flags & EWIKI_DB_F_TYPE) != EWIKI_DB_F_TEXT) and ($ring >= 1)) {
01421          return(ewiki_t("CANNOTCHANGEPAGE"));
01422       }
01423    }
01424 
01425    #-- "Edit Me"
01426    $o = ewiki_make_title($id, ewiki_t("EDITTHISPAGE").(" '{$id}'"), 2, $action, "", "_MAY_SPLIT=1");
01427 
01428    #-- preview
01429    if ($preview) {
01430       $o .= $ewiki_plugins["edit_preview"][0]($data);
01431    }
01432 
01433    #-- save
01434    if ($save) {
01435 
01436 
01437          #-- normalize to UNIX newlines
01438          $content = str_replace("\015\012", "\012", $content);
01439          $content = str_replace("\015", "\012", $content);
01440 
01441          #-- check for concurrent version saving
01442          $error = 0;
01443          if ((@$data["version"] >= 1) && ($data["version"] != $version) || ($version < 1)) {
01444 
01445             $pf = $ewiki_plugins["edit_patch"][0];
01446 
01447             if (!$pf || !$pf($id, $data)) {
01448                $error = 1;
01449                $o .= ewiki_t("ERRVERSIONSAVE") . "<br /><br />";
01450             }
01451 
01452          }
01453          if (!$error) {
01454 
01455             #-- new pages` flags
01456             if (! ($set_flags = @$data["flags"] & EWIKI_DB_F_COPYMASK)) {
01457                $set_flags = 1;
01458             }
01459             if (EWIKI_ALLOW_HTML) {
01460                $set_flags |= EWIKI_DB_F_HTML;
01461             }
01462 
01463             #-- mk db entry
01464             $save = array(
01465                "id" => $id,
01466                "version" => @$data["version"] + 1,
01467                "flags" => $set_flags,
01468                "content" => $content,
01469                "created" => ($uu=@$data["created"]) ? $uu : time(),
01470                "meta" => ($uu=@$data["meta"]) ? $uu : "",
01471                "hits" => ($uu=@$data["hits"]) ? $uu : "0",
01472             );
01473             ewiki_data_update($save);
01474 
01475             #-- edit storage hooks
01476             if ($pf_a = @$ewiki_plugins["edit_save"]) {
01477                foreach ($pf_a as $pf) {
01478                   $pf($save, $data);
01479                }
01480             }
01481 
01482             #-- save
01483             if (!$save || !ewiki_database("WRITE", $save)) {
01484 
01485                $o .= $ewiki_errmsg ? $ewiki_errmsg : ewiki_t("ERRORSAVING");
01486 
01487             }
01488             else {
01489                #-- prevent double saving, when ewiki_page() is re-called
01490                $_REQUEST = $_GET = $_POST = array();
01491 
01492                $o = ewiki_t("THANKSFORCONTRIBUTION") . "<br /><br />";
01493                $o .= ewiki_page($id);
01494 
01495                if (EWIKI_EDIT_REDIRECT) {
01496                   $url = ewiki_script("", $id, "thankyou=1", 0, 0, EWIKI_HTTP_HEADERS?ewiki_script_url():0);
01497 
01498                   if (EWIKI_HTTP_HEADERS && !headers_sent()) {
01499                      header("Status: 303 Redirect for GET");
01500                      header("Location: $url");
01501                      #header("URI: $url");
01502                      #header("Refresh: 0; URL=$url");
01503                   }
01504                   else {
01505                      $o .= '<meta http-equiv="Refresh" content="0; URL='.s($url).'">';
01506                   }
01507                }
01508 
01509             }
01510 
01511          }
01512 
01513          //@REWORK
01514          // header("Reload-Location: " . ewiki_script("", $id, "", 0, 0, ewiki_script_url()) );
01515 
01516    }
01517    else {
01518       #-- Edit <form>
01519       $o .= ewiki_page_edit_form($id, $data, $hidden_postdata);
01520 
01521       #-- additional forms
01522       if ($pf_a = $ewiki_plugins["edit_form_final"]) foreach ($pf_a as $pf) {
01523          $pf($o, $id, $data, $action);
01524       }
01525    }
01526 
01527    return($o);
01528 }
01529 
01530 
01531 function ewiki_data_update(&$data, $author="") {
01532    global $USER, $ewiki_links;
01533 
01534    #-- add backlinks entry
01535    ewiki_scan_wikiwords($data["content"], $ewiki_links, "_STRIP_EMAIL=1");
01536    $data["refs"] = "\n\n".implode("\n", array_keys($ewiki_links))."\n\n";
01537    $data["lastmodified"] = time();
01538    $data["author"] = ewiki_author($author);
01539    if (isset($USER->id)) {
01540        $data["userid"] = $USER->id;
01541    }
01542 }
01543 
01544 
01545 
01546 #-- edit <textarea>
01547 function ewiki_page_edit_form(&$id, &$data, &$hidden_postdata) {
01548    global $ewiki_plugins, $ewiki_config, $moodle_format;
01549 
01550    $content = optional_param('content', '', PARAM_CLEAN);
01551    $version = optional_param('version', '', PARAM_CLEAN);
01552 
01553    $o='';
01554 
01555    #-- previously edited, or db fetched content
01556    if ($content || $version) {
01557       $data = array(
01558          "version" => $version,
01559          "content" => $content
01560       );
01561    }
01562    else {
01563       if (empty($data["version"])) {
01564          $data["version"] = 1;
01565       }
01566       @$data["content"] .= "";
01567    }
01568 
01569    #-- normalize to DOS newlines
01570    $data["content"] = str_replace("\015\012", "\012", $data["content"]);
01571    $data["content"] = str_replace("\015", "\012", $data["content"]);
01572    $data["content"] = str_replace("\012", "\015\012", $data["content"]);
01573 
01574    $hidden_postdata["version"] = &$data["version"];
01575 
01576    #-- edit textarea/form
01577    // deleted name="ewiki", can not find the reference, and it's breaking xhtml
01578    $o .= ewiki_t("EDIT_FORM_1")
01579        . '<form method="post" enctype="multipart/form-data" action="'
01580        . ewiki_script("edit", $id) . '" '
01581        . ' accept-charset="'.EWIKI_CHARSET.'">' . "\n";
01582    $o .= '<div>';
01583    #-- additional POST vars
01584    foreach ($hidden_postdata as $name => $value) {
01585        $o .= '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
01586    }
01587 
01588    ($cols = strtok($ewiki_config["edit_box_size"], "x*/,;:")) && ($rows = strtok("x, ")) || ($cols=70) && ($rows=15);
01589    global $ewiki_use_editor, $ewiki_editor_content;
01590    $ewiki_editor_content=1;
01591    if($ewiki_use_editor) {
01592      ob_start();
01593      $usehtmleditor = can_use_html_editor();
01594      echo '<table><tr><td>';
01595      if ($usehtmleditor) { //clean and convert before editing
01596          $options = new stdClass();
01597          $options->smiley = false;
01598          $options->filter = false;
01599          $oldtext = format_text(ewiki_format($data["content"]), $moodle_format, $options);
01600      } else {
01601          $oldtext = ewiki_format($data["content"]);
01602      }
01603      print_textarea($usehtmleditor, $rows, $cols, 680, 400, "content", $oldtext);
01604      echo '</td></tr></table>';
01605 
01606      $o .= ob_get_contents();
01607      ob_end_clean();
01608 
01609    } else {
01610    ##### END MOODLE ADDITION #####
01611 
01612      $o .= '<textarea wrap="soft" id="ewiki_content" name="content" rows="'.$rows.'" cols="'.$cols.'">'
01613         . s($data["content"]) . "</textarea>"
01614         . $GLOBALS["ewiki_t"]["C"]["EDIT_TEXTAREA_RESIZE_JS"];
01615 
01616    ##### BEGIN MOODLE ADDITION #####
01617    }
01618    ##### END MOODLE ADDITION #####
01619 
01620    #-- more <input> elements before the submit button
01621    if ($pf_a = $ewiki_plugins["edit_form_insert"]) foreach ($pf_a as $pf) {
01622       $o .= $pf($id, $data, $action);
01623    }
01624 
01625    ##### BEGIN MOODLE ADDITION (Cancel Editing into Button) #####
01626    $o .= "\n<br />\n"
01627       . '<input type="submit" name="save" value="'. ewiki_t("SAVE") . '" />'."\n"
01628       . '<input type="submit" name="preview" value="'. ewiki_t("PREVIEW") . '" />' . "\n"
01629       . '<input type="submit" name="canceledit" value="'. ewiki_t("CANCEL_EDIT") . '" />' . "\n";
01630 #      . ' &nbsp; <a href="'. ewiki_script("", $id) . '">' . ewiki_t("CANCEL_EDIT") . '</a>';
01631    ##### END MOODLE ADDITION #####
01632 
01633    #-- additional form elements
01634    if ($pf_a = $ewiki_plugins["edit_form_append"]) foreach ($pf_a as $pf) {
01635       $o .= $pf($id, $data, $action);
01636    }
01637 
01638    $o .= "\n</div></form>\n";
01639    //   . ewiki_t("EDIT_FORM_2");  // MOODLE DELETION
01640 
01641    return('<div class="edit-box">'. $o .'</div>');
01642 }
01643 
01644 
01645 
01646 #-- pic upload form
01647 function ewiki_page_edit_form_final_imgupload(&$o, &$id, &$data, &$action) {
01648    if (EWIKI_SCRIPT_BINARY && EWIKI_UP_UPLOAD && EWIKI_IMAGE_MAXSIZE) {
01649       $o .= "\n<br />\n". '<div class="image-upload">'
01650       . '<form action='
01651       . '"'. ewiki_script_binary("", EWIKI_IDF_INTERNAL, "", "_UPLOAD=1") .'"'
01652       . ' method="post" enctype="multipart/form-data" target="_upload">'
01653       . '<fieldset class="invisiblefieldset">'
01654       . '<input type="hidden" name="MAX_FILE_SIZE" value="'.EWIKI_IMAGE_MAXSIZE.'" />'
01655       . '<input type="file" name="'.EWIKI_UP_UPLOAD.'"'
01656       . (defined("EWIKI_IMAGE_ACCEPT") ? ' accept="'.EWIKI_IMAGE_ACCEPT.'" />' : " />")
01657       . '<input type="hidden" name="'.EWIKI_UP_BINARY.'" value="'.EWIKI_IDF_INTERNAL.'" />'
01658       . '&nbsp;&nbsp;&nbsp;'
01659       . '<input type="submit" value="'.ewiki_t("UPLOAD_PICTURE_BUTTON").'" />'
01660       . '</fieldset></form></div>'. "\n";
01661   }
01662 }
01663 
01664 
01665 function ewiki_page_edit_preview(&$data) {
01666 #### BEGIN MOODLE CHANGES
01667    global $moodle_format;
01668    $preview_text=$GLOBALS["ewiki_plugins"]["render"][0](optional_param("content", null, PARAM_CLEAN), 1, EWIKI_ALLOW_HTML || (@$data["flags"]&EWIKI_DB_F_HTML));
01669    return( '<div class="preview">'
01670            . "<hr noshade>"
01671            . "<div class='mdl-right'>" . ewiki_t("PREVIEW") . "</div><hr noshade><br />\n"
01672            . format_text($preview_text, $moodle_format)
01673            . "<br /><br /><hr noshade><br />"
01674            . "</div>"
01675    );
01676 #### END MOODLE CHANGES
01677 }
01678 
01679 
01680 function ewiki_control_links($id, &$data, $action) {
01681 
01682    global $ewiki_plugins, $ewiki_ring, $ewiki_config;
01683    $action_links = & $ewiki_config["action_links"][$action];
01684 
01685    #-- disabled
01686    if (!$ewiki_config["control_line"]) {
01687       return("");
01688    }
01689 
01690    $o = "\n"
01691       . '<div class="mdl-right action-links control-links">'
01692       . "\n<br />\n"
01693       . "<hr noshade>" . "\n";
01694 
01695    if (@$data["forced_version"]) {
01696 
01697       $o .= '<form action="' . ewiki_script("edit", $id) . '" method="post">' .
01698             '<fieldset class="invisiblefieldset">'.
01699             '<input type="hidden" name="edit" value="old" />' .
01700             '<input type="hidden" name="version" value="'.$data["forced_version"].'" />' .
01701             '<input type="submit" value="' . ewiki_t("OLDVERCOMEBACK") . '" /></form> ';
01702    }
01703    else {
01704       foreach ($action_links as $action => $title)
01705       if (!empty($ewiki_plugins["action"][$action]) || !empty($ewiki_plugins["action_always"][$action]) || strpos($action, ":/"))
01706       {
01707          if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($id, $data, $action))  { continue; }
01708 
01709          $o .= '<a href="'
01710             . (strpos($action, ":/") ? $action : ewiki_script($action, $id))
01711             . '">' . ewiki_t($title) . '</a> &middot; ';
01712       }
01713    }
01714 
01715    if ($data["lastmodified"] >= UNIX_MILLENNIUM) {
01716       $o .= '<small>' . strftime(ewiki_t("LASTCHANGED"), @$data["lastmodified"]) . '</small>';
01717    }
01718 
01719    $o .= "</div>\n";
01720 
01721    return($o);
01722 }
01723 
01724 
01725 
01726 
01727 
01728 # ============================================================= rendering ===
01729 
01730 
01731 
01732 
01733 
01734 ########  ###   ###  #########  ###  ###   ###  #######
01735 ########  ####  ###  #########  ###  ####  ###  #######
01736 ###       ##### ###  ###             ##### ###  ###
01737 ######    #########  ###  ####  ###  #########  ######
01738 ######    #########  ###  ####  ###  #########  ######
01739 ###       ### #####  ###   ###  ###  ### #####  ###
01740 ########  ###  ####  #########  ###  ###  ####  #######
01741 ########  ###   ###  #########  ###  ###   ###  #######
01742 
01743 
01744 /*
01745    The _format() function transforms $wiki_source pages into <html> strings,
01746    also calls various markup and helper plugins during the transformation
01747    process. The $params array can activate various features and extensions.
01748    only accepts UNIX newlines!
01749 */
01750 function ewiki_format ( $wiki_source, $params = array()) {
01751    global $ewiki_links, $ewiki_plugins, $ewiki_config;
01752 
01753    #-- state vars
01754    $params = @array_merge($ewiki_config["format_params"], $params);
01755    $s = array(
01756       "in" => 0,         # current input $iii[] block array index
01757       "para" => "",
01758       "line" => "",
01759       "post" => "",      # string to append after current line/paragraph
01760       "line_i" => 0,
01761       "lines" => array(),
01762       "list" => "",      # lists
01763       "tbl" => 0,        # open table?
01764       "indent" => 0,     # indentation
01765       "close" => array(),
01766    );
01767    #-- aliases
01768    $in = &$s["in"];
01769    $line = &$s["line"];
01770    $lines = &$s["lines"];
01771    $para = &$s["para"];
01772    $post = &$s["post"];
01773    $list = &$s["list"];
01774 
01775    #-- input and output arrays
01776    if ($wiki_source[0] == "<") {            # also prepend an empty line
01777       $wiki_source = "\n" . $wiki_source;    # for faster strpos() searchs
01778    }
01779    $iii = array(
01780       0 => array(
01781          0 => $wiki_source."\n",    # body + empty line
01782          1 => 0x0FFF,               # flags (0x1=WikiMarkup, 0x2=WikiLinks, 0x100=BlockPlugins)
01783          2 => "core",               # block plugin name
01784       )
01785    );
01786    $ooo = array(
01787    );
01788    unset($wiki_source);
01789 
01790    #-- plugins
01791    $pf_tbl = @$ewiki_plugins["format_table"][0];
01792    $pf_line = @$ewiki_plugins["format_line"];
01793 
01794    #-- wikimarkup (wm)
01795    $htmlentities = $ewiki_config["htmlentities"];
01796    $wm_indent = &$ewiki_config["wm_indent"];
01797    $wm_table_defaults = &$ewiki_config["wm_table_defaults"];
01798    $wm_source = &$ewiki_config["wm_source"];
01799    $wm_list = &$ewiki_config["wm_list"];
01800    $wm_list_chars = implode("", array_keys($wm_list));
01801    $wm_style = &$ewiki_config["wm_style"];
01802    $wm_start_end = &$ewiki_config["wm_start_end"];
01803 
01804    #-- eleminate html
01805    $iii[0][0] = strtr($iii[0][0], $htmlentities);
01806    unset($htmlentities["&"]);
01807 
01808    #-- pre-processing plugins (working on wiki source)
01809    if ($pf_source = $ewiki_plugins["format_source"]) {
01810       foreach ($pf_source as $pf) $pf($iii[0][0]);
01811    }
01812 
01813    #-- simple markup
01814    $iii[0][0] = strtr($iii[0][0], $wm_source);
01815 
01816    #-- separate input into blocks ------------------------------------------
01817    foreach ($ewiki_config["format_block"] as $btype => $binfo) {
01818 
01819       #-- disabled block plugin?
01820       if ($binfo[2] && !$params[$binfo[2]])  {
01821          continue;
01822       }
01823 
01824       #-- traverse $iii[]
01825       $in = -1;
01826       while ((++$in) < count($iii)) {
01827 
01828          #-- search fragment delimeters
01829          if ($iii[$in][1] & 0x0100)
01830          while (
01831             ($c = & $iii[$in][0]) &&
01832             (($l = strpos($c, $binfo[0])) !== false) &&
01833             ($r = strpos($c, $binfo[1], $l))   )
01834          {
01835             $l_len = strlen($binfo[0]);
01836             $r_len = strlen($binfo[1]);
01837 
01838             $repl = array();
01839             // pre-text
01840             if (($l > 0) && trim($text = substr($c, 0, $l))) {
01841                $repl[] = array($text, 0xFFFF, "core");
01842             }
01843             // the extracted part
01844             if (trim($text = substr($c, $l+$l_len, $r-$l-$r_len))) {
01845                $repl[] = array($text, $binfo[3], "$btype");
01846             }
01847             // rest
01848             if (($r+$r_len < strlen($c)) && trim($text = substr($c, $r+$r_len))) {
01849                $repl[] = array($text, 0xFFFF, "core");
01850             }
01851             array_splice($iii, $in, 1, $repl);
01852 
01853             $in += 1;
01854          }
01855       }
01856    }
01857 
01858    #-- run format_block plugins
01859    $in = -1;
01860    while ((++$in) < count($iii)) {
01861       if (($btype = $iii[$in][2]) && ($pf_a = $ewiki_plugins["format_block"][$btype])) {
01862          $c = &$iii[$in][0];
01863          foreach ($pf_a as $pf) {
01864             # current buffer $c and pointer $in into $iii[] and state $s
01865             $pf($c, $in, $iii, $s, $btype);
01866          }
01867       }
01868    }
01869 
01870    #-- wiki markup ------------------------------------------------------
01871    $para = "";
01872    $in = -1;
01873    while ((++$in) < count($iii)) {
01874       #-- wikimarkup
01875       if ($iii[$in][1] & 0x0001) {
01876 
01877          #-- input $lines buffer, and output buffer $ooo array
01878          $lines = explode("\n", $iii[$in][0]);
01879          $ooo[$in] = array(
01880             0 => "",
01881             1 => $iii[$in][1]
01882          );
01883          $out = &$ooo[$in][0];
01884          $s["block"] = ($iii[$in][2] != "core");  # disables indentation & paragraphs
01885 
01886          #-- walk through wiki source lines
01887          $line_max = count($lines);
01888          foreach ($lines as $s["line_i"]=>$line) {
01889 //echo "<pre>line={$s[line_i]}:".htmlspecialchars($line).":".htmlspecialchars($line[0])."</pre>";
01890 
01891             #-- empty lines separate paragraphs
01892             if (!strlen($line)) {
01893                ewiki_format_close_para($ooo, $s);
01894                ewiki_format_close_tags($ooo, $s);
01895                if (!$s["block"]) {
01896                   $out .= "\n";
01897                }
01898             }
01899             #-- horiz bar
01900             if (!strncmp($line, "----", 4)) {
01901                $out .= "<hr noshade>\n";
01902                continue;
01903             }
01904             #-- html comment
01905             #if (!strncmp($line, "&lt;!--", 7)) {
01906             #   $out .= "<!-- " . htmlentities(str_replace("--", "__", substr($line, 7))) . " -->\n";
01907             #   continue;
01908             #}
01909 
01910             ($c0 = $line[0])
01911             or ($c0 = "\000");
01912 
01913             #-- tables
01914             ### MOODLE CHANGE: TRIM
01915             if (($c0 == "|") && ($line[strlen(trim($line))-1] == "|")) {
01916                if (!$s["tbl"]) {
01917                   ewiki_format_close_para($ooo, $s);
01918                   ewiki_format_close_tags($ooo, $s);
01919                   $s["list"] = "";
01920                }
01921                $line = substr($line, 1, -1);
01922                if ($pf_tbl) {
01923                   $pf_tbl($line, $ooo, $s);
01924                }
01925                else {
01926                   if (!$s["tbl"]) {
01927                      $out .= "<table " . $wm_table_defaults . ">\n";
01928                      $s["close"][] = "\n</table>";
01929                   }
01930                   $line = "<tr>\n<td>" . str_replace("|", "</td>\n<td>", $line) . "</td>\n</tr>";
01931                }
01932                $s["tbl"] = 1;
01933                $para = false;
01934             }
01935             elseif ($s["tbl"]) {
01936                $s["tbl"] = 0;
01937             }
01938 
01939 
01940             #-- headlines
01941             if (($c0 == "!") && ($excl = strspn($line, "!"))) {
01942                if ($excl > 3) {
01943                   $excl = 3;
01944                }
01945                $line = substr($line, $excl);
01946                $excl = 5 - $excl;
01947                $line = "<h$excl>" . $line . "</h$excl>";
01948                if ($para) {
01949                   ewiki_format_close_para($ooo, $s);
01950                }
01951                ewiki_format_close_tags($ooo, $s);
01952                $para = false;
01953             }
01954 
01955             #-- whole-line markup
01956             # ???
01957 
01958 
01959             #-- indentation (space/tab markup)
01960             $n_indent = 0;
01961             if (!$list && (!$s["block"]) && ($n_indent = strspn($line, " "))) {
01962                $n_indent = (int) ($n_indent / 2.65);
01963                while ($n_indent > $s["indent"]) {
01964                   $out .= $wm_indent;
01965                   $s["indent"]++;
01966                }
01967             }
01968             while ($n_indent < $s["indent"]) {
01969                $out .= "";
01970                $s["indent"]--;
01971             }
01972 
01973 
01974             #-- text style triggers
01975             foreach ($wm_style as $find=>$replace) {
01976                $find_len = strlen($find);
01977                $loop = 20;
01978                while(($loop--) && (($l = strpos($line, $find)) !== false) && ($r = strpos($line, $find, $l + $find_len))) {
01979                   $line = substr($line, 0, $l) . $replace[0] .
01980                           substr($line, $l + strlen($find), $r - $l - $find_len) .
01981                           $replace[1] . substr($line, $r + $find_len);
01982                }
01983             }
01984 
01985 
01986             #-- list markup
01987             if (isset($wm_list[$c0])) {
01988                if (!$list) {
01989                   ewiki_format_close_para($ooo, $s);
01990                   ewiki_format_close_tags($ooo, $s);
01991                }
01992                $new_len = strspn($line, $wm_list_chars);
01993                $new_list = substr($line, 0, $new_len);
01994                $old_len = strlen($list);
01995                $lchar = $new_list[$new_len-1];
01996                list($lopen, $ltag1, $ltag2) = $wm_list[$lchar];
01997 
01998                #-- cut line
01999                $line = substr($line, $new_len);
02000                $lspace = "";
02001                $linsert = "";
02002                if ($ltag1) {
02003                   $linsert = "<$ltag1>" . strtok($line, $lchar) . "</$ltag1> ";
02004                   $line = strtok("\000");
02005                }
02006 
02007                #-- add another <li>st entry
02008                if ($new_len == $old_len) {
02009                   $lspace = str_repeat("  ", $new_len);
02010                   $out .=  "</$ltag2>\n" . $lspace . $linsert . "<$ltag2>";
02011                }
02012                #-- add list
02013                elseif ($new_len > $old_len) {
02014                   while ($new_len > ($old_len=strlen($list))) {
02015                      $lchar = $new_list[$old_len];
02016                      $list .= $lchar;
02017                      list($lopen, $ltag1, $ltag2) = $wm_list[$lchar];
02018                      $lclose = strtok($lopen, " ");
02019                      $lspace = str_repeat("  ", $new_len);
02020 
02021                      $out .= "\n$lspace<$lopen>\n" . "$lspace". $linsert . "<$ltag2>";
02022                      $s["close"][] = "$lspace</$lclose>";
02023                      $s["close"][] = "$lspace</$ltag2>";
02024                   }
02025                }
02026                #-- close lists
02027                else {
02028                   while ($new_len < ($old_len=strlen($list))) {
02029                      $remove = $old_len-$new_len;
02030                      ewiki_format_close_tags($ooo, $s, 2*$remove);
02031                      $list = substr($list, 0, -$remove);
02032                   }
02033                   if ($new_len) {
02034                      $lspace = str_repeat("  ", $new_len);
02035                      $out .= "$lspace</$ltag2>\n" . $lspace . $linsert . "<$ltag2>";
02036                   }
02037                }
02038 
02039                $list = $new_list;
02040                $para = false;
02041             }
02042             elseif ($list) {
02043                if ($c0 == " ") {
02044                   $para = false;
02045                }
02046                else {
02047                   ewiki_format_close_tags($ooo, $s);
02048                   $list = "";
02049                }
02050             }
02051 
02052 
02053             #-- start-end markup
02054             foreach ($wm_start_end as $d) {
02055                $len0 = strlen($d[0]);
02056                $loop = 20;
02057                while(($loop--) && (($l = strpos($line, $d[0])) !== false) && ($r = strpos($line, $d[1], $l + $len0))) {
02058                   $len1 = strlen($d[1]);
02059                   $line = substr($line, 0, $l) . $d[2] .
02060                           substr($line, $l + $len0, $r - $l - $len0) .
02061                           $replace[1] . substr($line, $r + $len1);
02062                }
02063             }
02064 
02065             #-- call wiki source formatting plugins that work on current line
02066             if ($pf_line) {
02067                foreach ($pf_line as $pf) $pf($out, $line, $post);
02068             }
02069 
02070 
02071 
02072             #-- add formatted line to page-output
02073             $line .= $post;
02074             if ($para === false) {
02075                $out .= $line;
02076                $para = "";
02077             }
02078             else {
02079                $para .= $line . "\n";
02080             }
02081 
02082          }
02083 
02084          #-- last block, or next not WikiSource?
02085          if (!isset($iii[$in+1]) || !($iii[$in+1][1] & 0x0011)) {
02086             ewiki_format_close_para($ooo, $s);
02087             ewiki_format_close_tags($ooo, $s);
02088          }
02089       }
02090       #-- copy as is into output buffer
02091       else {
02092          $ooo[$in] = $iii[$in];
02093       }
02094       $iii[$in] = array();
02095    }
02096 
02097    #-- wiki linking ------------------------------------------------------
02098    $scan_src = "";
02099    for ($in=0; $in<count($ooo); $in++) {
02100       if (EWIKI_HTML_CHARS && ($ooo[$in][1] & 0x0004)) {  # html character entities
02101          $ooo[$in][0] = str_replace("&amp;#", "&#", $ooo[$in][0]);
02102       }
02103       if ($ooo[$in][1] & 0x0022) {
02104          #-- join together multiple WikiSource blocks
02105          while (isset($ooo[$in+1]) && ($ooo[$in][1] & 0x0002) && ($ooo[$in+1][1] & 0x0002)) {
02106             $ooo[$in] = array(
02107                0 => $ooo[$in][0] . "\n" . $ooo[$in+1][0],
02108                1 => $ooo[$in][1] | $ooo[$in+1][1],
02109             );
02110             array_splice($ooo, $in+1, 1);
02111          }
02112       }
02113       $scan_src .= $ooo[$in][0];
02114    }
02115 
02116 
02117    #-- pre-scan
02118    if (1+$params["scan_links"]) {
02119       ewiki_scan_wikiwords($scan_src, $ewiki_links);
02120    }
02121    if ($pf_linkprep = $ewiki_plugins["format_prepare_linking"]) {
02122       foreach ($pf_linkprep as $pf) $pf($scan_src);
02123    }
02124    $scan_src = NULL;
02125 
02126    #-- finally the link-detection-regex
02127    for ($in=0; $in<count($ooo); $in++) {
02128       if ($ooo[$in][1] & 0x0002) {
02129       ##### BEGIN MOODLE ADDITION #####
02130       # No WikiLinks in Editor
02131       #################################
02132         global $ewiki_use_editor, $ewiki_editor_content;
02133         if(!($ewiki_use_editor && $ewiki_editor_content)) {
02134       ##### END MOODLE ADDITION #####
02135           ewiki_render_wiki_links($ooo[$in][0]);
02136       ##### BEGIN MOODLE ADDITION #####
02137          }
02138       ##### END MOODLE ADDITION #####
02139       }
02140    }
02141 
02142    #-- fin: combine all blocks into html string ----------------------------
02143    $html = "";
02144    for ($in=0; $in<count($ooo); $in++) {
02145       $html .= $ooo[$in][0] . "\n";
02146       $ooo[$in] = 0;
02147    }
02148    #-- call post processing plugins
02149    if ($pf_final = $ewiki_plugins["format_final"]) {
02150       foreach ($pf_final as $pf) $pf($html);
02151    }
02152    return($html);
02153 }
02154 
02155 
02156 
02157 function ewiki_format_close_para(&$ooo, &$s) {
02158    $out = &$ooo[$s["in"]][0];
02159    #-- output text block
02160    if (trim($s["para"])) {
02161       if (!$s["block"]) {
02162          #### MOODLE CHANGES
02163          global $ewiki_use_editor;
02164          if(!$ewiki_use_editor) {
02165            $s["para"] = "\n<p>\n" . ltrim($s["para"], "\n") . "</p>\n";
02166          }
02167          #### MOODLE CHANGES
02168       }
02169       #-- paragraph formation plugins
02170       if ($pf_a = $GLOBALS["ewiki_plugins"]["format_para"]) {
02171          foreach ($pf_a as $pf) {
02172             $pf($s["para"], $ooo, $s);
02173          }
02174       }
02175       $out .= $s["para"];
02176       $s["para"] = "";
02177    }
02178    #-- indentation
02179    while ($s["indent"]) {
02180       $out .= "";
02181       $s["indent"]--;
02182    }
02183 }
02184 
02185 
02186 function ewiki_format_close_tags(&$ooo, &$s, $count=100) {
02187    $out = &$ooo[$s["in"]][0];
02188    if (!is_array($s) || !is_array($s["close"])) {
02189       die("\$s is garbaged == $s!!");
02190    }
02191    while (($count--) && ($add = array_pop($s["close"]))) {
02192       $out .= $add . "\n";
02193    }
02194 }
02195 
02196 
02197 function ewiki_format_pre(&$str, &$in, &$iii, &$s, $btype) {
02198    $str = "<pre class=\"markup $btype\">" . $str . "</pre>";
02199 }
02200 
02201 
02202 function ewiki_format_html(&$str, &$in, &$iii, &$s) {
02203    $he = array_reverse($GLOBALS["ewiki_config"]["htmlentities"]);
02204    $str = strtr($str, array_flip($he));
02205    $str = "<span class=\"markup html\">" . $str . "\n</span>\n";
02206 }
02207 
02208 
02209 function ewiki_format_comment(&$str, &$in, &$iii, &$s, $btype) {
02210    $str = "<!-- "  . str_replace("--", "¯¯", $str) . " -->";
02211 }
02212 
02213 
02214 
02215 
02216 /* unclean pre-scanning for WikiWords in a page,
02217    pre-query to the db */
02218 function ewiki_scan_wikiwords(&$wiki_source, &$ewiki_links, $se=0) {
02219 
02220    global $ewiki_config;
02221 
02222    #-- find matches
02223    preg_match_all($ewiki_config["wiki_pre_scan_regex"], $wiki_source, $uu);
02224    $uu = @array_merge($uu[1], $uu[2], $uu[3], $uu[4], (array)@$uu[5]);
02225 
02226    #-- clean up list, trim() spaces (allows more unclean regex) - page id unification
02227    foreach ($uu as $i=>$id) {
02228       $uu[$i] = trim($id);
02229    }
02230    unset($uu[""]);
02231    $uu = array_unique($uu);
02232 
02233    #-- query db
02234    $ewiki_links = ewiki_database("FIND",  $uu);
02235 
02236    #-- strip email adresses
02237    if ($se) {
02238       foreach ($ewiki_links as $c=>$uu) {
02239          if (strpos($c, "@") && (strpos($c, ".") || strpos($c, ":"))) {
02240             unset($ewiki_links[$c]);
02241          }
02242       }
02243    }
02244 
02245 }
02246 
02247 
02248 
02249 /* regex on page content,
02250    handled by callback (see below)
02251 */
02252 function ewiki_render_wiki_links(&$o) {
02253 
02254    global $ewiki_links, $ewiki_config, $ewiki_plugins;
02255 
02256    #-- merge with dynamic pages list
02257    ewiki_merge_links($ewiki_links);
02258 
02259    #-- replace WikiWords
02260    $link_regex = &$ewiki_config["wiki_link_regex"];
02261    $o = preg_replace_callback($link_regex, "ewiki_link_regex_callback", $o);
02262 
02263    #-- cleanup
02264    unset($ewiki_links);
02265 }
02266 
02267 
02268 /*
02269    combines with page plugin list,
02270    and makes all case-insensitive
02271 */
02272 function ewiki_merge_links(&$ewiki_links) {
02273    global $ewiki_plugins;
02274 #### BEGIN MOODLE CHANGES
02275      global $ewiki_link_case;
02276      $ewiki_link_case=array();
02277 #### END MOODLE CHANGES
02278      if ($ewiki_links !== true) {
02279       foreach ($ewiki_plugins["page"] as $page=>$uu) {
02280          $ewiki_links[$page] = 1;
02281       }
02282 #### BEGIN MOODLE CHANGES
02283      foreach($ewiki_links as $page => $uu) {
02284        if($uu) {
02285          $ewiki_link_case[strtolower($page)]=$page;
02286        }
02287      }
02288 #### END MOODLE CHANGES
02289       $ewiki_links = ewiki_array($ewiki_links);
02290    }
02291 }
02292 
02293 
02294 
02295 
02296 /* link rendering (p)regex callback
02297    (ooutch, this is a complicated one)
02298 */
02299 function ewiki_link_regex_callback($uu, $force_noimg=0) {
02300    global $DB, $CFG;
02301    #print "<pre>"; print_r($uu); print "</pre>";
02302    global $ewiki_links, $ewiki_plugins, $ewiki_config, $ewiki_id;
02303 
02304    $str = trim($uu[0]);
02305    $type = array();
02306    $states = array();
02307 
02308    #-- link bracket '[' escaped with '!' or '~'
02309    if (($str[0] == "!") || ($str[0] == "~")) {
02310       return(substr($str, 1));
02311    }
02312    if ($str[0] == "#") {
02313       $states["define"] = 1;
02314       $str = substr($str, 1);
02315    }
02316    if ($str[0] == "[") {
02317       $states["brackets"] = 1;
02318       $str = substr($str, 1, -1);
02319    }
02320 
02321    #-- explicit title given via [ title | WikiLink ]
02322    $href = $title = strtok($str, "|");
02323    if ($uu = strtok("|")) {
02324       $parts = explode('|', $str);
02325       $title = $parts[1] . ' | ' .$parts[0];
02326       $states["titled"] = 1;
02327    }
02328    #-- title and href swapped: swap back
02329    if (strpos("://", $title) || strpos($title, ":") && !strpos($href, ":")) {
02330       $uu = $title; $title = $href; $href = $uu;
02331    }
02332 
02333    #-- new entitling scheme [ url "title" ]
02334    if ((($l=strpos($str, '"')) < ($r=strrpos($str, '"'))) && ($l!==false) ) {
02335       $title = substr($str, $l + 1, $r - $l - 1);
02336       $href = substr($str, 0, $l) . substr($str, $r + 1);
02337       $states["titled"] = 1;
02338     }
02339 
02340    #-- strip spaces
02341    $spaces_l = ($href[0]==" ") ?1:0;
02342    $spaces_r = ($href[strlen($href)-1]==" ") ?1:0;
02343    $title = ltrim(trim($title), "^");
02344    $href = ltrim(trim($href), "^");
02345 
02346    #-- strip_htmlentities()
02347    if (1&&    (strpos($href, "&")!==false) && strpos($href, ";")) {
02348       foreach (array("&lt;"=>"<", "&gt;"=>">", "&amp;"=>"&") as $f=>$t) {
02349          $href = str_replace($f, $t, $href);
02350       }
02351    }
02352 
02353    #-- anchors
02354    $href2 = "";
02355    if (($p = strrpos($href, "#")) && ($p) && ($href[$p-1] != "&")) {
02356       $href2 = trim(substr($href, $p));
02357       $href = trim(substr($href, 0, $p));
02358    }
02359    elseif ($p === 0) {
02360       $states["define"] = 1;
02361    }
02362    if ($href == ".") {
02363       $href = $ewiki_id;
02364    }
02365 
02366    #-- for case-insensitivines
02367    $href_i = EWIKI_CASE_INSENSITIVE ? strtolower($href) : ($href);
02368 
02369    #-- injected URLs
02370    if (strpos($inj_url = $ewiki_links[$href_i], "://")) {
02371       if ($href==$title) { $href = $inj_url; }
02372    }
02373 
02374    #-- interwiki links
02375    if (strpos($href, ":") && ($uu = ewiki_interwiki($href, $type))) {
02376       $href = $uu;
02377       $str = "<a href=\"$href$href2\">$title</a>";
02378    }
02379    #-- action:WikiLinks
02380    elseif ($ewiki_plugins["action"][$a=strtolower(strtok($href, ":"))]) {
02381       $type = array($a, "action", "wikipage");
02382       $str = '<a href="' . ewiki_script($a, strtok("\000")) . '">' . $title . '</a>';
02383    }
02384    #-- page anchor definitions, if ($href[0]=="#")
02385    elseif (@$states["define"]) {
02386       $type = array("anchor");
02387       if ($title==$href) { $title="&nbsp;"; }
02388       $str = '<a name="' . s(ltrim($href, "#")) . '">' . ltrim($title, "#") . '</a>';
02389    }
02390    #-- inner page anchor jumps
02391    elseif (strlen($href2) && ($href==$ewiki_id) || ($href[0]=="#") && ($href2=&$href)) {
02392       $type = array("jump");
02393       $str = '<a href="' . s($href2) . '">' . $title . '</a>';
02394    }
02395    #-- ordinary internal WikiLinks
02396    elseif (($ewiki_links === true) || @$ewiki_links[$href_i]) {
02397       $type = array("wikipage");
02398 #### BEGIN MOODLE CHANGES
02399       global $ewiki_link_case;
02400       $href_realcase=array_key_exists($href_i,$ewiki_link_case) ? $ewiki_link_case[$href_i] : $href;
02401       $str = '[[' . $title . ']]';
02402 #### END MOODLE CHANGES
02403    }
02404    #-- guess for mail@addresses, convert to URI if
02405    elseif (strpos($href, "@") && !strpos($href, ":")) {
02406       $type = array("email");
02407       $href = "mailto:" . $href;
02408    }
02409    #-- not found fallback
02410    else {
02411       $str = "";
02412       #-- a plugin may take care
02413       if ($pf_a = $ewiki_plugins["link_notfound"]) {
02414          foreach ($pf_a as $pf) {
02415             if ($str = $pf($title, $href, $href2, $type)) {
02416                break;
02417          }  }
02418       }
02419 
02420       #-- (QuestionMarkLink to edit/ action)
02421       if (!$str) {
02422          $type = array("notfound");
02423          //$str = '<span class="NotFound"><b>' . $title . '</b><a href="' .
02424          //    ewiki_script("", $href) . '">?</a></span>';
02425          $str = '[['. $title . ']]';
02426       }
02427    }
02428 
02429    #-- convert standard URLs
02430    foreach ($ewiki_config["idf"]["url"] as $find)
02431     if (strpos($href, $find)===0) {
02432       $type[-2] = "url";
02433       $type[-1] = strtok($find, ":");
02434 
02435       #-- URL plugins
02436       if ($pf_a = $ewiki_plugins["link_url"]) foreach ($pf_a as $pf) {
02437          if ($str = $pf($href, $title)) { break 2; }
02438       }
02439       $meta = @$ewiki_links[$href];
02440 
02441       #-- check for image files
02442       $ext = substr($href, strrpos($href,"."));
02443       $nocache = strpos($ext, "no");
02444       $ext = strtok($ext, "?&#");
02445       $obj = in_array($ext, $ewiki_config["idf"]["obj"]);
02446       $img = $obj || in_array($ext, $ewiki_config["idf"]["img"]);
02447 
02448       #-- internal:// references (binary files)
02449       if (EWIKI_SCRIPT_BINARY && ((strpos($href, EWIKI_IDF_INTERNAL)===0)  ||
02450           EWIKI_IMAGE_MAXSIZE && EWIKI_CACHE_IMAGES && $img && !$nocache) )
02451       {
02452           $type = array("binary");
02453           //$href = ewiki_script_binary("", $href);
02454           //##### BEGIN MOODLE ADDITION #####
02455           $pattern = 'internal://';
02456           $matches = array();
02457           $filename = str_replace($pattern, '', $href);
02458           $filename = clean_param($filename, PARAM_FILE);
02459           $href = "@@PLUGINFILE@@/$filename";
02460           //##### END MOODLE ADDITION #####
02461       }
02462 
02463       #-- output html reference
02464       if (!$img || $force_noimg || !$states["brackets"] || (strpos($href, EWIKI_IDF_INTERNAL) === 0)) {
02465          $str = '<a href="' . $href . '">' . $title . '</a>';
02466       }
02467       #-- img tag
02468       else {
02469          if (is_string($meta)) {
02470             $meta = unserialize($meta);
02471          }
02472          $type = array("image");
02473          #-- uploaded images size
02474          $x = $meta["width"];
02475          $y = $meta["height"];
02476          if ($p = strpos('?', $href)) {      #-- width/height given in url
02477             parse_str(str_replace("&amp;", "&", substr($href, $p)), $meta);
02478             ($uu = $meta["x"] . $meta["width"]) and ($x = $uu);
02479             ($uu = $meta["y"] . $meta["height"]) and ($y = $uu);
02480             if ($scale = $meta["r"] . $meta["scale"]) {
02481                ($p = strpos($scale, "%")) and ($scale = strpos($scale, 0, $p) / 100);
02482                $x *= $scale; $y *= $scale;
02483             }
02484          }
02485          $align = array('', ' align="right"', ' align="left"', ' align="center"');
02486          $align = $align[$spaces_l + 2*$spaces_r];
02487          $str = ($obj ? '<embed width="70%"' : '<img') . ' src="' . $href . '"' .
02488                 ' alt="' . ($title) . '"' .
02489                 (@$states["titled"] ? ' title="' . ($title) . '"' : '').
02490         ($x && $y ? " width=\"$x\" height=\"$y\"" : "") .
02491                 $align . " />" . ($obj ? "</embed>" : "");
02492                                             # htmlentities($title)
02493       }
02494 
02495       break;
02496    }
02497 
02498    #-- icon/transform plugins
02499    ksort($type);
02500    if ($pf_a = @$ewiki_plugins["link_final"]) {
02501       foreach ($pf_a as $pf) { $pf($str, $type, $href, $title); }
02502    }
02503 
02504    return($str);
02505 }
02506 
02507 
02508 /*
02509    Returns URL if it encounters an InterWiki:Link or workalike.
02510 */
02511 function ewiki_interwiki($href, &$type) {
02512    global $ewiki_config, $ewiki_plugins;
02513 
02514    if (strpos($href, ":") and !strpos($href, "//") and ($p1 = strtok($href, ":"))) {
02515 
02516       $page = strtok("\000");
02517 
02518       if (!empty($ewiki_config["interwiki"]) && (($p1 = ewiki_array($ewiki_config["interwiki"], $p1)) !== NULL)) {
02519          $type = array("interwiki", $uu);
02520          while ($p1_alias = $ewiki_config["interwiki"][$p1]) {
02521              $type[] = $p1;
02522              $p1 = $p1_alias;
02523          }
02524          if (!strpos($p1, "%s")) {
02525              $p1 .= "%s";
02526          }
02527          $href = str_replace("%s", $page, $p1);
02528          return($href);
02529       }
02530       elseif ($pf = $ewiki_plugins["intermap"][$p1]) {
02531          return($pf($p1, $page));
02532       }
02533    }
02534 }
02535 
02536 
02537 /*
02538    implements FeatureWiki:InterMapWalking
02539 */
02540 function ewiki_intermap_walking($id, &$data, $action) {
02541    if (empty($data["version"]) && ($href = ewiki_interwiki($id, $uu))) {
02542       header("Location: $href");
02543       return("<a href=\"$href\">$href</a>");
02544    }
02545 }
02546 
02547 
02548 
02549 # =========================================================================
02550 
02551 
02552 
02553 #####    ##  ##   ##    ##    #####   ##  ##
02554 ######   ##  ###  ##   ####   ######  ##  ##
02555 ##  ##   ##  ###  ##  ######  ##  ##  ##  ##
02556 #####    ##  #### ##  ##  ##  ######  ######
02557 #####    ##  #######  ######  ####     ####
02558 ##  ###  ##  ## ####  ######  #####     ##
02559 ##  ###  ##  ##  ###  ##  ##  ## ###    ##
02560 ######   ##  ##  ###  ##  ##  ##  ##    ##
02561 ######   ##  ##   ##  ##  ##  ##  ##    ##
02562 
02563 
02564 
02565 
02566 /*  fetch & store
02567 */
02568 function ewiki_binary($break=0) {
02569    global $ewiki_plugins;
02570    global $USER;   // MOODLE
02571 
02572    $id = optional_param(EWIKI_UP_BINARY, '', PARAM_CLEAN);
02573 
02574    #-- reject calls
02575    if (!strlen($id) || !EWIKI_IDF_INTERNAL) {
02576       return(false);
02577    }
02578    if (headers_sent()) die("ewiki-binary configuration error");
02579 
02580    #-- upload requests
02581    $upload_file = @$_FILES[EWIKI_UP_UPLOAD];
02582    $add_meta = array();
02583    if ($orig_name = @$upload_file["name"]) {
02584       $add_meta["Content-Location"] = urlencode($orig_name);
02585       $add_meta["Content-Disposition"] = 'inline; filename="'.urlencode(basename("remote://$orig_name")).'"';
02586    }
02587 
02588    #-- what are we doing here?
02589    if (($id == EWIKI_IDF_INTERNAL) && ($upload_file)) {
02590       $do = "upload";
02591    }
02592    else {
02593       $data = ewiki_database("GET", array("id" => $id));
02594       $flags = @$data["flags"];
02595       if (EWIKI_DB_F_BINARY == ($flags & EWIKI_DB_F_TYPE)) {
02596          $do = "get";
02597       }
02598       elseif (empty($data["version"]) and EWIKI_CACHE_IMAGES) {
02599          $do = "cache";
02600       }
02601       else {
02602          $do = "nop";
02603       }
02604    }
02605 
02606    #-- auth only happens when enforced with _PROTECTED_MODE_XXL setting
02607    #   (authentication for inline images in violation of the WWW spirit)
02608    if ((EWIKI_PROTECTED_MODE>=5) && !ewiki_auth($id, $data, "binary-{$do}")) {
02609       $_REQUEST['id'] = $_POST['id'] = $_GET['id'] = "view/BinaryPermissionError";
02610       return("view/BinaryPermissionError");
02611    }
02612 
02613    #-- upload an image
02614    if ($do == "upload"){
02615       $id = ewiki_binary_save_image($upload_file["tmp_name"], "", $return=0, $add_meta);
02616       @unlink($upload_file["tmp_name"]);
02617       ($title = trim($orig_name, "/")) && ($title = preg_replace("/[^-._\w\d]+/", "_", substr(substr($orig_name, strrpos($title, "/")), 0, 20)))
02618       && ($title = '"'.$title.'"') || ($title="");
02619 
02620       if ($id) {
02621          echo<<<EOF
02622 <html><head><title>File/Picture Upload</title><script type="text/javascript"><!--
02623  opener.document.forms["ewiki"].elements["content"].value += "\\nUPLOADED PICTURE: [$id$title]\\n";
02624  window.setTimeout("self.close()", 5000);
02625 //--></script></head><body bgcolor="#440707" text="#FFFFFF">Your uploaded file was saved as<br /><big><b>
02626 [$id]
02627 </b></big>.<br /><br /><noscript>Please copy this &uarr; into the text input box:<br />select/mark it with your mouse, press [Ctrl]+[Insert], go back<br />to the previous screen and paste it into the textbox by pressing<br />[Shift]+[Insert] inside there.</noscript></body></html>
02628 EOF;
02629       }
02630    }
02631 
02632    #-- request for contents from the db
02633    elseif ($do == "get") {
02634 #### CHANGED FOR MOODLE
02635    if (EWIKI_HIT_COUNTING) {
02636       $tmp["id"]=$id;
02637       ewiki_database("HIT", $tmp);
02638    }
02639 #### CHANGED FOR MOODLE
02640 
02641       #-- send http_headers from meta
02642       if (is_array($data["meta"])) {
02643          foreach ($data["meta"] as $hdr=>$val) {
02644             if (($hdr[0] >= "A") && ($hdr[0] <= "Z")) {
02645                header("$hdr: $val");
02646             }
02647          }
02648       }
02649 
02650       #-- fetch from binary store
02651       if ($pf_a = $ewiki_plugins["binary_get"]) {
02652 #### CHANGED FOR MOODLE
02653         foreach ($pf_a as $pf) { $pf($id, $data["meta"]); }
02654 
02655 #### END CHANGED FOR MOODLE
02656       }
02657 
02658       #-- else fpassthru
02659       echo $data["content"];
02660    }
02661 
02662    #-- fetch & cache requested URL,
02663    elseif ($do == "cache") {
02664 
02665       #-- check for standard protocol names, to prevent us from serving
02666       #   evil requests for '/etc/passwd.jpeg' or '../.htaccess.gif'
02667       if (preg_match('@^\w?(http|ftp|https|ftps|sftp)\w?://@', $id)) {
02668 
02669          #-- generate local copy
02670          $filename = tempnam(EWIKI_TMP, "ewiki.local.temp.");
02671          if (($i = fopen($id, "rb")) && ($o = fopen($filename, "wb"))) {
02672 
02673             while (!feof($i)) {
02674                fwrite($o, fread($i, 65536));
02675             }
02676 
02677             fclose($i);
02678             fclose($o);
02679 
02680             $add_meta = array(
02681                "Content-Location" => urlencode($id),
02682                "Content-Disposition" => 'inline; filename="'.urlencode(basename($id)).'"'
02683             );
02684 
02685             $result = ewiki_binary_save_image($filename, $id, "RETURN", $add_meta);
02686          }
02687       }
02688 
02689       #-- deliver
02690       if ($result && !$break) {
02691          ewiki_binary($break=1);
02692       }
02693       #-- mark URL as unavailable
02694       else {
02695          $data = array(
02696             "id" => $id,
02697             "version" => 1,
02698             "flags" => EWIKI_DB_F_DISABLED,
02699             "lastmodified" => time(),
02700             "created" => time(),
02701             "author" => ewiki_author("ewiki_binary_cache"),
02702             "userid" => $USER->id,
02703             "content" => "",
02704             "meta" => array("Status"=>"404 Absent"),
02705          );
02706          ewiki_database("WRITE", $data);
02707          header("Location: $id");
02708          ewiki_log("imgcache: did not find '$id', and marked it now in database as DISABLED", 2);
02709       }
02710 
02711    }
02712 
02713    #-- "we don't sell this!"
02714    else {
02715       if (strpos($id, EWIKI_IDF_INTERNAL) === false) {
02716          header("Status: 301 Located SomeWhere Else");
02717          header("Location: $id");
02718       }
02719       else {
02720          header("Status: 404 Absent");
02721          header("X-Broken-URI: $id");
02722       }
02723    }
02724 
02725    // you should not remove this one, it is really a good idea to use it!
02726    die();
02727 }
02728 
02729 
02730 
02731 
02732 
02733 
02734 function ewiki_binary_save_image($filename, $id="", $return=0,
02735 $add_meta=array(), $accept_all=EWIKI_ACCEPT_BINARY, $care_for_images=1)
02736 {
02737    global $ewiki_plugins;
02738    global $USER;   // MOODLE
02739 
02740    #-- break on empty files
02741    if (!filesize($filename)) {
02742       return(false);
02743    }
02744 
02745    #-- check for image type and size
02746    $mime_types = array(
02747       "application/octet-stream",
02748       "image/gif",
02749       "image/jpeg",
02750       "image/png",
02751       "application/x-shockwave-flash"
02752    );
02753    $ext_types = array(
02754       "bin", "gif", "jpeg", "png", "swf"
02755    );
02756    list($width, $height, $mime_i, $uu) = getimagesize($filename);
02757    (!$mime_i) && ($mime_i=0) || ($mime = $mime_types[$mime_i]);
02758 
02759    #-- images expected
02760    if ($care_for_images) {
02761 
02762       #-- mime type
02763       if (!$mime_i && !$accept_all || !filesize($filename)) {
02764          ewiki_die(ewiki_t("BIN_NOIMG"), $return);
02765          return;
02766       }
02767 
02768       #-- resize image
02769       if (strpos($mime,"image/")!==false) {
02770       if ($pf_a = $ewiki_plugins["image_resize"]) {
02771       foreach ($pf_a as $pf) {
02772       if (EWIKI_IMAGE_RESIZE && (filesize($filename) > EWIKI_IMAGE_MAXSIZE)) {
02773          $pf($filename, $mime, $return);
02774          clearstatcache();
02775       }}}}
02776 
02777       #-- reject image if too large
02778       if (strlen($content) > EWIKI_IMAGE_MAXSIZE) {
02779          ewiki_die(ewiki_t("BIN_IMGTOOLARGE"), $return);
02780          return;
02781       }
02782 
02783       #-- again check mime type and image sizes
02784       list($width, $height, $mime_i, $uu) = getimagesize($filename);
02785       (!$mime_i) && ($mime_i=0) || ($mime = $mime_types[$mime_i]);
02786 
02787    }
02788    ($ext = $ext_types[$mime_i]) or ($ext = $ext_types[0]);
02789 
02790    #-- binary files
02791    if ((!$mime_i) && ($pf = $ewiki_plugins["mime_magic"][0])) {
02792       if ($tmp = $pf($content)) {
02793          $mime = $tmp;
02794       }
02795    }
02796    if (!strlen($mime)) {
02797       $mime = $mime_types[0];
02798    }
02799 
02800    #-- store size of binary file
02801    $add_meta["size"] = filesize($filename);
02802    $content = "";
02803 
02804    #-- handler for (large/) binary content?
02805    if ($pf_a = $ewiki_plugins["binary_store"]) {
02806       foreach ($pf_a as $pf) {
02807          $pf($filename, $id, $add_meta, $ext);
02808       }
02809    }
02810 
02811    #-- read file into memory (2MB), to store it into the database
02812    if ($filename) {
02813       $f = fopen($filename, "rb");
02814       $content = fread($f, 1<<21);
02815       fclose($f);
02816    }
02817 
02818    #-- generate db file name
02819    if (empty($id)) {
02820       $md5sum = md5($content);
02821       $id = EWIKI_IDF_INTERNAL . $md5sum . ".$ext";
02822       ewiki_log("generated md5sum '$md5sum' from file content");
02823    }
02824 
02825    #-- prepare meta data
02826    $meta = @array_merge(array(
02827       "class" => $mime_i ? "image" : "file",
02828       "Content-Type" => $mime,
02829       "Pragma" => "cache",
02830    ), $add_meta);
02831    if ($mime_i) {
02832       $meta["width"] = $width;
02833       $meta["height"] = $height;
02834    }
02835 
02836    #-- database entry
02837    $data = array(
02838       "id" => $id,
02839       "version" => "1",
02840       "author" => ewiki_author(),
02841       "userid" => $USER->id,
02842       "flags" => EWIKI_DB_F_BINARY | EWIKI_DB_F_READONLY,
02843       "created" => time(),
02844       "lastmodified" => time(),
02845       "meta" => &$meta,
02846       "content" => &$content,
02847    );
02848 
02849    #-- write if not exist
02850    $exists = ewiki_database("FIND", array($id));
02851    if (! $exists[$id] ) {
02852       $result = ewiki_database("WRITE", $data);
02853       ewiki_log("saving of '$id': " . ($result ? "ok" : "error"));
02854    }
02855    else {
02856       ewiki_log("binary_save_image: '$id' was already in the database", 2);
02857    }
02858 
02859    return($id);
02860 }
02861 
02862 
02863 
02864 
02865 # =========================================================================
02866 
02867 
02868 ####     ####  ####   ########     ########
02869 #####   #####  ####  ##########   ##########
02870 ###### ######  ####  ####   ###   ####    ###
02871 #############        ####        ####
02872 #############  ####   ########   ####
02873 #### ### ####  ####    ########  ####
02874 ####  #  ####  ####        ####  ####
02875 ####     ####  ####  ###   ####  ####    ###
02876 ####     ####  ####  #########    ##########
02877 ####     ####  ####   #######      ########
02878 
02879 
02880 
02881 /* yes! it is not neccessary to annoy users with country flags, if the
02882    http already provides means to determine preferred languages!
02883 */
02884 function ewiki_localization() {
02885 
02886    global $ewiki_t, $ewiki_plugins;
02887 
02888    $deflangs = ','.@$_ENV["LANGUAGE"] . ','.@$_ENV["LANG"]
02889              . ",".wiki_get_define('EWIKI_DEFAULT_LANG') . ",en,C";
02890 
02891    foreach (explode(",", @$_SERVER["HTTP_ACCEPT_LANGUAGE"].$deflangs) as $l) {
02892 
02893       $l = strtok($l, ";");
02894       $l = strtok($l, "-"); $l = strtok($l, "_"); $l = strtok($l, ".");
02895       $l = trim($l);
02896 
02897       $ewiki_t["languages"][] = strtolower($l);
02898    }
02899 }
02900 
02901 
02902 
02903 
02904 /* poor mans gettext, $repl is an array of string replacements to get
02905    applied to the fetched text chunk,
02906    "$const" is either an entry from $ewiki_t[] or a larger text block
02907    containing _{text} replacement braces of the form "_{...}"
02908 */
02909 function ewiki_t($const, $repl=array(), $pref_langs=array()) {
02910    ##### BEGIN MOODLE ADDITION #####
02911    $replacechars=array("." => "",
02912                        "," => "",
02913                        "!" => "",
02914                        ";" => "",
02915                        ":" => "",
02916                        "'" => "",
02917                        '"' => "",
02918                        "-" => "",
02919                        "_" => "",
02920                        " " => "",
02921                        "+" => "");
02922 
02923    $translation=get_string(strtolower(strtr($const,$replacechars)),"wiki",$repl);
02924    return $translation;
02925    ##### END MOODLE ADDITION #####
02926 
02927 /*   global $ewiki_t;
02928 
02929    #-- use default language wishes
02930    if (empty($pref_langs)) {
02931       $pref_langs = $ewiki_t["languages"];
02932    }
02933 
02934    #-- large text snippet replaceing
02935    if (strpos($const, "_{") !== false) {
02936       while ( (($l=strpos($const,"_{")) || ($l===0)) && ($r=strpos($const,"}",$l)) ) {
02937          $const = substr($const, 0, $l)
02938                 . ewiki_t(substr($const, $l+2, $r-$l-2))
02939                 . substr($const,$r+1);
02940       }
02941    }
02942 
02943    #-- just one string
02944    else foreach ($pref_langs as $l) {
02945 
02946       if (is_string($r = @$ewiki_t[$l][$const]) || ($r = @$ewiki_t[$l][strtoupper($const)])) {
02947 
02948          foreach ($repl as $key=>$value) {
02949             if ($key[0] != '$') {
02950                $key = '$'.$key;
02951             }
02952             $r = str_replace($key, $value, $r);
02953          }
02954          return($r);
02955 
02956       }
02957    }
02958 
02959    return($const);*/
02960 }
02961 
02962 
02963 
02964 
02965 
02966 
02967 function ewiki_log($msg, $error_type=3) {
02968 
02969    if ((EWIKI_LOGLEVEL >= 0) && ($error_type <= EWIKI_LOGLEVEL)) {
02970 
02971       $msg = time() . " - " .
02972              getremoteaddr() . ":" . $_SERVER["REMOTE_PORT"] . " - " .
02973              $_SERVER["REQUEST_METHOD"] . " " . $_SERVER["REQUEST_URI"] . " - " .
02974              strtr($msg, "\n\r\000\377\t\f", "\r\r\r\r\t\f") . "\n";
02975       error_log($msg, 3, EWIKI_LOGFILE);
02976    }
02977 }
02978 
02979 
02980 
02981 
02982 function ewiki_die($msg, $return=0) {
02983    ewiki_log($msg, 1);
02984    if ($return) {
02985       return($GLOBALS["ewiki_error"] = $msg);
02986    }
02987    else {
02988       die($msg);
02989    }
02990 }
02991 
02992 
02993 
02994 function ewiki_array_hash(&$a) {
02995    return(count($a) . ":" . implode(":", array_keys(array_slice($a, 0, 3))));
02996 }
02997 
02998 
02999 
03000 /* provides an case-insensitive in_array replacement to search a page name
03001    in a list of others;
03002    the supplied $array WILL be lowercased afterwards, unless $dn was set
03003 */
03004 function ewiki_in_array($value, &$array, $dn=0, $ci=EWIKI_CASE_INSENSITIVE) {
03005 
03006    static $as = array();
03007 
03008    #-- work around pass-by-reference
03009    if ($dn && $ci) {   $dest = array();   }
03010               else {   $dest = &$array;   }
03011 
03012    #-- make everything lowercase
03013    if ($ci) {
03014       $value = strtolower($value);
03015       if (empty($as[ewiki_array_hash($array)])) {  // prevent working on the
03016          foreach ($array as $i=>$v) {              // same array multiple times
03017             $dest[$i] = strtolower($v);
03018          }
03019          $as[ewiki_array_hash($dest)] = 1;
03020       }
03021    }
03022 
03023    #-- search in values
03024    return(in_array($value, $dest));
03025 }
03026 
03027 
03028 
03029 /* case-insensitively retrieves an entry from an $array,
03030    or returns the given $array lowercased if $key was obmitted
03031 */
03032 function ewiki_array($array, $key=false, $am=1, $ci=EWIKI_CASE_INSENSITIVE) {
03033 
03034    #-- make everything lowercase
03035    if ($ci) {
03036       $key = strtolower($key);
03037 
03038       $r = array();
03039       foreach ($array as $i=>$v) {
03040          $i = strtolower($i);
03041          if (!$am || empty($r[$i])) {
03042             $r[$i] = $v;
03043          }
03044          else {
03045             $r[$i] .= $v;   //RET: doubling for images`meta won't happen
03046          }          // but should be "+" here for integers
03047       }
03048       $array = &$r;
03049    }
03050 
03051    #-- search in values
03052    if ($key) {
03053       return(@$array[$key]);
03054    }
03055    else {
03056       return($array);
03057    }
03058 }
03059 
03060 
03061 
03062 
03063 
03064 
03065 function ewiki_author($defstr="") {
03066 
03067    $author = @$GLOBALS["ewiki_author"];
03068    ($ip = getremoteaddr()) or ($ip = "127.0.0.0");
03069    ($port = $_SERVER["REMOTE_PORT"]) or ($port = "null");
03070    $hostname = $ip;
03071    $remote = (($ip != $hostname) ? $hostname . " " : "")
03072            . $ip . ":" . $port;
03073 
03074    (empty($author)) && (
03075       ($author = $defstr) ||
03076       ($author = $_SERVER["HTTP_FROM"]) ||  // RFC2068 sect 14.22
03077       ($author = $_SERVER["PHP_AUTH_USER"])
03078    );
03079 
03080    (empty($author))
03081       && ($author = $remote)
03082       || ($author = $author . " (" . $remote . ")" );
03083 
03084    return($author);
03085 }
03086 
03087 
03088 
03089 
03090 
03091 /*  Returns a value of (true) if the currently logged in user (this must
03092     be handled by one of the plugin backends) is authenticated to do the
03093     current $action, or to view the current $id page.
03094   - alternatively just checks current authentication $ring permission level
03095   - errors are returned via the global $ewiki_errmsg
03096 */
03097 function ewiki_auth($id, &$data, $action, $ring=false, $request_auth=0) {
03098 
03099    global $ewiki_plugins, $ewiki_ring, $ewiki_author, $ewiki_errmsg;
03100    $ok = true;
03101    $ewiki_errmsg="";
03102 
03103 #echo "_a($id,dat,$action,$ring,$request_auth)<br />\n";
03104 
03105    if (EWIKI_PROTECTED_MODE) {
03106 
03107       #-- set required vars
03108       if (!isset($ewiki_ring)) {
03109          $ewiki_ring = (int)EWIKI_AUTH_DEFAULT_RING;
03110       }
03111       if ($ring===false) {
03112          $ring = NULL;
03113       }
03114 
03115       #-- plugins to call
03116       $pf_login = @$ewiki_plugins["auth_query"][0];
03117       $pf_perm = $ewiki_plugins["auth_perm"][0];
03118 
03119       #-- nobody is currently logged in, so try to fetch username,
03120       #   the login <form> is not yet enforced
03121       if ($pf_login && empty($ewiki_auth_user)) {
03122          $pf_login($data, 0);
03123       }
03124 
03125       #-- check permission for current request (page/action/ring)
03126       if ($pf_perm) {
03127 
03128          #-- via _auth handler
03129          $ok = $pf_perm($id, $data, $action, $ring, $request_auth);
03130 
03131          #-- if it failed, we really depend on the login <form>,
03132          #   and then recall the _perm plugin
03133          if ($pf_login && (($request_auth >= 2) || !$ok && $request_auth && (empty($ewiki_auth_user) || EWIKI_AUTO_LOGIN) && empty($ewiki_errmsg))) {
03134 //@FIXME: complicated if()  - strip empty(errmsg) ??
03135             $pf_login($data, $request_auth);
03136             $ok = $pf_perm($id, $data, $action, $ring, $request_auth=0);
03137          }
03138       }
03139       else {
03140          $ok = !isset($ring) || isset($ring) && ($ewiki_ring <= $ring);
03141       }
03142 
03143       #-- return error string
03144       if (!$ok && empty($ewiki_errmsg)) {
03145          $ewiki_errmsg = ewiki_t("FORBIDDEN");
03146       }
03147    }
03148 
03149    return($ok);
03150 }
03151 
03152 
03153 /*
03154    Queries all registered ["auth_userdb"] plugins for the given
03155    username, and compares password to against "db" value, sets
03156    $ewiki_ring and returns(true) if valid.
03157 */
03158 function ewiki_auth_user($username, $password) {
03159   global $ewiki_ring, $ewiki_errmsg, $ewiki_auth_user, $ewiki_plugins, $ewiki_author;
03160 
03161   if (empty($username)) {
03162      return(false);
03163   }
03164   if (($password[0] == "$") || (strlen($password) > 12)) {
03165      ewiki_log("_auth_userdb: password was transmitted in encoded form, or is just too long (login attemp for user '$username')", 2);
03166      return(false);
03167   }
03168 
03169   if ($pf_u = $ewiki_plugins["auth_userdb"])
03170   foreach ($pf_u as $pf) {
03171 
03172      if (function_exists($pf) && ($entry = $pf($username, $password))) {
03173 
03174         #-- get and compare password
03175         if ($entry = (array) $entry) {
03176            $enc_pw = $entry[0];
03177         }
03178         $success = false
03179                 || ($enc_pw == substr($password, 0, 12))
03180                 || ($enc_pw == md5($password))
03181                 || ($enc_pw == crypt($password, substr($enc_pw, 0, 2)))
03182                 || function_exists("sha1") && ($enc_pw == sha1($password));
03183         $success &= $enc_pw != "*";
03184 
03185         #-- return if it matches
03186         if ($success) {
03187            if (isset($entry[1])) {
03188               $ewiki_ring = (int)($entry[1]);
03189            } else {
03190               $ewiki_ring = 2;  //(EWIKI_AUTH_DEFAULT_RING - 1);
03191            }
03192            if (empty($ewiki_author)) {
03193               ($ewiki_author = $entry[2]) or
03194               ($ewiki_author = $username);
03195            }
03196            return($success && ($ewiki_auth_user=$username));
03197         }
03198      }
03199   }
03200 
03201   if ($username || $password) {
03202      ewiki_log("_auth_userdb: wrong password supplied for user '$username', not verified against any userdb", 3);
03203      $ewiki_errmsg = "wrong username and/or password";
03204 #     ewiki_auth($uu, $uu, $uu, $uu, 2);
03205   }
03206   return(false);
03207 }
03208 
03209 
03210 
03211 
03212 
03213 /*  reads all files from "./init-pages/" into the database,
03214     when ewiki is run for the very first time and the FrontPage
03215     does not yet exist in the database
03216 */
03217 function ewiki_eventually_initialize(&$id, &$data, &$action) {
03218 
03219    global $USER;
03220 
03221    #-- initialize database only if frontpage missing
03222    if (($id==EWIKI_PAGE_INDEX) && ($action=="edit") && empty($data["version"])) {
03223 
03224       ewiki_database("INIT", array());
03225 #### BEGIN MOODLE CHANGE
03226       $path=EWIKI_INIT_PAGES;
03227       if (!empty($path)) {
03228         if ($dh = @opendir($path=EWIKI_INIT_PAGES)) {
03229          while (false !== ($filename = readdir($dh))) {
03230 #### MOODLE CHANGE TO SOLVE BUG #3830. Original doesn't support dots in names.
03231     //Orig->if (preg_match('/^(['.EWIKI_CHARS_U.']+['.EWIKI_CHARS_L.']+\w*)+/', $filename)) {
03232             if ($filename == clean_filename($filename) && !is_dir($path.'/'.$filename)) {
03233 #### END OF MOODLE CHANGE TO SOLVE BUG #3830. Original doesn't support dots in names.
03234                $found = ewiki_database("FIND", array($filename));
03235                if (! $found[$filename]) {
03236                   $content = implode("", file("$path/$filename"));
03237                   ewiki_scan_wikiwords($content, $ewiki_links, "_STRIP_EMAIL=1");
03238                   $refs = "\n\n" . implode("\n", array_keys($ewiki_links)) . "\n\n";
03239                   $save = array(
03240                      "id" => "$filename",
03241                      "version" => "1",
03242                      "flags" => "1",
03243                      "content" => $content,
03244                      "author" => ewiki_author("ewiki_initialize"),
03245                      "userid" => $USER->id,
03246                      "refs" => $refs,
03247                      "lastmodified" => filemtime("$path/$filename"),
03248                      "created" => filectime("$path/$filename")   // (not exact)
03249                   );
03250                   ewiki_database("WRITE", $save);
03251                }
03252             }
03253          }
03254          closedir($dh);
03255         }
03256         else {
03257          echo "<b>ewiki error</b>: could not read from directory ". realpath($path) ."<br />\n";
03258         }
03259       }
03260 #### END MOODLE CHANGE
03261 
03262       #-- try to view/ that newly inserted page
03263       if ($data = ewiki_database("GET", array("id"=>$id))) {
03264          $action = "view";
03265       }
03266    }
03267 }
03268 
03269 
03270 
03271 
03272 #---------------------------------------------------------------------------
03273 
03274 
03275 
03276 ########     ###    ########    ###    ########     ###     ######  ########
03277 ########     ###    ########    ###    ########     ###     ######  ########
03278 ##     ##   ## ##      ##      ## ##   ##     ##   ## ##   ##    ## ##
03279 ##     ##   ## ##      ##      ## ##   ##     ##   ## ##   ##    ## ##
03280 ##     ##  ##   ##     ##     ##   ##  ##     ##  ##   ##  ##       ##
03281 ##     ##  ##   ##     ##     ##   ##  ##     ##  ##   ##  ##       ##
03282 ##     ## ##     ##    ##    ##     ## ########  ##     ##  ######  ######
03283 ##     ## ##     ##    ##    ##     ## ########  ##     ##  ######  ######
03284 ##     ## #########    ##    ######### ##     ## #########       ## ##
03285 ##     ## #########    ##    ######### ##     ## #########       ## ##
03286 ##     ## ##     ##    ##    ##     ## ##     ## ##     ## ##    ## ##
03287 ##     ## ##     ##    ##    ##     ## ##     ## ##     ## ##    ## ##
03288 ########  ##     ##    ##    ##     ## ########  ##     ##  ######  ########
03289 ########  ##     ##    ##    ##     ## ########  ##     ##  ######  ########
03290 
03291 
03292 
03293 
03294 /*  wrapper
03295 */
03296 function ewiki_database($action, $args, $sw1=0, $sw2=0, $pf=false) {
03297 
03298    #-- normalize (fetch bad parameters)
03299    if (($action=="GET") && !is_array($args) && is_string($args)) {
03300       $args = array("id" => $args);
03301    }
03302 
03303    #-- treat special
03304    switch ($action) {
03305 
03306       case "GETALL":
03307          $args = array_unique(@array_merge($args, array("flags", "version")));
03308          $args = array_diff($args, array("id"));
03309          break;
03310 
03311       case "SEARCH":
03312 #         unset($args["version"]);
03313 #         unset($args["flags"]);
03314          break;
03315 
03316       default:
03317          break;
03318    }
03319 
03320    #-- handle {meta} sub array as needed
03321    if (is_array(@$args["meta"])) {
03322       $args["meta"] = serialize($args["meta"]);
03323    }
03324 
03325    #-- database plugin
03326    if (($pf) || ($pf = @$GLOBALS["ewiki_plugins"]["database"][0])) {
03327       $r = $pf($action, $args, $sw1, $sw2);
03328    }
03329    else {
03330       ewiki_log("DB layer: no backend!", 0);
03331       $r = false;
03332    }
03333 
03334    #-- database layer generation 2 abstraction
03335    if (is_array($r) && (($action=="SEARCH") || ($action=="GETALL"))) {
03336       $z = new ewiki_dbquery_result(array_keys($args));
03337       foreach ($r as $id=>$row) {
03338          $z->add($row);
03339       }
03340       $r = $z;
03341    }
03342 
03343    #-- extract {meta} sub array
03344    if (is_array($r) && !is_array(@$r["meta"]) && strlen(@$r["meta"])) {
03345       $r["meta"] = unserialize($r["meta"]);
03346    }
03347 
03348    return($r);
03349 }
03350 
03351 
03352 
03353 /*  returned for SEARCH and GETALL queries, as those operations are
03354     otherwise too memory exhaustive
03355 */
03356 class ewiki_dbquery_result {
03357 
03358    var $keys = array();
03359    var $entries = array();
03360    var $buffer = EWIKI_DBQUERY_BUFFER;
03361    var $size = 0;
03362 
03363    function ewiki_dbquery_result($keys) {
03364       $keys = @array_merge($keys, array(-50=>"id", "version", "flags"));
03365       $this->keys = array_unique($keys);
03366    }
03367 
03368    function add($row) {
03369       if (is_array($row)) {
03370          if ($this->buffer) {
03371             $this->size += strlen(serialize($row));
03372             $this->buffer = $this->size <= EWIKI_DBQUERY_BUFFER;
03373          }
03374          else {
03375             $row = $row["id"];
03376          }
03377       }
03378       $this->entries[] = $row;
03379    }
03380 
03381    function get($all=0, $flags=0x00) {
03382       $row = array();
03383 
03384       $prot_hide = ($flags&0x0020) && EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING;
03385       do {
03386          if (count($this->entries)) {
03387 
03388             #-- fetch very first entry from $entries list
03389             $r = array_shift($this->entries);
03390 
03391             #-- finish if buffered entry
03392             if (is_array($r) && !$all) {
03393                $row = $r;
03394             }
03395             #-- else refetch complete entry from database
03396             else {
03397                if (is_array($r)) {
03398                   $r = $r["id"];
03399                }
03400                $r = ewiki_database("GET", array("id"=>$r));
03401                if (!$all) {
03402                   foreach ($this->keys as $key) {
03403                      $row[$key] = $r[$key];
03404                   }
03405                } else {
03406                   $row = $r;
03407                }
03408             }
03409             unset($r);
03410          }
03411          else {
03412             return(NULL);  // no more entries
03413          }
03414 
03415          #-- expand {meta} field
03416          if (is_array($row) && is_string(@$row["meta"])) {
03417             $row["meta"] = unserialize($row["meta"]);
03418          }
03419 
03420          #-- drop unwanted results
03421          if ($prot_hide && !ewiki_auth($row["id"], $row, $ewiki_action)) {
03422             $row = array();
03423          }
03424       } while ($prot_hide && empty($row));
03425 
03426       return($row);
03427    }
03428 
03429    function count() {
03430       return(count($this->entries));
03431    }
03432 }
03433 
03434 
03435 
03436 /*  MySQL database backend
03437     (default)
03438     Note: this is of course an abuse of the relational database scheme,
03439     but neccessary for real db independence and abstraction
03440 */
03441 function ewiki_database_mysql($action, &$args, $sw1, $sw2) {
03442 
03443    #-- reconnect to the database (if multiple are used)
03444    #<off>#  mysql_ping($GLOBALS["db"]);
03445 
03446    #-- result array
03447    $r = array();
03448 
03449    switch($action) {
03450 
03451       /*  Returns database entry as array for the page whose name was given
03452           with the "id" key in the $args array, usually fetches the latest
03453           version of a page, unless a specific "version" was requested in
03454           the $args array.
03455       */
03456       case "GET":
03457          $id = "'" . mysql_escape_string($args["id"]) . "'";
03458          ($version = 0 + @$args["version"]) and ($version = "AND (version=$version)") or ($version="");
03459          $result = mysql_query("SELECT * FROM " . EWIKI_DB_TABLE_NAME
03460             . " WHERE (pagename=$id) $version  ORDER BY version DESC  LIMIT 1"
03461          );
03462          if ($result && ($r = mysql_fetch_array($result, MYSQL_ASSOC))) {
03463             $r["id"] = $r["pagename"];
03464             unset($r["pagename"]);
03465          }
03466          if (strlen($r["meta"])) {
03467             $r["meta"] = @unserialize($r["meta"]);
03468          }
03469          break;
03470 
03471 
03472 
03473       /*  Increases the hit counter for the page name given in $args array
03474           with "id" index key.
03475       */
03476       case "HIT":
03477          mysql_query("UPDATE " . EWIKI_DB_TABLE_NAME . " SET hits=(hits+1) WHERE pagename='" . mysql_escape_string($args["id"]) . "'");
03478          break;
03479 
03480 
03481 
03482       /*  Stores the $data array into the database, while not overwriting
03483           existing entries (using WRITE); returns 0 on failure and 1 if
03484           saved correctly.
03485       */
03486       case "OVERWRITE":     // fall-through
03487          $COMMAND = "REPLACE";
03488 
03489       case "WRITE":
03490          $args["pagename"] = $args["id"];
03491          unset($args["id"]);
03492 
03493          if (is_array($args["meta"])) {
03494             $args["meta"] = serialize($args["meta"]);
03495          }
03496 
03497          $sql1 = $sql2 = "";
03498          foreach ($args as $index => $value) {
03499             if (is_int($index)) {
03500                continue;
03501             }
03502             $a = ($sql1 ? ', ' : '');
03503             $sql1 .= $a . $index;
03504             $sql2 .= $a . "'" . mysql_escape_string($value) . "'";
03505          }
03506 
03507          strlen(@$COMMAND) || ($COMMAND = "INSERT");
03508 
03509          $result = mysql_query("$COMMAND INTO " . EWIKI_DB_TABLE_NAME .
03510             " (" . $sql1 . ") VALUES (" . $sql2 . ")"
03511          );
03512 
03513          return($result && mysql_affected_rows() ?1:0);
03514          break;
03515 
03516 
03517 
03518       /*  Checks for existence of the WikiPages whose names are given in
03519           the $args array. Returns an array with the specified WikiPageNames
03520           associated with values of "0" or "1" (stating if the page exists
03521           in the database). For images/binary db entries returns the "meta"
03522           field instead of an "1".
03523       */
03524       case "FIND":
03525          $sql = "";
03526          foreach (array_values($args) as $id) if (strlen($id)) {
03527             $r[$id] = 0;
03528             $sql .= ($sql ? " OR " : "") .
03529                     "(pagename='" . mysql_escape_string($id) . "')";
03530          }
03531          $result = mysql_query($sql = "SELECT pagename AS id, meta FROM " .
03532             EWIKI_DB_TABLE_NAME . " WHERE $sql "
03533          );
03534          while ($result && ($row = mysql_fetch_row($result))) {
03535             $r[$row[0]] = strpos($row[1], 's:5:"image"') ? $row[1] : 1;
03536          }
03537          break;
03538 
03539 
03540 
03541       /*  Returns an array of __all__ pages, where each entry is made up
03542           of the fields from the database requested with the $args array,
03543           e.g. array("flags","meta","lastmodified");
03544       */
03545       case "GETALL":
03546          $result = mysql_query("SELECT pagename AS id, ".
03547             implode(", ", $args) .
03548             " FROM ". EWIKI_DB_TABLE_NAME .
03549             " GROUP BY id, version DESC"
03550          );
03551          $r = new ewiki_dbquery_result($args);
03552          $drop = "";
03553          while ($result && ($row = mysql_fetch_array($result, MYSQL_ASSOC))) {
03554             $i = EWIKI_CASE_INSENSITIVE ? strtolower($row["id"]) : $row["id"];
03555             if ($i != $drop) {
03556                $drop = $i;
03557                $r->add($row);
03558             }
03559          }
03560          break;
03561 
03562 
03563 
03564       /*  Returns array of database entries (also arrays), where the one
03565           specified column matches the specified content string, for example
03566           $args = array("content" => "text...piece")
03567           is not guaranteed to only search/return the latest version of a page
03568       */
03569       case "SEARCH":
03570          $field = implode("", array_keys($args));
03571          $content = strtolower(implode("", $args));
03572          if ($field == "id") { $field = "pagename"; }
03573 
03574          $result = mysql_query("SELECT pagename AS id, version, flags" .
03575             (EWIKI_DBQUERY_BUFFER && ($field!="pagename") ? ", $field" : "") .
03576             " FROM " . EWIKI_DB_TABLE_NAME .
03577             " WHERE LOCATE('" . mysql_escape_string($content) . "', LCASE($field)) " .
03578             " GROUP BY id, version DESC"
03579          );
03580          $r = new ewiki_dbquery_result(array("id","version",$field));
03581          $drop = "";
03582          while ($result && ($row = mysql_fetch_array($result, MYSQL_ASSOC))) {
03583             $i = EWIKI_CASE_INSENSITIVE ? strtolower($row["id"]) : $row["id"];
03584             if ($i != $drop) {
03585                $drop = $i;
03586                $r->add($row);
03587             }
03588          }
03589          break;
03590 
03591 
03592 
03593       case "DELETE":
03594          $id = mysql_escape_string($args["id"]);
03595          $version = $args["version"];
03596          mysql_query("DELETE FROM " . EWIKI_DB_TABLE_NAME ."
03597             WHERE pagename='$id' AND version=$version");
03598          break;
03599 
03600 
03601 
03602       case "INIT":
03603          mysql_query("CREATE TABLE " . EWIKI_DB_TABLE_NAME ."
03604             (pagename VARCHAR(160) NOT NULL,
03605             version INTEGER UNSIGNED NOT NULL DEFAULT 0,
03606             flags INTEGER UNSIGNED DEFAULT 0,
03607             content MEDIUMTEXT,
03608             author VARCHAR(100) DEFAULT 'ewiki',
03609             userid INTEGER UNSIGNED DEFAULT 0,
03610             created INTEGER UNSIGNED DEFAULT ".time().",
03611             lastmodified INTEGER UNSIGNED DEFAULT 0,
03612             refs MEDIUMTEXT,
03613             meta MEDIUMTEXT,
03614             hits INTEGER UNSIGNED DEFAULT 0,
03615             PRIMARY KEY id (pagename, version) )
03616             ");
03617          echo mysql_error();
03618          break;
03619 
03620       default:
03621    }
03622 
03623    return($r);
03624 }
03625 
03626 ?>
 All Data Structures Namespaces Files Functions Variables Enumerations