[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/mod/wiki/ewiki/ -> ewiki.php (source)

   1  <?php
   2  @define("EWIKI_VERSION", "R1.01d");
   3  
   4  /*
   5  
   6    ErfurtWiki - an embedable, fast and user-friendly wiki engine
   7    ---------
   8    This is Public Domain (no license, no warranty); but feel free
   9    to redistribute it under GPL or anything else you like.
  10  
  11    http://erfurtwiki.sourceforge.net/
  12    Mario Salzer <mario*erphesfurt·de> and many others(tm)
  13  
  14  
  15    Use it from inside yoursite.php like that:
  16    <html><body>...
  17    <?php
  18       include("ewiki.php");
  19       echo ewiki_page();
  20    ?>
  21  
  22  */
  23  
  24  #-- you could also establish a mysql connection in here, of course:
  25  // mysql_connect(":/var/run/mysqld/mysqld.sock", "user", "pw")
  26  // and mysql_query("USE mydatabase");
  27  
  28  
  29          #-------------------------------------------------------- config ---
  30  
  31          #-- I'm sorry for that, but all the @ annoy me
  32          error_reporting(0x0000377 & error_reporting());
  33  #   error_reporting(E_ALL^E_NOTICE);
  34  
  35      #-- the position of your ewiki-wrapper script
  36      define("EWIKI_SCRIPT", "?id=");     # relative/absolute to docroot
  37  #   define("EWIKI_SCRIPT_URL", "http://...?id=");       # absolute URL
  38  
  39          #-- change to your needs (site lang)
  40      define("EWIKI_NAME", "ErfurtWiki");
  41      define("EWIKI_PAGE_INDEX", "ErfurtWiki");
  42      define("EWIKI_PAGE_NEWEST", "NewestPages");
  43      define("EWIKI_PAGE_SEARCH", "SearchPages");
  44      define("EWIKI_PAGE_HITS", "MostVisitedPages");
  45      define("EWIKI_PAGE_VERSIONS", "MostOftenChangedPages");
  46      define("EWIKI_PAGE_UPDATES", "UpdatedPages");
  47  
  48      #-- default settings are good settings - most often ;)
  49          #- look & feel
  50      define("EWIKI_PRINT_TITLE", 1);     # <h2>WikiPageName</h2> on top
  51      define("EWIKI_SPLIT_TITLE", 0);     # <h2>Wiki Page Name</h2>
  52      define("EWIKI_CONTROL_LINE", 1);    # EditThisPage-link at bottom
  53      define("EWIKI_LIST_LIMIT", 20);     # listing limit
  54          #- behaviour
  55      define("EWIKI_AUTO_EDIT", 1);       # edit box for non-existent pages
  56      define("EWIKI_EDIT_REDIRECT", 1);   # redirect after edit save
  57      define("EWIKI_DEFAULT_ACTION", "view"); # (keep!)
  58      define("EWIKI_CASE_INSENSITIVE", 1);    # wikilink case sensitivity
  59      define("EWIKI_HIT_COUNTING", 1);
  60      define("UNIX_MILLENNIUM", 1000000000);
  61          #- rendering
  62      define("EWIKI_ALLOW_HTML", 0);      # often a very bad idea
  63      define("EWIKI_HTML_CHARS", 1);      # allows for &#200;
  64      define("EWIKI_ESCAPE_AT", 1);       # "@" -> "&#x40;"
  65          #- http/urls
  66      define("EWIKI_HTTP_HEADERS", 1);    # most often a good thing
  67      define("EWIKI_NO_CACHE", 1);        # browser+proxy shall not cache
  68      define("EWIKI_URLENCODE", 1);       # disable when _USE_PATH_INFO
  69      define("EWIKI_URLDECODE", 1);
  70      define("EWIKI_USE_PATH_INFO", 1  &&!strstr($_SERVER["SERVER_SOFTWARE"],"Apache"));
  71      define("EWIKI_USE_ACTION_PARAM", 1);
  72      define("EWIKI_ACTION_SEP_CHAR", "/");
  73      define("EWIKI_UP_PAGENUM", "n");    # _UP_ means "url parameter"
  74      define("EWIKI_UP_PAGEEND", "e");
  75      define("EWIKI_UP_BINARY", "binary");
  76      define("EWIKI_UP_UPLOAD", "upload");
  77          #- other stuff
  78          define("EWIKI_DEFAULT_LANG", "en");
  79          define("EWIKI_CHARSET", "UTF-8");
  80      #- user permissions
  81      define("EWIKI_PROTECTED_MODE", 0);  # disable funcs + require auth
  82      define("EWIKI_PROTECTED_MODE_HIDING", 0);  # hides disallowed actions
  83      define("EWIKI_AUTH_DEFAULT_RING", 3);   # 0=root 1=priv 2=user 3=view
  84      define("EWIKI_AUTO_LOGIN", 1);      # [auth_query] on startup
  85  
  86      #-- allowed WikiPageNameCharacters
  87  
  88  #### BEGIN MOODLE CHANGES - to remove auto-camelcase linking.   
  89      global $moodle_disable_camel_case;   
  90      if ($moodle_disable_camel_case) {
  91          define("EWIKI_CHARS_L", "");
  92          define("EWIKI_CHARS_U", "");
  93      }
  94      else {
  95  #### END MOODLE CHANGES
  96  
  97      define("EWIKI_CHARS_L", "a-z_µ¤$\337-\377");
  98      define("EWIKI_CHARS_U", "A-Z0-9\300-\336");
  99  
 100  #### BEGIN MOODLE CHANGES   
 101      }
 102  #### END MOODLE CHANGES
 103     
 104      define("EWIKI_CHARS", EWIKI_CHARS_L.EWIKI_CHARS_U);
 105  
 106          #-- database
 107      define("EWIKI_DB_TABLE_NAME", "ewiki");      # MySQL / ADOdb
 108      define("EWIKI_DBFILES_DIRECTORY", "/tmp");   # see "db_flat_files.php"
 109      define("EWIKI_DBA", "/tmp/ewiki.dba");       # see "db_dba.php"
 110      define("EWIKI_DBQUERY_BUFFER", 512*1024);    # 512K
 111      define("EWIKI_INIT_PAGES", "./init-pages");  # for initialization
 112  
 113      define("EWIKI_DB_F_TEXT", 1<<0);
 114      define("EWIKI_DB_F_BINARY", 1<<1);
 115      define("EWIKI_DB_F_DISABLED", 1<<2);
 116      define("EWIKI_DB_F_HTML", 1<<3);
 117      define("EWIKI_DB_F_READONLY", 1<<4);
 118      define("EWIKI_DB_F_WRITEABLE", 1<<5);
 119      define("EWIKI_DB_F_APPENDONLY", 1<<6);  #nyi
 120      define("EWIKI_DB_F_SYSTEM", 1<<7);
 121      define("EWIKI_DB_F_PART", 1<<8);
 122      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);
 123      define("EWIKI_DB_F_ACCESS", EWIKI_DB_F_READONLY | EWIKI_DB_F_WRITEABLE | EWIKI_DB_F_APPENDONLY);
 124      define("EWIKI_DB_F_COPYMASK", EWIKI_DB_F_TYPE | EWIKI_DB_F_ACCESS);
 125  
 126      define("EWIKI_DBFILES_NLR", '\\n');
 127      define("EWIKI_DBFILES_ENCODE", 0 || (DIRECTORY_SEPARATOR != "/"));
 128      define("EWIKI_DBFILES_GZLEVEL", "2");
 129  
 130      #-- internal
 131      define("EWIKI_ADDPARAMDELIM", (strstr(EWIKI_SCRIPT,"?") ? "&" : "?"));
 132  
 133      #-- binary content (images)
 134      define("EWIKI_SCRIPT_BINARY", /*"/binary.php?binary="*/  ltrim(strtok(" ".EWIKI_SCRIPT,"?"))."?".EWIKI_UP_BINARY."="  );
 135      define("EWIKI_CACHE_IMAGES", 1  &&!headers_sent());
 136      define("EWIKI_IMAGE_MAXSIZE", 64 *1024);
 137      define("EWIKI_IMAGE_MAXWIDTH", 3072);
 138      define("EWIKI_IMAGE_MAXHEIGHT", 2048);
 139      define("EWIKI_IMAGE_MAXALLOC", 1<<19);
 140      define("EWIKI_IMAGE_RESIZE", 1);
 141      define("EWIKI_IMAGE_ACCEPT", "image/jpeg,image/png,image/gif,application/x-shockwave-flash");
 142      define("EWIKI_IDF_INTERNAL", "internal://");
 143      define("EWIKI_ACCEPT_BINARY", 0);   # for arbitrary binary data files
 144  
 145      #-- misc
 146          define("EWIKI_TMP", $_SERVER["TEMP"] ? $_SERVER["TEMP"] : "/tmp");
 147      define("EWIKI_LOGLEVEL", -1);       # 0=error 1=warn 2=info 3=debug
 148      define("EWIKI_LOGFILE", "/tmp/ewiki.log");
 149  
 150      #-- plugins (tasks mapped to function names)
 151      $ewiki_plugins["database"][] = "ewiki_database_mysql";
 152      $ewiki_plugins["edit_preview"][] = "ewiki_page_edit_preview";
 153      $ewiki_plugins["render"][] = "ewiki_format";
 154      $ewiki_plugins["init"][-5] = "ewiki_localization";
 155      $ewiki_plugins["init"][-1] = "ewiki_binary";
 156          $ewiki_plugins["handler"][-105] = "ewiki_eventually_initialize";
 157          $ewiki_plugins["handler"][] = "ewiki_intermap_walking";
 158      $ewiki_plugins["view_append"][-1] = "ewiki_control_links";
 159          $ewiki_plugins["view_final"][-1] = "ewiki_add_title";
 160          $ewiki_plugins["page_final"][] = "ewiki_http_headers";
 161          $ewiki_plugins["page_final"][99115115] = "ewiki_page_css_container";
 162      $ewiki_plugins["edit_form_final"][] = "ewiki_page_edit_form_final_imgupload";
 163          $ewiki_plugins["format_block"]["pre"][] = "ewiki_format_pre";
 164          $ewiki_plugins["format_block"]["code"][] = "ewiki_format_pre";
 165          $ewiki_plugins["format_block"]["htm"][] = "ewiki_format_html";
 166          $ewiki_plugins["format_block"]["html"][] = "ewiki_format_html";
 167          $ewiki_plugins["format_block"]["comment"][] = "ewiki_format_comment";
 168  
 169  
 170      #-- internal pages
 171      $ewiki_plugins["page"][EWIKI_PAGE_NEWEST] = "ewiki_page_newest";
 172      $ewiki_plugins["page"][EWIKI_PAGE_SEARCH] = "ewiki_page_search";
 173      if (EWIKI_HIT_COUNTING) $ewiki_plugins["page"][EWIKI_PAGE_HITS] = "ewiki_page_hits";
 174      $ewiki_plugins["page"][EWIKI_PAGE_VERSIONS] = "ewiki_page_versions";
 175      $ewiki_plugins["page"][EWIKI_PAGE_UPDATES] = "ewiki_page_updates";
 176  
 177      #-- page actions
 178      $ewiki_plugins["action"]["edit"] = "ewiki_page_edit";
 179      $ewiki_plugins["action_always"]["links"] = "ewiki_page_links";
 180      $ewiki_plugins["action"]["info"] = "ewiki_page_info";
 181      $ewiki_plugins["action"]["view"] = "ewiki_page_view";
 182  
 183      #-- helper vars ---------------------------------------------------
 184      $ewiki_config["idf"]["url"] = array("http://", "mailto:", "internal://", "ftp://", "https://", "irc://", "telnet://", "news://", "chrome://", "file://", "gopher://", "httpz://");
 185      $ewiki_config["idf"]["img"] = array(".jpeg", ".png", ".jpg", ".gif", ".j2k");
 186      $ewiki_config["idf"]["obj"] = array(".swf", ".svg");
 187  
 188      #-- entitle actions
 189      $ewiki_config["action_links"]["view"] = @array_merge(array(
 190          "edit" => "EDITTHISPAGE",   # ewiki_t() is called on these
 191          "links" => "BACKLINKS",
 192          "info" => "PAGEHISTORY",
 193          "like" => "LIKEPAGES",
 194      ), @$ewiki_config["action_links"]["view"]
 195          );
 196      $ewiki_config["action_links"]["info"] = @array_merge(array(
 197          "view" => "browse",
 198          "edit" => "fetchback",
 199      ), @$ewiki_config["action_links"]["info"]
 200          );
 201  
 202          #-- variable configuration settings (go into '$ewiki_config')
 203          $ewiki_config_DEFAULTSTMP = array(
 204             "edit_thank_you" => 1,
 205             "edit_box_size" => "70x15",
 206             "print_title" => EWIKI_PRINT_TITLE,
 207             "split_title" => EWIKI_SPLIT_TITLE,
 208             "control_line" => EWIKI_CONTROL_LINE,
 209             "list_limit" => EWIKI_LIST_LIMIT,
 210             "script" => EWIKI_SCRIPT,
 211             "script_url" => (defined("EWIKI_SCRIPT_URL")?EWIKI_SCRIPT_URL:NULL),
 212             "script_binary" => EWIKI_SCRIPT_BINARY,
 213      #-- heart of the wiki -- don't try to read this! ;)
 214  
 215             "wiki_pre_scan_regex" => '/
 216          (?<![~!])
 217          ((?:(?:\w+:)*['.EWIKI_CHARS_U.']+['.EWIKI_CHARS_L.']+){2,}[\w\d]*)
 218          |\^([-'.EWIKI_CHARS_L.EWIKI_CHARS_U.']{3,})
 219          |\[ (?:"[^\]\"]+" | \s+ | [^:\]#]+\|)*  ([^\|\"\[\]\#]+)  (?:\s+ | "[^\]\"]+")* [\]\#] 
 220          |(\w{3,9}:\/\/[^?#\s\[\]\'\"\)\,<]+)    /x',
 221  
 222             "wiki_link_regex" => "\007 [!~]?(
 223          \#?\[[^<>\[\]\n]+\] |
 224          \^[-".EWIKI_CHARS_U.EWIKI_CHARS_L."]{3,} |
 225          \b([\w]{3,}:)*([".EWIKI_CHARS_U."]+[".EWIKI_CHARS_L."]+){2,}\#?[\w\d]* |
 226          ([a-z]{2,9}://|mailto:)[^\s\[\]\'\"\)\,<]+ |
 227          \w[-_.+\w]+@(\w[-_\w]+[.])+\w{2,}   ) \007x",
 228  
 229      #-- rendering ruleset
 230             "wm_indent" => '',
 231             "wm_table_defaults" => 'cellpadding="2" border="1" cellspacing="0"',
 232             "wm_whole_line" => array(),
 233             "htmlentities" => array(
 234          "&" => "&amp;",
 235          ">" => "&gt;",
 236          "<" => "&lt;",
 237             ),
 238             "wm_source" => array(
 239          "%%%" => "<br />",
 240          "\t" => "        ",
 241          "\n;:" => "\n      ",   # workaround, replaces the old ;:
 242             ),
 243             "wm_list" => array(
 244          "-" => array('ul type="square"', "", "li"),
 245          "*" => array('ul type="circle"', "", "li"),
 246          "#" => array("ol", "", "li"),
 247          ":" => array("dl", "dt", "dd"),
 248      #<out># ";" => array("dl", "dt", "dd"),
 249             ),
 250             "wm_style" => array(
 251          "'''''" => array("<b><i>", "</i></b>"),
 252          "'''" => array("<b>", "</b>"),
 253          "___" => array("<i><b>", "</b></i>"),
 254          "''" => array("<em>", "</em>"),
 255          "__" => array("<strong>", "</strong>"),
 256          "^^" => array("<sup>", "</sup>"),
 257          "==" => array("<tt>", "</tt>"),
 258      #<off># "***" => array("<b><i>", "</i></b>"),
 259      #<off># "###" => array("<big><b>", "</b></big>"),
 260          "**" => array("<b>", "</b>"),
 261          "##" => array("<big>", "</big>"),
 262          "µµ" => array("<small>", "</small>"),
 263             ),
 264             "wm_start_end" => array(
 265             ),
 266      #-- rendering plugins
 267             "format_block" => array(
 268          "html" => array("&lt;html&gt;", "&lt;/html&gt;", "html", 0x0000),
 269          "htm" => array("&lt;htm&gt;", "&lt;/htm&gt;", "html", 0x0003),
 270          "code" => array("&lt;code&gt;", "&lt;/code&gt;", false, 0x0000),
 271          "pre" => array("&lt;pre&gt;", "&lt;/pre&gt;", false, 0x003F),
 272          "comment" => array("\n&lt;!--", "--&gt;", false, 0x0030),
 273          #  "verbatim" => array("&lt;verbatim&gt;", "&lt;/verbatim&gt;", false, 0x0000),
 274             ),
 275             "format_params" => array(
 276          "scan_links" => 1,
 277          "html" => EWIKI_ALLOW_HTML,
 278          "mpi" => 1,
 279             ),
 280          );
 281          foreach ($ewiki_config_DEFAULTSTMP as $set => $val) {
 282             if (!isset($ewiki_config[$set])) {
 283                $ewiki_config[$set] = $val;
 284             }
 285             elseif (is_array($val)) foreach ($val as $vali=>$valv) {
 286                if (is_int($vali)) {
 287                   $ewiki_config[$set][] = $valv;
 288                }
 289                elseif (!isset($ewiki_config[$set][$vali])) {
 290                   $ewiki_config[$set][$vali] = $valv;
 291                }
 292             }
 293          }
 294          $ewiki_config_DEFAULTSTMP = $valv = $vali = $val = NULL;
 295  
 296      #-- init stuff, autostarted parts
 297      ksort($ewiki_plugins["init"]);
 298      if ($pf_a = $ewiki_plugins["init"]) foreach ($pf_a as $pf) {
 299             // Binary Handling starts here
 300             #### MOODLE CHANGE TO BE COMPATIBLE WITH PHP 4.1
 301             #if(headers_sent($file,$line)) {
 302             #  error("Headers already sent: $file:$line");
 303             if(headers_sent()) {
 304               error("Headers already sent.");
 305             }
 306             $pf($GLOBALS);
 307          }
 308      unset($ewiki_plugins["init"]);
 309  
 310      #-- text  (never remove the "C" or "en" sections!)
 311          #
 312      $ewiki_t["C"] = @array_merge(@$ewiki_t["C"], array(
 313             "DATE" => "%a, %d %b %G %T %Z",
 314         "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>',
 315          ));
 316          #
 317      $ewiki_t["en"] = @array_merge(@$ewiki_t["en"], array(
 318         "EDITTHISPAGE" => "EditThisPage",
 319             "APPENDTOPAGE" => "Add to",
 320         "BACKLINKS" => "BackLinks",
 321         "PAGESLINKINGTO" => "Pages linking to \$title",
 322         "PAGEHISTORY" => "PageInfo",
 323         "INFOABOUTPAGE" => "Information about page",
 324         "LIKEPAGES" => "Pages like this",
 325         "NEWESTPAGES" => "Newest Pages",
 326         "LASTCHANGED" => "last changed on %c",
 327         "DOESNOTEXIST" => "This page does not yet exist, please click on EditThisPage if you'd like to create it.",
 328         "DISABLEDPAGE" => "This page is currently not available.",
 329         "ERRVERSIONSAVE" => "Sorry, while you edited this page someone else
 330          did already save a changed version. Please go back to the
 331          previous screen and copy your changes to your computers
 332          clipboard to insert it again after you reload the edit
 333          screen.",
 334         "ERRORSAVING" => "An error occoured while saving your changes. Please try again.",
 335         "THANKSFORCONTRIBUTION" => "Thank you for your contribution!",
 336         "CANNOTCHANGEPAGE" => "This page cannot be changed.",
 337         "OLDVERCOMEBACK" => "Make this old version come back to replace the current one",
 338         "PREVIEW" => "Preview",
 339         "SAVE" => "Save",
 340         "CANCEL_EDIT" => "CancelEditing",
 341         "UPLOAD_PICTURE_BUTTON" => "upload picture &gt;&gt;&gt;",
 342         "EDIT_FORM_1" => "<a href=\"".EWIKI_SCRIPT."GoodStyle\">GoodStyle</a> is to
 343          write what comes to your mind. Don't care about how it
 344          looks too much now. You can add <a href=\"".EWIKI_SCRIPT."WikiMarkup\">WikiMarkup</a>
 345          also later if you think it is necessary.<br />",
 346         "EDIT_FORM_2" => "<br />Please do not write things, which may make other
 347          people angry. And please keep in mind that you are not all that
 348          anonymous in the internet (find out more about your computers
 349          '<a href=\"http://google.com/search?q=my+computers+IP+address\">IP address</a>' at Google).",
 350         "BIN_IMGTOOLARGE" => "Image file is too large!",
 351         "BIN_NOIMG" => "This is no image file (inacceptable file format)!",
 352         "FORBIDDEN" => "You are not authorized to access this page.",
 353      ));
 354          #
 355          $ewiki_t["es"] = @array_merge(@$ewiki_t["es"], array(
 356             "EDITTHISPAGE" => "EditarEstaPágina",
 357             "BACKLINKS" => "EnlacesInversos",
 358             "PAGESLINKINGTO" => "Páginas enlazando \$title",
 359             "PAGEHISTORY" => "InfoPágina",
 360             "INFOABOUTPAGE" => "Información sobre la página",
 361             "LIKEPAGES" => "Páginas como esta",
 362             "NEWESTPAGES" => "Páginas más nuevas",
 363             "LASTCHANGED" => "última modificación %d/%m/%Y a las %H:%M",
 364             "DOESNOTEXIST" => "Esta página aún no existe, por favor eliga EditarEstaPágina si desea crearla.",
 365             "DISABLEDPAGE" => "Esta página no está disponible en este momento.",
 366             "ERRVERSIONSAVE" => "Disculpe, mientras editaba esta página alguién más
 367          salvó una versión modificada. Por favor regrese a
 368          a la pantalla anterior y copie sus cambios a su computador
 369          para insertalos nuevamente después de que cargue
 370          la pantalla de edición.",
 371             "ERRORSAVING" => "Ocurrió un error mientras se salvavan sus cambios. Por favor intente de nuevo.",
 372             "THANKSFORCONTRIBUTION" => "Gracias por su contribución!",
 373             "CANNOTCHANGEPAGE" => "Esta página no puede ser modificada.",
 374             "OLDVERCOMEBACK" => "Hacer que esta versión antigua regrese a remplazar la actual",
 375             "PREVIEW" => "Previsualizar",
 376             "SAVE" => "Salvar",
 377             "CANCEL_EDIT" => "CancelarEdición",
 378             "UPLOAD_PICTURE_BUTTON" => "subir gráfica &gt;&gt;&gt;",
 379             "EDIT_FORM_1" => "<a href=\"".EWIKI_SCRIPT."BuenEstilo\">BuenEstilo</a> es
 380          escribir lo que viene a su mente. No se preocupe mucho
 381          por la apariencia. También puede agregar <a href=\"".EWIKI_SCRIPT."ReglasDeMarcadoWiki\">ReglasDeMarcadoWiki</a>
 382          más adelante si piensa que es necesario.<br />",
 383             "EDIT_FORM_2" => "<br />Por favor no escriba cosas, que puedan
 384          enfadar a otras personas. Y por favor tenga en mente que
 385          usted no es del todo anónimo en Internet 
 386          (encuentre más sobre 
 387          '<a href=\"http://google.com/search?q=my+computers+IP+address\">IP address</a>' de su computador con Google).",
 388             "BIN_IMGTOOLARGE" => "¡La gráfica es demasiado grande!",
 389             "BIN_NOIMG" => "¡No es un archivo con una gráfica (formato de archivo inaceptable)!",
 390             "FORBIDDEN" => "No está autorizado para acceder a esta página.",
 391          ));
 392          #
 393      $ewiki_t["de"] = @array_merge(@$ewiki_t["de"], array(
 394         "EDITTHISPAGE" => "DieseSeiteÄndern",
 395             "APPENDTOPAGE" => "Ergänze",
 396         "BACKLINKS" => "ZurückLinks",
 397         "PAGESLINKINGTO" => "Verweise zur Seite \$title",
 398         "PAGEHISTORY" => "SeitenInfo",
 399         "INFOABOUTPAGE" => "Informationen über Seite",
 400         "LIKEPAGES" => "Ähnliche Seiten",
 401         "NEWESTPAGES" => "Neueste Seiten",
 402         "LASTCHANGED" => "zuletzt geändert am %d.%m.%Y um %H:%M",
 403         "DISABLEDPAGE" => "Diese Seite kann momentan nicht angezeigt werden.",
 404         "ERRVERSIONSAVE" => "Entschuldige, aber während Du an der Seite
 405          gearbeitet hast, hat bereits jemand anders eine geänderte
 406          Fassung gespeichert. Damit nichts verloren geht, browse bitte
 407          zurück und speichere Deine Änderungen in der Zwischenablage
 408          (Bearbeiten->Kopieren) um sie dann wieder an der richtigen
 409          Stelle einzufügen, nachdem du die EditBoxSeite nocheinmal
 410          geladen hast.<br />
 411          Vielen Dank für Deine Mühe.",
 412         "ERRORSAVING" => "Beim Abspeichern ist ein Fehler aufgetreten. Bitte versuche es erneut.",
 413         "THANKSFORCONTRIBUTION" => "Vielen Dank für Deinen Beitrag!",
 414         "CANNOTCHANGEPAGE" => "Diese Seite kann nicht geändert werden.",
 415         "OLDVERCOMEBACK" => "Diese alte Version der Seite wieder zur Aktuellen machen",
 416         "PREVIEW" => "Vorschau",
 417         "SAVE" => "Speichern",
 418         "CANCEL_EDIT" => "ÄnderungenVerwerfen",
 419         "UPLOAD_PICTURE_BUTTON" => "Bild hochladen &gt;&gt;&gt;",
 420         "EDIT_FORM_1" => "<a href=\"".EWIKI_SCRIPT."GuterStil\">GuterStil</a> ist es,
 421          ganz einfach das zu schreiben, was einem gerade in den
 422          Sinn kommt. Du solltest dich jetzt noch nicht so sehr
 423          darum kümmern, wie die Seite aussieht. Du kannst später
 424          immernoch zurückkommen und den Text mit <a href=\"".EWIKI_SCRIPT."FormatierungsRegeln\">WikiTextFormatierungsRegeln</a>
 425          aufputschen.<br />",
 426         "EDIT_FORM_2" => "<br />Bitte schreib keine Dinge, die andere Leute
 427          verärgern könnten. Und bedenke auch, daß es schnell auf
 428          dich zurückfallen kann wenn du verschiedene andere Dinge sagst (mehr Informationen zur
 429          '<a href=\"http://google.de/search?q=computer+IP+adresse\">IP Adresse</a>'
 430          deines Computers findest du bei Google).",
 431      ));
 432  
 433      #-- InterWiki:Links
 434      $ewiki_config["interwiki"] = @array_merge(
 435      @$ewiki_config["interwiki"],
 436      array(
 437             "javascript" => "",  # this actually protects from javascript: links
 438             "url" => "",
 439  #          "self" => "this",
 440             "this" => EWIKI_SCRIPT,  # better was absolute _URL to ewiki wrapper
 441             "jump" => "",
 442         "ErfurtWiki" => "http://erfurtwiki.sourceforge.net/?id=",
 443         "InterWiki" => "InterWikiSearch",
 444         "InterWikiSearch" => "http://sunir.org/apps/meta.pl?",
 445         "Wiki" => "WardsWiki",
 446         "WardsWiki" => "http://www.c2.com/cgi/wiki?",
 447         "WikiFind" => "http://c2.com/cgi/wiki?FindPage&amp;value=",
 448         "WikiPedia" => "http://www.wikipedia.com/wiki.cgi?",
 449         "MeatBall" => "MeatballWiki",
 450         "MeatballWiki" => "http://www.usemod.com/cgi-bin/mb.pl?",
 451         "UseMod"       => "http://www.usemod.com/cgi-bin/wiki.pl?",
 452         "PhpWiki" => "http://phpwiki.sourceforge.net/phpwiki/index.php3?",
 453         "LinuxWiki" => "http://linuxwiki.de/",
 454         "OpenWiki" => "http://openwiki.com/?",
 455         "Tavi" => "http://andstuff.org/tavi/",
 456         "TWiki" => "http://twiki.sourceforge.net/cgi-bin/view/",
 457         "MoinMoin" => "http://www.purl.net/wiki/moin/",
 458         "Google" => "http://google.com/search?q=",
 459         "ISBN" => "http://www.amazon.com/exec/obidos/ISBN=",
 460         "icq" => "http://www.icq.com/",
 461      ));
 462  
 463  
 464  
 465  
 466  
 467  #-------------------------------------------------------------------- main ---
 468  
 469  /*  this is the main function, which you should preferrably call to
 470      integrate the ewiki into your web site; it chains to most other
 471      parts and plugins (including the edit box);
 472      if you do not supply the requested pages "$id" we will fetch it
 473      from the pre-defined possible URL parameters.
 474  */
 475  function ewiki_page($id=false) {
 476  
 477     global $ewiki_links, $ewiki_plugins, $ewiki_ring, $ewiki_t, $ewiki_errmsg;
 478     #-- output var
 479     $o = "";
 480  
 481     #-- selected page
 482     if (!isset($_REQUEST)) {
 483        $_REQUEST = @array_merge($_GET, $_POST);
 484     }
 485     if (!strlen($id)) {
 486        $id = ewiki_id();
 487     }
 488     $id = format_string($id,true);
 489     #-- page action
 490     $action = EWIKI_DEFAULT_ACTION;
 491     if ($delim = strpos($id, EWIKI_ACTION_SEP_CHAR)) {
 492        $action = substr($id, 0, $delim);
 493        $id = substr($id, $delim + 1);
 494     }
 495     elseif (EWIKI_USE_ACTION_PARAM && isset($_REQUEST["action"])) {
 496        $action = $_REQUEST["action"];
 497     }
 498     $GLOBALS["ewiki_id"] = $id;
 499     $GLOBALS["ewiki_title"] = ewiki_split_title($id);
 500     $GLOBALS["ewiki_action"] = $action;
 501  
 502     #-- fetch from db
 503     $dquery = array(
 504        "id" => $id
 505     );
 506     if (!isset($_REQUEST["content"]) && ($dquery["version"] = @$_REQUEST["version"])) {
 507        $dquery["forced_version"] = $dquery["version"];
 508     }
 509     $data = @array_merge($dquery, ewiki_database("GET", $dquery));
 510  
 511     #-- stop here if page is not marked as _TEXT,
 512     #   perform authentication then, and let only administrators proceed
 513     if (!empty($data["flags"]) && (($data["flags"] & EWIKI_DB_F_TYPE) != EWIKI_DB_F_TEXT)) {
 514        if (($data["flags"] & EWIKI_DB_F_BINARY) && ($pf = $ewiki_plugins["handler_binary"][0])) {
 515           return($pf($id, $data, $action)); //_BINARY entries handled separately
 516        }
 517        elseif (!EWIKI_PROTECTED_MODE || !ewiki_auth($id, $data, $action, 0, 1) && ($ewiki_ring!=0)) {
 518           return(ewiki_t("DISABLEDPAGE"));
 519        }
 520     }
 521  
 522     #-- pre-check if actions exist
 523     $pf_page = ewiki_array($ewiki_plugins["page"], $id);
 524  
 525     #-- edit <form> for non-existent pages
 526     if (($action==EWIKI_DEFAULT_ACTION) && empty($data["content"]) && empty($pf_page)) {
 527        if (EWIKI_AUTO_EDIT) {
 528           $action = "edit";
 529        }
 530        else {
 531           $data["content"] = ewiki_t("DOESNOTEXIST");
 532        }
 533     }
 534     #-- more initialization
 535     if ($pf_a = @$ewiki_plugins["page_init"]) {
 536        ksort($pf_a);
 537        foreach ($pf_a as $pf) {
 538           $o .= $pf($id, $data, $action);
 539        }
 540        unset($ewiki_plugins["page_init"]);
 541     }
 542     $pf_page = ewiki_array($ewiki_plugins["page"], $id);
 543  
 544     #-- require auth
 545     if (EWIKI_PROTECTED_MODE) {
 546        if (!ewiki_auth($id, $data, $action, $ring=false, $force=EWIKI_AUTO_LOGIN)) {
 547           return($o.=$ewiki_errmsg);
 548        }
 549     }
 550  
 551     #-- handlers
 552     $handler_o = "";
 553     if ($pf_a = @$ewiki_plugins["handler"]) {
 554        ksort($pf_a);
 555        foreach ($pf_a as $pf) {
 556           if ($handler_o = $pf($id, $data, $action)) { break; }
 557     }  }
 558  
 559     #-- finished by handler
 560     if ($handler_o) {
 561        $o .= $handler_o;
 562     }
 563     #-- actions that also work for static and internal pages
 564     elseif (($pf = @$ewiki_plugins["action_always"][$action]) && function_exists($pf)) {
 565        $o .= $pf($id, $data, $action);
 566     }
 567     #-- internal pages
 568     elseif ($pf_page && function_exists($pf_page)) {
 569        $o .= $pf_page($id, $data, $action);
 570     }
 571     #-- page actions
 572     else {
 573        $pf = @$ewiki_plugins["action"][$action];
 574  
 575        #-- fallback to "view" action
 576        if (empty($pf) || !function_exists($pf)) {
 577  
 578           $pf = "ewiki_page_view";
 579           $action = "view";     // we could also allow different (this is a
 580           // catch-all) view variants, but this would lead to some problems
 581        }
 582  
 583        $o .= $pf($id, $data, $action);
 584     }
 585  
 586     #-- error instead of page?
 587     if (empty($o) && $ewiki_errmsg) {
 588        $o = $ewiki_errmsg;
 589     }
 590  
 591     #-- html post processing
 592     if ($pf_a = $ewiki_plugins["page_final"]) {
 593        ksort($pf_a);
 594        foreach ($pf_a as $pf) {
 595           if ($action == 'edit' and $pf == 'ewiki_html_tag_balancer') {
 596              continue; // balancer breaks htmlarea buttons
 597           }
 598           $pf($o, $id, $data, $action);
 599        }
 600     }
 601  
 602     (EWIKI_ESCAPE_AT) && ($o = str_replace("@", "&#x40;", $o));
 603  
 604     return($o);
 605  }
 606  
 607  
 608  
 609  #-- HTTP meta headers
 610  function ewiki_http_headers(&$o, $id, &$data, $action) {
 611     global $ewiki_t;
 612     if (EWIKI_HTTP_HEADERS && !headers_sent()) {
 613        if (!empty($data)) {
 614           if ($uu = @$data["id"]) @header('Content-Disposition: inline; filename="' . urlencode($uu) . '.html"');
 615           if ($uu = @$data["version"]) @header('Content-Version: ' . $uu);
 616           if ($uu = @$data["lastmodified"]) @header('Last-Modified: ' . gmstrftime($ewiki_t["C"]["DATE"], $uu));
 617        }
 618        if (EWIKI_NO_CACHE) {
 619           header('Expires: ' . gmstrftime($ewiki_t["C"]["DATE"], UNIX_MILLENNIUM));
 620           header('Pragma: no-cache');
 621           header('Cache-Control: no-cache, private, must-revalidate');
 622           # change to "C-C: cache, must-revalidate" ??
 623           # private only for authenticated users / _PROT_MODE
 624        }
 625        #-- ETag
 626        if ($data["version"] && ($etag=ewiki_etag($data)) || ($etag=md5($o))) {
 627           $weak = "W/" . urlencode($id) . "." . $data["version"];
 628           header("ETag: \"$etag\"");     ###, \"$weak\"");
 629        }
 630     }
 631  }
 632  function ewiki_etag(&$data) {
 633     return(  urlencode($data["id"]) . ":" . dechex($data["version"]) . ":ewiki:" .
 634              dechex(crc32($data["content"]) & 0x7FFFBFFF)  );
 635  }
 636  
 637  
 638  
 639  #-- encloses whole page output with a descriptive <div>
 640  function ewiki_page_css_container(&$o, &$id, &$data, &$action) {
 641     $o = "<div class=\"wiki $action "
 642        . strtr($id, ' ./ --_!"§$%&()=?²³{[]}`+#*;:,<>| @µöäüÖÄÜߤ^°«»\'\\',
 643                     '-  -----------------------------------------------')
 644        . "\">\n"
 645        . $o . "\n</div>\n";
 646  }
 647  
 648  
 649  
 650  function ewiki_split_title ($id='', $split=EWIKI_SPLIT_TITLE, $entities=1) {
 651     strlen($id) or ($id = $GLOBALS["ewiki_id"]);
 652     if ($split) {
 653        $id = preg_replace("/([".EWIKI_CHARS_L."])([".EWIKI_CHARS_U."]+)/", "$1 $2", $id);
 654     }
 655     return($entities ? s($id) : $id);
 656  }
 657  
 658  
 659  
 660  function ewiki_add_title(&$html, $id, &$data, $action, $go_action="links") {
 661     $html = ewiki_make_title($id, '', 1, $action, $go_action) . $html;
 662  }
 663  
 664  
 665  function ewiki_make_title($id='', $title='', $class=3, $action="view", $go_action="links", $may_split=1) {
 666  
 667     global $ewiki_config, $ewiki_plugins, $ewiki_title, $ewiki_id;
 668  
 669     #-- advanced handler
 670     if ($pf = @$ewiki_plugins["make_title"][0]) {
 671        return($pf($title, $class, $action, $go_action, $may_split));
 672     }
 673     #-- disabled
 674     elseif (!$ewiki_config["print_title"]) {
 675        return("");
 676     }
 677  
 678     #-- get id
 679     if (empty($id)) {
 680        $id = $ewiki_id;
 681     }
 682  
 683     #-- get title
 684     if (!strlen($title)) {
 685        $title = $ewiki_title;  // already in &html; format
 686     }
 687     elseif ($ewiki_config["split_title"] && $may_split) {
 688        $title = ewiki_split_title($title, $ewiki_config["split_title"], 0&($title!=$ewiki_title));
 689     }
 690     else {
 691        $title = s($title);
 692     }
 693  
 694     #-- title mangling
 695     if ($pf_a = @$ewiki_plugins["title_transform"]) {
 696        foreach ($pf_a as $pf) { $pf($id, $title, $go_action); }
 697     }
 698  
 699     #-- clickable link or simple headline
 700     if ($class <= $ewiki_config["print_title"]) {
 701        if ($uu = @$ewiki_config["link_title_action"][$action]) {
 702           $go_action = $uu;
 703        }
 704        if ($uu = @$ewiki_config["link_title_url"]) {
 705           $href = $uu;
 706           unset($ewiki_config["link_title_url"]);
 707        }
 708        else {
 709           $href = ewiki_script($go_action, $id);
 710        }
 711        $o = '<a href="' . $href . '">' . ($title) . '</a>';
 712     }
 713     else {
 714        $o = $title;
 715     }
 716  
 717     return('<h2 class="page title">' . $o . '</h2>'."\n");
 718  }
 719  
 720  
 721  
 722  
 723  function ewiki_page_view($id, &$data, $action, $all=1) {
 724  
 725     global $ewiki_plugins, $ewiki_config;
 726     $o = "";
 727  
 728     #-- render requested wiki page  <-- goal !!!
 729     $render_args = array(
 730        "scan_links" => 1,
 731        "html" => (EWIKI_ALLOW_HTML||(@$data["flags"]&EWIKI_DB_F_HTML)),
 732     );
 733     $o .= $ewiki_plugins["render"][0] ($data["content"], $render_args);
 734     if (!$all) {
 735        return($o);
 736     }
 737     #### MOODLE CHANGE
 738     /// Add Moodle filters to text porion of wiki.
 739     global $moodle_format;   // from wiki/view.php
 740     $o = format_text($o, $moodle_format);
 741     $o.= "<br /><br />";
 742  
 743     #-- control line + other per-page info stuff
 744     if ($pf_a = $ewiki_plugins["view_append"]) {
 745        ksort($pf_a);
 746        foreach ($pf_a as $n => $pf) { $o .= $pf($id, $data, $action); }
 747     }
 748     if ($pf_a = $ewiki_plugins["view_final"]) {
 749        ksort($pf_a);
 750        foreach ($pf_a as $n => $pf) { $pf($o, $id, $data, $action); }
 751     }
 752  
 753     if (!empty($_REQUEST["thankyou"]) && $ewiki_config["edit_thank_you"]) {
 754        $o = ewiki_t("THANKSFORCONTRIBUTION") . $o;
 755     }
 756  
 757     
 758     if (EWIKI_HIT_COUNTING) {
 759        ewiki_database("HIT", $data);
 760     }
 761  
 762     return($o);
 763  }
 764  
 765  
 766  
 767  
 768  #-------------------------------------------------------------------- util ---
 769  
 770  
 771  /*  retrieves "$id/$action" string from URL / QueryString / PathInfo,
 772      change this in conjunction with ewiki_script() to customize your URLs
 773      further whenever desired
 774  */
 775  function ewiki_id() {
 776     ($id = @$_REQUEST["id"]) or
 777     ($id = @$_REQUEST["name"]) or
 778     ($id = @$_REQUEST["page"]) or
 779     ($id = @$_REQUEST["file"]) or
 780     (EWIKI_USE_PATH_INFO) and ($id = ltrim(@$_SERVER["PATH_INFO"], "/")) or
 781     (!isset($_REQUEST["id"])) and ($id = trim(strtok($_SERVER["QUERY_STRING"], "&")));
 782     if (!strlen($id) || ($id=="id=")) {
 783        $id = EWIKI_PAGE_INDEX;
 784     }
 785     (EWIKI_URLDECODE) && ($id = urldecode($id));
 786     return($id);
 787  }
 788  
 789  
 790  
 791  
 792  /*  replaces EWIKI_SCRIPT, works more sophisticated, and
 793      bypasses various design flaws
 794      - if only the first parameter is used (old style), it can contain
 795        a complete "action/WikiPage" - but this is ambigutious
 796      - else $asid is the action, and $id contains the WikiPageName
 797      - $ewiki_config["script"] will now be used in favour of the constant
 798      - needs more work on _BINARY, should be a separate function
 799  */
 800  ## MOODLE-CHANGE: $asid="", Knows the devil why....
 801  function ewiki_script($asid="", $id=false, $params="", $bin=0, $html=1, $script=NULL) {
 802     global $ewiki_config, $ewiki_plugins;
 803        
 804     #-- get base script url from config vars
 805     if (empty($script)) {
 806        $script = &$ewiki_config[!$bin?"script":"script_binary"];
 807     }
 808  
 809  
 810     #-- separate $action and $id for old style requests
 811     if ($id === false) {
 812        if (strpos($asid, EWIKI_ACTION_SEP_CHAR) !== false) {
 813           $asid = strtok($asid, EWIKI_ACTION_SEP_CHAR);
 814           $id = strtok("\000");
 815        }
 816        else {
 817           $id = $asid;
 818           $asid = "";
 819        }
 820     }
 821  
 822     #-- prepare params
 823     if (is_array($params)) {
 824        $uu = $params;
 825        $params = "";
 826        if ($uu) foreach ($uu as $k=>$v) {
 827           $params .= (strlen($params)?"&":"") . rawurlencode($k) . "=" . rawurlencode($v);
 828        }
 829     }
 830     #-- action= parameter
 831     if (EWIKI_USE_ACTION_PARAM >= 2) {
 832        $params = "action=$asid" . (strlen($params)?"&":"") . $params;
 833        $asid = "";
 834     }
 835  
 836     #-- workaround slashes in $id
 837     if (empty($asid) && (strpos($id, EWIKI_ACTION_SEP_CHAR) !== false) && !$bin) {
 838        $asid = "view";
 839     }
 840     /*paranoia*/ $asid = trim($asid, EWIKI_ACTION_SEP_CHAR);
 841  
 842     #-- make url
 843     if (EWIKI_URLENCODE) {
 844        $id = urlencode($id);
 845        $asid = urlencode($asid);
 846     }
 847     else {
 848        # only urlencode &, %, ? for example
 849     }
 850     $url = $script;
 851     if ($asid) {
 852        $id = $asid . EWIKI_ACTION_SEP_CHAR . $id;  #= "action/PageName"
 853     }
 854     if (strpos($url, "%s") !== false) {
 855        $url = str_replace("%s", $id, $url);
 856     }
 857     else {
 858        $url .= $id;
 859     }
 860  
 861     #-- add url params
 862     if (strlen($params)) {
 863        $url .= (strpos($url,"?")!==false ? "&":"?") . $params;
 864     }
 865  
   #-- fin
 866     if ($html) {
 867        //Don't replace & if it's part of encoded character (bug 2209)
 868        $url = preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,5};)/","&amp;", $url);
 869     } else {
 870        //This is going to be used in some header or meta redirect, so It cannot use &amp; (bug 2620)
 871        $url = preg_replace('/&amp;/', '&', $url); 
 872     }
 873     return($url);
 874  }
 875  
 876  
 877  /*  this ewiki_script() wrapper is used to generate URLs to binary
 878      content in the ewiki database
 879  */
 880  function ewiki_script_binary($asid, $id=false, $params=array(), $upload=0) {
 881  
 882     $upload |= is_string($params) && strlen($params) || count($params);
 883  
 884     #-- generate URL directly to the plainly saved data file,
 885     #   see also plugins/binary_store
 886  
 887     if (defined("EWIKI_DB_STORE_URL") && !$upload) {
 888        $url = EWIKI_DB_STORE_URL . rawurlencode($id);
 889     }
 890  
 891     #-- else get standard URL (thru ewiki.php) from ewiki_script()
 892     else {
 893        $url = ewiki_script($asid, $id, $params, "_BINARY=1");
 894     }
 895  
 896     return($url);
 897  }
 898  
 899  
 900  /*  this function returns the absolute ewiki_script url, if EWIKI_SCRIPT_URL
 901      is set, else it guesses the value
 902  */
 903  function ewiki_script_url() {
 904  
 905     global $ewiki_action, $ewiki_id, $ewiki_config;
 906  
 907     $scr_template = $ewiki_config["script"];
 908     $scr_current = ewiki_script($ewiki_action, $ewiki_id);
 909     $req_uri = $_SERVER["REQUEST_URI"];
 910  
 911     if ($url = $ewiki_config["script_url"]) {
 912        return($url);
 913     }
 914     elseif (strpos($req_uri, $scr_current) !== false) {
 915        $url = str_replace($req_uri, $scr_current, $scr_template);
 916     }
 917     elseif (strpos($req_uri, "?") && (strpos($scr_template, "?") !== false)) {
 918        $url = substr($req_uri, 0, strpos($req_uri, "?"))
 919             . substr($scr_template, strpos($scr_template, "?"));
 920     }
 921     elseif (strpos($req_uri, $sn = $_SERVER["SCRIPT_NAME"])) {
 922        $url = $sn . "?id=";
 923     }
 924     else {
 925        return(NULL);   #-- could not guess it
 926     }
 927   
 928     #$url = "http://" . $_SERVER["SERVER_NAME"] . $url;
 929     return($url);
 930  }
 931  
 932  
 933  
 934  
 935  #------------------------------------------------------------ page plugins ---
 936  
 937  
 938  
 939  function ewiki_page_links($id, &$data, $action) {
 940     $o = ewiki_make_title($id, ewiki_t("PAGESLINKINGTO", array("title"=>$id)), 1, $action, "", "_MAY_SPLIT=1");
 941     if ($pages = ewiki_get_backlinks($id)) {
 942        $o .= ewiki_list_pages($pages);
 943     } else {
 944        $o .= ewiki_t("This page isn't linked from anywhere else.");
 945     }
 946     return($o);
 947  }
 948  
 949  function ewiki_get_backlinks($id) {
 950     $result = ewiki_database("SEARCH", array("refs" => $id));
 951     $pages = array();
 952     while ($row = $result->get(0, 0x0020)) {
 953        if ( strpos($row["refs"], "\n$id\n") !== false) {
 954           $pages[] = $row["id"];
 955        }
 956     }
 957     return($pages);
 958  }
 959  
 960  function ewiki_get_links($id) {
 961     if ($data = ewiki_database("GET", array("id"=>$id))) {
 962        $refs = explode("\n", trim($data["refs"]));
 963        $r = array();
 964        foreach (ewiki_database("FIND", $refs) as $id=>$exists) {
 965           if ($exists) {
 966              $r[] = $id;
 967           }
 968        }
 969        return($r);
 970     }
 971  }
 972  
 973  
 974  function ewiki_list_pages($pages=array(), $limit=EWIKI_LIST_LIMIT,
 975                            $value_as_title=0, $pf_list=false)
 976  {
 977     global $ewiki_plugins;
 978     $o = "";
 979  
 980     $is_num = !empty($pages[0]);
 981     $lines = array();
 982     $n = 0;
 983  
 984     foreach ($pages as $id=>$add_text) {
 985  
 986        $title = $id;
 987        $params = "";
 988  
 989        if (is_array($add_text)) {
 990           list($id, $params, $title, $add_text) = $add_text;
 991        }
 992        elseif ($is_num) {
 993           $id = $title = $add_text;
 994           $add_text = "";
 995        }
 996        elseif ($value_as_title) {
 997           $title = $add_text;
 998           $add_text = "";
 999        }
1000  
1001        $lines[] = '<a href="' . ewiki_script("", $id, $params) . '">' . s($title) . '</a> ' . $add_text;
1002  
1003        if (($limit > 0)  &&  ($n++ >= $limit)) {
1004           break;
1005        }
1006     }
1007  
1008     if ($pf_a = @$ewiki_plugins["list_transform"])
1009     foreach ($pf_a as $pf_transform) {
1010        $pf_transform($lines);
1011     }
1012  
1013     if (($pf_list) || ($pf_list = @$ewiki_plugins["list_pages"][0])) {
1014        $o = $pf_list($lines);
1015     }
1016     elseif($lines) {
1017        $o = "&middot; " . implode("<br />\n&middot; ", $lines) . "<br />\n";
1018     }
1019  
1020     return($o);
1021  }
1022  
1023  
1024  
1025  
1026  function ewiki_page_ordered_list($orderby="created", $asc=0, $print, $title) {
1027  
1028     $o = ewiki_make_title("", $title, 2, ".list", "links", 0);
1029  
1030     $sorted = array();
1031     $result = ewiki_database("GETALL", array($orderby));
1032  
1033     while ($row = $result->get()) {
1034        $row = ewiki_database("GET", array(
1035           "id" => $row["id"],
1036           ($asc >= 0 ? "version" : "uu") => 1  // version 1 is most accurate for {hits}
1037        ));
1038        #-- text page?
1039        if (EWIKI_DB_F_TEXT == ($row["flags"] & EWIKI_DB_F_TYPE)) {
1040           #-- viewing allowed?
1041           if (!EWIKI_PROTECTED_MODE || !EWIKI_PROTECTED_MODE_HIDING || ewiki_auth($row["id"], $row, "view")) {
1042              $sorted[$row["id"]] = $row[$orderby];
1043           }
1044        }
1045     }
1046  
1047     if ($asc != 0) { arsort($sorted); }
1048     else { asort($sorted); }
1049  
1050     foreach ($sorted as $name => $value) { 
1051        if (empty($value)) { $value = "0"; }
1052     ##### BEGIN MOODLE ADDITION #####
1053        #$sorted[$name] = strftime(str_replace('%n', $value, $print), $value);      
1054        if($print=="LASTCHANGED") {
1055          $value=strftime("%c",$value);
1056        }
1057        $sorted[$name] = get_string(strtolower($print),"wiki",$value);
1058     ##### BEGIN MOODLE ADDITION #####
1059     }
1060     $o .= ewiki_list_pages($sorted);
1061     
1062     return($o);
1063  }
1064  
1065  
1066  
1067  function ewiki_page_newest($id=0, $data=0) {
1068     return( ewiki_page_ordered_list("created", 1, "LASTCHANGED", ewiki_t("NEWESTPAGES")) );
1069  }
1070  
1071  function ewiki_page_updates($id=0, $data=0) {
1072     return( ewiki_page_ordered_list("lastmodified", -1, "LASTCHANGED", EWIKI_PAGE_UPDATES) );
1073  }
1074  
1075  function ewiki_page_hits($id=0, $data=0) {
1076     ##### BEGIN MOODLE ADDITION #####
1077     return( ewiki_page_ordered_list("hits", 1, "hits", EWIKI_PAGE_HITS) );
1078  }
1079  
1080  function ewiki_page_versions($id=0, $data=0) {
1081     return( ewiki_page_ordered_list("version", -1, "changes", EWIKI_PAGE_VERSIONS) );
1082     ##### END MOODLE ADDITION #####
1083  }
1084  
1085  
1086  
1087  
1088  
1089  
1090  
1091  function ewiki_page_search($id, &$data, $action) {
1092  
1093     global $CFG;
1094  
1095     $o = ewiki_make_title($id, $id, 2, $action);
1096  
1097     if (! ($q = @$_REQUEST["q"])) {
1098  
1099        $o .= '<form action="' . ewiki_script("", $id) . '" method="post">';
1100        $o .= '<fieldset class="invisiblefieldset">';
1101        $o .= '<input name="q" size="30" /><br /><br />';
1102        $o .= '<input type="submit" value="'.$id.'" />';
1103        $o .= '</fieldset>';
1104        $o .= '</form>';
1105     }
1106     else {
1107        $found = array();
1108  
1109        if ($CFG->unicodedb) {
1110            $q = preg_replace('/\s*[\W]+\s*/u', ' ', $q);
1111        } else {
1112            $q = preg_replace('/\s*[^\w]+\s*/', ' ', $q);
1113        }
1114        foreach (explode(" ", $q) as $search) {
1115  
1116           if (empty($search)) { continue; }
1117  
1118           $result = ewiki_database("SEARCH", array("content" => $search));
1119  
1120           while ($row = $result->get()) {
1121  
1122              #-- show this entry in page listings?
1123              if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($row["id"], $row, "view")) {
1124                 continue;
1125              }
1126  
1127              $found[] = $row["id"];
1128           }
1129        }
1130  
1131        $o .= ewiki_list_pages($found);
1132     }
1133   
1134     return($o);
1135  }
1136  
1137  
1138  
1139  
1140  
1141  
1142  
1143  
1144  function ewiki_page_info($id, &$data, $action) {
1145  
1146     global $ewiki_plugins, $ewiki_config, $ewiki_links;
1147     global $CFG, $course;  // MOODLE HACK
1148  
1149     $o = ewiki_make_title($id, ewiki_t("INFOABOUTPAGE")." '{$id}'", 2, $action,"", "_MAY_SPLIT=1"); 
1150  
1151     $flagnames = array(
1152        "TEXT", "BIN", "DISABLED", "HTML", "READONLY", "WRITEABLE",
1153        "APPENDONLY", "SYSTEM",
1154     );
1155     $show = array(
1156        "version", "author", "userid", "created",
1157        "lastmodified", "refs",
1158        "flags", "meta", "content"
1159     );
1160  
1161     #-- versions to show
1162     $v_start = $data["version"];
1163     if ( ($uu=@$_REQUEST[EWIKI_UP_PAGENUM]) && ($uu<=$v_start) ) {
1164        $v_start = $uu;
1165     }
1166     $v_end = $v_start - $ewiki_config["list_limit"] + 1;
1167     if ( ($uu=@$_REQUEST[EWIKI_UP_PAGEEND]) && ($uu<=$v_start) ) {
1168        $v_end = $uu;
1169     }
1170     $v_end = max($v_end, 1);
1171  
1172     #-- go
1173     # the very ($first) entry is rendered more verbosely than the others
1174     for ($v=$v_start,$first=1; ($v>=$v_end); $v--,$first=0) {
1175  
1176        $current = ewiki_database("GET", array("id"=>$id, "version"=>$v));
1177  
1178        if (!strlen(trim($current["id"])) || !$current["version"] || !strlen(trim($current["content"]))) {
1179           continue;
1180        }
1181  
1182        $o .= '<table  class="version-info" cellpadding="2" cellspacing="1">' . "\n";
1183  
1184        #-- additional info-actions
1185        $commands = '';
1186        foreach ($ewiki_config["action_links"]["info"] as $thisaction=>$title)
1187        if (@$ewiki_plugins["action"][$thisaction] || @$ewiki_plugins["action_always"][$thisaction]) {
1188     ##### BEGIN MOODLE ADDITION #####
1189           if ($commands) {
1190               $commands .= '&nbsp;&nbsp;';
1191           }
1192           $commands .= '<a href="' .
1193             ewiki_script($thisaction, $id, array("version"=>$current["version"])) .
1194             '">' . get_string($title,"wiki") . '</a>';
1195     ##### END MOODLE ADDITION #####
1196        }
1197  
1198        #-- print page database entry
1199        foreach($show as $i) {
1200  
1201           $value = @$current[$i];
1202  
1203           #-- show database {fields} differently
1204           if ($i == "meta") {
1205              continue;  // MOODLE DOESN'T USE IT
1206              $str = "";
1207              if ($first && $value) { foreach ($value as $n=>$d) {
1208                 $str .= s("$n: $d") . "<br />\n";
1209              } }
1210              $value = $str;
1211           }
1212           elseif ($value >= UNIX_MILLENNIUM) {    #-- {lastmodified}, {created}
1213              #### BEGIN MOODLE CHANGE
1214              $value=userdate($value);
1215              #$value = strftime("%c", $value);
1216              #### END MOODLE CHANGE
1217           }
1218           elseif ($i == "content") {
1219              continue;  // MOODLE DOESN'T CARE
1220              $value = strlen(trim($value)) . " bytes";
1221              $i = "content size";
1222           }
1223           elseif ($first && ($i == "refs") && !(EWIKI_PROTECTED_MODE && (EWIKI_PROTECTED_MODE_HIDING>=2))) {
1224              $a = explode("\n", trim($value));
1225              $ewiki_links = ewiki_database("FIND", $a);
1226              ewiki_merge_links($ewiki_links);
1227              foreach ($a as $n=>$link) {
1228                 $a[$n] = ewiki_link_regex_callback(array("$link"), "force_noimg");
1229              }
1230              $value = trim(implode(", ", $a));
1231              if (!$value) {
1232                  continue;
1233              }
1234           }
1235           elseif (strpos($value, "\n") !== false) {       #-- also for {refs}
1236              $value = str_replace("\n", ", ", trim($value));
1237              if (!$value) {
1238                  continue;
1239              }
1240           }
1241           elseif ($i == "version") {
1242              $value = '<a href="' .
1243                 ewiki_script("", $id, array("version"=>$value)) . '">' .
1244                 $value . '</a> '."($commands)";
1245           }
1246           elseif ($i == "flags") {
1247              continue;  // MOODLE DOESN'T USE IT
1248              $fstr = "";
1249              for ($n = 0; $n < 32; $n++) {
1250                if ($value & (1 << $n)) {
1251                   if (! ($s=$flagnames[$n])) { $s = "UU$n"; }
1252                   $fstr .= $s . " ";
1253                }
1254              }
1255              $value = $fstr;
1256           }
1257           elseif ($i == "author") {
1258              continue;
1259              $ewiki_links=1;
1260              $value = preg_replace_callback("/((\w+:)?([".EWIKI_CHARS_U."]+[".EWIKI_CHARS_L."]+){2,}[\w\d]*)/", "ewiki_link_regex_callback", $value);
1261           }
1262           elseif ($i == "userid") {
1263               $i = 'author';
1264               if ($user = get_record('user', 'id', $value)) {
1265                   if (!isset($course->id)) {
1266                       $course->id = 1;
1267                   }
1268                   $picture = print_user_picture($user->id, $course->id, $user->picture, false, true, true);
1269                   $value = $picture." <a href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">".fullname($user)."</a>";
1270               } else {
1271                   continue;
1272                   //$value = @$current['author'];
1273               }
1274           }
1275  
1276     ##### BEGIN MOODLE ADDITION #####
1277           $o .= '<tr class="page-'.$i.'"><td style="vertical-align:top;text-align:right;white-space: nowrap;"><b>' .ewiki_t($i). ':</b></td>' .
1278                 '<td>' . $value . "</td></tr>\n";
1279     ##### END MOODLE ADDITION #####
1280  
1281        }
1282  
1283        $o .= "</table><br /><br />\n";
1284  
1285     }
1286  
1287     #-- page result split
1288     if ($v >= 1) {
1289        $o .= "<br />\n".get_string('showversions','wiki').' '.ewiki_chunked_page($action, $id, -1, $v, 1, 0, 0) . "\n <br />";
1290     }
1291  
1292     return($o);
1293  }
1294  
1295  
1296  
1297  
1298  function ewiki_chunked_page($action, $id, $dir=-1, $start=10, $end=1, $limit=0, $overlap=0.25, $collapse_last=0.67) {
1299  
1300     global $ewiki_config;
1301  
1302     if (empty($limit)) {
1303        $limit = $ewiki_config["list_limit"];
1304     }
1305     if ($overlap < 1) {
1306        $overlap = (int) ($limit * $overlap);
1307     }
1308  
1309     $p = "";
1310     $n = $start;
1311  
1312     while ($n) {
1313  
1314        $n -= $dir * $overlap;
1315  
1316        $e = $n + $dir * ($limit + $overlap) + 1;
1317  
1318        if ($dir<0) {
1319           $e = max(1, $e);
1320           if ($e <= $collapse_last * $limit) {
1321              $e = 1;
1322           }
1323        }
1324        else {
1325           $e = min($end, $e);
1326           if ($e >= $collapse_last * $limit) {
1327              $e = $end;
1328           }
1329        }
1330  
1331        $o .= ($o?" &middot; ":"")
1332           . '<a href="'.ewiki_script($action, $id, array(EWIKI_UP_PAGENUM=>$n, EWIKI_UP_PAGEEND=>$e))
1333           . '">'. "$n-$e" . '</a>';
1334  
1335        if (($n=$e-1) < $end) {
1336           $n = false;
1337        }
1338     }
1339  
1340     return('<span class="chunked-result">'. $o .'</span>');
1341  }
1342  
1343  
1344  
1345  
1346  
1347  
1348  function ewiki_page_edit($id, $data, $action) {
1349  
1350     global $ewiki_links, $ewiki_author, $ewiki_plugins, $ewiki_ring, $ewiki_errmsg;
1351  
1352     $hidden_postdata = array();
1353  
1354     #-- previous version come back
1355     if (@$data["forced_version"]) {
1356  
1357        $current = ewiki_database("GET", array("id"=>$id));
1358        $data["version"] = $current["version"];
1359        unset($current);
1360  
1361        unset($_REQUEST["content"]);
1362        unset($_REQUEST["version"]);
1363     }
1364  
1365     #-- edit hacks
1366     if ($pf_a = @$ewiki_plugins["edit_hook"]) foreach ($pf_a as $pf) {
1367        if ($output = $pf($id, $data, $hidden_postdata)) {
1368           return($output);
1369        }
1370     }
1371  
1372     #-- permission checks
1373     if (isset($ewiki_ring)) {
1374        $ring = $ewiki_ring;
1375     } else { 
1376        $ring = 3;
1377     }
1378     $flags = @$data["flags"];
1379     if (!($flags & EWIKI_DB_F_WRITEABLE)) {
1380  
1381        #-- perform auth
1382        $edit_ring = (EWIKI_PROTECTED_MODE>=2) ? (2) : (NULL);
1383        if (EWIKI_PROTECTED_MODE && !ewiki_auth($id, $data, $action, $edit_ring, "FORCE")) {
1384           return($ewiki_errmsg);
1385        }
1386  
1387        #-- flag checking
1388        if (($flags & EWIKI_DB_F_READONLY) and ($ring >= 2)) {
1389           return(ewiki_t("CANNOTCHANGEPAGE"));
1390        }
1391        if (($flags) and (($flags & EWIKI_DB_F_TYPE) != EWIKI_DB_F_TEXT) and ($ring >= 1)) {
1392           return(ewiki_t("CANNOTCHANGEPAGE"));
1393        }
1394     }
1395  
1396     #-- "Edit Me"
1397     $o = ewiki_make_title($id, ewiki_t("EDITTHISPAGE").(" '{$id}'"), 2, $action, "", "_MAY_SPLIT=1");
1398  
1399     #-- preview
1400     if (isset($_REQUEST["preview"])) {
1401        $o .= $ewiki_plugins["edit_preview"][0]($data);
1402     }
1403  
1404     #-- save
1405     if (isset($_REQUEST["save"])) {
1406  
1407  
1408           #-- normalize to UNIX newlines
1409           $_REQUEST["content"] = str_replace("\015\012", "\012", $_REQUEST["content"]);
1410           $_REQUEST["content"] = str_replace("\015", "\012", $_REQUEST["content"]);
1411  
1412           #-- check for concurrent version saving
1413           $error = 0;
1414           if ((@$data["version"] >= 1) && ($data["version"] != @$_REQUEST["version"]) || (@$_REQUEST["version"] < 1)) {
1415  
1416              $pf = $ewiki_plugins["edit_patch"][0];
1417  
1418              if (!$pf || !$pf($id, $data)) {
1419                 $error = 1;
1420                 $o .= ewiki_t("ERRVERSIONSAVE") . "<br /><br />";
1421              }
1422  
1423           }
1424           if (!$error) {
1425  
1426              #-- new pages` flags
1427              if (! ($set_flags = @$data["flags"] & EWIKI_DB_F_COPYMASK)) {
1428                 $set_flags = 1;
1429              }
1430              if (EWIKI_ALLOW_HTML) {
1431                 $set_flags |= EWIKI_DB_F_HTML;
1432              }
1433  
1434              #-- mk db entry
1435              $save = array(
1436                 "id" => $id,
1437                 "version" => @$data["version"] + 1,
1438                 "flags" => $set_flags,
1439                 "content" => $_REQUEST["content"],
1440                 "created" => ($uu=@$data["created"]) ? $uu : time(),
1441                 "meta" => ($uu=@$data["meta"]) ? $uu : "",
1442                 "hits" => ($uu=@$data["hits"]) ? $uu : "0",
1443              );
1444              ewiki_data_update($save);
1445  
1446              #-- edit storage hooks
1447              if ($pf_a = @$ewiki_plugins["edit_save"]) {
1448                 foreach ($pf_a as $pf) {
1449                    $pf($save, $data);
1450                 }
1451              }
1452  
1453              #-- save
1454              if (!$save || !ewiki_database("WRITE", $save)) {
1455  
1456                 $o .= $ewiki_errmsg ? $ewiki_errmsg : ewiki_t("ERRORSAVING");
1457  
1458              }
1459              else {
1460                 #-- prevent double saving, when ewiki_page() is re-called
1461                 $_REQUEST = $_GET = $_POST = array();
1462  
1463                 $o = ewiki_t("THANKSFORCONTRIBUTION") . "<br /><br />";
1464                 $o .= ewiki_page($id);
1465  
1466                 if (EWIKI_EDIT_REDIRECT) {
1467                    $url = ewiki_script("", $id, "thankyou=1", 0, 0, EWIKI_HTTP_HEADERS?ewiki_script_url():0);
1468                   
1469                    if (EWIKI_HTTP_HEADERS && !headers_sent()) {
1470                       header("Status: 303 Redirect for GET");
1471                       header("Location: $url");
1472                       #header("URI: $url");
1473                       #header("Refresh: 0; URL=$url");
1474                    }
1475                    else {
1476                       $o .= '<meta http-equiv="Refresh" content="0; URL='.s($url).'">';
1477                    }
1478                 }
1479  
1480              }
1481  
1482           }
1483  
1484           //@REWORK
1485           // header("Reload-Location: " . ewiki_script("", $id, "", 0, 0, ewiki_script_url()) );
1486  
1487     }
1488     else {
1489        #-- Edit <form>
1490        $o .= ewiki_page_edit_form($id, $data, $hidden_postdata);
1491  
1492        #-- additional forms
1493        if ($pf_a = $ewiki_plugins["edit_form_final"]) foreach ($pf_a as $pf) {
1494           $pf($o, $id, $data, $action);
1495        }
1496     }
1497  
1498     return($o);
1499  }
1500  
1501  
1502  function ewiki_data_update(&$data, $author="") {
1503     global $USER, $ewiki_links;
1504  
1505     #-- add backlinks entry
1506     ewiki_scan_wikiwords($data["content"], $ewiki_links, "_STRIP_EMAIL=1");
1507     $data["refs"] = "\n\n".implode("\n", array_keys($ewiki_links))."\n\n";
1508     $data["lastmodified"] = time();
1509     $data["author"] = ewiki_author($author);
1510     if (isset($USER->id)) {
1511         $data["userid"] = $USER->id;
1512     }
1513  }
1514  
1515  
1516  
1517  #-- edit <textarea>
1518  function ewiki_page_edit_form(&$id, &$data, &$hidden_postdata) {
1519     global $ewiki_plugins, $ewiki_config, $moodle_format;   
1520  
1521     $o='';
1522        
1523     #-- previously edited, or db fetched content
1524     if (@$_REQUEST["content"] || @$_REQUEST["version"]) {
1525        $data = array(
1526           "version" => &$_REQUEST["version"],
1527           "content" => &$_REQUEST["content"]
1528        );
1529     }
1530     else {
1531        if (empty($data["version"])) {
1532           $data["version"] = 1;
1533        }
1534        @$data["content"] .= "";
1535     }
1536  
1537     #-- normalize to DOS newlines
1538     $data["content"] = str_replace("\015\012", "\012", $data["content"]);
1539     $data["content"] = str_replace("\015", "\012", $data["content"]);
1540     $data["content"] = str_replace("\012", "\015\012", $data["content"]);
1541  
1542     $hidden_postdata["version"] = &$data["version"];
1543  
1544     #-- edit textarea/form
1545     // deleted name="ewiki", can not find the reference, and it's breaking xhtml
1546     $o .= ewiki_t("EDIT_FORM_1")
1547         . '<form method="post" enctype="multipart/form-data" action="'
1548         . ewiki_script("edit", $id) . '" '
1549         . ' accept-charset="'.EWIKI_CHARSET.'">' . "\n";
1550     $o .= '<div>';
1551     #-- additional POST vars
1552     foreach ($hidden_postdata as $name => $value) {
1553         $o .= '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
1554     }
1555  
1556     ($cols = strtok($ewiki_config["edit_box_size"], "x*/,;:")) && ($rows = strtok("x, ")) || ($cols=70) && ($rows=15);
1557     global $ewiki_use_editor, $ewiki_editor_content;
1558     $ewiki_editor_content=1;
1559     if($ewiki_use_editor) {
1560       ob_start();
1561       $usehtmleditor = can_use_html_editor();
1562       echo '<table><tr><td>';
1563       if ($usehtmleditor) { //clean and convert before editing
1564           $options = new object();
1565           $options->smiley = false;
1566           $options->filter = false;
1567           $oldtext = format_text(ewiki_format($data["content"]), $moodle_format, $options);
1568       } else {
1569           $oldtext = ewiki_format($data["content"]);
1570       }
1571       print_textarea($usehtmleditor, $rows, $cols, 680, 400, "content", $oldtext);
1572       echo '</td></tr></table>';
1573  
1574       if ($usehtmleditor) {
1575          use_html_editor("content");
1576       }
1577       $o .= ob_get_contents();     
1578       ob_end_clean();     
1579  
1580     } else {
1581     ##### END MOODLE ADDITION #####
1582  
1583       $o .= '<textarea wrap="soft" id="ewiki_content" name="content" rows="'.$rows.'" cols="'.$cols.'">'
1584          . s($data["content"]) . "</textarea>"
1585          . $GLOBALS["ewiki_t"]["C"]["EDIT_TEXTAREA_RESIZE_JS"];
1586  
1587     ##### BEGIN MOODLE ADDITION #####
1588     }
1589     ##### END MOODLE ADDITION #####
1590     
1591     #-- more <input> elements before the submit button
1592     if ($pf_a = $ewiki_plugins["edit_form_insert"]) foreach ($pf_a as $pf) {
1593        $o .= $pf($id, $data, $action);
1594     }
1595  
1596     ##### BEGIN MOODLE ADDITION (Cancel Editing into Button) #####
1597     $o .= "\n<br />\n"
1598        . '<input type="submit" name="save" value="'. ewiki_t("SAVE") . '" />'."\n"
1599        . '<input type="submit" name="preview" value="'. ewiki_t("PREVIEW") . '" />' . "\n"
1600        . '<input type="submit" name="canceledit" value="'. ewiki_t("CANCEL_EDIT") . '" />' . "\n";
1601  #      . ' &nbsp; <a href="'. ewiki_script("", $id) . '">' . ewiki_t("CANCEL_EDIT") . '</a>';
1602     ##### END MOODLE ADDITION #####
1603  
1604     #-- additional form elements
1605     if ($pf_a = $ewiki_plugins["edit_form_append"]) foreach ($pf_a as $pf) {
1606        $o .= $pf($id, $data, $action);
1607     }
1608  
1609     $o .= "\n</div></form>\n";
1610     //   . ewiki_t("EDIT_FORM_2");  // MOODLE DELETION
1611  
1612     return('<div class="edit-box">'. $o .'</div>');
1613  }
1614  
1615  
1616  
1617  #-- pic upload form
1618  function ewiki_page_edit_form_final_imgupload(&$o, &$id, &$data, &$action) {
1619     if (EWIKI_SCRIPT_BINARY && EWIKI_UP_UPLOAD && EWIKI_IMAGE_MAXSIZE) {
1620        $o .= "\n<br />\n". '<div class="image-upload">'
1621        . '<form action='
1622        . '"'. ewiki_script_binary("", EWIKI_IDF_INTERNAL, "", "_UPLOAD=1") .'"'
1623        . ' method="post" enctype="multipart/form-data" target="_upload">'
1624        . '<fieldset class="invisiblefieldset">'
1625        . '<input type="hidden" name="MAX_FILE_SIZE" value="'.EWIKI_IMAGE_MAXSIZE.'" />'
1626        . '<input type="file" name="'.EWIKI_UP_UPLOAD.'"'
1627        . (defined("EWIKI_IMAGE_ACCEPT") ? ' accept="'.EWIKI_IMAGE_ACCEPT.'" />' : " />")
1628        . '<input type="hidden" name="'.EWIKI_UP_BINARY.'" value="'.EWIKI_IDF_INTERNAL.'" />'
1629        . '&nbsp;&nbsp;&nbsp;'
1630        . '<input type="submit" value="'.ewiki_t("UPLOAD_PICTURE_BUTTON").'" />'
1631        . '</fieldset></form></div>'. "\n";
1632    }
1633  }
1634  
1635  
1636  function ewiki_page_edit_preview(&$data) {
1637  #### BEGIN MOODLE CHANGES   
1638     global $moodle_format;   
1639     $preview_text=$GLOBALS["ewiki_plugins"]["render"][0]($_REQUEST["content"], 1, EWIKI_ALLOW_HTML || (@$data["flags"]&EWIKI_DB_F_HTML));
1640     return( '<div class="preview">'
1641             . "<hr noshade>"
1642             . "<div align=\"right\">" . ewiki_t("PREVIEW") . "</div><hr noshade><br />\n"
1643             . format_text($preview_text, $moodle_format)
1644             . "<br /><br /><hr noshade><br />"
1645             . "</div>"
1646     );
1647  #### END MOODLE CHANGES   
1648  }
1649  
1650  
1651  function ewiki_control_links($id, &$data, $action) {
1652  
1653     global $ewiki_plugins, $ewiki_ring, $ewiki_config;
1654     $action_links = & $ewiki_config["action_links"][$action];
1655  
1656     #-- disabled
1657     if (!$ewiki_config["control_line"]) {
1658        return("");
1659     }
1660  
1661     $o = "\n"
1662        . '<div align="right" class="action-links control-links">'
1663        . "\n<br />\n"
1664        . "<hr noshade>" . "\n";
1665  
1666     if (@$data["forced_version"]) {
1667  
1668        $o .= '<form action="' . ewiki_script("edit", $id) . '" method="post">' .
1669              '<fieldset class="invisiblefieldset">'.
1670              '<input type="hidden" name="edit" value="old" />' .
1671              '<input type="hidden" name="version" value="'.$data["forced_version"].'" />' .
1672              '<input type="submit" value="' . ewiki_t("OLDVERCOMEBACK") . '" /></form> ';
1673     }
1674     else {
1675        foreach ($action_links as $action => $title)
1676        if (!empty($ewiki_plugins["action"][$action]) || !empty($ewiki_plugins["action_always"][$action]) || strpos($action, ":/"))
1677        {
1678           if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($id, $data, $action))  { continue; }
1679  
1680           $o .= '<a href="'
1681              . (strpos($action, ":/") ? $action : ewiki_script($action, $id))
1682              . '">' . ewiki_t($title) . '</a> &middot; ';
1683        }
1684     }
1685  
1686     if ($data["lastmodified"] >= UNIX_MILLENNIUM) { 
1687        $o .= '<small>' . strftime(ewiki_t("LASTCHANGED"), @$data["lastmodified"]) . '</small>';
1688     }
1689  
1690     $o .= "</div>\n";
1691  
1692     return($o);
1693  }
1694  
1695  
1696  
1697  
1698  
1699  # ============================================================= rendering ===
1700  
1701  
1702  
1703  
1704  
1705  ########  ###   ###  #########  ###  ###   ###  #######
1706  ########  ####  ###  #########  ###  ####  ###  #######
1707  ###       ##### ###  ###             ##### ###  ###
1708  ######    #########  ###  ####  ###  #########  ######
1709  ######    #########  ###  ####  ###  #########  ######
1710  ###       ### #####  ###   ###  ###  ### #####  ###
1711  ########  ###  ####  #########  ###  ###  ####  #######
1712  ########  ###   ###  #########  ###  ###   ###  #######
1713  
1714  
1715  /*
1716     The _format() function transforms $wiki_source pages into <html> strings,
1717     also calls various markup and helper plugins during the transformation
1718     process. The $params array can activate various features and extensions.
1719     only accepts UNIX newlines!
1720  */
1721  function ewiki_format (
1722              $wiki_source,
1723              $params = array()
1724           )
1725  {
1726     global $ewiki_links, $ewiki_plugins, $ewiki_config;
1727  
1728     #-- state vars
1729     $params = @array_merge($ewiki_config["format_params"], $params);
1730     $s = array(
1731        "in" => 0,         # current input $iii[] block array index
1732        "para" => "",
1733        "line" => "",
1734        "post" => "",      # string to append after current line/paragraph
1735        "line_i" => 0,
1736        "lines" => array(),
1737        "list" => "",      # lists
1738        "tbl" => 0,        # open table?
1739        "indent" => 0,     # indentation
1740        "close" => array(),
1741     );
1742     #-- aliases
1743     $in = &$s["in"]; 
1744     $line = &$s["line"];
1745     $lines = &$s["lines"];
1746     $para = &$s["para"];
1747     $post = &$s["post"];
1748     $list = &$s["list"];
1749  
1750     #-- input and output arrays
1751     if ($wiki_source[0] == "<") {            # also prepend an empty line 
1752        $wiki_source = "\n" . $wiki_source;    # for faster strpos() searchs
1753     }
1754     $iii = array(
1755        0 => array(
1756           0 => $wiki_source."\n",    # body + empty line
1757           1 => 0x0FFF,               # flags (0x1=WikiMarkup, 0x2=WikiLinks, 0x100=BlockPlugins)
1758           2 => "core",               # block plugin name
1759        )
1760     );
1761     $ooo = array(
1762     );
1763     unset($wiki_source);
1764  
1765     #-- plugins
1766     $pf_tbl = @$ewiki_plugins["format_table"][0];
1767     $pf_line = @$ewiki_plugins["format_line"];
1768  
1769     #-- wikimarkup (wm)
1770     $htmlentities = $ewiki_config["htmlentities"];
1771     $wm_indent = &$ewiki_config["wm_indent"];
1772     $wm_table_defaults = &$ewiki_config["wm_table_defaults"];
1773     $wm_source = &$ewiki_config["wm_source"];
1774     $wm_list = &$ewiki_config["wm_list"];
1775     $wm_list_chars = implode("", array_keys($wm_list));
1776     $wm_style = &$ewiki_config["wm_style"];
1777     $wm_start_end = &$ewiki_config["wm_start_end"];
1778  
1779     #-- eleminate html
1780     $iii[0][0] = strtr($iii[0][0], $htmlentities);
1781     unset($htmlentities["&"]);
1782  
1783     #-- pre-processing plugins (working on wiki source)
1784     if ($pf_source = $ewiki_plugins["format_source"]) {
1785        foreach ($pf_source as $pf) $pf($iii[0][0]);
1786     }
1787  
1788     #-- simple markup
1789     $iii[0][0] = strtr($iii[0][0], $wm_source);
1790  
1791     #-- separate input into blocks ------------------------------------------
1792     foreach ($ewiki_config["format_block"] as $btype => $binfo) {
1793  
1794        #-- disabled block plugin?
1795        if ($binfo[2] && !$params[$binfo[2]])  {
1796           continue;
1797        }
1798  
1799        #-- traverse $iii[]
1800        $in = -1;
1801        while ((++$in) < count($iii)) {
1802  
1803           #-- search fragment delimeters
1804           if ($iii[$in][1] & 0x0100)
1805           while (
1806              ($c = & $iii[$in][0]) &&
1807              (($l = strpos($c, $binfo[0])) !== false) &&
1808              ($r = strpos($c, $binfo[1], $l))   )
1809           {
1810              $l_len = strlen($binfo[0]);
1811              $r_len = strlen($binfo[1]);
1812  
1813              $repl = array();
1814              // pre-text
1815              if (($l > 0) && trim($text = substr($c, 0, $l))) {
1816                 $repl[] = array($text, 0xFFFF, "core");
1817              }
1818              // the extracted part
1819              if (trim($text = substr($c, $l+$l_len, $r-$l-$r_len))) {
1820                 $repl[] = array($text, $binfo[3], "$btype");
1821              }
1822              // rest
1823              if (($r+$r_len < strlen($c)) && trim($text = substr($c, $r+$r_len))) {
1824                 $repl[] = array($text, 0xFFFF, "core");
1825              }
1826              array_splice($iii, $in, 1, $repl);
1827  
1828              $in += 1;
1829           }
1830        }
1831     }
1832  
1833     #-- run format_block plugins
1834     $in = -1;
1835     while ((++$in) < count($iii)) {
1836        if (($btype = $iii[$in][2]) && ($pf_a = $ewiki_plugins["format_block"][$btype])) {
1837           $c = &$iii[$in][0];
1838           foreach ($pf_a as $pf) {   
1839              # current buffer $c and pointer $in into $iii[] and state $s
1840              $pf($c, $in, $iii, $s, $btype);
1841           }
1842        }
1843     }
1844  
1845     #-- wiki markup ------------------------------------------------------
1846     $para = "";
1847     $in = -1;   
1848     while ((++$in) < count($iii)) {
1849        #-- wikimarkup
1850        if ($iii[$in][1] & 0x0001) {
1851  
1852           #-- input $lines buffer, and output buffer $ooo array
1853           $lines = explode("\n", $iii[$in][0]);
1854           $ooo[$in] = array(
1855              0 => "",
1856              1 => $iii[$in][1]
1857           );
1858           $out = &$ooo[$in][0];
1859           $s["block"] = ($iii[$in][2] != "core");  # disables indentation & paragraphs
1860  
1861           #-- walk through wiki source lines
1862           $line_max = count($lines);
1863           foreach ($lines as $s["line_i"]=>$line) {
1864  //echo "<pre>line={$s[line_i]}:".htmlspecialchars($line).":".htmlspecialchars($line[0])."</pre>";
1865  
1866              #-- empty lines separate paragraphs
1867              if (!strlen($line)) {
1868                 ewiki_format_close_para($ooo, $s);
1869                 ewiki_format_close_tags($ooo, $s);
1870                 if (!$s["block"]) {
1871                    $out .= "\n";
1872                 }
1873              }
1874              #-- horiz bar
1875              if (!strncmp($line, "----", 4)) {
1876                 $out .= "<hr noshade>\n";
1877                 continue;
1878              }
1879              #-- html comment
1880              #if (!strncmp($line, "&lt;!--", 7)) {
1881              #   $out .= "<!-- " . htmlentities(str_replace("--", "__", substr($line, 7))) . " -->\n";
1882              #   continue;
1883              #}
1884  
1885              ($c0 = $line[0])
1886              or ($c0 = "\000");
1887  
1888              #-- tables
1889              ### MOODLE CHANGE: TRIM
1890              if (($c0 == "|") && ($line[strlen(trim($line))-1] == "|")) {
1891                 if (!$s["tbl"]) {
1892                    ewiki_format_close_para($ooo, $s);
1893                    ewiki_format_close_tags($ooo, $s);
1894                    $s["list"] = "";
1895                 }
1896                 $line = substr($line, 1, -1);
1897                 if ($pf_tbl) { 
1898                    $pf_tbl($line, $ooo, $s);
1899                 }
1900                 else {
1901                    if (!$s["tbl"]) {  
1902                       $out .= "<table " . $wm_table_defaults . ">\n";
1903                       $s["close"][] = "\n</table>"; 
1904                    }
1905                    $line = "<tr>\n<td>" . str_replace("|", "</td>\n<td>", $line) . "</td>\n</tr>";
1906                 }
1907                 $s["tbl"] = 1;
1908                 $para = false;
1909              }
1910              elseif ($s["tbl"]) {
1911                 $s["tbl"] = 0;
1912              }
1913  
1914  
1915              #-- headlines
1916              if (($c0 == "!") && ($excl = strspn($line, "!"))) {
1917                 if ($excl > 3) { 
1918                    $excl = 3;
1919                 }
1920                 $line = substr($line, $excl);
1921                 $excl = 5 - $excl;
1922                 $line = "<h$excl>" . $line . "</h$excl>";
1923                 if ($para) {
1924                    ewiki_format_close_para($ooo, $s);
1925                 }
1926                 ewiki_format_close_tags($ooo, $s);
1927                 $para = false;
1928              }
1929  
1930              #-- whole-line markup
1931              # ???
1932  
1933  
1934              #-- indentation (space/tab markup)
1935              $n_indent = 0;
1936              if (!$list && (!$s["block"]) && ($n_indent = strspn($line, " "))) {
1937                 $n_indent = (int) ($n_indent / 2.65);
1938                 while ($n_indent > $s["indent"]) { 
1939                    $out .= $wm_indent;
1940                    $s["indent"]++;
1941                 }
1942              }
1943              while ($n_indent < $s["indent"]) { 
1944                 $out .= "";
1945                 $s["indent"]--;
1946              }
1947  
1948  
1949              #-- text style triggers
1950              foreach ($wm_style as $find=>$replace) {
1951                 $find_len = strlen($find);
1952                 $loop = 20;
1953                 while(($loop--) && (($l = strpos($line, $find)) !== false) && ($r = strpos($line, $find, $l + $find_len))) {
1954                    $line = substr($line, 0, $l) . $replace[0] .
1955                            substr($line, $l + strlen($find), $r - $l - $find_len) .
1956                            $replace[1] . substr($line, $r + $find_len);
1957                 }
1958              }
1959  
1960  
1961              #-- list markup
1962              if (isset($wm_list[$c0])) {
1963                 if (!$list) {
1964                    ewiki_format_close_para($ooo, $s);
1965                    ewiki_format_close_tags($ooo, $s);
1966                 }
1967                 $new_len = strspn($line, $wm_list_chars);
1968                 $new_list = substr($line, 0, $new_len);
1969                 $old_len = strlen($list);
1970                 $lchar = $new_list[$new_len-1];
1971                 list($lopen, $ltag1, $ltag2) = $wm_list[$lchar];
1972  
1973                 #-- cut line
1974                 $line = substr($line, $new_len);
1975                 $lspace = "";
1976                 $linsert = "";
1977                 if ($ltag1) {
1978                    $linsert = "<$ltag1>" . strtok($line, $lchar) . "</$ltag1> ";
1979                    $line = strtok("\000");
1980                 }
1981  
1982                 #-- add another <li>st entry
1983                 if ($new_len == $old_len) {
1984                    $lspace = str_repeat("  ", $new_len);
1985                    $out .=  "</$ltag2>\n" . $lspace . $linsert . "<$ltag2>";
1986                 }
1987                 #-- add list
1988                 elseif ($new_len > $old_len) {
1989                    while ($new_len > ($old_len=strlen($list))) {
1990                       $lchar = $new_list[$old_len];
1991                       $list .= $lchar;
1992                       list($lopen, $ltag1, $ltag2) = $wm_list[$lchar];