PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/extras/lionwiki/index.php

http://txt2tags.googlecode.com/
PHP | 745 lines | 645 code | 73 blank | 27 comment | 78 complexity | 01f857d01e0e8540737197f8e36c4af8 MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0, WTFPL
  1. <?php // LionWiki-t2t 3.2.9d - 2013-08-14
  2. // This version (modified by Eric Forgeot) is an altered version of LionWiki 3.2.9 (c) Adam Zivner, licensed under GNU/GPL v2
  3. // and uses txt2tags.class.php to render the pages.
  4. // Don't forget to include txt2tags.class.php in the same folder as this file!
  5. // Use: Download and extract LionWiki from http://lionwiki.0o.cz/
  6. // Add those files instead of the ones in the original installation.
  7. // If you set a password in this file, convert it to SHA1 first, or
  8. // if you use config.php, put your real password
  9. // in plain text into $PASSWORD = sha1("password");
  10. //
  11. // <!> SECURITY WARNING: You should install this wiki in its current
  12. // configuration for personal webpages or notepad only.
  13. // if you intend to use this wiki for a public wiki, with edit access
  14. // for everyone, it could lead to some potential security gap:
  15. // - Txt2tags allows to alter virtually everything with its pre
  16. // and postproc feature. You can disable it in txt2tags.class.php
  17. // - It's possible to include php code with this current lionwiki
  18. // version. You should disable this in the part labelled
  19. // "security warning" below.
  20. foreach($_REQUEST as $k => $v)
  21. unset($$k); // register_globals = off
  22. // SETTINGS - default settings, can be overridden in config.php
  23. $WIKI_TITLE = 'My new wiki'; // name of the site
  24. $PASSWORD = ''; // SHA1 hash
  25. $TEMPLATE = 'templates/dandelion.html'; // presentation template
  26. $PROTECTED_READ = false; // if true, you need to fill password for reading pages too
  27. $NO_HTML = true; // XSS protection
  28. $START_PAGE = 'Main page'; // Which page should be default (start page)?
  29. $SYNTAX_PAGE = 'http://lionwiki.0o.cz/?page=Syntax+reference';
  30. $DATE_FORMAT = 'Y/m/d H:i';
  31. $LOCAL_HOUR = 0;
  32. @error_reporting(E_ERROR | E_WARNING | E_PARSE);
  33. @ini_set('default_charset', 'UTF-8');
  34. set_magic_quotes_runtime(0);
  35. umask(0);
  36. if(get_magic_quotes_gpc()) // magic_quotes_gpc can't be turned off
  37. for($i = 0, $_SG = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST), $c = count($_SG); $i < $c; ++$i)
  38. $_SG[$i] = array_map('stripslashes', $_SG[$i]);
  39. $self = basename($_SERVER['SCRIPT_NAME']);
  40. $REAL_PATH = realpath(dirname(__FILE__)).'/';
  41. $VAR_DIR = 'var/';
  42. $PG_DIR = $VAR_DIR.'pages/';
  43. $HIST_DIR = $VAR_DIR.'history/';
  44. $PLUGINS_DIR = 'plugins/';
  45. $PLUGINS_DATA_DIR = $VAR_DIR.'plugins/';
  46. $LANG_DIR = 'lang/';
  47. // default translation
  48. $T_HOME = 'Main page';
  49. $T_SYNTAX = 'Syntax';
  50. $T_DONE = 'Save changes';
  51. $T_DISCARD_CHANGES = 'Discard changes';
  52. $T_PREVIEW = 'Preview';
  53. $T_SEARCH = 'Search';
  54. $T_SEARCH_RESULTS = 'Search results';
  55. $T_LIST_OF_ALL_PAGES = 'List of all pages';
  56. $T_RECENT_CHANGES = 'Recent changes';
  57. $T_LAST_CHANGED = 'Last changed';
  58. $T_HISTORY = 'History';
  59. $T_RESTORE = 'Restore';
  60. $T_REV_DIFF = '<b>Difference between revisions from {REVISION1} and {REVISION2}.</b>';
  61. $T_REVISION = "'''This revision is from {TIME}. You can {RESTORE} it.'''\n\n";
  62. $T_PASSWORD = 'Password';
  63. $T_EDIT = 'Edit';
  64. $T_EDIT_SUMMARY = 'Summary of changes';
  65. $T_EDIT_CONFLICT = 'Edit conflict: somebody saved this page after you started editing. See last {DIFF} before saving your changes.';
  66. $T_SHOW_SOURCE = 'Show source';
  67. $T_SHOW_PAGE = 'Show page';
  68. $T_ERASE_COOKIE = 'Erase cookies';
  69. $T_MOVE_TEXT = 'New name';
  70. $T_DIFF = 'diff';
  71. $T_CREATE_PAGE = 'Create page';
  72. $T_PROTECTED_READ = 'You need to enter password to view content of site: ';
  73. $T_WRONG_PASSWORD = 'Password is incorrect.';
  74. if($_GET['lang']) {
  75. $LANG = clear_path($_GET['lang']);
  76. setcookie('LW_LANG', $LANG, time() + 365 * 86400);
  77. } elseif($_COOKIE['LW_LANG'])
  78. $LANG = clear_path($_COOKIE['LW_LANG']);
  79. else
  80. list($LANG) = explode(',', clear_path($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  81. if((@include("$LANG_DIR$LANG.php")) === false && (@include($LANG_DIR . substr($LANG, 0, 2) . '.php')) === false)
  82. $LANG = 'en';
  83. @include('config.php'); // config file is not required, see settings above
  84. // Creating essential directories if they don't exist
  85. if(!file_exists($VAR_DIR) && !mkdir(rtrim($VAR_DIR, "/")))
  86. die("Can't create directory $VAR_DIR. Please create $VAR_DIR with 0777 rights.");
  87. else foreach(array($PG_DIR, $HIST_DIR, $PLUGINS_DATA_DIR) as $DIR)
  88. if(@mkdir(rtrim($DIR, '/'), 0777)) {
  89. $f = fopen($DIR . ".htaccess", "w"); fwrite($f, "deny from all"); fclose($f); }
  90. if($_GET['erasecookie']) // remove cookie without reloading
  91. foreach($_COOKIE as $k => $v)
  92. if(substr($k, 0, 3) == 'LW_') {
  93. setcookie($k);
  94. unset($_COOKIE[$k]);
  95. }
  96. for($plugins = array(), $dir = @opendir($PLUGINS_DIR); $dir && $f = readdir($dir);) // load plugins
  97. if(preg_match('/wkp_(.+)\.php$/', $f, $m) > 0) {
  98. require $PLUGINS_DIR . $f;
  99. $plugins[$m[1]] = new $m[1]();
  100. if(isset($$m[1]))
  101. foreach($$m[1] as $name => $value)
  102. $plugins[$m[1]]->$name = $value;
  103. }
  104. plugin('pluginsLoaded');
  105. foreach(array('action', 'content', 'error', 'esum', 'f1', 'f2', 'last_changed', 'moveto', 'page', 'par', 'preview', 'query', 'restore', 'sc', 'showsource') as $req)
  106. $$req = $_REQUEST[$req]; // export request variables to global namespace
  107. foreach(array('par', 'restore', 'showsource') as $var)
  108. isset($$var) && $$var = intval($$var);
  109. $TITLE = $page = clear_path($page); $moveto = clear_path($moveto); $f1 = clear_path($f1); $f2 = clear_path($f2);
  110. $CON = $content;
  111. $error = h($error);
  112. plugin('actionBegin');
  113. if(!$action)
  114. if(!$page)
  115. die(header("Location:$self?page=" . u($START_PAGE)));
  116. elseif(file_exists("$PG_DIR$page.$LANG.txt")) // language variant
  117. die(header("Location:$self?page=" . u("$page.$LANG")));
  118. elseif(!file_exists("$PG_DIR$page.txt"))
  119. $action = 'edit'; // create page if it doesn't exist
  120. if($PROTECTED_READ && !authentified()) { // does user need password to read content of site. If yes, ask for it.
  121. $CON = "<form action=\"$self?page=".u($page)."\" method=\"post\"><p>$T_PROTECTED_READ <input type=\"password\" name=\"sc\"/> <input class=\"submit\" type=\"submit\"/></p></form>";
  122. $action = 'view-html';
  123. } else if($restore || $action == 'rev') { // Show old revision
  124. $CON = @file_get_contents("$HIST_DIR$page/$f1");
  125. if($action == 'rev') {
  126. $rev_restore = "[$T_RESTORE|./$self?page=".u($page)."&amp;action=edit&amp;f1=$f1&amp;restore=1]";
  127. $CON = strtr($T_REVISION, array('{TIME}' => rev_time($f1), '{RESTORE}' => $rev_restore)) . $CON;
  128. $action = '';
  129. }
  130. } else if($page && (!$action || $action == 'edit')) {
  131. $CON = @file_get_contents("$PG_DIR$page.txt");
  132. $CON = $par ? get_paragraph($CON, $par) : $CON;
  133. if(!$action && substr($CON, 0, 10) == '{redirect:' && $_REQUEST['redirect'] != 'no')
  134. die(header("Location:$self?page=".u(clear_path(substr($CON, 10, strpos($CON, '}') - 10)))));
  135. }
  136. if ($page)
  137. $last_changed_ts = @filemtime("$PG_DIR$page.txt");
  138. if($action == 'save' && !$preview && authentified()) { // do we have page to save?
  139. if(!trim($content) && !$par) // delete empty page
  140. @unlink("$PG_DIR$page.txt");
  141. elseif($last_changed < @filemtime("$PG_DIR$page.txt")) {
  142. $action = 'edit';
  143. $error = str_replace('{DIFF}', "<a href=\"$self?page=".u($page)."&amp;action=diff\">$T_DIFF</a>", $T_EDIT_CONFLICT);
  144. } elseif(!plugin('writingPage')) { // are plugins OK with page? (e.g. checking for spam)
  145. if($par) {
  146. $c = @file_get_contents("$PG_DIR$page.txt");
  147. $content = str_replace(get_paragraph($c, $par), $content, $c);
  148. }
  149. if(!$file = @fopen("$PG_DIR$page.txt", 'w'))
  150. die("Could not write page $PG_DIR$page.txt!");
  151. // Security warning: if you don't protect your wiki to public edition, people might be able to include php code. Uncomment the following line to prevent this:
  152. //$content = str_replace("<", "&lt;", $content); // prevention of php code inclusion
  153. fwrite($file, $content); fclose($file);
  154. // Backup old revision
  155. @mkdir($HIST_DIR.$page, 0777); // Create directory if does not exist
  156. $rightnow = date('Ymd-Hi-s', time() + $LOCAL_HOUR * 3600);
  157. if(!$bak = @fopen("$HIST_DIR$page/$rightnow.bak", 'w'))
  158. die("Could not write to $HIST_DIR$page!");
  159. fwrite($bak, $content); fclose($bak);
  160. $es = fopen("$HIST_DIR$page/meta.dat", 'ab');
  161. fwrite($es, '!' . $rightnow .
  162. str_pad($_SERVER['REMOTE_ADDR'], 16, ' ', STR_PAD_LEFT) .
  163. str_pad(filesize("$PG_DIR$page.txt"), 11, ' ', STR_PAD_LEFT) . ' ' .
  164. str_pad(substr($esum, 0, 128), 128 + 2)) . "\n";
  165. fclose($es);
  166. if($moveto != $page && $moveto)
  167. if(file_exists("$PG_DIR$moveto.txt"))
  168. die('Error: target filename already exists. Page was not moved.');
  169. elseif(!rename("$PG_DIR$page.txt", "$PG_DIR$moveto.txt"))
  170. die('Unknown error! Page was not moved.');
  171. elseif(!rename($HIST_DIR.$page, $HIST_DIR.$moveto)) {
  172. rename("$PG_DIR$moveto.txt", "$PG_DIR$page.txt"); // revert previous change
  173. die('Unknown error2! Page was not moved.');
  174. } else
  175. $page = $moveto;
  176. if(!plugin('pageWritten'))
  177. die(header("Location:$self?page=" . u($page) . '&redirect=no' . ($par ? "&par=$par" : '') . ($_REQUEST['ajax'] ? '&ajax=1' : '')));
  178. else
  179. $action = ''; // display content ...
  180. } else // there's some problem with page, give user a chance to fix it
  181. $action = 'edit';
  182. } elseif($action == 'save' && !$preview) { // wrong password, give user another chance
  183. $error = $T_WRONG_PASSWORD;
  184. $action = 'edit';
  185. }
  186. if($action == 'edit' || $preview) {
  187. $CON_FORM_BEGIN = "<form action=\"$self\" method=\"post\"><input type=\"hidden\" name=\"action\" value=\"save\"/><input type=\"hidden\" name=\"last_changed\" value=\"$last_changed_ts\"/><input type=\"hidden\" name=\"showsource\" value=\"$showsource\"/><input type=\"hidden\" name=\"par\" value=\"".h($par)."\"/><input type=\"hidden\" name=\"page\" value=\"".h($page)."\"/>";
  188. $CON_FORM_END = '</form>';
  189. $CON_TEXTAREA = '<textarea class="contentTextarea" name="content" style="width:100%" cols="100" rows="30">'.h(str_replace("&lt;", "<", $CON)).'</textarea>';
  190. $CON_PREVIEW = '<input class="submit" type="submit" name="preview" value="'.$T_PREVIEW.'"/>';
  191. if(!$showsource) {
  192. $CON_SUBMIT = '<input class="submit" type="submit" value="'.$T_DONE.'"/>';
  193. $EDIT_SUMMARY_TEXT = $T_EDIT_SUMMARY;
  194. $EDIT_SUMMARY = '<input type="text" name="esum" value="'.h($esum).'"/>';
  195. if(!authentified()) { // if not logged on, require password
  196. $FORM_PASSWORD = $T_PASSWORD;
  197. $FORM_PASSWORD_INPUT = '<input type="password" name="sc"/>';
  198. }
  199. if(!$par) {
  200. $RENAME_TEXT = $T_MOVE_TEXT;
  201. $RENAME_INPUT = '<input type="text" name="moveto" value="'.h($page).'"/>';
  202. }
  203. }
  204. if($preview)
  205. $TITLE = "$T_PREVIEW: $page";
  206. } elseif($action == 'history') { // show whole history of page
  207. for($files = array(), $dir = @opendir("$HIST_DIR$page/"); $f = @readdir($dir);)
  208. if(substr($f, -4) == '.bak')
  209. $files[] = $f;
  210. rsort($files);
  211. $CON = '<form action="'.$self.'" method="get"><input type="hidden" name="action" value="diff"/><input type="hidden" name="page" value="'.h($page).'"/><input type="submit" class="submit" value="'.$T_DIFF.'"/><br/>';
  212. $meta = @fopen("$HIST_DIR$page/meta.dat", "rb");
  213. for($i = 0, $mi = 1, $c = count($files); $i < $c; $i++) {
  214. if(($m = meta_getline($meta, $mi)) && !strcmp(basename($files[$i], ".bak"), $m[0]))
  215. $mi++;
  216. $CON .= '<input type="radio" name="f1" value="'.h($files[$i]).'"/><input type="radio" name="f2" value="'.h($files[$i]).'"/>';
  217. $CON .= "<a href=\"$self?page=".u($page)."&amp;action=rev&amp;f1=".$files[$i]."\">".rev_time($files[$i])."</a> - ($m[2] B) $m[1] <i>".h($m[3])."</i><br/>";
  218. }
  219. $CON .= '</form>';
  220. } elseif($action == 'diff') {
  221. if(!$f1 && $dir = @opendir("$HIST_DIR$page/")) { // diff is made on two last revisions
  222. while($f = @readdir($dir))
  223. if(substr($f, -4) == '.bak')
  224. $files[] = clear_path($f);
  225. rsort($files);
  226. die(header("Location:$self?action=diff&page=".u($page)."&f1=".u($files[0])."&f2=".u($files[1])));
  227. }
  228. $r1 = "<a href=\"$self?page=".u($page)."&amp;action=rev&amp;f1=$f1\">".rev_time($f1)."</a>";
  229. $r2 = "<a href=\"$self?page=".u($page)."&amp;action=rev&amp;f1=$f2\">".rev_time($f2)."</a>";
  230. $CON = str_replace(array("{REVISION1}", "{REVISION2}"), array($r1, $r2), $T_REV_DIFF);
  231. $CON .= diff($f1, $f2);
  232. } elseif($action == 'search') {
  233. for($files = array(), $dir = opendir($PG_DIR); $f = readdir($dir);)
  234. if(substr($f, -4) == '.txt' && ($c = @file_get_contents($PG_DIR . $f)))
  235. if(!$query || stristr($f . $c, $query) !== false)
  236. $files[] = clear_path(substr($f, 0, -4));
  237. sort($files);
  238. foreach($files as $f)
  239. $list .= "<li><a href=\"$self?page=".u($f).'&amp;redirect=no">'.h($f)."</a></li>";
  240. $CON = "<ul>$list</ul>";
  241. if($query && !file_exists("$PG_DIR$query.txt")) // offer to create the page
  242. $CON = "<p><i><a href=\"$self?action=edit&amp;page=".u($query)."\">$T_CREATE_PAGE ".h($query)."</a>.</i></p>".$CON;
  243. $TITLE = (!$query ? $T_LIST_OF_ALL_PAGES : "$T_SEARCH_RESULTS $query") . " (".count($files).")";
  244. } elseif($action == 'recent') { // recent changes
  245. for($files = array(), $dir = opendir($PG_DIR); $f = readdir($dir);)
  246. if(substr($f, -4) == '.txt')
  247. $files[substr($f, 0, -4)] = filemtime($PG_DIR . $f);
  248. arsort($files);
  249. foreach(array_slice($files, 0, 100) as $f => $ts) { // just first 100 files
  250. if($meta = @fopen($HIST_DIR . basename($f, '.txt') . '/meta.dat', 'r')) {
  251. $m = meta_getline($meta, 1);
  252. fclose($meta);
  253. }
  254. $recent .= "<tr><td class=\"rc-diff\"><a href=\"$self?page=".u($f)."&amp;action=diff\">$T_DIFF</a></td><td class=\"rc-date\" nowrap>".date($DATE_FORMAT, $ts + $LOCAL_HOUR * 3600)."</td><td class=\"rc-ip\">$m[1]</td><td class=\"rc-page\"><a href=\"$self?page=".u($f)."&amp;redirect=no\">".h($f)."</a> <span class=\"rc-size\">($m[2] B)</span><i class=\"rc-esum\"> ".h($m[3])."</i></td></tr>";
  255. }
  256. $CON = "<table>$recent</table>";
  257. $TITLE = $T_RECENT_CHANGES;
  258. } else
  259. plugin('action', $action);
  260. if(!$action || $preview) { // page parsing
  261. if(preg_match("/(?<!\^)\{title:([^}\n]*)\}/U", $CON, $m)) { // Change page title
  262. $TITLE = $m[1];
  263. $CON = str_replace($m[0], "", $CON);
  264. }
  265. // This part will load the txt2tags class, and parse the txt file with it
  266. require_once('txt2tags.class.php');
  267. $CON = preg_replace("/=================(.*)/", "--------------------", $CON);
  268. $CON = preg_replace("/=====(.*)=====/m", "!!!$1", $CON);
  269. $CON = preg_replace("/====(.*)====/m", "!!!$1", $CON);
  270. $CON = preg_replace("/===(.*)===/m", "!!$1", $CON);
  271. $CON = preg_replace("/==(.*)==/m", "!$1", $CON);
  272. // heading 1 = heading 2 here:
  273. $CON = preg_replace("/=(.*)=/m", "!$1", $CON);
  274. $CON = preg_replace("/%%toc/m", "{TOC}", $CON);
  275. $stack = array();
  276. $x = new T2T($CON);
  277. // doesn't work yet, you have to enable it in the txt2tags.class.php:
  278. $x->enableheaders = 0;
  279. //$x->snippets['**'] = "<strong>%s</strong>"; # instead of <b>
  280. $x->go();
  281. $CON = $x->bodyhtml;
  282. // end txt2tags part
  283. // subpages
  284. while(preg_match('/(?<!\^){include:([^}]+)}/Um', $CON, $m)) {
  285. $includePage = clear_path($m[1]);
  286. if(!strcmp($includePage, $page)) // limited recursion protection
  287. $CON = str_replace($m[0], "'''Warning: subpage recursion!'''", $CON);
  288. elseif(file_exists("$PG_DIR$includePage.txt"))
  289. $CON = str_replace($m[0], file_get_contents("$PG_DIR$includePage.txt"), $CON);
  290. else
  291. $CON = str_replace($m[0], "'''Warning: subpage $includePage was not found!'''", $CON);
  292. }
  293. plugin('subPagesLoaded');
  294. // save content not intended for substitutions ({html} tag)
  295. if(!$NO_HTML) { // XSS protection
  296. preg_match_all("/(?<!\^)\{html\}(.+)\{\/html\}/Ums", $CON, $htmlcodes, PREG_PATTERN_ORDER);
  297. $CON = preg_replace("/(?<!\^)\{html\}.+\{\/html\}/Ums", "{HTML}", $CON);
  298. foreach($htmlcodes[1] as &$hc)
  299. $hc = str_replace("&lt;", "<", $hc);
  300. }
  301. $CON = preg_replace("/(?<!\^)<!--.*-->/U", "", $CON); // internal comments
  302. $CON = preg_replace("/\^(.)/e", "'&#'.ord('$1').';'", $CON);
  303. // we disable this replacement because the txt2tags class is handling this instead
  304. //$CON = str_replace(array("<", "&"), array("&lt;", "&amp;"), $CON);
  305. $CON = preg_replace("/&amp;([a-z]+;|\#[0-9]+;)/U", "&$1", $CON); // keep HTML entities
  306. $CON = preg_replace("/(\r\n|\r)/", "\n", $CON); // unifying newlines to Unix ones
  307. preg_match_all("/{{(.+)}}/Ums", $CON, $codes, PREG_PATTERN_ORDER);
  308. $CON = preg_replace("/{{(.+)}}/Ums", "<pre>{CODE}</pre>", $CON);
  309. // spans
  310. preg_match_all("/\{([\.#][^\s\"\}]*)(\s([^\}\"]*))?\}/m", $CON, $spans, PREG_SET_ORDER);
  311. foreach($spans as $m) {
  312. $class = $id = '';
  313. $parts = preg_split('/([\.#])/', $m[1], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  314. for($i = 0, $c = count($parts); $c > 1 && $i < $c; $i += 2)
  315. if($parts[$i] == '.')
  316. $class .= $parts[$i + 1] . ' ';
  317. else
  318. $id = $parts[$i + 1];
  319. $CON = str_replace($m[0], '<span'.($id ? " id=\"$id\"" : '').($class ? " class=\"$class\"" : '').($m[3] ? " style=\"$m[3]\"" : '').'>', $CON);
  320. }
  321. $CON = str_replace('{/}', '</span>', $CON);
  322. plugin('formatBegin');
  323. $CON = strtr($CON, array('&lt;-->' => '&harr;', '-->' => '&rarr;', '&lt;--' => '&larr;', "(c)" => '&copy;', "(r)" => '&reg;'));
  324. $CON = preg_replace("/\{small\}(.*)\{\/small\}/U", "<small>$1</small>", $CON); // small
  325. $CON = preg_replace("/\{su([bp])\}(.*)\{\/su([bp])\}/U", "<su$1>$2</su$3>", $CON); // sup and sub
  326. // txt2tags.class.php is already doing this part:
  327. //$CON = preg_replace("/^([^!\*#\n][^\n]+)$/Um", '<p>$1</p>', $CON); // paragraphs
  328. // images
  329. preg_match_all("#\[((https?://|\./)[^|\]\"]+\.(jpeg|jpg|gif|png))(\|[^\]]+)?\]#", $CON, $imgs, PREG_SET_ORDER);
  330. foreach($imgs as $img) {
  331. $link = $i_attr = $a_attr = $center = $tag = "";
  332. preg_match_all("/\|([^\]\|=]+)(=([^\]\|\"]+))?(?=[\]\|])/", $img[0], $options, PREG_SET_ORDER);
  333. foreach($options as $o)
  334. if($o[1] == 'center') $center = true;
  335. elseif($o[1] == 'right' || $o[1] == 'left') $i_attr .= " style=\"float:$o[1]\"";
  336. elseif($o[1] == 'link') $link = (substr($o[3], 0, 4) == "http" || substr($o[3], 0, 2) == "./") ? $o[3] : "$self?page=" . u($o[3]);
  337. elseif($o[1] == 'alt') $i_attr .= ' alt="'.h($o[3]).'"';
  338. elseif($o[1] == 'title') $a_attr .= ' title="'.h($o[3]).'"';
  339. $tag = "<img src=\"$img[1]\"$i_attr/>";
  340. if($link) $tag = "<a href=\"$link\"$a_attr>$tag</a>";
  341. if($center) $tag = "<div style=\"text-align:center\">$tag</div>";
  342. $CON = str_replace($img[0], $tag, $CON);
  343. }
  344. // txt2tags is already doing that so we remove this part:
  345. //$CON = preg_replace('#([0-9a-zA-Z\./~\-_]+@[0-9a-z/~\-_]+\.[0-9a-z\./~\-_]+)#i', '<a href="mailto:$0">$0</a>', $CON); // mail recognition
  346. // links
  347. //$CON = preg_replace("#\[([^\]\|]+)\|(\./([^\]]+)|(https?://[0-9a-zA-Z\.\#/~\-_%=\?\&,\+\:@;!\(\)\*\$']*))\]#U", '<a href="$2" class="external">$1</a>', $CON);
  348. //$CON = preg_replace("#(?<!\")https?://[0-9a-zA-Z\.\#/~\-_%=\?\&,\+\:@;!\(\)\*\$']*#i", '<a href="$0" class="external">$0</a>', $CON);
  349. preg_match_all("/\[(?:([^|\]\"]+)\|)?([^\]\"#]+)(?:#([^\]\"]+))?\]/", $CON, $matches, PREG_SET_ORDER); // matching Wiki links
  350. foreach($matches as $m) {
  351. $m[1] = $m[1] ? $m[1] : $m[2]; // is page label same as its name?
  352. $m[3] = $m[3] ? '#'.u(preg_replace('/[^\da-z]/i', '_', $m[3])) : ''; // anchor
  353. $attr = file_exists("$PG_DIR$m[2].txt") ? $m[3] : '&amp;action=edit" class="pending';
  354. $CON = str_replace($m[0], '<a href="'.$self.'?page='.u($m[2]).$attr.'">'.$m[1].'</a>', $CON);
  355. }
  356. for($i = 10; $i >= 1; $i--) { // Lists, ordered, unordered
  357. $CON = preg_replace('/^'.str_repeat('\*', $i)."(.*)(\n?)/m", str_repeat('<ul>', $i).'<li>$1</li>'.str_repeat('</ul>', $i).'$2', $CON);
  358. $CON = preg_replace('/^'.str_repeat('\#', $i)."(.*)(\n?)/m", str_repeat('<ol>', $i).'<li>$1</li>'.str_repeat('</ol>', $i).'$2', $CON);
  359. $CON = preg_replace("#(</ol>\n?<ol>|</ul>\n?<ul>)#", '', $CON);
  360. }
  361. // headings
  362. preg_match_all('/^(!+)(.*)$/m', $CON, $matches, PREG_SET_ORDER);
  363. $stack = array();
  364. for($h_id = max($par, 1), $i = 0, $c = count($matches); $i < $c && $m = $matches[$i]; $i++, $h_id++) {
  365. $excl = strlen($m[1]) + 1;
  366. $hash = preg_replace('/[^\da-z]/i', '_', $m[2]);
  367. for($ret = ''; end($stack) >= $excl; $ret .= '</div>', array_pop($stack));
  368. $stack[] = $excl;
  369. $ret .= "<div class=\"par-div\" id=\"par-$h_id\"><h$excl id=\"$hash\">$m[2]";
  370. if(is_writable($PG_DIR . $page . '.txt'))
  371. $ret .= "<span class=\"par-edit\">(<a href=\"$self?action=edit&amp;page=".u($page)."&amp;par=$h_id\">$T_EDIT</a>)</span>";
  372. $CON = preg_replace('/' . preg_quote($m[0], '/') . '/', "$ret</h$excl>", $CON, 1);
  373. $TOC .= str_repeat("<ul>", $excl - 2).'<li><a href="'.$self.'?page='.u($page).'#'.u($hash).'">'.$m[2].'</a></li>'.str_repeat("</ul>", $excl - 2);
  374. }
  375. $CON .= str_repeat('</div>', count($stack));
  376. $TOC = '<ul id="toc">' . preg_replace(array_fill(0, 5, "#</ul>\n*<ul>#"), array_fill(0, 5, ''), $TOC) . '</ul>';
  377. $TOC = str_replace(array('</li><ul>', '</ul><li>', '</ul></ul>', '<ul><ul>'), array('<ul>', '</ul></li><li>', '</ul></li></ul>', '<ul><li><ul>'), $TOC);
  378. $CON = preg_replace("/'--(.*)--'/Um", '<del>$1</del>', $CON); // strikethrough
  379. $CON = preg_replace("/'__(.*)__'/Um", '<u>$1</u>', $CON); // underlining
  380. $CON = preg_replace("/'''(.*)'''/Um", '<strong>$1</strong>', $CON); // bold
  381. $CON = preg_replace("/''(.*)''/Um", '<em>$1</em>', $CON); // italic
  382. $CON = str_replace('{br}', '<br style="clear:both"/>', $CON); // new line
  383. $CON = preg_replace('/-----*/', '<hr/>', $CON); // horizontal line
  384. $CON = str_replace('--', '&mdash;', $CON); // --
  385. $CON = preg_replace(array_fill(0, count($codes[1]) + 1, '/{CODE}/'), $codes[1], $CON, 1); // put HTML and "normal" codes back
  386. $CON = preg_replace(array_fill(0, count($htmlcodes[1]) + 1, '/{HTML}/'), $htmlcodes[1], $CON, 1);
  387. plugin('formatEnd');
  388. }
  389. plugin('formatFinished');
  390. // Loading template. If does not exist, use built-in default
  391. $html = file_exists($TEMPLATE) ? file_get_contents(clear_path($TEMPLATE)) : fallback_template();
  392. // including pages in pure HTML
  393. if (!$NO_HTML)
  394. while(preg_match('/{include:([^}]+)}/U', $html, $m)) {
  395. $inc = str_replace(array('{html}', '{/html}'), '', @file_get_contents("$PG_DIR$m[1].txt"));
  396. $html = str_replace($m[0], $inc, $html);
  397. }
  398. plugin('template'); // plugin templating
  399. $html = preg_replace('/\{([^}]* )?plugin:.+( [^}]*)?\}/U', '', $html); // get rid of absent plugin tags
  400. $tpl_subs = array(
  401. 'HEAD' => $HEAD . ($action ? '<meta name="robots" content="noindex, nofollow"/>' : ''),
  402. 'SEARCH_FORM' => '<form action="'.$self.'" method="get"><span><input type="hidden" name="action" value="search"/><input type="submit" style="display:none;"/>',
  403. '\/SEARCH_FORM' => "</span></form>",
  404. 'SEARCH_INPUT' => '<input type="text" name="query" value="'.h($query).'"/>',
  405. 'SEARCH_SUBMIT' => "<input class=\"submit\" type=\"submit\" value=\"$T_SEARCH\"/>",
  406. 'HOME' => "<a href=\"$self?page=".u($START_PAGE)."\">$T_HOME</a>",
  407. 'RECENT_CHANGES' => "<a href=\"$self?action=recent\">$T_RECENT_CHANGES</a>",
  408. 'ERROR' => $error,
  409. 'HISTORY' => $page ? "<a href=\"$self?page=".u($page)."&amp;action=history\">$T_HISTORY</a>" : "",
  410. 'PAGE_TITLE' => h($page == $START_PAGE && $page == $TITLE ? $WIKI_TITLE : $TITLE),
  411. 'PAGE_TITLE_HEAD' => h($TITLE),
  412. 'PAGE_URL' => u($page),
  413. 'EDIT' => !$action ? ("<a href=\"$self?page=".u($page)."&amp;action=edit".(is_writable("$PG_DIR$page.txt") ? "\">$T_EDIT</a>" : "&amp;showsource=1\">$T_SHOW_SOURCE</a>")) : "",
  414. 'WIKI_TITLE' => h($WIKI_TITLE),
  415. 'LAST_CHANGED_TEXT' => $last_changed_ts ? $T_LAST_CHANGED : "",
  416. 'LAST_CHANGED' => $last_changed_ts ? date($DATE_FORMAT, $last_changed_ts + $LOCAL_HOUR * 3600) : "",
  417. 'CONTENT' => $action != "edit" ? $CON : "",
  418. 'TOC' => $TOC,
  419. 'SYNTAX' => $action == "edit" || $preview ? "<a href=\"$SYNTAX_PAGE\">$T_SYNTAX</a>" : "",
  420. 'SHOW_PAGE' => $action == "edit" || $preview ? "<a href=\"$self?page=".u($page)."\">$T_SHOW_PAGE</a>" : "",
  421. 'COOKIE' => '<a href="'.$self.'?page='.u($page).'&amp;action='.u($action).'&amp;erasecookie=1">'.$T_ERASE_COOKIE.'</a>',
  422. 'CONTENT_FORM' => $CON_FORM_BEGIN,
  423. '\/CONTENT_FORM' => $CON_FORM_END,
  424. 'CONTENT_TEXTAREA' => $CON_TEXTAREA,
  425. 'CONTENT_SUBMIT' => $CON_SUBMIT,
  426. 'CONTENT_PREVIEW' => $CON_PREVIEW,
  427. 'RENAME_TEXT' => $RENAME_TEXT,
  428. 'RENAME_INPUT' => $RENAME_INPUT,
  429. 'EDIT_SUMMARY_TEXT' => $EDIT_SUMMARY_TEXT,
  430. 'EDIT_SUMMARY_INPUT' => $EDIT_SUMMARY,
  431. 'FORM_PASSWORD' => $FORM_PASSWORD,
  432. 'FORM_PASSWORD_INPUT' => $FORM_PASSWORD_INPUT
  433. );
  434. foreach($tpl_subs as $tpl => $rpl) // substituting values
  435. $html = template_replace($tpl, $rpl, $html);
  436. header('Content-type: text/html; charset=UTF-8');
  437. die($html);
  438. // Function library
  439. function h($t) { return htmlspecialchars($t); }
  440. function u($t) { return urlencode($t); }
  441. function template_replace($what, $subs, $where) { return preg_replace("/\{(([^}{]*) )?$what( ([^}]*))?\}/U", empty($subs) ? "" : "\${2}".str_replace("$", "&#36;", trim($subs))."\${4}", $where); }
  442. function template_match($what, $where, &$dest) { return preg_match("/\{(([^}{]*) )?$what( ([^}]*))?\}/U", $where, $dest); }
  443. function clear_path($s) {
  444. for($i = 0, $ret = "", $c = strlen($s); $i < $c; $i++)
  445. $ret .= ctype_cntrl($s[$i]) ? "" : $s[$i];
  446. return trim(str_replace(array('..', '<', '>', '"', '//', '/.', '\\\\'), "", $ret), "/");
  447. }
  448. function rev_time($time) {
  449. preg_match('/(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})-(\d{2})/U', $time, $m);
  450. return date($GLOBALS['DATE_FORMAT'], mktime($m[4], $m[5], $m[6], $m[2], $m[3], $m[1]));
  451. }
  452. // get paragraph number $par_id.
  453. function get_paragraph($text, $par_id) {
  454. $par = array(); // paragraph
  455. $count = 1; // paragraph count
  456. $par_excl = 0; // number of !
  457. $inside_code = $inside_html = false; // exclamation marks inside {{}} and {html}{/html} are not headings
  458. $lines = explode("\n", $text);
  459. foreach($lines as $l) {
  460. // t2t hack to be able to edit a single paragraph. We don't include the numbered heading (+)
  461. if(($l[0] == '!' || $l[0] == '=') && !$inside_html && !$inside_code) {
  462. for($excl = 1, $c = strlen($l); $excl < $c && $l[$excl] == '!'; $excl++);
  463. if($count == $par_id) {
  464. $par[] = $l;
  465. $par_excl = $excl;
  466. } elseif($par_excl)
  467. if($excl > $par_excl)
  468. $par[] = $l;
  469. else
  470. break;
  471. $count++;
  472. }
  473. elseif($par_excl)
  474. $par[] = $l;
  475. if(preg_match('/(?<!\^)\{html\}/', $l)) $inside_html = true;
  476. if(preg_match('/(?<!\^)\{\/html\}/', $l)) $inside_html = false;
  477. if(preg_match('/(?<!\^)\{\{/', $l)) $inside_code = true;
  478. if(preg_match('/(?<!\^)\}\}/', $l)) $inside_code = false;
  479. }
  480. return join("\n", $par);
  481. }
  482. function diff($f1, $f2) { // executes either builtin simple diff or complex diff plugin, if present ...
  483. list($f1, $f2) = array(min($f1, $f2), max($f1, $f2));
  484. return plugin('diff', $f1, $f2) ? $GLOBALS['plugin_ret_diff'] : diff_builtin($f1, $f2);
  485. }
  486. function diff_builtin($f1, $f2) {
  487. $dir = $GLOBALS['HIST_DIR'] . $GLOBALS['page'] . '/';
  488. $a1 = explode("\n", @file_get_contents($dir.$f1));
  489. $a2 = explode("\n", @file_get_contents($dir.$f2));
  490. $d1 = array_diff($a1, $a2);
  491. $d2 = array_diff($a2, $a1);
  492. for($i = 0, $ret = ''; $i <= max(count($a2), count($a1)); $i++) {
  493. if($r1 = array_key_exists($i, $d1)) $ret .= '<del>'.h(trim($d1[$i]))."</del>\n";
  494. if($r2 = array_key_exists($i, $d2)) $ret .= '<ins>'.h(trim($d2[$i]))."</ins>\n";
  495. if(!$r1 && !$r2) $ret .= h(trim($a2[$i]))."\n";
  496. }
  497. return "<pre id=\"diff\">$ret</pre>";
  498. }
  499. function authentified() {
  500. if(!$GLOBALS['PASSWORD'] || !strcasecmp($_COOKIE['LW_AUT'], $GLOBALS['PASSWORD']) || !strcasecmp(sha1($GLOBALS['sc']), $GLOBALS['PASSWORD'])) {
  501. setsafecookie('LW_AUT', $GLOBALS['PASSWORD'], time() + ($GLOBALS['PROTECTED_READ'] ? 4 * 3600 : 365 * 86400));
  502. return true;
  503. } else
  504. return false;
  505. }
  506. function setsafecookie() { // setcookie for sensitive informations
  507. $args = func_get_args();
  508. if(version_compare(PHP_VERSION, '5.2.0') >= 0) {
  509. while(count($args) != 6)
  510. $args[] = '';
  511. $args[] = true; // httponly, supported only in some browsers and PHP >= 5.2.0. Successfully prevents XSS attacks.
  512. }
  513. call_user_func_array('setcookie', $args);
  514. }
  515. // returns "line" from meta.dat files. $lnum is number of line from the end of file starting with 1
  516. function meta_getline($file, $lnum) {
  517. if(fseek($file, -($lnum * 175), SEEK_END) || !($line = fread($file, 175)) || $line[0] != "!")
  518. return false; // ! is control character
  519. $date = substr($line, 1, 16);
  520. $ip = trim(substr($line, 19, 15));
  521. $size = (int) substr($line, 35, 10);
  522. $esum = trim(substr($line, 45, 128));
  523. return array($date, $ip, $size, $esum);
  524. }
  525. // Call a method for all plugins, second to last arguments are forwarded to plugins as arguments
  526. function plugin($method) {
  527. $ret = false;
  528. $args = array_slice(func_get_args(), 1);
  529. foreach($GLOBALS['plugins'] as $idx => $plugin)
  530. $ret |= method_exists($GLOBALS['plugins'][$idx], $method) && call_user_func_array(array(&$GLOBALS['plugins'][$idx], $method), $args);
  531. return $ret; // returns true if treated by a plugin
  532. }
  533. function fallback_template() { return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  534. <html xmlns="http://www.w3.org/1999/xhtml">
  535. <head>
  536. <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  537. <title>{PAGE_TITLE_HEAD - }{WIKI_TITLE}</title>
  538. <style type="text/css">
  539. *{margin:0;padding:0}
  540. body{font-size:12px;line-height:16px;padding:10px 20px 20px 20px}
  541. p{margin:5px}
  542. a{color:#060;text-decoration:none;border-bottom:1px dotted #060}
  543. a.pending{color:#900}
  544. a.external:after{content:"\2197"}
  545. pre{border:1px dotted #ccc;padding:4px;overflow:auto;margin:3px}
  546. img,a img{border:0}
  547. h1,h2,h3,h4,h5,h6{letter-spacing:2px;font-weight:normal;margin:15px 0 15px 0;color:#060}
  548. h1 a:hover,h2 a:hover,h3 a:hover,h4 a:hover,h5 a:hover,h6 a:hover{color:#060}
  549. h1 a{border-bottom:0}
  550. h2 .par-edit,h3 .par-edit,h4 .par-edit,h5 .par-edit,h6 .par-edit{visibility:hidden;font-size:x-small}
  551. h2:hover .par-edit,h3:hover .par-edit,h4:hover .par-edit,h5:hover .par-edit,h6:hover .par-edit{visibility:visible}
  552. hr{margin:10px 0 10px 0;height:1px;overflow:hidden;border:0;background:#060}
  553. ul,ol{padding:5px 0px 5px 20px}
  554. table{text-align:left}
  555. input,select,textarea{border:1px solid #AAA;padding:2px;font-size:12px}
  556. #toc{border:1px dashed #060;margin:5px 0 5px 10px;padding:6px 5px 7px 0;float:right;padding-right:2em;list-style:none}
  557. #toc ul{list-style:none;padding:3px 0 3px 10px}
  558. #toc li{font-size:11px;padding-left:10px}
  559. #diff{padding:1em;white-space:pre-wrap;width:97%}
  560. #diff ins{color:green;font-weight:bold}
  561. #diff del{color:red;text-decoration:line-through}
  562. #diff .orig{color:#666;font-size:90%}
  563. /* Plugins */
  564. .tagList{padding:0.2em 0.4em 0.2em 0.4em;margin-top:0.5em;border:1px dashed #060;clear:right}
  565. .tagCloud{float:right;width:200px;padding:0.5em;margin:1em;border:1px dashed #060;clear:right}
  566. .pageVersionsList{letter-spacing:0;font-variant:normal;font-size:12px}
  567. .resizeTextarea a{border-bottom:none}
  568. </style>
  569. {HEAD}
  570. </head>
  571. <body>
  572. <table width="100%" cellpadding="4">
  573. <tr>
  574. <td colspan="2">{HOME} {RECENT_CHANGES}</td>
  575. <td style="text-align:right">{EDIT} {SYNTAX} {HISTORY}</td>
  576. </tr>
  577. <tr><th colspan="3"><hr/><h1 id="page-title">{PAGE_TITLE} {<span class="pageVersionsList">( plugin:VERSIONS_LIST )</span>}</h1></th></tr>
  578. <tr>
  579. <td colspan="3">
  580. {<div style="color:#F25A5A;font-weight:bold;"> ERROR </div>}
  581. {CONTENT} {plugin:TAG_LIST}
  582. {CONTENT_FORM} {RENAME_TEXT} {RENAME_INPUT <br/><br/>} {CONTENT_TEXTAREA}
  583. <p style="float:right;margin:6px">{FORM_PASSWORD} {FORM_PASSWORD_INPUT} {plugin:CAPTCHA_QUESTION} {plugin:CAPTCHA_INPUT}
  584. {EDIT_SUMMARY_TEXT} {EDIT_SUMMARY_INPUT} {CONTENT_SUBMIT} {CONTENT_PREVIEW}</p>{/CONTENT_FORM}
  585. </td>
  586. </tr>
  587. <tr><td colspan="3"><hr/></td></tr>
  588. <tr>
  589. <td><div>{SEARCH_FORM}{SEARCH_INPUT}{SEARCH_SUBMIT}{/SEARCH_FORM}</div></td>
  590. <td>Powered by <a href="http://lionwiki.0o.cz/">LionWiki</a>. {LAST_CHANGED_TEXT}: {LAST_CHANGED} {COOKIE}</td>
  591. <td style="text-align:right">{EDIT} {SYNTAX} {HISTORY}</td>
  592. </tr>
  593. </table>
  594. </body>
  595. </html>'; }