PageRenderTime 48ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/old_index.php

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