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

/phpBB/includes/functions_content.php

http://github.com/phpbb/phpbb3
PHP | 1792 lines | 1091 code | 240 blank | 461 comment | 179 complexity | a43715f93f2b90828a146f47e7330aca MD5 | raw file
Possible License(s): AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. *
  4. * This file is part of the phpBB Forum Software package.
  5. *
  6. * @copyright (c) phpBB Limited <https://www.phpbb.com>
  7. * @license GNU General Public License, version 2 (GPL-2.0)
  8. *
  9. * For full copyright and license information, please see
  10. * the docs/CREDITS.txt file.
  11. *
  12. */
  13. /**
  14. * @ignore
  15. */
  16. if (!defined('IN_PHPBB'))
  17. {
  18. exit;
  19. }
  20. /**
  21. * gen_sort_selects()
  22. * make_jumpbox()
  23. * bump_topic_allowed()
  24. * get_context()
  25. * phpbb_clean_search_string()
  26. * decode_message()
  27. * strip_bbcode()
  28. * generate_text_for_display()
  29. * generate_text_for_storage()
  30. * generate_text_for_edit()
  31. * make_clickable_callback()
  32. * make_clickable()
  33. * censor_text()
  34. * bbcode_nl2br()
  35. * smiley_text()
  36. * parse_attachments()
  37. * extension_allowed()
  38. * truncate_string()
  39. * get_username_string()
  40. * class bitfield
  41. */
  42. /**
  43. * Generate sort selection fields
  44. */
  45. 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)
  46. {
  47. global $user, $phpbb_dispatcher;
  48. $sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
  49. $sorts = array(
  50. 'st' => array(
  51. 'key' => 'sort_days',
  52. 'default' => $def_st,
  53. 'options' => $limit_days,
  54. 'output' => &$s_limit_days,
  55. ),
  56. 'sk' => array(
  57. 'key' => 'sort_key',
  58. 'default' => $def_sk,
  59. 'options' => $sort_by_text,
  60. 'output' => &$s_sort_key,
  61. ),
  62. 'sd' => array(
  63. 'key' => 'sort_dir',
  64. 'default' => $def_sd,
  65. 'options' => $sort_dir_text,
  66. 'output' => &$s_sort_dir,
  67. ),
  68. );
  69. $u_sort_param = '';
  70. foreach ($sorts as $name => $sort_ary)
  71. {
  72. $key = $sort_ary['key'];
  73. $selected = ${$sort_ary['key']};
  74. // Check if the key is selectable. If not, we reset to the default or first key found.
  75. // This ensures the values are always valid. We also set $sort_dir/sort_key/etc. to the
  76. // correct value, else the protection is void. ;)
  77. if (!isset($sort_ary['options'][$selected]))
  78. {
  79. if ($sort_ary['default'] !== false)
  80. {
  81. $selected = ${$key} = $sort_ary['default'];
  82. }
  83. else
  84. {
  85. @reset($sort_ary['options']);
  86. $selected = ${$key} = key($sort_ary['options']);
  87. }
  88. }
  89. $sort_ary['output'] = '<select name="' . $name . '" id="' . $name . '">';
  90. foreach ($sort_ary['options'] as $option => $text)
  91. {
  92. $sort_ary['output'] .= '<option value="' . $option . '"' . (($selected == $option) ? ' selected="selected"' : '') . '>' . $text . '</option>';
  93. }
  94. $sort_ary['output'] .= '</select>';
  95. $u_sort_param .= ($selected !== $sort_ary['default']) ? ((strlen($u_sort_param)) ? '&amp;' : '') . "{$name}={$selected}" : '';
  96. }
  97. /**
  98. * Run code before generated sort selects are returned
  99. *
  100. * @event core.gen_sort_selects_after
  101. * @var int limit_days Days limit
  102. * @var array sort_by_text Sort by text options
  103. * @var int sort_days Sort by days flag
  104. * @var string sort_key Sort key
  105. * @var string sort_dir Sort dir
  106. * @var string s_limit_days String of days limit
  107. * @var string s_sort_key String of sort key
  108. * @var string s_sort_dir String of sort dir
  109. * @var string u_sort_param Sort URL params
  110. * @var bool def_st Default sort days
  111. * @var bool def_sk Default sort key
  112. * @var bool def_sd Default sort dir
  113. * @var array sorts Sorts
  114. * @since 3.1.9-RC1
  115. */
  116. $vars = array(
  117. 'limit_days',
  118. 'sort_by_text',
  119. 'sort_days',
  120. 'sort_key',
  121. 'sort_dir',
  122. 's_limit_days',
  123. 's_sort_key',
  124. 's_sort_dir',
  125. 'u_sort_param',
  126. 'def_st',
  127. 'def_sk',
  128. 'def_sd',
  129. 'sorts',
  130. );
  131. extract($phpbb_dispatcher->trigger_event('core.gen_sort_selects_after', compact($vars)));
  132. return;
  133. }
  134. /**
  135. * Generate Jumpbox
  136. */
  137. function make_jumpbox($action, $forum_id = false, $select_all = false, $acl_list = false, $force_display = false)
  138. {
  139. global $config, $auth, $template, $user, $db, $phpbb_path_helper, $phpbb_dispatcher;
  140. // We only return if the jumpbox is not forced to be displayed (in case it is needed for functionality)
  141. if (!$config['load_jumpbox'] && $force_display === false)
  142. {
  143. return;
  144. }
  145. $sql = 'SELECT forum_id, forum_name, parent_id, forum_type, left_id, right_id
  146. FROM ' . FORUMS_TABLE . '
  147. ORDER BY left_id ASC';
  148. $result = $db->sql_query($sql, 600);
  149. $rowset = array();
  150. while ($row = $db->sql_fetchrow($result))
  151. {
  152. $rowset[(int) $row['forum_id']] = $row;
  153. }
  154. $db->sql_freeresult($result);
  155. $right = $padding = 0;
  156. $padding_store = array('0' => 0);
  157. $display_jumpbox = false;
  158. $iteration = 0;
  159. /**
  160. * Modify the jumpbox forum list data
  161. *
  162. * @event core.make_jumpbox_modify_forum_list
  163. * @var array rowset Array with the forums list data
  164. * @since 3.1.10-RC1
  165. */
  166. $vars = array('rowset');
  167. extract($phpbb_dispatcher->trigger_event('core.make_jumpbox_modify_forum_list', compact($vars)));
  168. // Sometimes it could happen that forums will be displayed here not be displayed within the index page
  169. // This is the result of forums not displayed at index, having list permissions and a parent of a forum with no permissions.
  170. // If this happens, the padding could be "broken"
  171. foreach ($rowset as $row)
  172. {
  173. if ($row['left_id'] < $right)
  174. {
  175. $padding++;
  176. $padding_store[$row['parent_id']] = $padding;
  177. }
  178. else if ($row['left_id'] > $right + 1)
  179. {
  180. // Ok, if the $padding_store for this parent is empty there is something wrong. For now we will skip over it.
  181. // @todo digging deep to find out "how" this can happen.
  182. $padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : $padding;
  183. }
  184. $right = $row['right_id'];
  185. if ($row['forum_type'] == FORUM_CAT && ($row['left_id'] + 1 == $row['right_id']))
  186. {
  187. // Non-postable forum with no subforums, don't display
  188. continue;
  189. }
  190. if (!$auth->acl_get('f_list', $row['forum_id']))
  191. {
  192. // if the user does not have permissions to list this forum skip
  193. continue;
  194. }
  195. if ($acl_list && !$auth->acl_gets($acl_list, $row['forum_id']))
  196. {
  197. continue;
  198. }
  199. $tpl_ary = array();
  200. if (!$display_jumpbox)
  201. {
  202. $tpl_ary[] = array(
  203. 'FORUM_ID' => ($select_all) ? 0 : -1,
  204. 'FORUM_NAME' => ($select_all) ? $user->lang['ALL_FORUMS'] : $user->lang['SELECT_FORUM'],
  205. 'S_FORUM_COUNT' => $iteration,
  206. 'LINK' => $phpbb_path_helper->append_url_params($action, array('f' => $forum_id)),
  207. );
  208. $iteration++;
  209. $display_jumpbox = true;
  210. }
  211. $tpl_ary[] = array(
  212. 'FORUM_ID' => $row['forum_id'],
  213. 'FORUM_NAME' => $row['forum_name'],
  214. 'SELECTED' => ($row['forum_id'] == $forum_id) ? ' selected="selected"' : '',
  215. 'S_FORUM_COUNT' => $iteration,
  216. 'S_IS_CAT' => ($row['forum_type'] == FORUM_CAT) ? true : false,
  217. 'S_IS_LINK' => ($row['forum_type'] == FORUM_LINK) ? true : false,
  218. 'S_IS_POST' => ($row['forum_type'] == FORUM_POST) ? true : false,
  219. 'LINK' => $phpbb_path_helper->append_url_params($action, array('f' => $row['forum_id'])),
  220. );
  221. /**
  222. * Modify the jumpbox before it is assigned to the template
  223. *
  224. * @event core.make_jumpbox_modify_tpl_ary
  225. * @var array row The data of the forum
  226. * @var array tpl_ary Template data of the forum
  227. * @since 3.1.10-RC1
  228. */
  229. $vars = array(
  230. 'row',
  231. 'tpl_ary',
  232. );
  233. extract($phpbb_dispatcher->trigger_event('core.make_jumpbox_modify_tpl_ary', compact($vars)));
  234. $template->assign_block_vars_array('jumpbox_forums', $tpl_ary);
  235. unset($tpl_ary);
  236. for ($i = 0; $i < $padding; $i++)
  237. {
  238. $template->assign_block_vars('jumpbox_forums.level', array());
  239. }
  240. $iteration++;
  241. }
  242. unset($padding_store, $rowset);
  243. $url_parts = $phpbb_path_helper->get_url_parts($action);
  244. $template->assign_vars(array(
  245. 'S_DISPLAY_JUMPBOX' => $display_jumpbox,
  246. 'S_JUMPBOX_ACTION' => $action,
  247. 'HIDDEN_FIELDS_FOR_JUMPBOX' => build_hidden_fields($url_parts['params']),
  248. ));
  249. return;
  250. }
  251. /**
  252. * Bump Topic Check - used by posting and viewtopic
  253. */
  254. function bump_topic_allowed($forum_id, $topic_bumped, $last_post_time, $topic_poster, $last_topic_poster)
  255. {
  256. global $config, $auth, $user;
  257. // Check permission and make sure the last post was not already bumped
  258. if (!$auth->acl_get('f_bump', $forum_id) || $topic_bumped)
  259. {
  260. return false;
  261. }
  262. // Check bump time range, is the user really allowed to bump the topic at this time?
  263. $bump_time = ($config['bump_type'] == 'm') ? $config['bump_interval'] * 60 : (($config['bump_type'] == 'h') ? $config['bump_interval'] * 3600 : $config['bump_interval'] * 86400);
  264. // Check bump time
  265. if ($last_post_time + $bump_time > time())
  266. {
  267. return false;
  268. }
  269. // Check bumper, only topic poster and last poster are allowed to bump
  270. if ($topic_poster != $user->data['user_id'] && $last_topic_poster != $user->data['user_id'])
  271. {
  272. return false;
  273. }
  274. // A bump time of 0 will completely disable the bump feature... not intended but might be useful.
  275. return $bump_time;
  276. }
  277. /**
  278. * Generates a text with approx. the specified length which contains the specified words and their context
  279. *
  280. * @param string $text The full text from which context shall be extracted
  281. * @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!)
  282. * @param int $length The desired length of the resulting text, however the result might be shorter or longer than this value
  283. *
  284. * @return string Context of the specified words separated by "..."
  285. */
  286. function get_context($text, $words, $length = 400)
  287. {
  288. // first replace all whitespaces with single spaces
  289. $text = preg_replace('/ +/', ' ', strtr($text, "\t\n\r\x0C ", ' '));
  290. // we need to turn the entities back into their original form, to not cut the message in between them
  291. $entities = array('&lt;', '&gt;', '&#91;', '&#93;', '&#46;', '&#58;', '&#058;');
  292. $characters = array('<', '>', '[', ']', '.', ':', ':');
  293. $text = str_replace($entities, $characters, $text);
  294. $word_indizes = array();
  295. if (count($words))
  296. {
  297. $match = '';
  298. // find the starting indizes of all words
  299. foreach ($words as $word)
  300. {
  301. if ($word)
  302. {
  303. if (preg_match('#(?:[^\w]|^)(' . $word . ')(?:[^\w]|$)#i', $text, $match))
  304. {
  305. if (empty($match[1]))
  306. {
  307. continue;
  308. }
  309. $pos = utf8_strpos($text, $match[1]);
  310. if ($pos !== false)
  311. {
  312. $word_indizes[] = $pos;
  313. }
  314. }
  315. }
  316. }
  317. unset($match);
  318. if (count($word_indizes))
  319. {
  320. $word_indizes = array_unique($word_indizes);
  321. sort($word_indizes);
  322. $wordnum = count($word_indizes);
  323. // number of characters on the right and left side of each word
  324. $sequence_length = (int) ($length / (2 * $wordnum)) - 2;
  325. $final_text = '';
  326. $word = $j = 0;
  327. $final_text_index = -1;
  328. // cycle through every character in the original text
  329. for ($i = $word_indizes[$word], $n = utf8_strlen($text); $i < $n; $i++)
  330. {
  331. // if the current position is the start of one of the words then append $sequence_length characters to the final text
  332. if (isset($word_indizes[$word]) && ($i == $word_indizes[$word]))
  333. {
  334. if ($final_text_index < $i - $sequence_length - 1)
  335. {
  336. $final_text .= '... ' . preg_replace('#^([^ ]*)#', '', utf8_substr($text, $i - $sequence_length, $sequence_length));
  337. }
  338. else
  339. {
  340. // if the final text is already nearer to the current word than $sequence_length we only append the text
  341. // from its current index on and distribute the unused length to all other sequenes
  342. $sequence_length += (int) (($final_text_index - $i + $sequence_length + 1) / (2 * $wordnum));
  343. $final_text .= utf8_substr($text, $final_text_index + 1, $i - $final_text_index - 1);
  344. }
  345. $final_text_index = $i - 1;
  346. // add the following characters to the final text (see below)
  347. $word++;
  348. $j = 1;
  349. }
  350. if ($j > 0)
  351. {
  352. // add the character to the final text and increment the sequence counter
  353. $final_text .= utf8_substr($text, $i, 1);
  354. $final_text_index++;
  355. $j++;
  356. // if this is a whitespace then check whether we are done with this sequence
  357. if (utf8_substr($text, $i, 1) == ' ')
  358. {
  359. // only check whether we have to exit the context generation completely if we haven't already reached the end anyway
  360. if ($i + 4 < $n)
  361. {
  362. if (($j > $sequence_length && $word >= $wordnum) || utf8_strlen($final_text) > $length)
  363. {
  364. $final_text .= ' ...';
  365. break;
  366. }
  367. }
  368. else
  369. {
  370. // make sure the text really reaches the end
  371. $j -= 4;
  372. }
  373. // stop context generation and wait for the next word
  374. if ($j > $sequence_length)
  375. {
  376. $j = 0;
  377. }
  378. }
  379. }
  380. }
  381. return str_replace($characters, $entities, $final_text);
  382. }
  383. }
  384. if (!count($words) || !count($word_indizes))
  385. {
  386. return str_replace($characters, $entities, ((utf8_strlen($text) >= $length + 3) ? utf8_substr($text, 0, $length) . '...' : $text));
  387. }
  388. }
  389. /**
  390. * Cleans a search string by removing single wildcards from it and replacing multiple spaces with a single one.
  391. *
  392. * @param string $search_string The full search string which should be cleaned.
  393. *
  394. * @return string The cleaned search string without any wildcards and multiple spaces.
  395. */
  396. function phpbb_clean_search_string($search_string)
  397. {
  398. // This regular expressions matches every single wildcard.
  399. // That means one after a whitespace or the beginning of the string or one before a whitespace or the end of the string.
  400. $search_string = preg_replace('#(?<=^|\s)\*+(?=\s|$)#', '', $search_string);
  401. $search_string = trim($search_string);
  402. $search_string = preg_replace(array('#\s+#u', '#\*+#u'), array(' ', '*'), $search_string);
  403. return $search_string;
  404. }
  405. /**
  406. * Decode text whereby text is coming from the db and expected to be pre-parsed content
  407. * We are placing this outside of the message parser because we are often in need of it...
  408. *
  409. * NOTE: special chars are kept encoded
  410. *
  411. * @param string &$message Original message, passed by reference
  412. * @param string $bbcode_uid BBCode UID
  413. * @return null
  414. */
  415. function decode_message(&$message, $bbcode_uid = '')
  416. {
  417. global $phpbb_container, $phpbb_dispatcher;
  418. /**
  419. * Use this event to modify the message before it is decoded
  420. *
  421. * @event core.decode_message_before
  422. * @var string message_text The message content
  423. * @var string bbcode_uid The message BBCode UID
  424. * @since 3.1.9-RC1
  425. */
  426. $message_text = $message;
  427. $vars = array('message_text', 'bbcode_uid');
  428. extract($phpbb_dispatcher->trigger_event('core.decode_message_before', compact($vars)));
  429. $message = $message_text;
  430. if (preg_match('#^<[rt][ >]#', $message))
  431. {
  432. $message = htmlspecialchars($phpbb_container->get('text_formatter.utils')->unparse($message), ENT_COMPAT);
  433. }
  434. else
  435. {
  436. if ($bbcode_uid)
  437. {
  438. $match = array('<br />', "[/*:m:$bbcode_uid]", ":u:$bbcode_uid", ":o:$bbcode_uid", ":$bbcode_uid");
  439. $replace = array("\n", '', '', '', '');
  440. }
  441. else
  442. {
  443. $match = array('<br />');
  444. $replace = array("\n");
  445. }
  446. $message = str_replace($match, $replace, $message);
  447. $match = get_preg_expression('bbcode_htm');
  448. $replace = array('\1', '\1', '\2', '\2', '\1', '', '');
  449. $message = preg_replace($match, $replace, $message);
  450. }
  451. /**
  452. * Use this event to modify the message after it is decoded
  453. *
  454. * @event core.decode_message_after
  455. * @var string message_text The message content
  456. * @var string bbcode_uid The message BBCode UID
  457. * @since 3.1.9-RC1
  458. */
  459. $message_text = $message;
  460. $vars = array('message_text', 'bbcode_uid');
  461. extract($phpbb_dispatcher->trigger_event('core.decode_message_after', compact($vars)));
  462. $message = $message_text;
  463. }
  464. /**
  465. * Strips all bbcode from a text in place
  466. */
  467. function strip_bbcode(&$text, $uid = '')
  468. {
  469. global $phpbb_container;
  470. if (preg_match('#^<[rt][ >]#', $text))
  471. {
  472. $text = $phpbb_container->get('text_formatter.utils')->clean_formatting($text);
  473. }
  474. else
  475. {
  476. if (!$uid)
  477. {
  478. $uid = '[0-9a-z]{5,}';
  479. }
  480. $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:&quot;.*&quot;|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);
  481. $match = get_preg_expression('bbcode_htm');
  482. $replace = array('\1', '\1', '\2', '\1', '', '');
  483. $text = preg_replace($match, $replace, $text);
  484. }
  485. }
  486. /**
  487. * For display of custom parsed text on user-facing pages
  488. * Expects $text to be the value directly from the database (stored value)
  489. */
  490. function generate_text_for_display($text, $uid, $bitfield, $flags, $censor_text = true)
  491. {
  492. static $bbcode;
  493. global $auth, $config, $user;
  494. global $phpbb_dispatcher, $phpbb_container;
  495. if ($text === '')
  496. {
  497. return '';
  498. }
  499. /**
  500. * Use this event to modify the text before it is parsed
  501. *
  502. * @event core.modify_text_for_display_before
  503. * @var string text The text to parse
  504. * @var string uid The BBCode UID
  505. * @var string bitfield The BBCode Bitfield
  506. * @var int flags The BBCode Flags
  507. * @var bool censor_text Whether or not to apply word censors
  508. * @since 3.1.0-a1
  509. */
  510. $vars = array('text', 'uid', 'bitfield', 'flags', 'censor_text');
  511. extract($phpbb_dispatcher->trigger_event('core.modify_text_for_display_before', compact($vars)));
  512. if (preg_match('#^<[rt][ >]#', $text))
  513. {
  514. $renderer = $phpbb_container->get('text_formatter.renderer');
  515. // Temporarily switch off viewcensors if applicable
  516. $old_censor = $renderer->get_viewcensors();
  517. // Check here if the user is having viewing censors disabled (and also allowed to do so).
  518. if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
  519. {
  520. $censor_text = false;
  521. }
  522. if ($old_censor !== $censor_text)
  523. {
  524. $renderer->set_viewcensors($censor_text);
  525. }
  526. $text = $renderer->render($text);
  527. // Restore the previous value
  528. if ($old_censor !== $censor_text)
  529. {
  530. $renderer->set_viewcensors($old_censor);
  531. }
  532. }
  533. else
  534. {
  535. if ($censor_text)
  536. {
  537. $text = censor_text($text);
  538. }
  539. // Parse bbcode if bbcode uid stored and bbcode enabled
  540. if ($uid && ($flags & OPTION_FLAG_BBCODE))
  541. {
  542. if (!class_exists('bbcode'))
  543. {
  544. global $phpbb_root_path, $phpEx;
  545. include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
  546. }
  547. if (empty($bbcode))
  548. {
  549. $bbcode = new bbcode($bitfield);
  550. }
  551. else
  552. {
  553. $bbcode->bbcode_set_bitfield($bitfield);
  554. }
  555. $bbcode->bbcode_second_pass($text, $uid);
  556. }
  557. $text = bbcode_nl2br($text);
  558. $text = smiley_text($text, !($flags & OPTION_FLAG_SMILIES));
  559. }
  560. /**
  561. * Use this event to modify the text after it is parsed
  562. *
  563. * @event core.modify_text_for_display_after
  564. * @var string text The text to parse
  565. * @var string uid The BBCode UID
  566. * @var string bitfield The BBCode Bitfield
  567. * @var int flags The BBCode Flags
  568. * @since 3.1.0-a1
  569. */
  570. $vars = array('text', 'uid', 'bitfield', 'flags');
  571. extract($phpbb_dispatcher->trigger_event('core.modify_text_for_display_after', compact($vars)));
  572. return $text;
  573. }
  574. /**
  575. * For parsing custom parsed text to be stored within the database.
  576. * This function additionally returns the uid and bitfield that needs to be stored.
  577. * Expects $text to be the value directly from $request->variable() and in it's non-parsed form
  578. *
  579. * @param string $text The text to be replaced with the parsed one
  580. * @param string $uid The BBCode uid for this parse
  581. * @param string $bitfield The BBCode bitfield for this parse
  582. * @param int $flags The allow_bbcode, allow_urls and allow_smilies compiled into a single integer.
  583. * @param bool $allow_bbcode If BBCode is allowed (i.e. if BBCode is parsed)
  584. * @param bool $allow_urls If urls is allowed
  585. * @param bool $allow_smilies If smilies are allowed
  586. * @param bool $allow_img_bbcode
  587. * @param bool $allow_flash_bbcode
  588. * @param bool $allow_quote_bbcode
  589. * @param bool $allow_url_bbcode
  590. * @param string $mode Mode to parse text as, e.g. post or sig
  591. *
  592. * @return array An array of string with the errors that occurred while parsing
  593. */
  594. function generate_text_for_storage(&$text, &$uid, &$bitfield, &$flags, $allow_bbcode = false, $allow_urls = false, $allow_smilies = false, $allow_img_bbcode = true, $allow_flash_bbcode = true, $allow_quote_bbcode = true, $allow_url_bbcode = true, $mode = 'post')
  595. {
  596. global $phpbb_root_path, $phpEx, $phpbb_dispatcher;
  597. /**
  598. * Use this event to modify the text before it is prepared for storage
  599. *
  600. * @event core.modify_text_for_storage_before
  601. * @var string text The text to parse
  602. * @var string uid The BBCode UID
  603. * @var string bitfield The BBCode Bitfield
  604. * @var int flags The BBCode Flags
  605. * @var bool allow_bbcode Whether or not to parse BBCode
  606. * @var bool allow_urls Whether or not to parse URLs
  607. * @var bool allow_smilies Whether or not to parse Smilies
  608. * @var bool allow_img_bbcode Whether or not to parse the [img] BBCode
  609. * @var bool allow_flash_bbcode Whether or not to parse the [flash] BBCode
  610. * @var bool allow_quote_bbcode Whether or not to parse the [quote] BBCode
  611. * @var bool allow_url_bbcode Whether or not to parse the [url] BBCode
  612. * @var string mode Mode to parse text as, e.g. post or sig
  613. * @since 3.1.0-a1
  614. * @changed 3.2.0-a1 Added mode
  615. */
  616. $vars = array(
  617. 'text',
  618. 'uid',
  619. 'bitfield',
  620. 'flags',
  621. 'allow_bbcode',
  622. 'allow_urls',
  623. 'allow_smilies',
  624. 'allow_img_bbcode',
  625. 'allow_flash_bbcode',
  626. 'allow_quote_bbcode',
  627. 'allow_url_bbcode',
  628. 'mode',
  629. );
  630. extract($phpbb_dispatcher->trigger_event('core.modify_text_for_storage_before', compact($vars)));
  631. $uid = $bitfield = '';
  632. $flags = (($allow_bbcode) ? OPTION_FLAG_BBCODE : 0) + (($allow_smilies) ? OPTION_FLAG_SMILIES : 0) + (($allow_urls) ? OPTION_FLAG_LINKS : 0);
  633. if (!class_exists('parse_message'))
  634. {
  635. include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
  636. }
  637. $message_parser = new parse_message($text);
  638. $message_parser->parse($allow_bbcode, $allow_urls, $allow_smilies, $allow_img_bbcode, $allow_flash_bbcode, $allow_quote_bbcode, $allow_url_bbcode, true, $mode);
  639. $text = $message_parser->message;
  640. $uid = $message_parser->bbcode_uid;
  641. // If the bbcode_bitfield is empty, there is no need for the uid to be stored.
  642. if (!$message_parser->bbcode_bitfield)
  643. {
  644. $uid = '';
  645. }
  646. $bitfield = $message_parser->bbcode_bitfield;
  647. /**
  648. * Use this event to modify the text after it is prepared for storage
  649. *
  650. * @event core.modify_text_for_storage_after
  651. * @var string text The text to parse
  652. * @var string uid The BBCode UID
  653. * @var string bitfield The BBCode Bitfield
  654. * @var int flags The BBCode Flags
  655. * @var string message_parser The message_parser object
  656. * @since 3.1.0-a1
  657. * @changed 3.1.11-RC1 Added message_parser to vars
  658. */
  659. $vars = array('text', 'uid', 'bitfield', 'flags', 'message_parser');
  660. extract($phpbb_dispatcher->trigger_event('core.modify_text_for_storage_after', compact($vars)));
  661. return $message_parser->warn_msg;
  662. }
  663. /**
  664. * For decoding custom parsed text for edits as well as extracting the flags
  665. * Expects $text to be the value directly from the database (pre-parsed content)
  666. */
  667. function generate_text_for_edit($text, $uid, $flags)
  668. {
  669. global $phpbb_dispatcher;
  670. /**
  671. * Use this event to modify the text before it is decoded for editing
  672. *
  673. * @event core.modify_text_for_edit_before
  674. * @var string text The text to parse
  675. * @var string uid The BBCode UID
  676. * @var int flags The BBCode Flags
  677. * @since 3.1.0-a1
  678. */
  679. $vars = array('text', 'uid', 'flags');
  680. extract($phpbb_dispatcher->trigger_event('core.modify_text_for_edit_before', compact($vars)));
  681. decode_message($text, $uid);
  682. /**
  683. * Use this event to modify the text after it is decoded for editing
  684. *
  685. * @event core.modify_text_for_edit_after
  686. * @var string text The text to parse
  687. * @var int flags The BBCode Flags
  688. * @since 3.1.0-a1
  689. */
  690. $vars = array('text', 'flags');
  691. extract($phpbb_dispatcher->trigger_event('core.modify_text_for_edit_after', compact($vars)));
  692. return array(
  693. 'allow_bbcode' => ($flags & OPTION_FLAG_BBCODE) ? 1 : 0,
  694. 'allow_smilies' => ($flags & OPTION_FLAG_SMILIES) ? 1 : 0,
  695. 'allow_urls' => ($flags & OPTION_FLAG_LINKS) ? 1 : 0,
  696. 'text' => $text
  697. );
  698. }
  699. /**
  700. * A subroutine of make_clickable used with preg_replace
  701. * It places correct HTML around an url, shortens the displayed text
  702. * and makes sure no entities are inside URLs
  703. */
  704. function make_clickable_callback($type, $whitespace, $url, $relative_url, $class)
  705. {
  706. $orig_url = $url;
  707. $orig_relative = $relative_url;
  708. $append = '';
  709. $url = htmlspecialchars_decode($url);
  710. $relative_url = htmlspecialchars_decode($relative_url);
  711. // make sure no HTML entities were matched
  712. $chars = array('<', '>', '"');
  713. $split = false;
  714. foreach ($chars as $char)
  715. {
  716. $next_split = strpos($url, $char);
  717. if ($next_split !== false)
  718. {
  719. $split = ($split !== false) ? min($split, $next_split) : $next_split;
  720. }
  721. }
  722. if ($split !== false)
  723. {
  724. // an HTML entity was found, so the URL has to end before it
  725. $append = substr($url, $split) . $relative_url;
  726. $url = substr($url, 0, $split);
  727. $relative_url = '';
  728. }
  729. else if ($relative_url)
  730. {
  731. // same for $relative_url
  732. $split = false;
  733. foreach ($chars as $char)
  734. {
  735. $next_split = strpos($relative_url, $char);
  736. if ($next_split !== false)
  737. {
  738. $split = ($split !== false) ? min($split, $next_split) : $next_split;
  739. }
  740. }
  741. if ($split !== false)
  742. {
  743. $append = substr($relative_url, $split);
  744. $relative_url = substr($relative_url, 0, $split);
  745. }
  746. }
  747. // if the last character of the url is a punctuation mark, exclude it from the url
  748. $last_char = ($relative_url) ? $relative_url[strlen($relative_url) - 1] : $url[strlen($url) - 1];
  749. switch ($last_char)
  750. {
  751. case '.':
  752. case '?':
  753. case '!':
  754. case ':':
  755. case ',':
  756. $append = $last_char;
  757. if ($relative_url)
  758. {
  759. $relative_url = substr($relative_url, 0, -1);
  760. }
  761. else
  762. {
  763. $url = substr($url, 0, -1);
  764. }
  765. break;
  766. // set last_char to empty here, so the variable can be used later to
  767. // check whether a character was removed
  768. default:
  769. $last_char = '';
  770. break;
  771. }
  772. $short_url = (utf8_strlen($url) > 55) ? utf8_substr($url, 0, 39) . ' ... ' . utf8_substr($url, -10) : $url;
  773. switch ($type)
  774. {
  775. case MAGIC_URL_LOCAL:
  776. $tag = 'l';
  777. $relative_url = preg_replace('/[&?]sid=[0-9a-f]{32}$/', '', preg_replace('/([&?])sid=[0-9a-f]{32}&/', '$1', $relative_url));
  778. $url = $url . '/' . $relative_url;
  779. $text = $relative_url;
  780. // this url goes to http://domain.tld/path/to/board/ which
  781. // would result in an empty link if treated as local so
  782. // don't touch it and let MAGIC_URL_FULL take care of it.
  783. if (!$relative_url)
  784. {
  785. return $whitespace . $orig_url . '/' . $orig_relative; // slash is taken away by relative url pattern
  786. }
  787. break;
  788. case MAGIC_URL_FULL:
  789. $tag = 'm';
  790. $text = $short_url;
  791. break;
  792. case MAGIC_URL_WWW:
  793. $tag = 'w';
  794. $url = 'http://' . $url;
  795. $text = $short_url;
  796. break;
  797. case MAGIC_URL_EMAIL:
  798. $tag = 'e';
  799. $text = $short_url;
  800. $url = 'mailto:' . $url;
  801. break;
  802. }
  803. $url = htmlspecialchars($url);
  804. $text = htmlspecialchars($text);
  805. $append = htmlspecialchars($append);
  806. $html = "$whitespace<!-- $tag --><a$class href=\"$url\">$text</a><!-- $tag -->$append";
  807. return $html;
  808. }
  809. /**
  810. * make_clickable function
  811. *
  812. * Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
  813. * Cuts down displayed size of link if over 50 chars, turns absolute links
  814. * into relative versions when the server/script path matches the link
  815. */
  816. function make_clickable($text, $server_url = false, $class = 'postlink')
  817. {
  818. if ($server_url === false)
  819. {
  820. $server_url = generate_board_url();
  821. }
  822. static $static_class;
  823. static $magic_url_match_args;
  824. if (!isset($magic_url_match_args[$server_url]) || $static_class != $class)
  825. {
  826. $static_class = $class;
  827. $class = ($static_class) ? ' class="' . $static_class . '"' : '';
  828. $local_class = ($static_class) ? ' class="' . $static_class . '-local"' : '';
  829. if (!is_array($magic_url_match_args))
  830. {
  831. $magic_url_match_args = array();
  832. }
  833. // relative urls for this board
  834. $magic_url_match_args[$server_url][] = array(
  835. '#(^|[\n\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#iu',
  836. MAGIC_URL_LOCAL,
  837. $local_class,
  838. );
  839. // matches a xxxx://aaaaa.bbb.cccc. ...
  840. $magic_url_match_args[$server_url][] = array(
  841. '#(^|[\n\t (>.])(' . get_preg_expression('url_inline') . ')#iu',
  842. MAGIC_URL_FULL,
  843. $class,
  844. );
  845. // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
  846. $magic_url_match_args[$server_url][] = array(
  847. '#(^|[\n\t (>])(' . get_preg_expression('www_url_inline') . ')#iu',
  848. MAGIC_URL_WWW,
  849. $class,
  850. );
  851. // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
  852. $magic_url_match_args[$server_url][] = array(
  853. '/(^|[\n\t (>])(' . get_preg_expression('email') . ')/iu',
  854. MAGIC_URL_EMAIL,
  855. '',
  856. );
  857. }
  858. foreach ($magic_url_match_args[$server_url] as $magic_args)
  859. {
  860. if (preg_match($magic_args[0], $text, $matches))
  861. {
  862. $text = preg_replace_callback($magic_args[0], function($matches) use ($magic_args)
  863. {
  864. $relative_url = isset($matches[3]) ? $matches[3] : '';
  865. return make_clickable_callback($magic_args[1], $matches[1], $matches[2], $relative_url, $magic_args[2]);
  866. }, $text);
  867. }
  868. }
  869. return $text;
  870. }
  871. /**
  872. * Censoring
  873. */
  874. function censor_text($text)
  875. {
  876. static $censors;
  877. // Nothing to do?
  878. if ($text === '')
  879. {
  880. return '';
  881. }
  882. // We moved the word censor checks in here because we call this function quite often - and then only need to do the check once
  883. if (!isset($censors) || !is_array($censors))
  884. {
  885. global $config, $user, $auth, $cache;
  886. // We check here if the user is having viewing censors disabled (and also allowed to do so).
  887. if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
  888. {
  889. $censors = array();
  890. }
  891. else
  892. {
  893. $censors = $cache->obtain_word_list();
  894. }
  895. }
  896. if (count($censors))
  897. {
  898. return preg_replace($censors['match'], $censors['replace'], $text);
  899. }
  900. return $text;
  901. }
  902. /**
  903. * custom version of nl2br which takes custom BBCodes into account
  904. */
  905. function bbcode_nl2br($text)
  906. {
  907. // custom BBCodes might contain carriage returns so they
  908. // are not converted into <br /> so now revert that
  909. $text = str_replace(array("\n", "\r"), array('<br />', "\n"), $text);
  910. return $text;
  911. }
  912. /**
  913. * Smiley processing
  914. */
  915. function smiley_text($text, $force_option = false)
  916. {
  917. global $config, $user, $phpbb_path_helper, $phpbb_dispatcher;
  918. if ($force_option || !$config['allow_smilies'] || !$user->optionget('viewsmilies'))
  919. {
  920. return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#', '\1', $text);
  921. }
  922. else
  923. {
  924. $root_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? generate_board_url() . '/' : $phpbb_path_helper->get_web_root_path();
  925. /**
  926. * Event to override the root_path for smilies
  927. *
  928. * @event core.smiley_text_root_path
  929. * @var string root_path root_path for smilies
  930. * @since 3.1.11-RC1
  931. */
  932. $vars = array('root_path');
  933. extract($phpbb_dispatcher->trigger_event('core.smiley_text_root_path', compact($vars)));
  934. return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/(.*?) \/><!\-\- s\1 \-\->#', '<img class="smilies" src="' . $root_path . $config['smilies_path'] . '/\2 />', $text);
  935. }
  936. }
  937. /**
  938. * General attachment parsing
  939. *
  940. * @param mixed $forum_id The forum id the attachments are displayed in (false if in private message)
  941. * @param string &$message The post/private message
  942. * @param array &$attachments The attachments to parse for (inline) display. The attachments array will hold templated data after parsing.
  943. * @param array &$update_count_ary The attachment counts to be updated - will be filled
  944. * @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.
  945. */
  946. function parse_attachments($forum_id, &$message, &$attachments, &$update_count_ary, $preview = false)
  947. {
  948. if (!count($attachments))
  949. {
  950. return;
  951. }
  952. global $template, $cache, $user, $phpbb_dispatcher;
  953. global $extensions, $config, $phpbb_root_path, $phpEx;
  954. global $phpbb_container;
  955. $storage_attachment = $phpbb_container->get('storage.attachment');
  956. //
  957. $compiled_attachments = array();
  958. if (!isset($template->filename['attachment_tpl']))
  959. {
  960. $template->set_filenames(array(
  961. 'attachment_tpl' => 'attachment.html')
  962. );
  963. }
  964. if (empty($extensions) || !is_array($extensions))
  965. {
  966. $extensions = $cache->obtain_attach_extensions($forum_id);
  967. }
  968. // Look for missing attachment information...
  969. $attach_ids = array();
  970. foreach ($attachments as $pos => $attachment)
  971. {
  972. // If is_orphan is set, we need to retrieve the attachments again...
  973. if (!isset($attachment['extension']) && !isset($attachment['physical_filename']))
  974. {
  975. $attach_ids[(int) $attachment['attach_id']] = $pos;
  976. }
  977. }
  978. // Grab attachments (security precaution)
  979. if (count($attach_ids))
  980. {
  981. global $db;
  982. $new_attachment_data = array();
  983. $sql = 'SELECT *
  984. FROM ' . ATTACHMENTS_TABLE . '
  985. WHERE ' . $db->sql_in_set('attach_id', array_keys($attach_ids));
  986. $result = $db->sql_query($sql);
  987. while ($row = $db->sql_fetchrow($result))
  988. {
  989. if (!isset($attach_ids[$row['attach_id']]))
  990. {
  991. continue;
  992. }
  993. // If we preview attachments we will set some retrieved values here
  994. if ($preview)
  995. {
  996. $row['attach_comment'] = $attachments[$attach_ids[$row['attach_id']]]['attach_comment'];
  997. }
  998. $new_attachment_data[$attach_ids[$row['attach_id']]] = $row;
  999. }
  1000. $db->sql_freeresult($result);
  1001. $attachments = $new_attachment_data;
  1002. unset($new_attachment_data);
  1003. }
  1004. // Make sure attachments are properly ordered
  1005. ksort($attachments);
  1006. foreach ($attachments as $attachment)
  1007. {
  1008. if (!count($attachment))
  1009. {
  1010. continue;
  1011. }
  1012. // We need to reset/empty the _file block var, because this function might be called more than once
  1013. $template->destroy_block_vars('_file');
  1014. $block_array = array();
  1015. // Some basics...
  1016. $attachment['extension'] = strtolower(trim($attachment['extension']));
  1017. $filename = utf8_basename($attachment['physical_filename']);
  1018. $upload_icon = '';
  1019. $download_link = '';
  1020. $display_cat = false;
  1021. if (isset($extensions[$attachment['extension']]))
  1022. {
  1023. if ($user->img('icon_topic_attach', '') && !$extensions[$attachment['extension']]['upload_icon'])
  1024. {
  1025. $upload_icon = $user->img('icon_topic_attach', '');
  1026. }
  1027. else if ($extensions[$attachment['extension']]['upload_icon'])
  1028. {
  1029. $upload_icon = '<img src="' . $phpbb_root_path . $config['upload_icons_path'] . '/' . trim($extensions[$attachment['extension']]['upload_icon']) . '" alt="" />';
  1030. }
  1031. }
  1032. $filesize = get_formatted_filesize($attachment['filesize'], false);
  1033. $comment = bbcode_nl2br(censor_text($attachment['attach_comment']));
  1034. $block_array += array(
  1035. 'UPLOAD_ICON' => $upload_icon,
  1036. 'FILESIZE' => $filesize['value'],
  1037. 'SIZE_LANG' => $filesize['unit'],
  1038. 'DOWNLOAD_NAME' => utf8_basename($attachment['real_filename']),
  1039. 'COMMENT' => $comment,
  1040. );
  1041. $denied = false;
  1042. if (!extension_allowed($forum_id, $attachment['extension'], $extensions))
  1043. {
  1044. $denied = true;
  1045. $block_array += array(
  1046. 'S_DENIED' => true,
  1047. 'DENIED_MESSAGE' => sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])
  1048. );
  1049. }
  1050. if (!$denied)
  1051. {
  1052. $display_cat = $extensions[$attachment['extension']]['display_cat'];
  1053. if ($display_cat == ATTACHMENT_CATEGORY_IMAGE)
  1054. {
  1055. if ($attachment['thumbnail'])
  1056. {
  1057. $display_cat = ATTACHMENT_CATEGORY_THUMB;
  1058. }
  1059. else
  1060. {
  1061. if ($config['img_display_inlined'])
  1062. {
  1063. if ($config['img_link_width'] || $config['img_link_height'])
  1064. {
  1065. try
  1066. {
  1067. $file_info = $storage_attachment->file_info($filename);
  1068. $display_cat = ($file_info->image_width <= $config['img_link_width'] && $file_info->image_height <= $config['img_link_height']) ? ATTACHMENT_CATEGORY_IMAGE : ATTACHMENT_CATEGORY_NONE;
  1069. }
  1070. catch (\Exception $e)
  1071. {
  1072. $display_cat = ATTACHMENT_CATEGORY_NONE;
  1073. }
  1074. }
  1075. }
  1076. else
  1077. {
  1078. $display_cat = ATTACHMENT_CATEGORY_NONE;
  1079. }
  1080. }
  1081. }
  1082. // Make some descisions based on user options being set.
  1083. if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
  1084. {
  1085. $display_cat = ATTACHMENT_CATEGORY_NONE;
  1086. }
  1087. $download_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id']);
  1088. $l_downloaded_viewed = 'VIEWED_COUNTS';
  1089. switch ($display_cat)
  1090. {
  1091. // Images
  1092. case ATTACHMENT_CATEGORY_IMAGE:
  1093. $inline_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id']);
  1094. $download_link .= '&amp;mode=view';
  1095. $block_array += array(
  1096. 'S_IMAGE' => true,
  1097. 'U_INLINE_LINK' => $inline_link,
  1098. );
  1099. $update_count_ary[] = $attachment['attach_id'];
  1100. break;
  1101. // Images, but display Thumbnail
  1102. case ATTACHMENT_CATEGORY_THUMB:
  1103. $thumbnail_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id'] . '&amp;t=1');
  1104. $download_link .= '&amp;mode=view';
  1105. $block_array += array(
  1106. 'S_THUMBNAIL' => true,
  1107. 'THUMB_IMAGE' => $thumbnail_link,
  1108. );
  1109. $update_count_ary[] = $attachment['attach_id'];
  1110. break;
  1111. default:
  1112. $l_downloaded_viewed = 'DOWNLOAD_COUNTS';
  1113. $block_array += array(
  1114. 'S_FILE' => true,
  1115. );
  1116. break;
  1117. }
  1118. if (!isset($attachment['download_count']))
  1119. {
  1120. $attachment['download_count'] = 0;
  1121. }
  1122. $block_array += array(
  1123. 'U_DOWNLOAD_LINK' => $download_link,
  1124. 'L_DOWNLOAD_COUNT' => $user->lang($l_downloaded_viewed, (int) $attachment['download_count']),
  1125. );
  1126. }
  1127. $update_count = $update_count_ary;
  1128. /**
  1129. * Use this event to modify the attachment template data.
  1130. *
  1131. * This event is triggered once per attachment.
  1132. *
  1133. * @event core.parse_attachments_modify_template_data
  1134. * @var array attachment Array with attachment data
  1135. * @var array block_array Template data of the attachment
  1136. * @var int display_cat Attachment category data
  1137. * @var string download_link Attachment download link
  1138. * @var array extensions Array with attachment extensions data
  1139. * @var mixed forum_id The forum id the attachments are displayed in (false if in private message)
  1140. * @var bool preview Flag indicating if we are in post preview mode
  1141. * @var array update_count Array with attachment ids to update download count
  1142. * @since 3.1.0-RC5
  1143. */
  1144. $vars = array(
  1145. 'attachment',
  1146. 'block_array',
  1147. 'display_cat',
  1148. 'download_link',
  1149. 'extensions',
  1150. 'forum_id',
  1151. 'preview',
  1152. 'update_count',
  1153. );
  1154. extract($phpbb_dispatcher->trigger_event('core.parse_attachments_modify_template_data', compact($vars)));
  1155. $update_count_ary = $update_count;
  1156. unset($update_count, $display_cat, $download_link);
  1157. $template->assign_block_vars('_file', $block_array);
  1158. $compiled_attachments[] = $template->assign_display('attachment_tpl');
  1159. }
  1160. $attachments = $compiled_attachments;
  1161. unset($compiled_attachments);
  1162. $unset_tpl = array();
  1163. preg_match_all('#<!\-\- ia([0-9]+) \-\->(.*?)<!\-\- ia\1 \-\->#', $message, $matches, PREG_PATTERN_ORDER);
  1164. $replace = array();
  1165. foreach ($matches[0] as $num => $capture)
  1166. {
  1167. $index = $matches[1][$num];
  1168. $replace['from'][] = $matches[0][$num];
  1169. $replace['to'][] = (isset($attachments[$index])) ? $attachments[$index] : sprintf($user->lang['MISSING_INLINE_ATTACHMENT'], $matches[2][array_search($index, $matches[1])]);
  1170. $unset_tpl[] = $index;
  1171. }
  1172. if (isset($replace['from']))
  1173. {
  1174. $message = str_replace($replace['from'], $replace['to'], $message);
  1175. }
  1176. $unset_tpl = array_unique($unset_tpl);
  1177. // Sort correctly
  1178. if ($config['display_order'])
  1179. {
  1180. // Ascending sort
  1181. krsort($attachments);
  1182. }
  1183. else
  1184. {
  1185. // Descending sort
  1186. ksort($attachments);
  1187. }
  1188. // Needed to let not display the inlined attachments at the end of the post again
  1189. foreach ($unset_tpl as $index)
  1190. {
  1191. unset($attachments[$index]);
  1192. }
  1193. }
  1194. /**
  1195. * Check if extension is allowed to be posted.
  1196. *
  1197. * @param mixed $forum_id The forum id to check or false if private message
  1198. * @param string $extension The extension to check, for example zip.
  1199. * @param array &$extensions The extension array holding the information from the cache (will be obtained if empty)
  1200. *
  1201. * @return bool False if the extension is not allowed to be posted, else true.
  1202. */
  1203. function extension_allowed($forum_id, $extension, &$extensions)
  1204. {
  1205. if (empty($extensions))
  1206. {
  1207. global $cache;
  1208. $extensions = $cache->obtain_attach_extensions($forum_id);
  1209. }
  1210. return (!isset($extensions['_allowed_'][$extension])) ? false : true;
  1211. }
  1212. /**
  1213. * Truncates string while retaining special characters if going over the max length
  1214. * The default max length is 60 at the moment
  1215. * The maximum storage length is there to fit the string within the given length. The string may be further truncated due to html entities.
  1216. * For example: string given is 'a "quote"' (length: 9), would be a stored as 'a &quot;quote&quot;' (length: 19)
  1217. *
  1218. * @param string $string The text to truncate to the given length. String is specialchared.
  1219. * @param int $max_length Maximum length of string (multibyte character count as 1 char / Html entity count as 1 char)
  1220. * @param int $max_store_length Maximum character length of string (multibyte character count as 1 char / Html entity count as entity chars).
  1221. * @param bool $allow_reply Allow Re: in front of string
  1222. * NOTE: This parameter can cause undesired behavior (returning strings longer than $max_store_length) and is deprecated.
  1223. * @param string $append String to be appended
  1224. */
  1225. function truncate_string($string, $max_length = 60, $max_store_length = 255, $allow_reply = false, $append = '')
  1226. {
  1227. $strip_reply = false;
  1228. $stripped = false;
  1229. if ($allow_reply && strpos($string, 'Re: ') === 0)
  1230. {
  1231. $strip_reply = true;
  1232. $string = substr($string, 4);
  1233. }
  1234. $_chars = utf8_str_split(htmlspecialchars_decode($string));
  1235. $chars = array_map('utf8_htmlspecialchars', $_chars);
  1236. // Now check the length ;)
  1237. if (count($chars) > $max_length)
  1238. {
  1239. // Cut off the last elements from the array
  1240. $string = implode('', array_slice($chars, 0, $max_length - utf8_strlen($append)));
  1241. $stripped = true;
  1242. }
  1243. // Due to specialchars, we may not be able to store the string...
  1244. if (utf8_strlen($string) > $max_store_length)
  1245. {
  1246. // let's split again, we do not want half-baked strings where entities are split
  1247. $_chars = utf8_str_split(htmlspecialchars_decode($string));
  1248. $chars = array_map('utf8_htmlspecialchars', $_chars);
  1249. do
  1250. {
  1251. array_pop($chars);
  1252. $string = implode('', $chars);
  1253. }
  1254. while (!empty($chars) && utf8_strlen($string) > $max_store_length);
  1255. }
  1256. if ($strip_reply)
  1257. {
  1258. $string = 'Re: ' . $string;
  1259. }
  1260. if ($append != '' && $stripped)
  1261. {
  1262. $string = $string . $append;
  1263. }
  1264. return $string;
  1265. }
  1266. /**
  1267. * Get username details for placing into templates.
  1268. * This function caches all modes on first call, except for no_profile and anonymous user - determined by $user_id.
  1269. *
  1270. * @html Username spans and links
  1271. *
  1272. * @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)
  1273. * @param int $user_id The users id
  1274. * @param string $username The users name
  1275. * @param string $username_colour The users colour
  1276. * @param string $guest_username optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then.
  1277. * @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}
  1278. *
  1279. * @return string A string consisting of what is wanted based on $mode.
  1280. */
  1281. function get_username_string($mode, $user_id, $username, $username_colour = '', $guest_username = false, $custom_profile_url = false)
  1282. {
  1283. static $_profile_cache;
  1284. global $phpbb_dispatcher;
  1285. // We cache some common variables we need within this function
  1286. if (empty($_profile_cache))
  1287. {
  1288. global $phpbb_root_path, $phpEx;
  1289. /** @html Username spans and links for usage in the template */
  1290. $_profile_cache['base_url'] = append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile&amp;u={USER_ID}');
  1291. $_profile_cache['tpl_noprofile'] = '<span class="username">{USERNAME}</span>';
  1292. $_profile_cache['tpl_noprofile_colour'] = '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
  1293. $_profile_cache['tpl_profile'] = '<a href="{PROFILE_URL}" class="username">{USERNAME}</a>';
  1294. $_profile_cache['tpl_profile_colour'] = '<a href="{PROFILE_URL}" style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</a>';
  1295. }
  1296. global $user, $auth;
  1297. // This switch makes sure we only run code required for the mode
  1298. switch ($mode)
  1299. {
  1300. case 'full':
  1301. case 'no_profile':
  1302. case 'colour':
  1303. // Build correct username colour
  1304. $username_colour = ($username_colour) ? '#' . $username_colour : '';
  1305. // Return colour
  1306. if ($mode == 'colour')
  1307. {
  1308. $username_string = $username_colour;
  1309. break;
  1310. }
  1311. // no break;
  1312. case 'username':
  1313. // Build correct username
  1314. if ($guest_username === false)
  1315. {
  1316. $username = ($username) ? $username : $user->lang['GUEST'];
  1317. }
  1318. else
  1319. {
  1320. $username = ($user_id && $user_id != ANONYMOUS) ? $username : ((!empty($guest_username)) ? $guest_username : $user->lang['GUEST']);
  1321. }
  1322. // Return username
  1323. if ($mode == 'username')
  1324. {
  1325. $username_string = $username;
  1326. break;
  1327. }
  1328. // no break;
  1329. case 'profile':
  1330. // Build correct profile url - only show if not anonymous and permission to view profile if registered user
  1331. // For anonymous the link leads to a login page.
  1332. if ($user_id && $user_id != ANONYMOUS && ($user->data['user_id'] == ANONYMOUS || $auth->acl_get('u_viewprofile')))
  1333. {
  1334. $profile_url = ($custom_profile_url !== false) ? $custom_profile_url . '&amp;u=' . (int) $user_id : str_replace(array('={USER_ID}', '=%7BUSER_ID%7D'), '=' . (int) $user_id, $_profile_cache['base_url']);
  1335. }
  1336. else
  1337. {
  1338. $profile_url = '';
  1339. }
  1340. // Return profile
  1341. if ($mode == 'profile')
  1342. {
  1343. $username_string = $profile_url;
  1344. break;
  1345. }
  1346. // no break;
  1347. }
  1348. if (!isset($username_string))
  1349. {
  1350. if (($mode == 'full' && !$profile_url) || $mode == 'no_profile')
  1351. {
  1352. $username_string = str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($username_colour, $username), (!$username_colour) ? $_profile_cache['tpl_noprofile'] : $_profile_cache['tpl_noprofile_colour']);
  1353. }
  1354. else
  1355. {
  1356. $username_string = str_replace(array('{PROFILE_URL}', '{USERNAME_COLOUR}', '{USERNAME}'), array($profile_url, $username_colour, $username), (!$username_colour) ? $_profile_cache['tpl_profile'] : $_profile_cache['tpl_profile_colour']);
  1357. }
  1358. }
  1359. /**
  1360. * Use this event to change the output of get_username_string()
  1361. *
  1362. * @event core.modify_username_string
  1363. * @var string mode profile|username|colour|full|no_profile
  1364. * @var int user_id String or array of additional url
  1365. * parameters
  1366. * @var string username The user's username
  1367. * @var string username_colour The user's colour
  1368. * @var string guest_username Optional parameter to specify the
  1369. * guest username.
  1370. * @var string custom_profile_url Optional parameter to specify a
  1371. * profile url.
  1372. * @var string username_string The string that has been generated
  1373. * @var array _profile_cache Array of original return templates
  1374. * @since 3.1.0-a1
  1375. */
  1376. $vars = array(
  1377. 'mode',
  1378. 'user_id',
  1379. 'username',
  1380. 'username_colour',
  1381. 'guest_username',
  1382. 'custom_profile_url',
  1383. 'username_string',
  1384. '_profile_cache',
  1385. );
  1386. extract($phpbb_dispatcher->trigger_event('core.modify_username_string', compact($vars)));
  1387. return $username_string;
  1388. }
  1389. /**
  1390. * Add an option to the quick-mod tools.
  1391. *
  1392. * @param string $url The recepting URL for the quickmod actions.
  1393. * @param string $option The language key for the value of the option.
  1394. * @param string $lang_string The language string to use.
  1395. */
  1396. function phpbb_add_quickmod_option($url, $option, $lang_string)
  1397. {
  1398. global $template, $user, $phpbb_path_helper;
  1399. $lang_string = $user->lang($lang_string);
  1400. $template->assign_block_vars('quickmod', array(
  1401. 'VALUE' => $option,
  1402. 'TITLE' => $lang_string,
  1403. 'LINK' => $phpbb_path_helper->append_url_params($url, array('action' => $option)),
  1404. ));
  1405. }
  1406. /**
  1407. * Concatenate an array into a string list.
  1408. *
  1409. * @param array $items Array of items to concatenate
  1410. * @param object $user The phpBB $user object.
  1411. *
  1412. * @return string String list. Examples: "A"; "A and B"; "A, B, and C"
  1413. */
  1414. function phpbb_generate_string_list($items, $user)
  1415. {
  1416. if (empty($items))
  1417. {
  1418. return '';
  1419. }
  1420. $count = count($items);
  1421. $last_item = array_pop($items);
  1422. $lang_key = 'STRING_LIST_MULTI';
  1423. if ($count == 1)
  1424. {
  1425. return $last_item;
  1426. }
  1427. else if ($count == 2)
  1428. {
  1429. $lang_key = 'STRING_LIST_SIMPLE';
  1430. }
  1431. $list = implode($user->lang['COMMA_SEPARATOR'], $items);
  1432. return $user->lang($lang_key, $list, $last_item);
  1433. }
  1434. class bitfield
  1435. {
  1436. var $data;
  1437. function __construct($bitfield = '')
  1438. {
  1439. $this->data = base64_decode($bitfield);
  1440. }
  1441. /**
  1442. */
  1443. function get($n)
  1444. {
  1445. // Get the ($n / 8)th char
  1446. $byte = $n >> 3;
  1447. if (strlen($this->data) >= $byte + 1)
  1448. {
  1449. $c = $this->data[$byte];
  1450. // Lookup the ($n % 8)th bit of the byte
  1451. $bit = 7 - ($n & 7);
  1452. return (bool) (ord($c) & (1 << $bit));
  1453. }
  1454. else
  1455. {
  1456. return false;
  1457. }
  1458. }
  1459. function set($n)
  1460. {
  1461. $byte = $n >> 3;
  1462. $bit = 7 - ($n & 7);
  1463. if (strlen($this->data) >= $byte + 1)
  1464. {
  1465. $this->data[$byte] = $this->data[$byte] | chr(1 << $bit);
  1466. }
  1467. else
  1468. {
  1469. $this->data .= str_repeat("\0", $byte - strlen($this->data));
  1470. $this->data .= chr(1 << $bit);
  1471. }
  1472. }
  1473. function clear($n)
  1474. {
  1475. $byte = $n >> 3;
  1476. if (strlen($this->data) >= $byte + 1)
  1477. {
  1478. $bit = 7 - ($n & 7);
  1479. $this->data[$byte] = $this->data[$byte] &~ chr(1 << $bit);
  1480. }
  1481. }
  1482. function get_blob()
  1483. {
  1484. return $this->data;
  1485. }
  1486. function get_base64()
  1487. {
  1488. return base64_encode($this->data);
  1489. }
  1490. function get_

Large files files are truncated, but you can click here to view the full file