The version of vichan running on lainchan.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

463 lines
13KB

  1. <?php
  2. /*
  3. * Copyright (c) 2010-2013 Tinyboard Development Group
  4. */
  5. if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) {
  6. // You cannot request this file directly.
  7. exit;
  8. }
  9. /*
  10. joaoptm78@gmail.com
  11. http://www.php.net/manual/en/function.filesize.php#100097
  12. */
  13. function format_bytes($size) {
  14. $units = array(' B', ' KB', ' MB', ' GB', ' TB');
  15. for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
  16. return round($size, 2).$units[$i];
  17. }
  18. function doBoardListPart($list, $root, &$boards) {
  19. global $config;
  20. $body = '';
  21. foreach ($list as $key => $board) {
  22. if (is_array($board))
  23. $body .= ' <span class="sub" data-description="' . $key . '">[' . doBoardListPart($board, $root, $boards) . ']</span> ';
  24. else {
  25. if (gettype($key) == 'string') {
  26. $body .= ' <a href="' . $board . '">' . $key . '</a> /';
  27. } else {
  28. $title = '';
  29. if (isset ($boards[$board])) {
  30. $title = ' title="'.$boards[$board].'"';
  31. }
  32. $body .= ' <a href="' . $root . $board . '/' . $config['file_index'] . '"'.$title.'>' . $board . '</a> /';
  33. }
  34. }
  35. }
  36. $body = preg_replace('/\/$/', '', $body);
  37. return $body;
  38. }
  39. function createBoardlist($mod=false) {
  40. global $config;
  41. if (!isset($config['boards'])) return array('top'=>'','bottom'=>'');
  42. $xboards = listBoards();
  43. $boards = array();
  44. foreach ($xboards as $val) {
  45. $boards[$val['uri']] = $val['title'];
  46. }
  47. $body = doBoardListPart($config['boards'], $mod?'?/':$config['root'], $boards);
  48. if ($config['boardlist_wrap_bracket'] && !preg_match('/\] $/', $body))
  49. $body = '[' . $body . ']';
  50. $body = trim($body);
  51. // Message compact-boardlist.js faster, so that page looks less ugly during loading
  52. $top = "<script type='text/javascript'>if (typeof do_boardlist != 'undefined') do_boardlist();</script>";
  53. return array(
  54. 'top' => '<div class="boardlist">' . $body . '</div>' . $top,
  55. 'bottom' => '<div class="boardlist bottom">' . $body . '</div>'
  56. );
  57. }
  58. function error($message, $priority = true, $debug_stuff = false) {
  59. global $board, $mod, $config, $db_error;
  60. if ($config['syslog'] && $priority !== false) {
  61. // Use LOG_NOTICE instead of LOG_ERR or LOG_WARNING because most error message are not significant.
  62. _syslog($priority !== true ? $priority : LOG_NOTICE, $message);
  63. }
  64. if (defined('STDIN')) {
  65. // Running from CLI
  66. echo('Error: ' . $message . "\n");
  67. debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  68. die();
  69. }
  70. if ($config['debug'] && isset($db_error)) {
  71. $debug_stuff = array_combine(array('SQLSTATE', 'Error code', 'Error message'), $db_error);
  72. }
  73. if ($config['debug']) {
  74. $debug_stuff['backtrace'] = debug_backtrace();
  75. }
  76. // Return the bad request header, necessary for AJAX posts
  77. // czaks: is it really so? the ajax errors only work when this is commented out
  78. // better yet use it when ajax is disabled
  79. if (!isset ($_POST['json_response'])) {
  80. header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
  81. }
  82. // Is there a reason to disable this?
  83. if (isset($_POST['json_response'])) {
  84. header('Content-Type: text/json; charset=utf-8');
  85. die(json_encode(array(
  86. 'error' => $message
  87. )));
  88. }
  89. $pw = $config['db']['password'];
  90. $debug_callback = function(&$item) use (&$debug_callback, $pw) {
  91. if (is_array($item)) {
  92. $item = array_filter($item, $debug_callback);
  93. }
  94. return ($item !== $pw || !$pw);
  95. };
  96. if ($debug_stuff)
  97. $debug_stuff = array_filter($debug_stuff, $debug_callback);
  98. die(Element('page.html', array(
  99. 'config' => $config,
  100. 'title' => _('Error'),
  101. 'subtitle' => _('An error has occured.'),
  102. 'body' => Element('error.html', array(
  103. 'config' => $config,
  104. 'message' => $message,
  105. 'mod' => $mod,
  106. 'board' => isset($board) ? $board : false,
  107. 'debug' => is_array($debug_stuff) ? str_replace("\n", '&#10;', utf8tohtml(print_r($debug_stuff, true))) : utf8tohtml($debug_stuff)
  108. ))
  109. )));
  110. }
  111. function loginForm($error=false, $username=false, $redirect=false) {
  112. global $config;
  113. die(Element('page.html', array(
  114. 'index' => $config['root'],
  115. 'title' => _('Login'),
  116. 'config' => $config,
  117. 'body' => Element('login.html', array(
  118. 'config'=>$config,
  119. 'error'=>$error,
  120. 'username'=>utf8tohtml($username),
  121. 'redirect'=>$redirect
  122. )
  123. )
  124. )));
  125. }
  126. function pm_snippet($body, $len=null) {
  127. global $config;
  128. if (!isset($len))
  129. $len = &$config['mod']['snippet_length'];
  130. // Replace line breaks with some whitespace
  131. $body = preg_replace('@<br/?>@i', ' ', $body);
  132. // Strip tags
  133. $body = strip_tags($body);
  134. // Unescape HTML characters, to avoid splitting them in half
  135. $body = html_entity_decode($body, ENT_COMPAT, 'UTF-8');
  136. // calculate strlen() so we can add "..." after if needed
  137. $strlen = mb_strlen($body);
  138. $body = mb_substr($body, 0, $len);
  139. // Re-escape the characters.
  140. return '<em>' . utf8tohtml($body) . ($strlen > $len ? '&hellip;' : '') . '</em>';
  141. }
  142. function capcode($cap) {
  143. global $config;
  144. if (!$cap)
  145. return false;
  146. $capcode = array();
  147. if (isset($config['custom_capcode'][$cap])) {
  148. if (is_array($config['custom_capcode'][$cap])) {
  149. $capcode['cap'] = sprintf($config['custom_capcode'][$cap][0], $cap);
  150. if (isset($config['custom_capcode'][$cap][1]))
  151. $capcode['name'] = $config['custom_capcode'][$cap][1];
  152. if (isset($config['custom_capcode'][$cap][2]))
  153. $capcode['trip'] = $config['custom_capcode'][$cap][2];
  154. } else {
  155. $capcode['cap'] = sprintf($config['custom_capcode'][$cap], $cap);
  156. }
  157. } else {
  158. $capcode['cap'] = sprintf($config['capcode'], $cap);
  159. }
  160. return $capcode;
  161. }
  162. function truncate($body, $url, $max_lines = false, $max_chars = false) {
  163. global $config;
  164. if ($max_lines === false)
  165. $max_lines = $config['body_truncate'];
  166. if ($max_chars === false)
  167. $max_chars = $config['body_truncate_char'];
  168. // We don't want to risk truncating in the middle of an HTML comment.
  169. // It's easiest just to remove them all first.
  170. $body = preg_replace('/<!--.*?-->/s', '', $body);
  171. $original_body = $body;
  172. $lines = substr_count($body, '<br/>');
  173. // Limit line count
  174. if ($lines > $max_lines) {
  175. if (preg_match('/(((.*?)<br\/>){' . $max_lines . '})/', $body, $m))
  176. $body = $m[0];
  177. }
  178. $body = mb_substr($body, 0, $max_chars);
  179. if ($body != $original_body) {
  180. // Remove any corrupt tags at the end
  181. $body = preg_replace('/<([\w]+)?([^>]*)?$/', '', $body);
  182. // Open tags
  183. if (preg_match_all('/<([\w]+)[^>]*>/', $body, $open_tags)) {
  184. $tags = array();
  185. for ($x=0;$x<count($open_tags[0]);$x++) {
  186. if (!preg_match('/\/(\s+)?>$/', $open_tags[0][$x]))
  187. $tags[] = $open_tags[1][$x];
  188. }
  189. // List successfully closed tags
  190. if (preg_match_all('/(<\/([\w]+))>/', $body, $closed_tags)) {
  191. for ($x=0;$x<count($closed_tags[0]);$x++) {
  192. unset($tags[array_search($closed_tags[2][$x], $tags)]);
  193. }
  194. }
  195. // remove broken HTML entity at the end (if existent)
  196. $body = preg_replace('/&[^;]+$/', '', $body);
  197. $tags_no_close_needed = array("colgroup", "dd", "dt", "li", "optgroup", "option", "p", "tbody", "td", "tfoot", "th", "thead", "tr", "br", "img");
  198. // Close any open tags
  199. foreach ($tags as &$tag) {
  200. if (!in_array($tag, $tags_no_close_needed))
  201. $body .= "</{$tag}>";
  202. }
  203. } else {
  204. // remove broken HTML entity at the end (if existent)
  205. $body = preg_replace('/&[^;]*$/', '', $body);
  206. }
  207. $body .= '<span class="toolong">'.sprintf(_('Post too long. Click <a href="%s">here</a> to view the full text.'), $url).'</span>';
  208. }
  209. return $body;
  210. }
  211. function bidi_cleanup($data) {
  212. // Closes all embedded RTL and LTR unicode formatting blocks in a string so that
  213. // it can be used inside another without controlling its direction.
  214. $explicits = '\xE2\x80\xAA|\xE2\x80\xAB|\xE2\x80\xAD|\xE2\x80\xAE';
  215. $pdf = '\xE2\x80\xAC';
  216. preg_match_all("!$explicits!", $data, $m1, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  217. preg_match_all("!$pdf!", $data, $m2, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  218. if (count($m1) || count($m2)){
  219. $p = array();
  220. foreach ($m1 as $m){ $p[$m[0][1]] = 'push'; }
  221. foreach ($m2 as $m){ $p[$m[0][1]] = 'pop'; }
  222. ksort($p);
  223. $offset = 0;
  224. $stack = 0;
  225. foreach ($p as $pos => $type){
  226. if ($type == 'push'){
  227. $stack++;
  228. }else{
  229. if ($stack){
  230. $stack--;
  231. }else{
  232. # we have a pop without a push - remove it
  233. $data = substr($data, 0, $pos-$offset)
  234. .substr($data, $pos+3-$offset);
  235. $offset += 3;
  236. }
  237. }
  238. }
  239. # now add some pops if your stack is bigger than 0
  240. for ($i=0; $i<$stack; $i++){
  241. $data .= "\xE2\x80\xAC";
  242. }
  243. return $data;
  244. }
  245. return $data;
  246. }
  247. function secure_link_confirm($text, $title, $confirm_message, $href) {
  248. global $config;
  249. return '<a onclick="if (event.which==2) return true;if (confirm(\'' . htmlentities(addslashes($confirm_message)) . '\')) document.location=\'?/' . htmlspecialchars(addslashes($href . '/' . make_secure_link_token($href))) . '\';return false;" title="' . htmlentities($title) . '" href="?/' . $href . '">' . $text . '</a>';
  250. }
  251. function secure_link($href) {
  252. return $href . '/' . make_secure_link_token($href);
  253. }
  254. function embed_html($link) {
  255. global $config;
  256. foreach ($config['embedding'] as $embed) {
  257. if ($html = preg_replace($embed[0], $embed[1], $link)) {
  258. if ($html == $link)
  259. continue; // Nope
  260. $html = str_replace('%%tb_width%%', $config['embed_width'], $html);
  261. $html = str_replace('%%tb_height%%', $config['embed_height'], $html);
  262. return $html;
  263. }
  264. }
  265. if ($link[0] == '<') {
  266. // Prior to v0.9.6-dev-8, HTML code for embedding was stored in the database instead of the link.
  267. return $link;
  268. }
  269. return 'Embedding error.';
  270. }
  271. class Post {
  272. public function __construct($post, $root=null, $mod=false) {
  273. global $config;
  274. if (!isset($root))
  275. $root = &$config['root'];
  276. foreach ($post as $key => $value) {
  277. $this->{$key} = $value;
  278. }
  279. if (isset($this->files) && $this->files)
  280. $this->files = json_decode($this->files);
  281. $this->subject = utf8tohtml($this->subject);
  282. $this->name = utf8tohtml($this->name);
  283. $this->mod = $mod;
  284. $this->root = $root;
  285. if ($this->embed)
  286. $this->embed = embed_html($this->embed);
  287. $this->modifiers = extract_modifiers($this->body_nomarkup);
  288. if ($config['always_regenerate_markup']) {
  289. $this->body = $this->body_nomarkup;
  290. markup($this->body);
  291. }
  292. if ($this->mod)
  293. // Fix internal links
  294. // Very complicated regex
  295. $this->body = preg_replace(
  296. '/<a((([a-zA-Z]+="[^"]+")|[a-zA-Z]+=[a-zA-Z]+|\s)*)href="' . preg_quote($config['root'], '/') . '(' . sprintf(preg_quote($config['board_path'], '/'), $config['board_regex']) . ')/u',
  297. '<a $1href="?/$4',
  298. $this->body
  299. );
  300. }
  301. public function link($pre = '', $page = false) {
  302. global $config, $board;
  303. return $this->root . $board['dir'] . $config['dir']['res'] . link_for((array)$this, $page == '50') . '#' . $pre . $this->id;
  304. }
  305. public function build($index=false) {
  306. global $board, $config;
  307. return Element('post_reply.html', array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index, 'mod' => $this->mod));
  308. }
  309. };
  310. class Thread {
  311. public function __construct($post, $root = null, $mod = false, $hr = true) {
  312. global $config;
  313. if (!isset($root))
  314. $root = &$config['root'];
  315. foreach ($post as $key => $value) {
  316. $this->{$key} = $value;
  317. }
  318. if (isset($this->files))
  319. $this->files = json_decode($this->files);
  320. $this->subject = utf8tohtml($this->subject);
  321. $this->name = utf8tohtml($this->name);
  322. $this->mod = $mod;
  323. $this->root = $root;
  324. $this->hr = $hr;
  325. $this->posts = array();
  326. $this->omitted = 0;
  327. $this->omitted_images = 0;
  328. if ($this->embed)
  329. $this->embed = embed_html($this->embed);
  330. $this->modifiers = extract_modifiers($this->body_nomarkup);
  331. if ($config['always_regenerate_markup']) {
  332. $this->body = $this->body_nomarkup;
  333. markup($this->body);
  334. }
  335. if ($this->mod)
  336. // Fix internal links
  337. // Very complicated regex
  338. $this->body = preg_replace(
  339. '/<a((([a-zA-Z]+="[^"]+")|[a-zA-Z]+=[a-zA-Z]+|\s)*)href="' . preg_quote($config['root'], '/') . '(' . sprintf(preg_quote($config['board_path'], '/'), $config['board_regex']) . ')/u',
  340. '<a $1href="?/$4',
  341. $this->body
  342. );
  343. }
  344. public function link($pre = '', $page = false) {
  345. global $config, $board;
  346. return $this->root . $board['dir'] . $config['dir']['res'] . link_for((array)$this, $page == '50') . '#' . $pre . $this->id;
  347. }
  348. public function add(Post $post) {
  349. $this->posts[] = $post;
  350. }
  351. public function postCount() {
  352. return count($this->posts) + $this->omitted;
  353. }
  354. public function build($index=false, $isnoko50=false) {
  355. global $board, $config, $debug;
  356. $hasnoko50 = $this->postCount() >= $config['noko50_min'];
  357. event('show-thread', $this);
  358. $file = ($index && $config['file_board']) ? 'post_thread_fileboard.html' : 'post_thread.html';
  359. $built = Element($file, array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index, 'hasnoko50' => $hasnoko50, 'isnoko50' => $isnoko50, 'mod' => $this->mod));
  360. return $built;
  361. }
  362. };