PageRenderTime 47ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/station/forum/includes/functions_content.php

https://github.com/bryanveloso/sayonarane
PHP | 1320 lines | 881 code | 204 blank | 235 comment | 167 complexity | b0f62cd9945ae756a18c7e55f8661eee MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /**
  3. *
  4. * @package phpBB3
  5. * @version $Id: functions_content.php 8970 2008-10-06 05:44:32Z acydburn $
  6. * @copyright (c) 2005 phpBB Group
  7. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  8. *
  9. */
  10. /**
  11. * @ignore
  12. */
  13. if (!defined('IN_PHPBB'))
  14. {
  15. exit;
  16. }
  17. /**
  18. * gen_sort_selects()
  19. * make_jumpbox()
  20. * bump_topic_allowed()
  21. * get_context()
  22. * decode_message()
  23. * strip_bbcode()
  24. * generate_text_for_display()
  25. * generate_text_for_storage()
  26. * generate_text_for_edit()
  27. * make_clickable_callback()
  28. * make_clickable()
  29. * censor_text()
  30. * bbcode_nl2br()
  31. * smiley_text()
  32. * parse_attachments()
  33. * extension_allowed()
  34. * truncate_string()
  35. * get_username_string()
  36. * class bitfield
  37. */
  38. /**
  39. * Generate sort selection fields
  40. */
  41. function gen_sort_selects(&$limit_days, &$sort_by_text, &$sort_days, &$sort_key, &$sort_dir, &$s_limit_days, &$s_sort_key, &$s_sort_dir, &$u_sort_param, $def_st = false, $def_sk = false, $def_sd = false)
  42. {
  43. global $user;
  44. $sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
  45. $sorts = array(
  46. 'st' => array(
  47. 'key' => 'sort_days',
  48. 'default' => $def_st,
  49. 'options' => $limit_days,
  50. 'output' => &$s_limit_days,
  51. ),
  52. 'sk' => array(
  53. 'key' => 'sort_key',
  54. 'default' => $def_sk,
  55. 'options' => $sort_by_text,
  56. 'output' => &$s_sort_key,
  57. ),
  58. 'sd' => array(
  59. 'key' => 'sort_dir',
  60. 'default' => $def_sd,
  61. 'options' => $sort_dir_text,
  62. 'output' => &$s_sort_dir,
  63. ),
  64. );
  65. $u_sort_param = '';
  66. foreach ($sorts as $name => $sort_ary)
  67. {
  68. $key = $sort_ary['key'];
  69. $selected = $$sort_ary['key'];
  70. // Check if the key is selectable. If not, we reset to the default or first key found.
  71. // This ensures the values are always valid. We also set $sort_dir/sort_key/etc. to the
  72. // correct value, else the protection is void. ;)
  73. if (!isset($sort_ary['options'][$selected]))
  74. {
  75. if ($sort_ary['default'] !== false)
  76. {
  77. $selected = $$key = $sort_ary['default'];
  78. }
  79. else
  80. {
  81. @reset($sort_ary['options']);
  82. $selected = $$key = key($sort_ary['options']);
  83. }
  84. }
  85. $sort_ary['output'] = '<select name="' . $name . '" id="' . $name . '">';
  86. foreach ($sort_ary['options'] as $option => $text)
  87. {
  88. $sort_ary['output'] .= '<option value="' . $option . '"' . (($selected == $option) ? ' selected="selected"' : '') . '>' . $text . '</option>';
  89. }
  90. $sort_ary['output'] .= '</select>';
  91. $u_sort_param .= ($selected !== $sort_ary['default']) ? ((strlen($u_sort_param)) ? '&amp;' : '') . "{$name}={$selected}" : '';
  92. }
  93. return;
  94. }
  95. /**
  96. * Generate Jumpbox
  97. */
  98. function make_jumpbox($action, $forum_id = false, $select_all = false, $acl_list = false, $force_display = false)
  99. {
  100. global $config, $auth, $template, $user, $db;
  101. // We only return if the jumpbox is not forced to be displayed (in case it is needed for functionality)
  102. if (!$config['load_jumpbox'] && $force_display === false)
  103. {
  104. return;
  105. }
  106. $sql = 'SELECT forum_id, forum_name, parent_id, forum_type, left_id, right_id
  107. FROM ' . FORUMS_TABLE . '
  108. ORDER BY left_id ASC';
  109. $result = $db->sql_query($sql, 600);
  110. $right = $padding = 0;
  111. $padding_store = array('0' => 0);
  112. $display_jumpbox = false;
  113. $iteration = 0;
  114. // Sometimes it could happen that forums will be displayed here not be displayed within the index page
  115. // This is the result of forums not displayed at index, having list permissions and a parent of a forum with no permissions.
  116. // If this happens, the padding could be "broken"
  117. while ($row = $db->sql_fetchrow($result))
  118. {
  119. if ($row['left_id'] < $right)
  120. {
  121. $padding++;
  122. $padding_store[$row['parent_id']] = $padding;
  123. }
  124. else if ($row['left_id'] > $right + 1)
  125. {
  126. // Ok, if the $padding_store for this parent is empty there is something wrong. For now we will skip over it.
  127. // @todo digging deep to find out "how" this can happen.
  128. $padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : $padding;
  129. }
  130. $right = $row['right_id'];
  131. if ($row['forum_type'] == FORUM_CAT && ($row['left_id'] + 1 == $row['right_id']))
  132. {
  133. // Non-postable forum with no subforums, don't display
  134. continue;
  135. }
  136. if (!$auth->acl_get('f_list', $row['forum_id']))
  137. {
  138. // if the user does not have permissions to list this forum skip
  139. continue;
  140. }
  141. if ($acl_list && !$auth->acl_gets($acl_list, $row['forum_id']))
  142. {
  143. continue;
  144. }
  145. if (!$display_jumpbox)
  146. {
  147. $template->assign_block_vars('jumpbox_forums', array(
  148. 'FORUM_ID' => ($select_all) ? 0 : -1,
  149. 'FORUM_NAME' => ($select_all) ? $user->lang['ALL_FORUMS'] : $user->lang['SELECT_FORUM'],
  150. 'S_FORUM_COUNT' => $iteration)
  151. );
  152. $iteration++;
  153. $display_jumpbox = true;
  154. }
  155. $template->assign_block_vars('jumpbox_forums', array(
  156. 'FORUM_ID' => $row['forum_id'],
  157. 'FORUM_NAME' => $row['forum_name'],
  158. 'SELECTED' => ($row['forum_id'] == $forum_id) ? ' selected="selected"' : '',
  159. 'S_FORUM_COUNT' => $iteration,
  160. 'S_IS_CAT' => ($row['forum_type'] == FORUM_CAT) ? true : false,
  161. 'S_IS_LINK' => ($row['forum_type'] == FORUM_LINK) ? true : false,
  162. 'S_IS_POST' => ($row['forum_type'] == FORUM_POST) ? true : false)
  163. );
  164. for ($i = 0; $i < $padding; $i++)
  165. {
  166. $template->assign_block_vars('jumpbox_forums.level', array());
  167. }
  168. $iteration++;
  169. }
  170. $db->sql_freeresult($result);
  171. unset($padding_store);
  172. $template->assign_vars(array(
  173. 'S_DISPLAY_JUMPBOX' => $display_jumpbox,
  174. 'S_JUMPBOX_ACTION' => $action)
  175. );
  176. return;
  177. }
  178. /**
  179. * Bump Topic Check - used by posting and viewtopic
  180. */
  181. function bump_topic_allowed($forum_id, $topic_bumped, $last_post_time, $topic_poster, $last_topic_poster)
  182. {
  183. global $config, $auth, $user;
  184. // Check permission and make sure the last post was not already bumped
  185. if (!$auth->acl_get('f_bump', $forum_id) || $topic_bumped)
  186. {
  187. return false;
  188. }
  189. // Check bump time range, is the user really allowed to bump the topic at this time?
  190. $bump_time = ($config['bump_type'] == 'm') ? $config['bump_interval'] * 60 : (($config['bump_type'] == 'h') ? $config['bump_interval'] * 3600 : $config['bump_interval'] * 86400);
  191. // Check bump time
  192. if ($last_post_time + $bump_time > time())
  193. {
  194. return false;
  195. }
  196. // Check bumper, only topic poster and last poster are allowed to bump
  197. if ($topic_poster != $user->data['user_id'] && $last_topic_poster != $user->data['user_id'])
  198. {
  199. return false;
  200. }
  201. // A bump time of 0 will completely disable the bump feature... not intended but might be useful.
  202. return $bump_time;
  203. }
  204. /**
  205. * Generates a text with approx. the specified length which contains the specified words and their context
  206. *
  207. * @param string $text The full text from which context shall be extracted
  208. * @param string $words An array of words which should be contained in the result, has to be a valid part of a PCRE pattern (escape with preg_quote!)
  209. * @param int $length The desired length of the resulting text, however the result might be shorter or longer than this value
  210. *
  211. * @return string Context of the specified words separated by "..."
  212. */
  213. function get_context($text, $words, $length = 400)
  214. {
  215. // first replace all whitespaces with single spaces
  216. $text = preg_replace('/ +/', ' ', strtr($text, "\t\n\r\x0C ", ' '));
  217. $word_indizes = array();
  218. if (sizeof($words))
  219. {
  220. $match = '';
  221. // find the starting indizes of all words
  222. foreach ($words as $word)
  223. {
  224. if ($word)
  225. {
  226. if (preg_match('#(?:[^\w]|^)(' . $word . ')(?:[^\w]|$)#i', $text, $match))
  227. {
  228. $pos = utf8_strpos($text, $match[1]);
  229. if ($pos !== false)
  230. {
  231. $word_indizes[] = $pos;
  232. }
  233. }
  234. }
  235. }
  236. unset($match);
  237. if (sizeof($word_indizes))
  238. {
  239. $word_indizes = array_unique($word_indizes);
  240. sort($word_indizes);
  241. $wordnum = sizeof($word_indizes);
  242. // number of characters on the right and left side of each word
  243. $sequence_length = (int) ($length / (2 * $wordnum)) - 2;
  244. $final_text = '';
  245. $word = $j = 0;
  246. $final_text_index = -1;
  247. // cycle through every character in the original text
  248. for ($i = $word_indizes[$word], $n = utf8_strlen($text); $i < $n; $i++)
  249. {
  250. // if the current position is the start of one of the words then append $sequence_length characters to the final text
  251. if (isset($word_indizes[$word]) && ($i == $word_indizes[$word]))
  252. {
  253. if ($final_text_index < $i - $sequence_length - 1)
  254. {
  255. $final_text .= '... ' . preg_replace('#^([^ ]*)#', '', utf8_substr($text, $i - $sequence_length, $sequence_length));
  256. }
  257. else
  258. {
  259. // if the final text is already nearer to the current word than $sequence_length we only append the text
  260. // from its current index on and distribute the unused length to all other sequenes
  261. $sequence_length += (int) (($final_text_index - $i + $sequence_length + 1) / (2 * $wordnum));
  262. $final_text .= utf8_substr($text, $final_text_index + 1, $i - $final_text_index - 1);
  263. }
  264. $final_text_index = $i - 1;
  265. // add the following characters to the final text (see below)
  266. $word++;
  267. $j = 1;
  268. }
  269. if ($j > 0)
  270. {
  271. // add the character to the final text and increment the sequence counter
  272. $final_text .= utf8_substr($text, $i, 1);
  273. $final_text_index++;
  274. $j++;
  275. // if this is a whitespace then check whether we are done with this sequence
  276. if (utf8_substr($text, $i, 1) == ' ')
  277. {
  278. // only check whether we have to exit the context generation completely if we haven't already reached the end anyway
  279. if ($i + 4 < $n)
  280. {
  281. if (($j > $sequence_length && $word >= $wordnum) || utf8_strlen($final_text) > $length)
  282. {
  283. $final_text .= ' ...';
  284. break;
  285. }
  286. }
  287. else
  288. {
  289. // make sure the text really reaches the end
  290. $j -= 4;
  291. }
  292. // stop context generation and wait for the next word
  293. if ($j > $sequence_length)
  294. {
  295. $j = 0;
  296. }
  297. }
  298. }
  299. }
  300. return $final_text;
  301. }
  302. }
  303. if (!sizeof($words) || !sizeof($word_indizes))
  304. {
  305. return (utf8_strlen($text) >= $length + 3) ? utf8_substr($text, 0, $length) . '...' : $text;
  306. }
  307. }
  308. /**
  309. * Decode text whereby text is coming from the db and expected to be pre-parsed content
  310. * We are placing this outside of the message parser because we are often in need of it...
  311. */
  312. function decode_message(&$message, $bbcode_uid = '')
  313. {
  314. global $config;
  315. if ($bbcode_uid)
  316. {
  317. $match = array('<br />', "[/*:m:$bbcode_uid]", ":u:$bbcode_uid", ":o:$bbcode_uid", ":$bbcode_uid");
  318. $replace = array("\n", '', '', '', '');
  319. }
  320. else
  321. {
  322. $match = array('<br />');
  323. $replace = array("\n");
  324. }
  325. $message = str_replace($match, $replace, $message);
  326. $match = get_preg_expression('bbcode_htm');
  327. $replace = array('\1', '\1', '\2', '\1', '', '');
  328. $message = preg_replace($match, $replace, $message);
  329. }
  330. /**
  331. * Strips all bbcode from a text and returns the plain content
  332. */
  333. function strip_bbcode(&$text, $uid = '')
  334. {
  335. if (!$uid)
  336. {
  337. $uid = '[0-9a-z]{5,}';
  338. }
  339. $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:&quot;.*&quot;|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);
  340. $match = get_preg_expression('bbcode_htm');
  341. $replace = array('\1', '\1', '\2', '\1', '', '');
  342. $text = preg_replace($match, $replace, $text);
  343. }
  344. /**
  345. * For display of custom parsed text on user-facing pages
  346. * Expects $text to be the value directly from the database (stored value)
  347. */
  348. function generate_text_for_display($text, $uid, $bitfield, $flags)
  349. {
  350. static $bbcode;
  351. if (!$text)
  352. {
  353. return '';
  354. }
  355. $text = censor_text($text);
  356. // Parse bbcode if bbcode uid stored and bbcode enabled
  357. if ($uid && ($flags & OPTION_FLAG_BBCODE))
  358. {
  359. if (!class_exists('bbcode'))
  360. {
  361. global $phpbb_root_path, $phpEx;
  362. include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
  363. }
  364. if (empty($bbcode))
  365. {
  366. $bbcode = new bbcode($bitfield);
  367. }
  368. else
  369. {
  370. $bbcode->bbcode($bitfield);
  371. }
  372. $bbcode->bbcode_second_pass($text, $uid);
  373. }
  374. $text = bbcode_nl2br($text);
  375. $text = smiley_text($text, !($flags & OPTION_FLAG_SMILIES));
  376. return $text;
  377. }
  378. /**
  379. * For parsing custom parsed text to be stored within the database.
  380. * This function additionally returns the uid and bitfield that needs to be stored.
  381. * Expects $text to be the value directly from request_var() and in it's non-parsed form
  382. */
  383. function generate_text_for_storage(&$text, &$uid, &$bitfield, &$flags, $allow_bbcode = false, $allow_urls = false, $allow_smilies = false)
  384. {
  385. global $phpbb_root_path, $phpEx;
  386. $uid = $bitfield = '';
  387. $flags = (($allow_bbcode) ? OPTION_FLAG_BBCODE : 0) + (($allow_smilies) ? OPTION_FLAG_SMILIES : 0) + (($allow_urls) ? OPTION_FLAG_LINKS : 0);
  388. if (!$text)
  389. {
  390. return;
  391. }
  392. if (!class_exists('parse_message'))
  393. {
  394. include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
  395. }
  396. $message_parser = new parse_message($text);
  397. $message_parser->parse($allow_bbcode, $allow_urls, $allow_smilies);
  398. $text = $message_parser->message;
  399. $uid = $message_parser->bbcode_uid;
  400. // If the bbcode_bitfield is empty, there is no need for the uid to be stored.
  401. if (!$message_parser->bbcode_bitfield)
  402. {
  403. $uid = '';
  404. }
  405. $bitfield = $message_parser->bbcode_bitfield;
  406. return;
  407. }
  408. /**
  409. * For decoding custom parsed text for edits as well as extracting the flags
  410. * Expects $text to be the value directly from the database (pre-parsed content)
  411. */
  412. function generate_text_for_edit($text, $uid, $flags)
  413. {
  414. global $phpbb_root_path, $phpEx;
  415. decode_message($text, $uid);
  416. return array(
  417. 'allow_bbcode' => ($flags & OPTION_FLAG_BBCODE) ? 1 : 0,
  418. 'allow_smilies' => ($flags & OPTION_FLAG_SMILIES) ? 1 : 0,
  419. 'allow_urls' => ($flags & OPTION_FLAG_LINKS) ? 1 : 0,
  420. 'text' => $text
  421. );
  422. }
  423. /**
  424. * A subroutine of make_clickable used with preg_replace
  425. * It places correct HTML around an url, shortens the displayed text
  426. * and makes sure no entities are inside URLs
  427. */
  428. function make_clickable_callback($type, $whitespace, $url, $relative_url, $class)
  429. {
  430. $orig_url = $url . $relative_url;
  431. $append = '';
  432. $url = htmlspecialchars_decode($url);
  433. $relative_url = htmlspecialchars_decode($relative_url);
  434. // make sure no HTML entities were matched
  435. $chars = array('<', '>', '"');
  436. $split = false;
  437. foreach ($chars as $char)
  438. {
  439. $next_split = strpos($url, $char);
  440. if ($next_split !== false)
  441. {
  442. $split = ($split !== false) ? min($split, $next_split) : $next_split;
  443. }
  444. }
  445. if ($split !== false)
  446. {
  447. // an HTML entity was found, so the URL has to end before it
  448. $append = substr($url, $split) . $relative_url;
  449. $url = substr($url, 0, $split);
  450. $relative_url = '';
  451. }
  452. else if ($relative_url)
  453. {
  454. // same for $relative_url
  455. $split = false;
  456. foreach ($chars as $char)
  457. {
  458. $next_split = strpos($relative_url, $char);
  459. if ($next_split !== false)
  460. {
  461. $split = ($split !== false) ? min($split, $next_split) : $next_split;
  462. }
  463. }
  464. if ($split !== false)
  465. {
  466. $append = substr($relative_url, $split);
  467. $relative_url = substr($relative_url, 0, $split);
  468. }
  469. }
  470. // if the last character of the url is a punctuation mark, exclude it from the url
  471. $last_char = ($relative_url) ? $relative_url[strlen($relative_url) - 1] : $url[strlen($url) - 1];
  472. switch ($last_char)
  473. {
  474. case '.':
  475. case '?':
  476. case '!':
  477. case ':':
  478. case ',':
  479. $append = $last_char;
  480. if ($relative_url)
  481. {
  482. $relative_url = substr($relative_url, 0, -1);
  483. }
  484. else
  485. {
  486. $url = substr($url, 0, -1);
  487. }
  488. break;
  489. }
  490. $short_url = (strlen($url) > 55) ? substr($url, 0, 39) . ' ... ' . substr($url, -10) : $url;
  491. switch ($type)
  492. {
  493. case MAGIC_URL_LOCAL:
  494. $tag = 'l';
  495. $relative_url = preg_replace('/[&?]sid=[0-9a-f]{32}$/', '', preg_replace('/([&?])sid=[0-9a-f]{32}&/', '$1', $relative_url));
  496. $url = $url . '/' . $relative_url;
  497. $text = $relative_url;
  498. // this url goes to http://domain.tld/path/to/board/ which
  499. // would result in an empty link if treated as local so
  500. // don't touch it and let MAGIC_URL_FULL take care of it.
  501. if (!$relative_url)
  502. {
  503. return $whitespace . $orig_url . '/'; // slash is taken away by relative url pattern
  504. }
  505. break;
  506. case MAGIC_URL_FULL:
  507. $tag = 'm';
  508. $text = $short_url;
  509. break;
  510. case MAGIC_URL_WWW:
  511. $tag = 'w';
  512. $url = 'http://' . $url;
  513. $text = $short_url;
  514. break;
  515. case MAGIC_URL_EMAIL:
  516. $tag = 'e';
  517. $text = $short_url;
  518. $url = 'mailto:' . $url;
  519. break;
  520. }
  521. $url = htmlspecialchars($url);
  522. $text = htmlspecialchars($text);
  523. $append = htmlspecialchars($append);
  524. $html = "$whitespace<!-- $tag --><a$class href=\"$url\">$text</a><!-- $tag -->$append";
  525. return $html;
  526. }
  527. /**
  528. * make_clickable function
  529. *
  530. * Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
  531. * Cuts down displayed size of link if over 50 chars, turns absolute links
  532. * into relative versions when the server/script path matches the link
  533. */
  534. function make_clickable($text, $server_url = false, $class = 'postlink')
  535. {
  536. if ($server_url === false)
  537. {
  538. $server_url = generate_board_url();
  539. }
  540. static $magic_url_match;
  541. static $magic_url_replace;
  542. static $static_class;
  543. if (!is_array($magic_url_match) || $static_class != $class)
  544. {
  545. $static_class = $class;
  546. $class = ($static_class) ? ' class="' . $static_class . '"' : '';
  547. $local_class = ($static_class) ? ' class="' . $static_class . '-local"' : '';
  548. $magic_url_match = $magic_url_replace = array();
  549. // Be sure to not let the matches cross over. ;)
  550. // relative urls for this board
  551. $magic_url_match[] = '#(^|[\n\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#ie';
  552. $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_LOCAL, '\$1', '\$2', '\$3', '$local_class')";
  553. // matches a xxxx://aaaaa.bbb.cccc. ...
  554. $magic_url_match[] = '#(^|[\n\t (>.])(' . get_preg_expression('url_inline') . ')#ie';
  555. $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_FULL, '\$1', '\$2', '', '$class')";
  556. // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
  557. $magic_url_match[] = '#(^|[\n\t (>])(' . get_preg_expression('www_url_inline') . ')#ie';
  558. $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_WWW, '\$1', '\$2', '', '$class')";
  559. // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
  560. $magic_url_match[] = '/(^|[\n\t (>])(' . get_preg_expression('email') . ')/ie';
  561. $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_EMAIL, '\$1', '\$2', '', '')";
  562. }
  563. return preg_replace($magic_url_match, $magic_url_replace, $text);
  564. }
  565. /**
  566. * Censoring
  567. */
  568. function censor_text($text)
  569. {
  570. static $censors;
  571. // We moved the word censor checks in here because we call this function quite often - and then only need to do the check once
  572. if (!isset($censors) || !is_array($censors))
  573. {
  574. global $config, $user, $auth, $cache;
  575. // We check here if the user is having viewing censors disabled (and also allowed to do so).
  576. if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
  577. {
  578. $censors = array();
  579. }
  580. else
  581. {
  582. $censors = $cache->obtain_word_list();
  583. }
  584. }
  585. if (sizeof($censors))
  586. {
  587. return preg_replace($censors['match'], $censors['replace'], $text);
  588. }
  589. return $text;
  590. }
  591. /**
  592. * custom version of nl2br which takes custom BBCodes into account
  593. */
  594. function bbcode_nl2br($text)
  595. {
  596. // custom BBCodes might contain carriage returns so they
  597. // are not converted into <br /> so now revert that
  598. $text = str_replace(array("\n", "\r"), array('<br />', "\n"), $text);
  599. return $text;
  600. }
  601. /**
  602. * Smiley processing
  603. */
  604. function smiley_text($text, $force_option = false)
  605. {
  606. global $config, $user, $phpbb_root_path;
  607. if ($force_option || !$config['allow_smilies'] || !$user->optionget('viewsmilies'))
  608. {
  609. return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#', '\1', $text);
  610. }
  611. else
  612. {
  613. return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/(.*?) \/><!\-\- s\1 \-\->#', '<img src="' . $phpbb_root_path . $config['smilies_path'] . '/\2 />', $text);
  614. }
  615. }
  616. /**
  617. * General attachment parsing
  618. *
  619. * @param mixed $forum_id The forum id the attachments are displayed in (false if in private message)
  620. * @param string &$message The post/private message
  621. * @param array &$attachments The attachments to parse for (inline) display. The attachments array will hold templated data after parsing.
  622. * @param array &$update_count The attachment counts to be updated - will be filled
  623. * @param bool $preview If set to true the attachments are parsed for preview. Within preview mode the comments are fetched from the given $attachments array and not fetched from the database.
  624. */
  625. function parse_attachments($forum_id, &$message, &$attachments, &$update_count, $preview = false)
  626. {
  627. if (!sizeof($attachments))
  628. {
  629. return;
  630. }
  631. global $template, $cache, $user;
  632. global $extensions, $config, $phpbb_root_path, $phpEx;
  633. //
  634. $compiled_attachments = array();
  635. if (!isset($template->filename['attachment_tpl']))
  636. {
  637. $template->set_filenames(array(
  638. 'attachment_tpl' => 'attachment.html')
  639. );
  640. }
  641. if (empty($extensions) || !is_array($extensions))
  642. {
  643. $extensions = $cache->obtain_attach_extensions($forum_id);
  644. }
  645. // Look for missing attachment information...
  646. $attach_ids = array();
  647. foreach ($attachments as $pos => $attachment)
  648. {
  649. // If is_orphan is set, we need to retrieve the attachments again...
  650. if (!isset($attachment['extension']) && !isset($attachment['physical_filename']))
  651. {
  652. $attach_ids[(int) $attachment['attach_id']] = $pos;
  653. }
  654. }
  655. // Grab attachments (security precaution)
  656. if (sizeof($attach_ids))
  657. {
  658. global $db;
  659. $new_attachment_data = array();
  660. $sql = 'SELECT *
  661. FROM ' . ATTACHMENTS_TABLE . '
  662. WHERE ' . $db->sql_in_set('attach_id', array_keys($attach_ids));
  663. $result = $db->sql_query($sql);
  664. while ($row = $db->sql_fetchrow($result))
  665. {
  666. if (!isset($attach_ids[$row['attach_id']]))
  667. {
  668. continue;
  669. }
  670. // If we preview attachments we will set some retrieved values here
  671. if ($preview)
  672. {
  673. $row['attach_comment'] = $attachments[$attach_ids[$row['attach_id']]]['attach_comment'];
  674. }
  675. $new_attachment_data[$attach_ids[$row['attach_id']]] = $row;
  676. }
  677. $db->sql_freeresult($result);
  678. $attachments = $new_attachment_data;
  679. unset($new_attachment_data);
  680. }
  681. // Sort correctly
  682. if ($config['display_order'])
  683. {
  684. // Ascending sort
  685. krsort($attachments);
  686. }
  687. else
  688. {
  689. // Descending sort
  690. ksort($attachments);
  691. }
  692. foreach ($attachments as $attachment)
  693. {
  694. if (!sizeof($attachment))
  695. {
  696. continue;
  697. }
  698. // We need to reset/empty the _file block var, because this function might be called more than once
  699. $template->destroy_block_vars('_file');
  700. $block_array = array();
  701. // Some basics...
  702. $attachment['extension'] = strtolower(trim($attachment['extension']));
  703. $filename = $phpbb_root_path . $config['upload_path'] . '/' . basename($attachment['physical_filename']);
  704. $thumbnail_filename = $phpbb_root_path . $config['upload_path'] . '/thumb_' . basename($attachment['physical_filename']);
  705. $upload_icon = '';
  706. if (isset($extensions[$attachment['extension']]))
  707. {
  708. if ($user->img('icon_topic_attach', '') && !$extensions[$attachment['extension']]['upload_icon'])
  709. {
  710. $upload_icon = $user->img('icon_topic_attach', '');
  711. }
  712. else if ($extensions[$attachment['extension']]['upload_icon'])
  713. {
  714. $upload_icon = '<img src="' . $phpbb_root_path . $config['upload_icons_path'] . '/' . trim($extensions[$attachment['extension']]['upload_icon']) . '" alt="" />';
  715. }
  716. }
  717. $filesize = $attachment['filesize'];
  718. $size_lang = ($filesize >= 1048576) ? $user->lang['MIB'] : (($filesize >= 1024) ? $user->lang['KIB'] : $user->lang['BYTES']);
  719. $filesize = get_formatted_filesize($filesize, false);
  720. $comment = bbcode_nl2br(censor_text($attachment['attach_comment']));
  721. $block_array += array(
  722. 'UPLOAD_ICON' => $upload_icon,
  723. 'FILESIZE' => $filesize,
  724. 'SIZE_LANG' => $size_lang,
  725. 'DOWNLOAD_NAME' => basename($attachment['real_filename']),
  726. 'COMMENT' => $comment,
  727. );
  728. $denied = false;
  729. if (!extension_allowed($forum_id, $attachment['extension'], $extensions))
  730. {
  731. $denied = true;
  732. $block_array += array(
  733. 'S_DENIED' => true,
  734. 'DENIED_MESSAGE' => sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])
  735. );
  736. }
  737. if (!$denied)
  738. {
  739. $l_downloaded_viewed = $download_link = '';
  740. $display_cat = $extensions[$attachment['extension']]['display_cat'];
  741. if ($display_cat == ATTACHMENT_CATEGORY_IMAGE)
  742. {
  743. if ($attachment['thumbnail'])
  744. {
  745. $display_cat = ATTACHMENT_CATEGORY_THUMB;
  746. }
  747. else
  748. {
  749. if ($config['img_display_inlined'])
  750. {
  751. if ($config['img_link_width'] || $config['img_link_height'])
  752. {
  753. $dimension = @getimagesize($filename);
  754. // If the dimensions could not be determined or the image being 0x0 we display it as a link for safety purposes
  755. if ($dimension === false || empty($dimension[0]) || empty($dimension[1]))
  756. {
  757. $display_cat = ATTACHMENT_CATEGORY_NONE;
  758. }
  759. else
  760. {
  761. $display_cat = ($dimension[0] <= $config['img_link_width'] && $dimension[1] <= $config['img_link_height']) ? ATTACHMENT_CATEGORY_IMAGE : ATTACHMENT_CATEGORY_NONE;
  762. }
  763. }
  764. }
  765. else
  766. {
  767. $display_cat = ATTACHMENT_CATEGORY_NONE;
  768. }
  769. }
  770. }
  771. // Make some descisions based on user options being set.
  772. if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
  773. {
  774. $display_cat = ATTACHMENT_CATEGORY_NONE;
  775. }
  776. if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !$user->optionget('viewflash'))
  777. {
  778. $display_cat = ATTACHMENT_CATEGORY_NONE;
  779. }
  780. $download_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id']);
  781. switch ($display_cat)
  782. {
  783. // Images
  784. case ATTACHMENT_CATEGORY_IMAGE:
  785. $l_downloaded_viewed = 'VIEWED_COUNT';
  786. $inline_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id']);
  787. $download_link .= '&amp;mode=view';
  788. $block_array += array(
  789. 'S_IMAGE' => true,
  790. 'U_INLINE_LINK' => $inline_link,
  791. );
  792. $update_count[] = $attachment['attach_id'];
  793. break;
  794. // Images, but display Thumbnail
  795. case ATTACHMENT_CATEGORY_THUMB:
  796. $l_downloaded_viewed = 'VIEWED_COUNT';
  797. $thumbnail_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id'] . '&amp;t=1');
  798. $download_link .= '&amp;mode=view';
  799. $block_array += array(
  800. 'S_THUMBNAIL' => true,
  801. 'THUMB_IMAGE' => $thumbnail_link,
  802. );
  803. break;
  804. // Windows Media Streams
  805. case ATTACHMENT_CATEGORY_WM:
  806. $l_downloaded_viewed = 'VIEWED_COUNT';
  807. // Giving the filename directly because within the wm object all variables are in local context making it impossible
  808. // to validate against a valid session (all params can differ)
  809. // $download_link = $filename;
  810. $block_array += array(
  811. 'U_FORUM' => generate_board_url(),
  812. 'ATTACH_ID' => $attachment['attach_id'],
  813. 'S_WM_FILE' => true,
  814. );
  815. // Viewed/Heared File ... update the download count
  816. $update_count[] = $attachment['attach_id'];
  817. break;
  818. // Real Media Streams
  819. case ATTACHMENT_CATEGORY_RM:
  820. case ATTACHMENT_CATEGORY_QUICKTIME:
  821. $l_downloaded_viewed = 'VIEWED_COUNT';
  822. $block_array += array(
  823. 'S_RM_FILE' => ($display_cat == ATTACHMENT_CATEGORY_RM) ? true : false,
  824. 'S_QUICKTIME_FILE' => ($display_cat == ATTACHMENT_CATEGORY_QUICKTIME) ? true : false,
  825. 'U_FORUM' => generate_board_url(),
  826. 'ATTACH_ID' => $attachment['attach_id'],
  827. );
  828. // Viewed/Heared File ... update the download count
  829. $update_count[] = $attachment['attach_id'];
  830. break;
  831. // Macromedia Flash Files
  832. case ATTACHMENT_CATEGORY_FLASH:
  833. list($width, $height) = @getimagesize($filename);
  834. $l_downloaded_viewed = 'VIEWED_COUNT';
  835. $block_array += array(
  836. 'S_FLASH_FILE' => true,
  837. 'WIDTH' => $width,
  838. 'HEIGHT' => $height,
  839. );
  840. // Viewed/Heared File ... update the download count
  841. $update_count[] = $attachment['attach_id'];
  842. break;
  843. default:
  844. $l_downloaded_viewed = 'DOWNLOAD_COUNT';
  845. $block_array += array(
  846. 'S_FILE' => true,
  847. );
  848. break;
  849. }
  850. $l_download_count = (!isset($attachment['download_count']) || $attachment['download_count'] == 0) ? $user->lang[$l_downloaded_viewed . '_NONE'] : (($attachment['download_count'] == 1) ? sprintf($user->lang[$l_downloaded_viewed], $attachment['download_count']) : sprintf($user->lang[$l_downloaded_viewed . 'S'], $attachment['download_count']));
  851. $block_array += array(
  852. 'U_DOWNLOAD_LINK' => $download_link,
  853. 'L_DOWNLOAD_COUNT' => $l_download_count
  854. );
  855. }
  856. $template->assign_block_vars('_file', $block_array);
  857. $compiled_attachments[] = $template->assign_display('attachment_tpl');
  858. }
  859. $attachments = $compiled_attachments;
  860. unset($compiled_attachments);
  861. $tpl_size = sizeof($attachments);
  862. $unset_tpl = array();
  863. preg_match_all('#<!\-\- ia([0-9]+) \-\->(.*?)<!\-\- ia\1 \-\->#', $message, $matches, PREG_PATTERN_ORDER);
  864. $replace = array();
  865. foreach ($matches[0] as $num => $capture)
  866. {
  867. // Flip index if we are displaying the reverse way
  868. $index = ($config['display_order']) ? ($tpl_size-($matches[1][$num] + 1)) : $matches[1][$num];
  869. $replace['from'][] = $matches[0][$num];
  870. $replace['to'][] = (isset($attachments[$index])) ? $attachments[$index] : sprintf($user->lang['MISSING_INLINE_ATTACHMENT'], $matches[2][array_search($index, $matches[1])]);
  871. $unset_tpl[] = $index;
  872. }
  873. if (isset($replace['from']))
  874. {
  875. $message = str_replace($replace['from'], $replace['to'], $message);
  876. }
  877. $unset_tpl = array_unique($unset_tpl);
  878. // Needed to let not display the inlined attachments at the end of the post again
  879. foreach ($unset_tpl as $index)
  880. {
  881. unset($attachments[$index]);
  882. }
  883. }
  884. /**
  885. * Check if extension is allowed to be posted.
  886. *
  887. * @param mixed $forum_id The forum id to check or false if private message
  888. * @param string $extension The extension to check, for example zip.
  889. * @param array &$extensions The extension array holding the information from the cache (will be obtained if empty)
  890. *
  891. * @return bool False if the extension is not allowed to be posted, else true.
  892. */
  893. function extension_allowed($forum_id, $extension, &$extensions)
  894. {
  895. if (empty($extensions))
  896. {
  897. global $cache;
  898. $extensions = $cache->obtain_attach_extensions($forum_id);
  899. }
  900. return (!isset($extensions['_allowed_'][$extension])) ? false : true;
  901. }
  902. /**
  903. * Truncates string while retaining special characters if going over the max length
  904. * The default max length is 60 at the moment
  905. * The maximum storage length is there to fit the string within the given length. The string may be further truncated due to html entities.
  906. * For example: string given is 'a "quote"' (length: 9), would be a stored as 'a &quot;quote&quot;' (length: 19)
  907. *
  908. * @param string $string The text to truncate to the given length. String is specialchared.
  909. * @param int $max_length Maximum length of string (multibyte character count as 1 char / Html entity count as 1 char)
  910. * @param int $max_store_length Maximum character length of string (multibyte character count as 1 char / Html entity count as entity chars).
  911. * @param bool $allow_reply Allow Re: in front of string
  912. * @param string $append String to be appended
  913. */
  914. function truncate_string($string, $max_length = 60, $max_store_length = 255, $allow_reply = true, $append = '')
  915. {
  916. $chars = array();
  917. $strip_reply = false;
  918. $stripped = false;
  919. if ($allow_reply && strpos($string, 'Re: ') === 0)
  920. {
  921. $strip_reply = true;
  922. $string = substr($string, 4);
  923. }
  924. $_chars = utf8_str_split(htmlspecialchars_decode($string));
  925. $chars = array_map('utf8_htmlspecialchars', $_chars);
  926. // Now check the length ;)
  927. if (sizeof($chars) > $max_length)
  928. {
  929. // Cut off the last elements from the array
  930. $string = implode('', array_slice($chars, 0, $max_length - utf8_strlen($append)));
  931. $stripped = true;
  932. }
  933. // Due to specialchars, we may not be able to store the string...
  934. if (utf8_strlen($string) > $max_store_length)
  935. {
  936. // let's split again, we do not want half-baked strings where entities are split
  937. $_chars = utf8_str_split(htmlspecialchars_decode($string));
  938. $chars = array_map('utf8_htmlspecialchars', $_chars);
  939. do
  940. {
  941. array_pop($chars);
  942. $string = implode('', $chars);
  943. }
  944. while (utf8_strlen($string) > $max_store_length || !sizeof($chars));
  945. }
  946. if ($strip_reply)
  947. {
  948. $string = 'Re: ' . $string;
  949. }
  950. if ($append != '' && $stripped)
  951. {
  952. $string = $string . $append;
  953. }
  954. return $string;
  955. }
  956. /**
  957. * Get username details for placing into templates.
  958. *
  959. * @param string $mode Can be profile (for getting an url to the profile), username (for obtaining the username), colour (for obtaining the user colour), full (for obtaining a html string representing a coloured link to the users profile) or no_profile (the same as full but forcing no profile link)
  960. * @param int $user_id The users id
  961. * @param string $username The users name
  962. * @param string $username_colour The users colour
  963. * @param string $guest_username optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then.
  964. * @param string $custom_profile_url optional parameter to specify a profile url. The user id get appended to this url as &amp;u={user_id}
  965. *
  966. * @return string A string consisting of what is wanted based on $mode.
  967. */
  968. function get_username_string($mode, $user_id, $username, $username_colour = '', $guest_username = false, $custom_profile_url = false)
  969. {
  970. global $phpbb_root_path, $phpEx, $user, $auth;
  971. $profile_url = '';
  972. $username_colour = ($username_colour) ? '#' . $username_colour : '';
  973. if ($guest_username === false)
  974. {
  975. $username = ($username) ? $username : $user->lang['GUEST'];
  976. }
  977. else
  978. {
  979. $username = ($user_id && $user_id != ANONYMOUS) ? $username : ((!empty($guest_username)) ? $guest_username : $user->lang['GUEST']);
  980. }
  981. // Only show the link if not anonymous
  982. if ($mode != 'no_profile' && $user_id && $user_id != ANONYMOUS)
  983. {
  984. // Do not show the link if the user is already logged in but do not have u_viewprofile permissions (relevant for bots mostly).
  985. // For all others the link leads to a login page or the profile.
  986. if ($user->data['user_id'] != ANONYMOUS && !$auth->acl_get('u_viewprofile'))
  987. {
  988. $profile_url = '';
  989. }
  990. else
  991. {
  992. $profile_url = ($custom_profile_url !== false) ? $custom_profile_url . '&amp;u=' . (int) $user_id : append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile&amp;u=' . (int) $user_id);
  993. }
  994. }
  995. else
  996. {
  997. $profile_url = '';
  998. }
  999. switch ($mode)
  1000. {
  1001. case 'profile':
  1002. return $profile_url;
  1003. break;
  1004. case 'username':
  1005. return $username;
  1006. break;
  1007. case 'colour':
  1008. return $username_colour;
  1009. break;
  1010. case 'no_profile':
  1011. case 'full':
  1012. default:
  1013. $tpl = '';
  1014. if (!$profile_url && !$username_colour)
  1015. {
  1016. $tpl = '{USERNAME}';
  1017. }
  1018. else if (!$profile_url && $username_colour)
  1019. {
  1020. $tpl = '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
  1021. }
  1022. else if ($profile_url && !$username_colour)
  1023. {
  1024. $tpl = '<a href="{PROFILE_URL}">{USERNAME}</a>';
  1025. }
  1026. else if ($profile_url && $username_colour)
  1027. {
  1028. $tpl = '<a href="{PROFILE_URL}" style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</a>';
  1029. }
  1030. return str_replace(array('{PROFILE_URL}', '{USERNAME_COLOUR}', '{USERNAME}'), array($profile_url, $username_colour, $username), $tpl);
  1031. break;
  1032. }
  1033. }
  1034. /**
  1035. * @package phpBB3
  1036. */
  1037. class bitfield
  1038. {
  1039. var $data;
  1040. function bitfield($bitfield = '')
  1041. {
  1042. $this->data = base64_decode($bitfield);
  1043. }
  1044. /**
  1045. */
  1046. function get($n)
  1047. {
  1048. // Get the ($n / 8)th char
  1049. $byte = $n >> 3;
  1050. if (strlen($this->data) >= $byte + 1)
  1051. {
  1052. $c = $this->data[$byte];
  1053. // Lookup the ($n % 8)th bit of the byte
  1054. $bit = 7 - ($n & 7);
  1055. return (bool) (ord($c) & (1 << $bit));
  1056. }
  1057. else
  1058. {
  1059. return false;
  1060. }
  1061. }
  1062. function set($n)
  1063. {
  1064. $byte = $n >> 3;
  1065. $bit = 7 - ($n & 7);
  1066. if (strlen($this->data) >= $byte + 1)
  1067. {
  1068. $this->data[$byte] = $this->data[$byte] | chr(1 << $bit);
  1069. }
  1070. else
  1071. {
  1072. $this->data .= str_repeat("\0", $byte - strlen($this->data));
  1073. $this->data .= chr(1 << $bit);
  1074. }
  1075. }
  1076. function clear($n)
  1077. {
  1078. $byte = $n >> 3;
  1079. if (strlen($this->data) >= $byte + 1)
  1080. {
  1081. $bit = 7 - ($n & 7);
  1082. $this->data[$byte] = $this->data[$byte] &~ chr(1 << $bit);
  1083. }
  1084. }
  1085. function get_blob()
  1086. {
  1087. return $this->data;
  1088. }
  1089. function get_base64()
  1090. {
  1091. return base64_encode($this->data);
  1092. }
  1093. function get_bin()
  1094. {
  1095. $bin = '';
  1096. $len = strlen($this->data);
  1097. for ($i = 0; $i < $len; ++$i)
  1098. {
  1099. $bin .= str_pad(decbin(ord($this->data[$i])), 8, '0', STR_PAD_LEFT);
  1100. }
  1101. return $bin;
  1102. }
  1103. function get_all_set()
  1104. {
  1105. return array_keys(array_filter(str_split($this->get_bin())));
  1106. }
  1107. function merge($bitfield)
  1108. {
  1109. $this->data = $this->data | $bitfield->get_blob();
  1110. }
  1111. }
  1112. ?>