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

/wwwroot/phpbb/includes/functions_content.php

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