PageRenderTime 68ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/phpBB/includes/functions_content.php

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