PageRenderTime 77ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/sources/Subs.php

https://github.com/Arantor/Elkarte
PHP | 4142 lines | 2863 code | 493 blank | 786 comment | 702 complexity | fd7dfb7282fc0705c0cb0c5e04a37a29 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0
  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * This file has all the main functions in it that relate to, well, everything.
  16. *
  17. */
  18. if (!defined('ELKARTE'))
  19. die('No access...');
  20. /**
  21. * Update some basic statistics.
  22. *
  23. * 'member' statistic updates the latest member, the total member
  24. * count, and the number of unapproved members.
  25. * 'member' also only counts approved members when approval is on, but
  26. * is much more efficient with it off.
  27. *
  28. * 'message' changes the total number of messages, and the
  29. * highest message id by id_msg - which can be parameters 1 and 2,
  30. * respectively.
  31. *
  32. * 'topic' updates the total number of topics, or if parameter1 is true
  33. * simply increments them.
  34. *
  35. * 'subject' updateds the log_search_subjects in the event of a topic being
  36. * moved, removed or split. parameter1 is the topicid, parameter2 is the new subject
  37. *
  38. * 'postgroups' case updates those members who match condition's
  39. * post-based membergroups in the database (restricted by parameter1).
  40. *
  41. * @param string $type Stat type - can be 'member', 'message', 'topic', 'subject' or 'postgroups'
  42. * @param mixed $parameter1 = null
  43. * @param mixed $parameter2 = null
  44. */
  45. function updateStats($type, $parameter1 = null, $parameter2 = null)
  46. {
  47. global $modSettings, $smcFunc;
  48. switch ($type)
  49. {
  50. case 'member':
  51. $changes = array(
  52. 'memberlist_updated' => time(),
  53. );
  54. // #1 latest member ID, #2 the real name for a new registration.
  55. if (is_numeric($parameter1))
  56. {
  57. $changes['latestMember'] = $parameter1;
  58. $changes['latestRealName'] = $parameter2;
  59. updateSettings(array('totalMembers' => true), true);
  60. }
  61. // We need to calculate the totals.
  62. else
  63. {
  64. // Update the latest activated member (highest id_member) and count.
  65. $result = $smcFunc['db_query']('', '
  66. SELECT COUNT(*), MAX(id_member)
  67. FROM {db_prefix}members
  68. WHERE is_activated = {int:is_activated}',
  69. array(
  70. 'is_activated' => 1,
  71. )
  72. );
  73. list ($changes['totalMembers'], $changes['latestMember']) = $smcFunc['db_fetch_row']($result);
  74. $smcFunc['db_free_result']($result);
  75. // Get the latest activated member's display name.
  76. $result = $smcFunc['db_query']('', '
  77. SELECT real_name
  78. FROM {db_prefix}members
  79. WHERE id_member = {int:id_member}
  80. LIMIT 1',
  81. array(
  82. 'id_member' => (int) $changes['latestMember'],
  83. )
  84. );
  85. list ($changes['latestRealName']) = $smcFunc['db_fetch_row']($result);
  86. $smcFunc['db_free_result']($result);
  87. // Are we using registration approval?
  88. if ((!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 2) || !empty($modSettings['approveAccountDeletion']))
  89. {
  90. // Update the amount of members awaiting approval - ignoring COPPA accounts, as you can't approve them until you get permission.
  91. $result = $smcFunc['db_query']('', '
  92. SELECT COUNT(*)
  93. FROM {db_prefix}members
  94. WHERE is_activated IN ({array_int:activation_status})',
  95. array(
  96. 'activation_status' => array(3, 4),
  97. )
  98. );
  99. list ($changes['unapprovedMembers']) = $smcFunc['db_fetch_row']($result);
  100. $smcFunc['db_free_result']($result);
  101. }
  102. }
  103. updateSettings($changes);
  104. break;
  105. case 'message':
  106. if ($parameter1 === true && $parameter2 !== null)
  107. updateSettings(array('totalMessages' => true, 'maxMsgID' => $parameter2), true);
  108. else
  109. {
  110. // SUM and MAX on a smaller table is better for InnoDB tables.
  111. $result = $smcFunc['db_query']('', '
  112. SELECT SUM(num_posts + unapproved_posts) AS total_messages, MAX(id_last_msg) AS max_msg_id
  113. FROM {db_prefix}boards
  114. WHERE redirect = {string:blank_redirect}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  115. AND id_board != {int:recycle_board}' : ''),
  116. array(
  117. 'recycle_board' => isset($modSettings['recycle_board']) ? $modSettings['recycle_board'] : 0,
  118. 'blank_redirect' => '',
  119. )
  120. );
  121. $row = $smcFunc['db_fetch_assoc']($result);
  122. $smcFunc['db_free_result']($result);
  123. updateSettings(array(
  124. 'totalMessages' => $row['total_messages'] === null ? 0 : $row['total_messages'],
  125. 'maxMsgID' => $row['max_msg_id'] === null ? 0 : $row['max_msg_id']
  126. ));
  127. }
  128. break;
  129. case 'subject':
  130. // Remove the previous subject (if any).
  131. $smcFunc['db_query']('', '
  132. DELETE FROM {db_prefix}log_search_subjects
  133. WHERE id_topic = {int:id_topic}',
  134. array(
  135. 'id_topic' => (int) $parameter1,
  136. )
  137. );
  138. // Insert the new subject.
  139. if ($parameter2 !== null)
  140. {
  141. $parameter1 = (int) $parameter1;
  142. $parameter2 = text2words($parameter2);
  143. $inserts = array();
  144. foreach ($parameter2 as $word)
  145. $inserts[] = array($word, $parameter1);
  146. if (!empty($inserts))
  147. $smcFunc['db_insert']('ignore',
  148. '{db_prefix}log_search_subjects',
  149. array('word' => 'string', 'id_topic' => 'int'),
  150. $inserts,
  151. array('word', 'id_topic')
  152. );
  153. }
  154. break;
  155. case 'topic':
  156. if ($parameter1 === true)
  157. updateSettings(array('totalTopics' => true), true);
  158. else
  159. {
  160. // Get the number of topics - a SUM is better for InnoDB tables.
  161. // We also ignore the recycle bin here because there will probably be a bunch of one-post topics there.
  162. $result = $smcFunc['db_query']('', '
  163. SELECT SUM(num_topics + unapproved_topics) AS total_topics
  164. FROM {db_prefix}boards' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  165. WHERE id_board != {int:recycle_board}' : ''),
  166. array(
  167. 'recycle_board' => !empty($modSettings['recycle_board']) ? $modSettings['recycle_board'] : 0,
  168. )
  169. );
  170. $row = $smcFunc['db_fetch_assoc']($result);
  171. $smcFunc['db_free_result']($result);
  172. updateSettings(array('totalTopics' => $row['total_topics'] === null ? 0 : $row['total_topics']));
  173. }
  174. break;
  175. case 'postgroups':
  176. // Parameter two is the updated columns: we should check to see if we base groups off any of these.
  177. if ($parameter2 !== null && !in_array('posts', $parameter2))
  178. return;
  179. $postgroups = cache_get_data('updateStats:postgroups', 360);
  180. if ($postgroups === null || $parameter1 === null)
  181. {
  182. // Fetch the postgroups!
  183. $request = $smcFunc['db_query']('', '
  184. SELECT id_group, min_posts
  185. FROM {db_prefix}membergroups
  186. WHERE min_posts != {int:min_posts}',
  187. array(
  188. 'min_posts' => -1,
  189. )
  190. );
  191. $postgroups = array();
  192. while ($row = $smcFunc['db_fetch_assoc']($request))
  193. $postgroups[$row['id_group']] = $row['min_posts'];
  194. $smcFunc['db_free_result']($request);
  195. // Sort them this way because if it's done with MySQL it causes a filesort :(.
  196. arsort($postgroups);
  197. cache_put_data('updateStats:postgroups', $postgroups, 360);
  198. }
  199. // Oh great, they've screwed their post groups.
  200. if (empty($postgroups))
  201. return;
  202. // Set all membergroups from most posts to least posts.
  203. $conditions = '';
  204. $lastMin = 0;
  205. foreach ($postgroups as $id => $min_posts)
  206. {
  207. $conditions .= '
  208. WHEN posts >= ' . $min_posts . (!empty($lastMin) ? ' AND posts <= ' . $lastMin : '') . ' THEN ' . $id;
  209. $lastMin = $min_posts;
  210. }
  211. // A big fat CASE WHEN... END is faster than a zillion UPDATE's ;).
  212. $smcFunc['db_query']('', '
  213. UPDATE {db_prefix}members
  214. SET id_post_group = CASE ' . $conditions . '
  215. ELSE 0
  216. END' . ($parameter1 != null ? '
  217. WHERE ' . (is_array($parameter1) ? 'id_member IN ({array_int:members})' : 'id_member = {int:members}') : ''),
  218. array(
  219. 'members' => $parameter1,
  220. )
  221. );
  222. break;
  223. default:
  224. trigger_error('updateStats(): Invalid statistic type \'' . $type . '\'', E_USER_NOTICE);
  225. }
  226. }
  227. /**
  228. * Updates the columns in the members table.
  229. * Assumes the data has been htmlspecialchar'd.
  230. * this function should be used whenever member data needs to be
  231. * updated in place of an UPDATE query.
  232. *
  233. * id_member is either an int or an array of ints to be updated.
  234. *
  235. * data is an associative array of the columns to be updated and their respective values.
  236. * any string values updated should be quoted and slashed.
  237. *
  238. * the value of any column can be '+' or '-', which mean 'increment'
  239. * and decrement, respectively.
  240. *
  241. * if the member's post number is updated, updates their post groups.
  242. *
  243. * @param mixed $members An array of integers
  244. * @param array $data
  245. */
  246. function updateMemberData($members, $data)
  247. {
  248. global $modSettings, $user_info, $smcFunc;
  249. $parameters = array();
  250. if (is_array($members))
  251. {
  252. $condition = 'id_member IN ({array_int:members})';
  253. $parameters['members'] = $members;
  254. }
  255. elseif ($members === null)
  256. $condition = '1=1';
  257. else
  258. {
  259. $condition = 'id_member = {int:member}';
  260. $parameters['member'] = $members;
  261. }
  262. // Everything is assumed to be a string unless it's in the below.
  263. $knownInts = array(
  264. 'date_registered', 'posts', 'id_group', 'last_login', 'instant_messages', 'unread_messages',
  265. 'new_pm', 'pm_prefs', 'gender', 'hide_email', 'show_online', 'pm_email_notify', 'pm_receive_from', 'karma_good', 'karma_bad',
  266. 'notify_announcements', 'notify_send_body', 'notify_regularity', 'notify_types',
  267. 'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning',
  268. );
  269. $knownFloats = array(
  270. 'time_offset',
  271. );
  272. if (!empty($modSettings['integrate_change_member_data']))
  273. {
  274. // Only a few member variables are really interesting for integration.
  275. $integration_vars = array(
  276. 'member_name',
  277. 'real_name',
  278. 'email_address',
  279. 'id_group',
  280. 'gender',
  281. 'birthdate',
  282. 'website_title',
  283. 'website_url',
  284. 'location',
  285. 'hide_email',
  286. 'time_format',
  287. 'time_offset',
  288. 'avatar',
  289. 'lngfile',
  290. );
  291. $vars_to_integrate = array_intersect($integration_vars, array_keys($data));
  292. // Only proceed if there are any variables left to call the integration function.
  293. if (count($vars_to_integrate) != 0)
  294. {
  295. // Fetch a list of member_names if necessary
  296. if ((!is_array($members) && $members === $user_info['id']) || (is_array($members) && count($members) == 1 && in_array($user_info['id'], $members)))
  297. $member_names = array($user_info['username']);
  298. else
  299. {
  300. $member_names = array();
  301. $request = $smcFunc['db_query']('', '
  302. SELECT member_name
  303. FROM {db_prefix}members
  304. WHERE ' . $condition,
  305. $parameters
  306. );
  307. while ($row = $smcFunc['db_fetch_assoc']($request))
  308. $member_names[] = $row['member_name'];
  309. $smcFunc['db_free_result']($request);
  310. }
  311. if (!empty($member_names))
  312. foreach ($vars_to_integrate as $var)
  313. call_integration_hook('integrate_change_member_data', array($member_names, $var, $data[$var], $knownInts, $knownFloats));
  314. }
  315. }
  316. $setString = '';
  317. foreach ($data as $var => $val)
  318. {
  319. $type = 'string';
  320. if (in_array($var, $knownInts))
  321. $type = 'int';
  322. elseif (in_array($var, $knownFloats))
  323. $type = 'float';
  324. elseif ($var == 'birthdate')
  325. $type = 'date';
  326. // Doing an increment?
  327. if ($type == 'int' && ($val === '+' || $val === '-'))
  328. {
  329. $val = $var . ' ' . $val . ' 1';
  330. $type = 'raw';
  331. }
  332. // Ensure posts, instant_messages, and unread_messages don't overflow or underflow.
  333. if (in_array($var, array('posts', 'instant_messages', 'unread_messages')))
  334. {
  335. if (preg_match('~^' . $var . ' (\+ |- |\+ -)([\d]+)~', $val, $match))
  336. {
  337. if ($match[1] != '+ ')
  338. $val = 'CASE WHEN ' . $var . ' <= ' . abs($match[2]) . ' THEN 0 ELSE ' . $val . ' END';
  339. $type = 'raw';
  340. }
  341. }
  342. $setString .= ' ' . $var . ' = {' . $type . ':p_' . $var . '},';
  343. $parameters['p_' . $var] = $val;
  344. }
  345. $smcFunc['db_query']('', '
  346. UPDATE {db_prefix}members
  347. SET' . substr($setString, 0, -1) . '
  348. WHERE ' . $condition,
  349. $parameters
  350. );
  351. updateStats('postgroups', $members, array_keys($data));
  352. // Clear any caching?
  353. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2 && !empty($members))
  354. {
  355. if (!is_array($members))
  356. $members = array($members);
  357. foreach ($members as $member)
  358. {
  359. if ($modSettings['cache_enable'] >= 3)
  360. {
  361. cache_put_data('member_data-profile-' . $member, null, 120);
  362. cache_put_data('member_data-normal-' . $member, null, 120);
  363. cache_put_data('member_data-minimal-' . $member, null, 120);
  364. }
  365. cache_put_data('user_settings-' . $member, null, 60);
  366. }
  367. }
  368. }
  369. /**
  370. * Updates the settings table as well as $modSettings... only does one at a time if $update is true.
  371. *
  372. * - updates both the settings table and $modSettings array.
  373. * - all of changeArray's indexes and values are assumed to have escaped apostrophes (')!
  374. * - if a variable is already set to what you want to change it to, that
  375. * variable will be skipped over; it would be unnecessary to reset.
  376. * - When use_update is true, UPDATEs will be used instead of REPLACE.
  377. * - when use_update is true, the value can be true or false to increment
  378. * or decrement it, respectively.
  379. *
  380. * @param array $changeArray
  381. * @param bool $update = false
  382. * @param bool $debug = false
  383. */
  384. function updateSettings($changeArray, $update = false, $debug = false)
  385. {
  386. global $modSettings, $smcFunc;
  387. if (empty($changeArray) || !is_array($changeArray))
  388. return;
  389. // In some cases, this may be better and faster, but for large sets we don't want so many UPDATEs.
  390. if ($update)
  391. {
  392. foreach ($changeArray as $variable => $value)
  393. {
  394. $smcFunc['db_query']('', '
  395. UPDATE {db_prefix}settings
  396. SET value = {' . ($value === false || $value === true ? 'raw' : 'string') . ':value}
  397. WHERE variable = {string:variable}',
  398. array(
  399. 'value' => $value === true ? 'value + 1' : ($value === false ? 'value - 1' : $value),
  400. 'variable' => $variable,
  401. )
  402. );
  403. $modSettings[$variable] = $value === true ? $modSettings[$variable] + 1 : ($value === false ? $modSettings[$variable] - 1 : $value);
  404. }
  405. // Clean out the cache and make sure the cobwebs are gone too.
  406. cache_put_data('modSettings', null, 90);
  407. return;
  408. }
  409. $replaceArray = array();
  410. foreach ($changeArray as $variable => $value)
  411. {
  412. // Don't bother if it's already like that ;).
  413. if (isset($modSettings[$variable]) && $modSettings[$variable] == $value)
  414. continue;
  415. // If the variable isn't set, but would only be set to nothing'ness, then don't bother setting it.
  416. elseif (!isset($modSettings[$variable]) && empty($value))
  417. continue;
  418. $replaceArray[] = array($variable, $value);
  419. $modSettings[$variable] = $value;
  420. }
  421. if (empty($replaceArray))
  422. return;
  423. $smcFunc['db_insert']('replace',
  424. '{db_prefix}settings',
  425. array('variable' => 'string-255', 'value' => 'string-65534'),
  426. $replaceArray,
  427. array('variable')
  428. );
  429. // Kill the cache - it needs redoing now, but we won't bother ourselves with that here.
  430. cache_put_data('modSettings', null, 90);
  431. }
  432. /**
  433. * Constructs a page list.
  434. *
  435. * - builds the page list, e.g. 1 ... 6 7 [8] 9 10 ... 15.
  436. * - flexible_start causes it to use "url.page" instead of "url;start=page".
  437. * - handles any wireless settings (adding special things to URLs.)
  438. * - very importantly, cleans up the start value passed, and forces it to
  439. * be a multiple of num_per_page.
  440. * - checks that start is not more than max_value.
  441. * - base_url should be the URL without any start parameter on it.
  442. * - uses the compactTopicPagesEnable and compactTopicPagesContiguous
  443. * settings to decide how to display the menu.
  444. *
  445. * an example is available near the function definition.
  446. * $pageindex = constructPageIndex($scripturl . '?board=' . $board, $_REQUEST['start'], $num_messages, $maxindex, true);
  447. *
  448. * @param string $base_url
  449. * @param int $start
  450. * @param int $max_value
  451. * @param int $num_per_page
  452. * @param bool $flexible_start = false
  453. * @param bool $show_prevnext = true
  454. */
  455. function constructPageIndex($base_url, &$start, $max_value, $num_per_page, $flexible_start = false, $show_prevnext = true)
  456. {
  457. global $modSettings, $context, $txt;
  458. // Save whether $start was less than 0 or not.
  459. $start = (int) $start;
  460. $start_invalid = $start < 0;
  461. // Make sure $start is a proper variable - not less than 0.
  462. if ($start_invalid)
  463. $start = 0;
  464. // Not greater than the upper bound.
  465. elseif ($start >= $max_value)
  466. $start = max(0, (int) $max_value - (((int) $max_value % (int) $num_per_page) == 0 ? $num_per_page : ((int) $max_value % (int) $num_per_page)));
  467. // And it has to be a multiple of $num_per_page!
  468. else
  469. $start = max(0, (int) $start - ((int) $start % (int) $num_per_page));
  470. $context['current_page'] = $start / $num_per_page;
  471. $base_link = '<a class="navPages" href="' . ($flexible_start ? $base_url : strtr($base_url, array('%' => '%%')) . ';start=%1$d') . '">%2$s</a> ';
  472. // Compact pages is off or on?
  473. if (empty($modSettings['compactTopicPagesEnable']))
  474. {
  475. // Show the left arrow.
  476. $pageindex = $start == 0 ? ' ' : sprintf($base_link, $start - $num_per_page, '<span class="previous_page">' . $txt['prev'] . '</span>');
  477. // Show all the pages.
  478. $display_page = 1;
  479. for ($counter = 0; $counter < $max_value; $counter += $num_per_page)
  480. $pageindex .= $start == $counter && !$start_invalid ? '<span class="current_page"><strong>' . $display_page++ . '</strong></span> ' : sprintf($base_link, $counter, $display_page++);
  481. // Show the right arrow.
  482. $display_page = ($start + $num_per_page) > $max_value ? $max_value : ($start + $num_per_page);
  483. if ($start != $counter - $max_value && !$start_invalid)
  484. $pageindex .= $display_page > $counter - $num_per_page ? ' ' : sprintf($base_link, $display_page, '<span class="next_page">' . $txt['next'] . '</span>');
  485. }
  486. else
  487. {
  488. // If they didn't enter an odd value, pretend they did.
  489. $PageContiguous = (int) ($modSettings['compactTopicPagesContiguous'] - ($modSettings['compactTopicPagesContiguous'] % 2)) / 2;
  490. // Show the "prev page" link. (>prev page< 1 ... 6 7 [8] 9 10 ... 15 next page)
  491. if (!empty($start) && $show_prevnext)
  492. $pageindex = sprintf($base_link, $start - $num_per_page, '<span class="previous_page">' . $txt['prev'] . '</span>');
  493. else
  494. $pageindex = '';
  495. // Show the first page. (prev page >1< ... 6 7 [8] 9 10 ... 15)
  496. if ($start > $num_per_page * $PageContiguous)
  497. $pageindex .= sprintf($base_link, 0, '1');
  498. // Show the ... after the first page. (prev page 1 >...< 6 7 [8] 9 10 ... 15 next page)
  499. if ($start > $num_per_page * ($PageContiguous + 1))
  500. $pageindex .= '<span class="expand_pages" onclick="' . htmlspecialchars('expandPages(this, ' . JavaScriptEscape(($flexible_start ? $base_url : strtr($base_url, array('%' => '%%')) . ';start=%1$d')) . ', ' . $num_per_page . ', ' . ($start - $num_per_page * $PageContiguous) . ', ' . $num_per_page . ');') . '" onmouseover="this.style.cursor = \'pointer\';"><strong> ... </strong></span>';
  501. // Show the pages before the current one. (prev page 1 ... >6 7< [8] 9 10 ... 15 next page)
  502. for ($nCont = $PageContiguous; $nCont >= 1; $nCont--)
  503. if ($start >= $num_per_page * $nCont)
  504. {
  505. $tmpStart = $start - $num_per_page * $nCont;
  506. $pageindex.= sprintf($base_link, $tmpStart, $tmpStart / $num_per_page + 1);
  507. }
  508. // Show the current page. (prev page 1 ... 6 7 >[8]< 9 10 ... 15 next page)
  509. if (!$start_invalid)
  510. $pageindex .= '<span class="current_page"><strong>' . ($start / $num_per_page + 1) . '</strong></span>';
  511. else
  512. $pageindex .= sprintf($base_link, $start, $start / $num_per_page + 1);
  513. // Show the pages after the current one... (prev page 1 ... 6 7 [8] >9 10< ... 15 next page)
  514. $tmpMaxPages = (int) (($max_value - 1) / $num_per_page) * $num_per_page;
  515. for ($nCont = 1; $nCont <= $PageContiguous; $nCont++)
  516. if ($start + $num_per_page * $nCont <= $tmpMaxPages)
  517. {
  518. $tmpStart = $start + $num_per_page * $nCont;
  519. $pageindex .= sprintf($base_link, $tmpStart, $tmpStart / $num_per_page + 1);
  520. }
  521. // Show the '...' part near the end. (prev page 1 ... 6 7 [8] 9 10 >...< 15 next page)
  522. if ($start + $num_per_page * ($PageContiguous + 1) < $tmpMaxPages)
  523. $pageindex .= '<span class="expand_pages" onclick="' . htmlspecialchars('expandPages(this, ' . JavaScriptEscape(($flexible_start ? $base_url : strtr($base_url, array('%' => '%%')) . ';start=%1$d')) . ', ' . ($start + $num_per_page * ($PageContiguous + 1)) . ', ' . $tmpMaxPages . ', ' . $num_per_page . ');') . '" onmouseover="this.style.cursor=\'pointer\';"><strong> ... </strong></span>';
  524. // Show the last number in the list. (prev page 1 ... 6 7 [8] 9 10 ... >15< next page)
  525. if ($start + $num_per_page * $PageContiguous < $tmpMaxPages)
  526. $pageindex .= sprintf($base_link, $tmpMaxPages, $tmpMaxPages / $num_per_page + 1);
  527. // Show the "next page" link. (prev page 1 ... 6 7 [8] 9 10 ... 15 >next page<)
  528. if ($start != $tmpMaxPages && $show_prevnext)
  529. $pageindex .= sprintf($base_link, $start + $num_per_page, '<span class="next_page">' . $txt['next'] . '</span>');
  530. }
  531. return $pageindex;
  532. }
  533. /**
  534. * Formats a number.
  535. * - uses the format of number_format to decide how to format the number.
  536. * for example, it might display "1 234,50".
  537. * - caches the formatting data from the setting for optimization.
  538. *
  539. * @param float $number
  540. * @param bool $override_decimal_count = false
  541. */
  542. function comma_format($number, $override_decimal_count = false)
  543. {
  544. global $txt;
  545. static $thousands_separator = null, $decimal_separator = null, $decimal_count = null;
  546. // Cache these values...
  547. if ($decimal_separator === null)
  548. {
  549. // Not set for whatever reason?
  550. if (empty($txt['number_format']) || preg_match('~^1([^\d]*)?234([^\d]*)(0*?)$~', $txt['number_format'], $matches) != 1)
  551. return $number;
  552. // Cache these each load...
  553. $thousands_separator = $matches[1];
  554. $decimal_separator = $matches[2];
  555. $decimal_count = strlen($matches[3]);
  556. }
  557. // Format the string with our friend, number_format.
  558. return number_format($number, (float) $number === $number ? ($override_decimal_count === false ? $decimal_count : $override_decimal_count) : 0, $decimal_separator, $thousands_separator);
  559. }
  560. /**
  561. * Format a time to make it look purdy.
  562. *
  563. * - returns a pretty formated version of time based on the user's format in $user_info['time_format'].
  564. * - applies all necessary time offsets to the timestamp, unless offset_type is set.
  565. * - if todayMod is set and show_today was not not specified or true, an
  566. * alternate format string is used to show the date with something to show it is "today" or "yesterday".
  567. * - performs localization (more than just strftime would do alone.)
  568. *
  569. * @param int $log_time
  570. * @param bool $show_today = true
  571. * @param string $offset_type = false
  572. */
  573. function timeformat($log_time, $show_today = true, $offset_type = false)
  574. {
  575. global $context, $user_info, $txt, $modSettings, $smcFunc;
  576. static $non_twelve_hour;
  577. // Offset the time.
  578. if (!$offset_type)
  579. $time = $log_time + ($user_info['time_offset'] + $modSettings['time_offset']) * 3600;
  580. // Just the forum offset?
  581. elseif ($offset_type == 'forum')
  582. $time = $log_time + $modSettings['time_offset'] * 3600;
  583. else
  584. $time = $log_time;
  585. // We can't have a negative date (on Windows, at least.)
  586. if ($log_time < 0)
  587. $log_time = 0;
  588. // Today and Yesterday?
  589. if ($modSettings['todayMod'] >= 1 && $show_today === true)
  590. {
  591. // Get the current time.
  592. $nowtime = forum_time();
  593. $then = @getdate($time);
  594. $now = @getdate($nowtime);
  595. // Try to make something of a time format string...
  596. $s = strpos($user_info['time_format'], '%S') === false ? '' : ':%S';
  597. if (strpos($user_info['time_format'], '%H') === false && strpos($user_info['time_format'], '%T') === false)
  598. {
  599. $h = strpos($user_info['time_format'], '%l') === false ? '%I' : '%l';
  600. $today_fmt = $h . ':%M' . $s . ' %p';
  601. }
  602. else
  603. $today_fmt = '%H:%M' . $s;
  604. // Same day of the year, same year.... Today!
  605. if ($then['yday'] == $now['yday'] && $then['year'] == $now['year'])
  606. return $txt['today'] . timeformat($log_time, $today_fmt, $offset_type);
  607. // Day-of-year is one less and same year, or it's the first of the year and that's the last of the year...
  608. if ($modSettings['todayMod'] == '2' && (($then['yday'] == $now['yday'] - 1 && $then['year'] == $now['year']) || ($now['yday'] == 0 && $then['year'] == $now['year'] - 1) && $then['mon'] == 12 && $then['mday'] == 31))
  609. return $txt['yesterday'] . timeformat($log_time, $today_fmt, $offset_type);
  610. }
  611. $str = !is_bool($show_today) ? $show_today : $user_info['time_format'];
  612. if (setlocale(LC_TIME, $txt['lang_locale']))
  613. {
  614. if (!isset($non_twelve_hour))
  615. $non_twelve_hour = trim(strftime('%p')) === '';
  616. if ($non_twelve_hour && strpos($str, '%p') !== false)
  617. $str = str_replace('%p', (strftime('%H', $time) < 12 ? $txt['time_am'] : $txt['time_pm']), $str);
  618. foreach (array('%a', '%A', '%b', '%B') as $token)
  619. if (strpos($str, $token) !== false)
  620. $str = str_replace($token, !empty($txt['lang_capitalize_dates']) ? $smcFunc['ucwords'](strftime($token, $time)) : strftime($token, $time), $str);
  621. }
  622. else
  623. {
  624. // Do-it-yourself time localization. Fun.
  625. foreach (array('%a' => 'days_short', '%A' => 'days', '%b' => 'months_short', '%B' => 'months') as $token => $text_label)
  626. if (strpos($str, $token) !== false)
  627. $str = str_replace($token, $txt[$text_label][(int) strftime($token === '%a' || $token === '%A' ? '%w' : '%m', $time)], $str);
  628. if (strpos($str, '%p') !== false)
  629. $str = str_replace('%p', (strftime('%H', $time) < 12 ? $txt['time_am'] : $txt['time_pm']), $str);
  630. }
  631. // Windows doesn't support %e; on some versions, strftime fails altogether if used, so let's prevent that.
  632. if ($context['server']['is_windows'] && strpos($str, '%e') !== false)
  633. $str = str_replace('%e', ltrim(strftime('%d', $time), '0'), $str);
  634. // Format any other characters..
  635. return strftime($str, $time);
  636. }
  637. /**
  638. * Removes special entities from strings. Compatibility...
  639. * Faster than html_entity_decode
  640. *
  641. * - removes the base entities ( &amp; &quot; &#039; &lt; and &gt;. ) from text with htmlspecialchars_decode
  642. * - additionally converts &nbsp with str_replace
  643. *
  644. * @param string $string
  645. * @return the string without entities
  646. */
  647. function un_htmlspecialchars($string)
  648. {
  649. $string = htmlspecialchars_decode($string, ENT_QUOTES);
  650. $string = str_replace('&nbsp;', ' ', $string);
  651. return $string;
  652. }
  653. /**
  654. * Shorten a subject + internationalization concerns.
  655. *
  656. * - shortens a subject so that it is either shorter than length, or that length plus an ellipsis.
  657. * - respects internationalization characters and entities as one character.
  658. * - avoids trailing entities.
  659. * - returns the shortened string.
  660. *
  661. * @param string $subject
  662. * @param int $len
  663. */
  664. function shorten_subject($subject, $len)
  665. {
  666. global $smcFunc;
  667. // It was already short enough!
  668. if ($smcFunc['strlen']($subject) <= $len)
  669. return $subject;
  670. // Shorten it by the length it was too long, and strip off junk from the end.
  671. return $smcFunc['substr']($subject, 0, $len) . '...';
  672. }
  673. /**
  674. * Gets the current time with offset.
  675. *
  676. * - always applies the offset in the time_offset setting.
  677. *
  678. * @param bool $use_user_offset = true if use_user_offset is true, applies the user's offset as well
  679. * @param int $timestamp = null
  680. * @return int seconds since the unix epoch
  681. */
  682. function forum_time($use_user_offset = true, $timestamp = null)
  683. {
  684. global $user_info, $modSettings;
  685. if ($timestamp === null)
  686. $timestamp = time();
  687. elseif ($timestamp == 0)
  688. return 0;
  689. return $timestamp + ($modSettings['time_offset'] + ($use_user_offset ? $user_info['time_offset'] : 0)) * 3600;
  690. }
  691. /**
  692. * Calculates all the possible permutations (orders) of array.
  693. * should not be called on huge arrays (bigger than like 10 elements.)
  694. * returns an array containing each permutation.
  695. *
  696. * @param array $array
  697. * @return array
  698. */
  699. function permute($array)
  700. {
  701. $orders = array($array);
  702. $n = count($array);
  703. $p = range(0, $n);
  704. for ($i = 1; $i < $n; null)
  705. {
  706. $p[$i]--;
  707. $j = $i % 2 != 0 ? $p[$i] : 0;
  708. $temp = $array[$i];
  709. $array[$i] = $array[$j];
  710. $array[$j] = $temp;
  711. for ($i = 1; $p[$i] == 0; $i++)
  712. $p[$i] = 1;
  713. $orders[] = $array;
  714. }
  715. return $orders;
  716. }
  717. /**
  718. * Parse bulletin board code in a string, as well as smileys optionally.
  719. *
  720. * - only parses bbc tags which are not disabled in disabledBBC.
  721. * - handles basic HTML, if enablePostHTML is on.
  722. * - caches the from/to replace regular expressions so as not to reload them every time a string is parsed.
  723. * - only parses smileys if smileys is true.
  724. * - does nothing if the enableBBC setting is off.
  725. * - uses the cache_id as a unique identifier to facilitate any caching it may do.
  726. * -returns the modified message.
  727. *
  728. * @param string $message
  729. * @param bool $smileys = true
  730. * @param string $cache_id = ''
  731. * @param array $parse_tags = null
  732. * @return string
  733. */
  734. function parse_bbc($message, $smileys = true, $cache_id = '', $parse_tags = array())
  735. {
  736. global $txt, $scripturl, $context, $modSettings, $user_info, $smcFunc;
  737. static $bbc_codes = array(), $itemcodes = array(), $no_autolink_tags = array();
  738. static $disabled;
  739. // Don't waste cycles
  740. if ($message === '')
  741. return '';
  742. // Clean up any cut/paste issues we may have
  743. $message = sanitizeMSCutPaste($message);
  744. // If the load average is too high, don't parse the BBC.
  745. if (!empty($context['load_average']) && !empty($modSettings['bbc']) && $context['load_average'] >= $modSettings['bbc'])
  746. {
  747. $context['disabled_parse_bbc'] = true;
  748. return $message;
  749. }
  750. if ($smileys !== null && ($smileys == '1' || $smileys == '0'))
  751. $smileys = (bool) $smileys;
  752. if (empty($modSettings['enableBBC']) && $message !== false)
  753. {
  754. if ($smileys === true)
  755. parsesmileys($message);
  756. return $message;
  757. }
  758. // If we are not doing every tag then we don't cache this run.
  759. if (!empty($parse_tags) && !empty($bbc_codes))
  760. {
  761. $temp_bbc = $bbc_codes;
  762. $bbc_codes = array();
  763. }
  764. // Allow mods access before entering the main parse_bbc loop
  765. call_integration_hook('integrate_pre_parsebbc', array($message, $smileys, $cache_id, $parse_tags));
  766. // Sift out the bbc for a performance improvement.
  767. if (empty($bbc_codes) || $message === false || !empty($parse_tags))
  768. {
  769. if (!empty($modSettings['disabledBBC']))
  770. {
  771. $temp = explode(',', strtolower($modSettings['disabledBBC']));
  772. foreach ($temp as $tag)
  773. $disabled[trim($tag)] = true;
  774. }
  775. if (empty($modSettings['enableEmbeddedFlash']))
  776. $disabled['flash'] = true;
  777. /* The following bbc are formatted as an array, with keys as follows:
  778. tag: the tag's name - should be lowercase!
  779. type: one of...
  780. - (missing): [tag]parsed content[/tag]
  781. - unparsed_equals: [tag=xyz]parsed content[/tag]
  782. - parsed_equals: [tag=parsed data]parsed content[/tag]
  783. - unparsed_content: [tag]unparsed content[/tag]
  784. - closed: [tag], [tag/], [tag /]
  785. - unparsed_commas: [tag=1,2,3]parsed content[/tag]
  786. - unparsed_commas_content: [tag=1,2,3]unparsed content[/tag]
  787. - unparsed_equals_content: [tag=...]unparsed content[/tag]
  788. parameters: an optional array of parameters, for the form
  789. [tag abc=123]content[/tag]. The array is an associative array
  790. where the keys are the parameter names, and the values are an
  791. array which may contain the following:
  792. - match: a regular expression to validate and match the value.
  793. - quoted: true if the value should be quoted.
  794. - validate: callback to evaluate on the data, which is $data.
  795. - value: a string in which to replace $1 with the data.
  796. either it or validate may be used, not both.
  797. - optional: true if the parameter is optional.
  798. test: a regular expression to test immediately after the tag's
  799. '=', ' ' or ']'. Typically, should have a \] at the end.
  800. Optional.
  801. content: only available for unparsed_content, closed,
  802. unparsed_commas_content, and unparsed_equals_content.
  803. $1 is replaced with the content of the tag. Parameters
  804. are replaced in the form {param}. For unparsed_commas_content,
  805. $2, $3, ..., $n are replaced.
  806. before: only when content is not used, to go before any
  807. content. For unparsed_equals, $1 is replaced with the value.
  808. For unparsed_commas, $1, $2, ..., $n are replaced.
  809. after: similar to before in every way, except that it is used
  810. when the tag is closed.
  811. disabled_content: used in place of content when the tag is
  812. disabled. For closed, default is '', otherwise it is '$1' if
  813. block_level is false, '<div>$1</div>' elsewise.
  814. disabled_before: used in place of before when disabled. Defaults
  815. to '<div>' if block_level, '' if not.
  816. disabled_after: used in place of after when disabled. Defaults
  817. to '</div>' if block_level, '' if not.
  818. block_level: set to true the tag is a "block level" tag, similar
  819. to HTML. Block level tags cannot be nested inside tags that are
  820. not block level, and will not be implicitly closed as easily.
  821. One break following a block level tag may also be removed.
  822. trim: if set, and 'inside' whitespace after the begin tag will be
  823. removed. If set to 'outside', whitespace after the end tag will
  824. meet the same fate.
  825. validate: except when type is missing or 'closed', a callback to
  826. validate the data as $data. Depending on the tag's type, $data
  827. may be a string or an array of strings (corresponding to the
  828. replacement.)
  829. quoted: when type is 'unparsed_equals' or 'parsed_equals' only,
  830. may be not set, 'optional', or 'required' corresponding to if
  831. the content may be quoted. This allows the parser to read
  832. [tag="abc]def[esdf]"] properly.
  833. require_parents: an array of tag names, or not set. If set, the
  834. enclosing tag *must* be one of the listed tags, or parsing won't
  835. occur.
  836. require_children: similar to require_parents, if set children
  837. won't be parsed if they are not in the list.
  838. disallow_children: similar to, but very different from,
  839. require_children, if it is set the listed tags will not be
  840. parsed inside the tag.
  841. parsed_tags_allowed: an array restricting what BBC can be in the
  842. parsed_equals parameter, if desired.
  843. */
  844. $codes = array(
  845. array(
  846. 'tag' => 'abbr',
  847. 'type' => 'unparsed_equals',
  848. 'before' => '<abbr title="$1">',
  849. 'after' => '</abbr>',
  850. 'quoted' => 'optional',
  851. 'disabled_after' => ' ($1)',
  852. ),
  853. array(
  854. 'tag' => 'acronym',
  855. 'type' => 'unparsed_equals',
  856. 'before' => '<acronym title="$1">',
  857. 'after' => '</acronym>',
  858. 'quoted' => 'optional',
  859. 'disabled_after' => ' ($1)',
  860. ),
  861. array(
  862. 'tag' => 'anchor',
  863. 'type' => 'unparsed_equals',
  864. 'test' => '[#]?([A-Za-z][A-Za-z0-9_\-]*)\]',
  865. 'before' => '<span id="post_$1">',
  866. 'after' => '</span>',
  867. ),
  868. array(
  869. 'tag' => 'b',
  870. 'before' => '<strong class="bbc_strong">',
  871. 'after' => '</strong>',
  872. ),
  873. array(
  874. 'tag' => 'bdo',
  875. 'type' => 'unparsed_equals',
  876. 'before' => '<bdo dir="$1">',
  877. 'after' => '</bdo>',
  878. 'test' => '(rtl|ltr)\]',
  879. 'block_level' => true,
  880. ),
  881. array(
  882. 'tag' => 'black',
  883. 'before' => '<span style="color: black;" class="bbc_color">',
  884. 'after' => '</span>',
  885. ),
  886. array(
  887. 'tag' => 'blue',
  888. 'before' => '<span style="color: blue;" class="bbc_color">',
  889. 'after' => '</span>',
  890. ),
  891. array(
  892. 'tag' => 'br',
  893. 'type' => 'closed',
  894. 'content' => '<br />',
  895. ),
  896. array(
  897. 'tag' => 'center',
  898. 'before' => '<div align="center">',
  899. 'after' => '</div>',
  900. 'block_level' => true,
  901. ),
  902. array(
  903. 'tag' => 'code',
  904. 'type' => 'unparsed_content',
  905. 'content' => '<div class="codeheader">' . $txt['code'] . ': <a href="javascript:void(0);" onclick="return smfSelectText(this);" class="codeoperation">' . $txt['code_select'] . '</a></div><pre class="bbc_code">$1</pre>',
  906. // @todo Maybe this can be simplified?
  907. 'validate' => isset($disabled['code']) ? null : create_function('&$tag, &$data, $disabled', '
  908. global $context;
  909. if (!isset($disabled[\'code\']))
  910. {
  911. $php_parts = preg_split(\'~(&lt;\?php|\?&gt;)~\', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
  912. for ($php_i = 0, $php_n = count($php_parts); $php_i < $php_n; $php_i++)
  913. {
  914. // Do PHP code coloring?
  915. if ($php_parts[$php_i] != \'&lt;?php\')
  916. continue;
  917. $php_string = \'\';
  918. while ($php_i + 1 < count($php_parts) && $php_parts[$php_i] != \'?&gt;\')
  919. {
  920. $php_string .= $php_parts[$php_i];
  921. $php_parts[$php_i++] = \'\';
  922. }
  923. $php_parts[$php_i] = highlight_php_code($php_string . $php_parts[$php_i]);
  924. }
  925. // Fix the PHP code stuff...
  926. $data = str_replace("<pre style=\"display: inline;\">\t</pre>", "\t", implode(\'\', $php_parts));
  927. $data = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data);
  928. // Recent Opera bug requiring temporary fix. &nsbp; is needed before </code> to avoid broken selection.
  929. if ($context[\'browser\'][\'is_opera\'])
  930. $data .= \'&nbsp;\';
  931. }'),
  932. 'block_level' => true,
  933. ),
  934. array(
  935. 'tag' => 'code',
  936. 'type' => 'unparsed_equals_content',
  937. 'content' => '<div class="codeheader">' . $txt['code'] . ': ($2) <a href="#" onclick="return smfSelectText(this);" class="codeoperation">' . $txt['code_select'] . '</a></div><pre class="bbc_code">$1</pre>',
  938. // @todo Maybe this can be simplified?
  939. 'validate' => isset($disabled['code']) ? null : create_function('&$tag, &$data, $disabled', '
  940. global $context;
  941. if (!isset($disabled[\'code\']))
  942. {
  943. $php_parts = preg_split(\'~(&lt;\?php|\?&gt;)~\', $data[0], -1, PREG_SPLIT_DELIM_CAPTURE);
  944. for ($php_i = 0, $php_n = count($php_parts); $php_i < $php_n; $php_i++)
  945. {
  946. // Do PHP code coloring?
  947. if ($php_parts[$php_i] != \'&lt;?php\')
  948. continue;
  949. $php_string = \'\';
  950. while ($php_i + 1 < count($php_parts) && $php_parts[$php_i] != \'?&gt;\')
  951. {
  952. $php_string .= $php_parts[$php_i];
  953. $php_parts[$php_i++] = \'\';
  954. }
  955. $php_parts[$php_i] = highlight_php_code($php_string . $php_parts[$php_i]);
  956. }
  957. // Fix the PHP code stuff...
  958. $data[0] = str_replace("<pre style=\"display: inline;\">\t</pre>", "\t", implode(\'\', $php_parts));
  959. $data[0] = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data[0]);
  960. // Recent Opera bug requiring temporary fix. &nsbp; is needed before </code> to avoid broken selection.
  961. if ($context[\'browser\'][\'is_opera\'])
  962. $data[0] .= \'&nbsp;\';
  963. }'),
  964. 'block_level' => true,
  965. ),
  966. array(
  967. 'tag' => 'color',
  968. 'type' => 'unparsed_equals',
  969. 'test' => '(#[\da-fA-F]{3}|#[\da-fA-F]{6}|[A-Za-z]{1,20}|rgb\(\d{1,3}, ?\d{1,3}, ?\d{1,3}\))\]',
  970. 'before' => '<span style="color: $1;" class="bbc_color">',
  971. 'after' => '</span>',
  972. ),
  973. array(
  974. 'tag' => 'email',
  975. 'type' => 'unparsed_content',
  976. 'content' => '<a href="mailto:$1" class="bbc_email">$1</a>',
  977. // @todo Should this respect guest_hideContacts?
  978. 'validate' => create_function('&$tag, &$data, $disabled', '$data = strtr($data, array(\'<br />\' => \'\'));'),
  979. ),
  980. array(
  981. 'tag' => 'email',
  982. 'type' => 'unparsed_equals',
  983. 'before' => '<a href="mailto:$1" class="bbc_email">',
  984. 'after' => '</a>',
  985. // @todo Should this respect guest_hideContacts?
  986. 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
  987. 'disabled_after' => ' ($1)',
  988. ),
  989. array(
  990. 'tag' => 'flash',
  991. 'type' => 'unparsed_commas_content',
  992. 'test' => '\d+,\d+\]',
  993. 'content' => (isBrowser('ie') ? '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="$2" height="$3"><param name="movie" value="$1" /><param name="play" value="true" /><param name="loop" value="true" /><param name="quality" value="high" /><param name="AllowScriptAccess" value="never" /><embed src="$1" width="$2" height="$3" play="true" loop="true" quality="high" AllowScriptAccess="never" /><noembed><a href="$1" target="_blank" class="new_win">$1</a></noembed></object>' : '<embed type="application/x-shockwave-flash" src="$1" width="$2" height="$3" play="true" loop="true" quality="high" AllowScriptAccess="never" /><noembed><a href="$1" target="_blank" class="new_win">$1</a></noembed>'),
  994. 'validate' => create_function('&$tag, &$data, $disabled', '
  995. if (isset($disabled[\'url\']))
  996. $tag[\'content\'] = \'$1\';
  997. elseif (strpos($data[0], \'http://\') !== 0 && strpos($data[0], \'https://\') !== 0)
  998. $data[0] = \'http://\' . $data[0];
  999. '),
  1000. 'disabled_content' => '<a href="$1" target="_blank" class="new_win">$1</a>',
  1001. ),
  1002. array(
  1003. 'tag' => 'font',
  1004. 'type' => 'unparsed_equals',
  1005. 'test' => '[A-Za-z0-9_,\-\s]+?\]',
  1006. 'before' => '<span style="font-family: $1;" class="bbc_font">',
  1007. 'after' => '</span>',
  1008. ),
  1009. array(
  1010. 'tag' => 'ftp',
  1011. 'type' => 'unparsed_content',
  1012. 'content' => '<a href="$1" class="bbc_ftp new_win" target="_blank">$1</a>',
  1013. 'validate' => create_function('&$tag, &$data, $disabled', '
  1014. $data = strtr($data, array(\'<br />\' => \'\'));
  1015. if (strpos($data, \'ftp://\') !== 0 && strpos($data, \'ftps://\') !== 0)
  1016. $data = \'ftp://\' . $data;
  1017. '),
  1018. ),
  1019. array(
  1020. 'tag' => 'ftp',
  1021. 'type' => 'unparsed_equals',
  1022. 'before' => '<a href="$1" class="bbc_ftp new_win" target="_blank">',
  1023. 'after' => '</a>',
  1024. 'validate' => create_function('&$tag, &$data, $disabled', '
  1025. if (strpos($data, \'ftp://\') !== 0 && strpos($data, \'ftps://\') !== 0)
  1026. $data = \'ftp://\' . $data;
  1027. '),
  1028. 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
  1029. 'disabled_after' => ' ($1)',
  1030. ),
  1031. array(
  1032. 'tag' => 'glow',
  1033. 'type' => 'unparsed_commas',
  1034. 'test' => '[#0-9a-zA-Z\-]{3,12},([012]\d{1,2}|\d{1,2})(,[^]]+)?\]',
  1035. 'before' => isBrowser('ie') ? '<table style="border-collapse: collapse; border-spacing: 0;display: inline; vertical-align: middle; font: inherit;"><tr><td style="filter: Glow(color=$1, strength=$2); font: inherit;">' : '<span style="text-shadow: $1 1px 1px 1px">',
  1036. 'after' => isBrowser('ie') ? '</td></tr></table> ' : '</span>',
  1037. ),
  1038. array(
  1039. 'tag' => 'green',
  1040. 'before' => '<span style="color: green;" class="bbc_color">',
  1041. 'after' => '</span>',
  1042. ),
  1043. array(
  1044. 'tag' => 'html',
  1045. 'type' => 'unparsed_content',
  1046. 'content' => '$1',
  1047. 'block_level' => true,
  1048. 'disabled_content' => '$1',
  1049. ),
  1050. array(
  1051. 'tag' => 'hr',
  1052. 'type' => 'closed',
  1053. 'content' => '<hr />',
  1054. 'block_level' => true,
  1055. ),
  1056. array(
  1057. 'tag' => 'i',
  1058. 'before' => '<em>',
  1059. 'after' => '</em>',
  1060. ),
  1061. array(
  1062. 'tag' => 'img',
  1063. 'type' => 'unparsed_content',
  1064. 'parameters' => array(
  1065. 'alt' => array('optional' => true),
  1066. 'width' => array('optional' => true, 'value' => ' width="$1"', 'match' => '(\d+)'),
  1067. 'height' => array('optional' => true, 'value' => ' height="$1"', 'match' => '(\d+)'),
  1068. ),
  1069. 'content' => '<img src="$1" alt="{alt}"{width}{height} class="bbc_img resized" />',
  1070. 'validate' => create_function('&$tag, &$data, $disabled', '
  1071. $data = strtr($data, array(\'<br />\' => \'\'));
  1072. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1073. $data = \'http://\' . $data;
  1074. '),
  1075. 'disabled_content' => '($1)',
  1076. ),
  1077. array(
  1078. 'tag' => 'img',
  1079. 'type' => 'unparsed_content',
  1080. 'content' => '<img src="$1" alt="" class="bbc_img" />',
  1081. 'validate' => create_function('&$tag, &$data, $disabled', '
  1082. $data = strtr($data, array(\'<br />\' => \'\'));
  1083. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1084. $data = \'http://\' . $data;
  1085. '),
  1086. 'disabled_content' => '($1)',
  1087. ),
  1088. array(
  1089. 'tag' => 'iurl',
  1090. 'type' => 'unparsed_content',
  1091. 'content' => '<a href="$1" class="bbc_link">$1</a>',
  1092. 'validate' => create_function('&$tag, &$data, $disabled', '
  1093. $data = strtr($data, array(\'<br />\' => \'\'));
  1094. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1095. $data = \'http://\' . $data;
  1096. '),
  1097. ),
  1098. array(
  1099. 'tag' => 'iurl',
  1100. 'type' => 'unparsed_equals',
  1101. 'before' => '<a href="$1" class="bbc_link">',
  1102. 'after' => '</a>',
  1103. 'validate' => create_function('&$tag, &$data, $disabled', '
  1104. if (substr($data, 0, 1) == \'#\')
  1105. $data = \'#post_\' . substr($data, 1);
  1106. elseif (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1107. $data = \'http://\' . $data;
  1108. '),
  1109. 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
  1110. 'disabled_after' => ' ($1)',
  1111. ),
  1112. array(
  1113. 'tag' => 'left',
  1114. 'before' => '<div style="text-align: left;">',
  1115. 'after' => '</div>',
  1116. 'block_level' => true,
  1117. ),
  1118. array(
  1119. 'tag' => 'li',
  1120. 'before' => '<li>',
  1121. 'after' => '</li>',
  1122. 'trim' => 'outside',
  1123. 'require_parents' => array('list'),
  1124. 'block_level' => true,
  1125. 'disabled_before' => '',
  1126. 'disabled_after' => '<br />',
  1127. ),
  1128. array(
  1129. 'tag' => 'list',
  1130. 'before' => '<ul class="bbc_list">',
  1131. 'after' => '</ul>',
  1132. 'trim' => 'inside',
  1133. 'require_children' => array('li', 'list'),
  1134. 'block_level' => true,
  1135. ),
  1136. array(
  1137. 'tag' => 'list',
  1138. 'parameters' => array(
  1139. 'type' => array('match' => '(none|disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-alpha|upper-alpha|lower-greek|lower-latin|upper-latin|hebrew|armenian|georgian|cjk-ideographic|hiragana|katakana|hiragana-iroha|katakana-iroha)'),
  1140. ),
  1141. 'before' => '<ul class="bbc_list" style="list-style-type: {type};">',
  1142. 'after' => '</ul>',
  1143. 'trim' => 'inside',
  1144. 'require_children' => array('li'),
  1145. 'block_level' => true,
  1146. ),
  1147. array(
  1148. 'tag' => 'ltr',
  1149. 'before' => '<div dir="ltr">',
  1150. 'after' => '</div>',
  1151. 'block_level' => true,
  1152. ),
  1153. array(
  1154. 'tag' => 'me',
  1155. 'type' => 'unparsed_equals',
  1156. 'before' => '<div class="meaction">* $1 ',
  1157. 'after' => '</div>',
  1158. 'quoted' => 'optional',
  1159. 'block_level' => true,
  1160. 'disabled_before' => '/me ',
  1161. 'disabled_after' => '<br />',
  1162. ),
  1163. array(
  1164. 'tag' => 'move',
  1165. 'before' => '<marquee>',
  1166. 'after' => '</marquee>',
  1167. 'block_level' => true,
  1168. 'disallow_children' => array('move'),
  1169. ),
  1170. array(
  1171. 'tag' => 'nobbc',
  1172. 'type' => 'unparsed_content',
  1173. 'content' => '$1',
  1174. ),
  1175. array(
  1176. 'tag' => 'php',
  1177. 'type' => 'unparsed_content',
  1178. 'content' => '<span class="phpcode">$1</span>',
  1179. 'validate' => isset($disabled['php']) ? null : create_function('&$tag, &$data, $disabled', '
  1180. if (!isset($disabled[\'php\']))
  1181. {
  1182. $add_begin = substr(trim($data), 0, 5) != \'&lt;?\';
  1183. $data = highlight_php_code($add_begin ? \'&lt;?php \' . $data . \'?&gt;\' : $data);
  1184. if ($add_begin)
  1185. $data = preg_replace(array(\'~^(.+?)&lt;\?.{0,40}?php(?:&nbsp;|\s)~\', \'~\?&gt;((?:</(font|span)>)*)$~\'), \'$1\', $data, 2);
  1186. // Fix the PHP code stuff...
  1187. $data = str_replace("<pre style=\"display: inline;\">\t</pre>", "\t", $data);
  1188. $data = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data);
  1189. }'),
  1190. 'block_level' => false,
  1191. 'disabled_content' => '$1',
  1192. ),
  1193. array(
  1194. 'tag' => 'pre',
  1195. 'before' => '<pre>',
  1196. 'after' => '</pre>',
  1197. ),
  1198. array(
  1199. 'tag' => 'quote',
  1200. 'before' => '<div class="quoteheader"><div class="topslice_quote">' . $txt['quote'] . '</div></div><blockquote>',
  1201. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1202. 'block_level' => true,
  1203. ),
  1204. array(
  1205. 'tag' => 'quote',
  1206. 'parameters' => array(
  1207. 'author' => array('match' => '(.{1,192}?)', 'quoted' => true),
  1208. ),
  1209. 'before' => '<div class="quoteheader"><div class="topslice_quote">' . $txt['quote_from'] . ': {author}</div></div><blockquote>',
  1210. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1211. 'block_level' => true,
  1212. ),
  1213. array(
  1214. 'tag' => 'quote',
  1215. 'type' => 'parsed_equals',
  1216. 'before' => '<div class="quoteheader"><div class="topslice_quote">' . $txt['quote_from'] . ': $1</div></div><blockquote>',
  1217. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1218. 'quoted' => 'optional',
  1219. // Don't allow everything to be embedded with the author name.
  1220. 'parsed_tags_allowed' => array('url', 'iurl', 'ftp'),
  1221. 'block_level' => true,
  1222. ),
  1223. array(
  1224. 'tag' => 'quote',
  1225. 'parameters' => array(
  1226. 'author' => array('match' => '([^<>]{1,192}?)'),
  1227. 'link' => array('match' => '(?:board=\d+;)?((?:topic|threadid)=[\dmsg#\./]{1,40}(?:;start=[\dmsg#\./]{1,40})?|action=profile;u=\d+)'),
  1228. 'date' => array('match' => '(\d+)', 'validate' => 'timeformat'),
  1229. ),
  1230. 'before' => '<div class="quoteheader"><div class="topslice_quote"><a href="' . $scripturl . '?{link}">' . $txt['quote_from'] . ': {author} ' . $txt['search_on'] . ' {date}</a></div></div><blockquote>',
  1231. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1232. 'block_level' => true,
  1233. ),
  1234. array(
  1235. 'tag' => 'quote',
  1236. 'parameters' => array(
  1237. 'author' => array('match' => '(.{1,192}?)'),
  1238. ),
  1239. 'before' => '<div class="quoteheader"><div class="topslice_quote">' . $txt['quote_from'] . ': {author}</div></div><blockquote>',
  1240. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1241. 'block_level' => true,
  1242. ),
  1243. array(
  1244. 'tag' => 'red',
  1245. 'before' => '<span style="color: red;" class="bbc_color">',
  1246. 'after' => '</span>',
  1247. ),
  1248. array(
  1249. 'tag' => 'right',
  1250. 'before' => '<div style="text-align: right;">',
  1251. 'after' => '</div>',
  1252. 'block_level' => true,
  1253. ),
  1254. array(
  1255. 'tag' => 'rtl',
  1256. 'before' => '<div dir="rtl">',
  1257. 'after' => '</div>',
  1258. 'block_level' => true,
  1259. ),
  1260. array(
  1261. 'tag' => 's',
  1262. 'before' => '<del>',
  1263. 'after' => '</del>',
  1264. ),
  1265. array(
  1266. 'tag' => 'shadow',
  1267. 'type' => 'unparsed_commas',
  1268. 'test' => '[#0-9a-zA-Z\-]{3,12},(left|right|top|bottom|[0123]\d{0,2})\]',
  1269. 'before' => isBrowser('ie') ? '<span style="display: inline-block; filter: Shadow(color=$1, direction=$2); height: 1.2em;">' : '<span style="text-shadow: $1 $2">',
  1270. 'after' => '</span>',
  1271. 'validate' => isBrowser('ie') ? create_function('&$tag, &$data, $disabled', '
  1272. if ($data[1] == \'left\')
  1273. $data[1] = 270;
  1274. elseif ($data[1] == \'right\')
  1275. $data[1] = 90;
  1276. elseif ($data[1] == \'top\')
  1277. $data[1] = 0;
  1278. elseif ($data[1] == \'bottom\')
  1279. $data[1] = 180;
  1280. else
  1281. $data[1] = (int) $data[1];') : create_function('&$tag, &$data, $disabled', '
  1282. if ($data[1] == \'top\' || (is_numeric($data[1]) && $data[1] < 50))
  1283. $data[1] = \'0 -2px 1px\';
  1284. elseif ($data[1] == \'right\' || (is_numeric($data[1]) && $data[1] < 100))
  1285. $data[1] = \'2px 0 1px\';
  1286. elseif ($data[1] == \'bottom\' || (is_numeric($data[1]) && $data[1] < 190))
  1287. $data[1] = \'0 2px 1px\';
  1288. elseif ($data[1] == \'left\' || (is_numeric($data[1]) && $data[1] < 280))
  1289. $data[1] = \'-2px 0 1px\';
  1290. else
  1291. $data[1] = \'1px 1px 1px\';'),
  1292. ),
  1293. array(
  1294. 'tag' => 'size',
  1295. 'type' => 'unparsed_equals',
  1296. 'test' => '([1-9][\d]?p[xt]|small(?:er)?|large[r]?|x[x]?-(?:small|large)|medium|(0\.[1-9]|[1-9](\.[\d][\d]?)?)?em)\]',
  1297. 'before' => '<span style="font-size: $1;" class="bbc_size">',
  1298. 'after' => '</span>',
  1299. ),
  1300. array(
  1301. 'tag' => 'size',
  1302. 'type' => 'unparsed_equals',
  1303. 'test' => '[1-7]\]',
  1304. 'before' => '<span style="font-size: $1;" class="bbc_size">',
  1305. 'after' => '</span>',
  1306. 'validate' => create_function('&$tag, &$data, $disabled', '
  1307. $sizes = array(1 => 0.7, 2 => 1.0, 3 => 1.35, 4 => 1.45, 5 => 2.0, 6 => 2.65, 7 => 3.95);
  1308. $data = $sizes[$data] . \'em\';'
  1309. ),
  1310. ),
  1311. array(
  1312. 'tag' => 'sub',
  1313. 'before' => '<sub>',
  1314. 'after' => '</sub>',
  1315. ),
  1316. array(
  1317. 'tag' => 'sup',
  1318. 'before' => '<sup>',
  1319. 'after' => '</sup>',
  1320. ),
  1321. array(
  1322. 'tag' => 'table',
  1323. 'before' => '<table class="bbc_table">',
  1324. 'after' => '</table>',
  1325. 'trim' => 'inside',
  1326. 'require_children' => array('tr'),
  1327. 'block_level' => true,
  1328. ),
  1329. array(
  1330. 'tag' => 'td',
  1331. 'before' => '<td>',
  1332. 'after' => '</td>',
  1333. 'require_parents' => array('tr'),
  1334. 'trim' => 'outside',
  1335. 'block_level' => true,
  1336. 'disabled_before' => '',
  1337. 'disabled_after' => '',
  1338. ),
  1339. array(
  1340. 'tag' => 'time',
  1341. 'type' => 'unparsed_content',
  1342. 'content' => '$1',
  1343. 'validate' => create_function('&$tag, &$data, $disabled', '
  1344. if (is_numeric($data))
  1345. $data = timeformat($data);
  1346. else
  1347. $tag[\'content\'] = \'[time]$1[/time]\';'),
  1348. ),
  1349. array(
  1350. 'tag' => 'tr',
  1351. 'before' => '<tr>',
  1352. 'after' => '</tr>',
  1353. 'require_parents' => array('table'),
  1354. 'require_children' => array('td'),
  1355. 'trim' => 'both',
  1356. 'block_level' => true,
  1357. 'disabled_before' => '',
  1358. 'disabled_after' => '',
  1359. ),
  1360. array(
  1361. 'tag' => 'tt',
  1362. 'before' => '<span class="bbc_tt">',
  1363. 'after' => '</span>',
  1364. ),
  1365. array(
  1366. 'tag' => 'u',
  1367. 'before' => '<span class="bbc_u">',
  1368. 'after' => '</span>',
  1369. ),
  1370. array(
  1371. 'tag' => 'url',
  1372. 'type' => 'unparsed_content',
  1373. 'content' => '<a href="$1" class="bbc_link" target="_blank">$1</a>',
  1374. 'validate' => create_function('&$tag, &$data, $disabled', '
  1375. $data = strtr($data, array(\'<br />\' => \'\'));
  1376. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1377. $data = \'http://\' . $data;
  1378. '),
  1379. ),
  1380. array(
  1381. 'tag' => 'url',
  1382. 'type' => 'unparsed_equals',
  1383. 'before' => '<a href="$1" class="bbc_link" target="_blank">',
  1384. 'after' => '</a>',
  1385. 'validate' => create_function('&$tag, &$data, $disabled', '
  1386. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1387. $data = \'http://\' . $data;
  1388. '),
  1389. 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
  1390. 'disabled_after' => ' ($1)',
  1391. ),
  1392. array(
  1393. 'tag' => 'white',
  1394. 'before' => '<span style="color: white;" class="bbc_color">',
  1395. 'after' => '</span>',
  1396. ),
  1397. );
  1398. // Let mods add new BBC without hassle.
  1399. call_integration_hook('integrate_bbc_codes', array(&$codes));
  1400. // This is mainly for the bbc manager, so it's easy to add tags above. Custom BBC should be added above this line.
  1401. if ($message === false)
  1402. {
  1403. if (isset($temp_bbc))
  1404. $bbc_codes = $temp_bbc;
  1405. return $codes;
  1406. }
  1407. // So the parser won't skip them.
  1408. $itemcodes = array(
  1409. '*' => 'disc',
  1410. '@' => 'disc',
  1411. '+' => 'square',
  1412. 'x' => 'square',
  1413. '#' => 'square',
  1414. 'o' => 'circle',
  1415. 'O' => 'circle',
  1416. '0' => 'circle',
  1417. );
  1418. if (!isset($disabled['li']) && !isset($disabled['list']))
  1419. {
  1420. foreach ($itemcodes as $c => $dummy)
  1421. $bbc_codes[$c] = array();
  1422. }
  1423. // Inside these tags autolink is not recommendable.
  1424. $no_autolink_tags = array(
  1425. 'url',
  1426. 'iurl',
  1427. 'ftp',
  1428. 'email',
  1429. );
  1430. foreach ($codes as $code)
  1431. {
  1432. // If we are not doing every tag only do ones we are interested in.
  1433. if (empty($parse_tags) || in_array($code['tag'], $parse_tags))
  1434. $bbc_codes[substr($code['tag'], 0, 1)][] = $code;
  1435. }
  1436. $codes = null;
  1437. }
  1438. // Shall we take the time to cache this?
  1439. if ($cache_id != '' && !empty($modSettings['cache_enable']) && (($modSettings['cache_enable'] >= 2 && isset($message[1000])) || isset($message[2400])) && empty($parse_tags))
  1440. {
  1441. // It's likely this will change if the message is modified.
  1442. $cache_key = 'parse:' . $cache_id . '-' . md5(md5($message) . '-' . $smileys . (empty($disabled) ? '' : implode(',', array_keys($disabled))) . serialize($context['browser']) . $txt['lang_locale'] . $user_info['time_offset'] . $user_info['time_format']);
  1443. if (($temp = cache_get_data($cache_key, 240)) != null)
  1444. return $temp;
  1445. $cache_t = microtime(true);
  1446. }
  1447. if ($smileys === 'print')
  1448. {
  1449. // [glow], [shadow], and [move] can't really be printed.
  1450. $disabled['glow'] = true;
  1451. $disabled['shadow'] = true;
  1452. $disabled['move'] = true;
  1453. // Colors can't well be displayed... supposed to be black and white.
  1454. $disabled['color'] = true;
  1455. $disabled['black'] = true;
  1456. $disabled['blue'] = true;
  1457. $disabled['white'] = true;
  1458. $disabled['red'] = true;
  1459. $disabled['green'] = true;
  1460. $disabled['me'] = true;
  1461. // Color coding doesn't make sense.
  1462. $disabled['php'] = true;
  1463. // Links are useless on paper... just show the link.
  1464. $disabled['ftp'] = true;
  1465. $disabled['url'] = true;
  1466. $disabled['iurl'] = true;
  1467. $disabled['email'] = true;
  1468. $disabled['flash'] = true;
  1469. // @todo Change maybe?
  1470. if (!isset($_GET['images']))
  1471. $disabled['img'] = true;
  1472. // @todo Interface/setting to add more?
  1473. }
  1474. $open_tags = array();
  1475. $message = strtr($message, array("\n" => '<br />'));
  1476. // The non-breaking-space looks a bit different each time.
  1477. $non_breaking_space = '\x{A0}';
  1478. $pos = -1;
  1479. while ($pos !== false)
  1480. {
  1481. $last_pos = isset($last_pos) ? max($pos, $last_pos) : $pos;
  1482. $pos = strpos($message, '[', $pos + 1);
  1483. // Failsafe.
  1484. if ($pos === false || $last_pos > $pos)
  1485. $pos = strlen($message) + 1;
  1486. // Can't have a one letter smiley, URL, or email! (sorry.)
  1487. if ($last_pos < $pos - 1)
  1488. {
  1489. // Make sure the $last_pos is not negative.
  1490. $last_pos = max($last_pos, 0);
  1491. // Pick a block of data to do some raw fixing on.
  1492. $data = substr($message, $last_pos, $pos - $last_pos);
  1493. // Take care of some HTML!
  1494. if (!empty($modSettings['enablePostHTML']) && strpos($data, '&lt;') !== false)
  1495. {
  1496. $data = preg_replace('~&lt;a\s+href=((?:&quot;)?)((?:https?://|ftps?://|mailto:)\S+?)\\1&gt;~i', '[url=$2]', $data);
  1497. $data = preg_replace('~&lt;/a&gt;~i', '[/url]', $data);
  1498. // <br /> should be empty.
  1499. $empty_tags = array('br', 'hr');
  1500. foreach ($empty_tags as $tag)
  1501. $data = str_replace(array('&lt;' . $tag . '&gt;', '&lt;' . $tag . '/&gt;', '&lt;' . $tag . ' /&gt;'), '[' . $tag . ' /]', $data);
  1502. // b, u, i, s, pre... basic tags.
  1503. $closable_tags = array('b', 'u', 'i', 's', 'em', 'ins', 'del', 'pre', 'blockquote');
  1504. foreach ($closable_tags as $tag)
  1505. {
  1506. $diff = substr_count($data, '&lt;' . $tag . '&gt;') - substr_count($data, '&lt;/' . $tag . '&gt;');
  1507. $data = strtr($data, array('&lt;' . $tag . '&gt;' => '<' . $tag . '>', '&lt;/' . $tag . '&gt;' => '</' . $tag . '>'));
  1508. if ($diff > 0)
  1509. $data = substr($data, 0, -1) . str_repeat('</' . $tag . '>', $diff) . substr($data, -1);
  1510. }
  1511. // Do <img ... /> - with security... action= -> action-.
  1512. preg_match_all('~&lt;img\s+src=((?:&quot;)?)((?:https?://|ftps?://)\S+?)\\1(?:\s+alt=(&quot;.*?&quot;|\S*?))?(?:\s?/)?&gt;~i', $data, $matches, PREG_PATTERN_ORDER);
  1513. if (!empty($matches[0]))
  1514. {
  1515. $replaces = array();
  1516. foreach ($matches[2] as $match => $imgtag)
  1517. {
  1518. $alt = empty($matches[3][$match]) ? '' : ' alt=' . preg_replace('~^&quot;|&quot;$~', '', $matches[3][$match]);
  1519. // Remove action= from the URL - no funny business, now.
  1520. if (preg_match('~action(=|%3d)(?!dlattach)~i', $imgtag) != 0)
  1521. $imgtag = preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $imgtag);
  1522. // Check if the image is larger than allowed.
  1523. if (!empty($modSettings['max_image_width']) && !empty($modSettings['max_image_height']))
  1524. {
  1525. // For images, we'll want this.
  1526. require_once(SUBSDIR . '/Attachments.subs.php');
  1527. list ($width, $height) = url_image_size($imgtag);
  1528. if (!empty($modSettings['max_image_width']) && $width > $modSettings['max_image_width'])
  1529. {
  1530. $height = (int) (($modSettings['max_image_width'] * $height) / $width);
  1531. $width = $modSettings['max_image_width'];
  1532. }
  1533. if (!empty($modSettings['max_image_height']) && $height > $modSettings['max_image_height'])
  1534. {
  1535. $width = (int) (($modSettings['max_image_height'] * $width) / $height);
  1536. $height = $modSettings['max_image_height'];
  1537. }
  1538. // Set the new image tag.
  1539. $replaces[$matches[0][$match]] = '[img width=' . $width . ' height=' . $height . $alt . ']' . $imgtag . '[/img]';
  1540. }
  1541. else
  1542. $replaces[$matches[0][$match]] = '[img' . $alt . ']' . $imgtag . '[/img]';
  1543. }
  1544. $data = strtr($data, $replaces);
  1545. }
  1546. }
  1547. if (!empty($modSettings['autoLinkUrls']))
  1548. {
  1549. // Are we inside tags that should be auto linked?
  1550. $no_autolink_area = false;
  1551. if (!empty($open_tags))
  1552. {
  1553. foreach ($open_tags as $open_tag)
  1554. if (in_array($open_tag['tag'], $no_autolink_tags))
  1555. $no_autolink_area = true;
  1556. }
  1557. // Don't go backwards.
  1558. // @todo Don't think is the real solution....
  1559. $lastAutoPos = isset($lastAutoPos) ? $lastAutoPos : 0;
  1560. if ($pos < $lastAutoPos)
  1561. $no_autolink_area = true;
  1562. $lastAutoPos = $pos;
  1563. if (!$no_autolink_area)
  1564. {
  1565. // Parse any URLs.... have to get rid of the @ problems some things cause... stupid email addresses.
  1566. if (!isset($disabled['url']) && (strpos($data, '://') !== false || strpos($data, 'www.') !== false) && strpos($data, '[url') === false)
  1567. {
  1568. // Switch out quotes really quick because they can cause problems.
  1569. $data = strtr($data, array('&#039;' => '\'', '&nbsp;' => "\xC2\xA0", '&quot;' => '>">', '"' => '<"<', '&lt;' => '<lt<'));
  1570. // Only do this if the preg survives.
  1571. if (is_string($result = preg_replace(array(
  1572. '~(?<=[\s>\.(;\'"]|^)((?:http|https)://[\w\-_%@:|]+(?:\.[\w\-_%]+)*(?::\d+)?(?:/[\w\-_\~%\.@!,\?&;=#(){}+:\'\\\\]*)*[/\w\-_\~%@\?;=#}\\\\]?)~i',
  1573. '~(?<=[\s>\.(;\'"]|^)((?:ftp|ftps)://[\w\-_%@:|]+(?:\.[\w\-_%]+)*(?::\d+)?(?:/[\w\-_\~%\.@,\?&;=#(){}+:\'\\\\]*)*[/\w\-_\~%@\?;=#}\\\\]?)~i',
  1574. '~(?<=[\s>(\'<]|^)(www(?:\.[\w\-_]+)+(?::\d+)?(?:/[\w\-_\~%\.@!,\?&;=#(){}+:\'\\\\]*)*[/\w\-_\~%@\?;=#}\\\\])~i'
  1575. ), array(
  1576. '[url]$1[/url]',
  1577. '[ftp]$1[/ftp]',
  1578. '[url=http://$1]$1[/url]'
  1579. ), $data)))
  1580. $data = $result;
  1581. $data = strtr($data, array('\'' => '&#039;', "\xC2\xA0" => '&nbsp;', '>">' => '&quot;', '<"<' => '"', '<lt<' => '&lt;'));
  1582. }
  1583. // Next, emails...
  1584. if (!isset($disabled['email']) && strpos($data, '@') !== false && strpos($data, '[email') === false)
  1585. {
  1586. $data = preg_replace('~(?<=[\?\s' . $non_breaking_space . '\[\]()*\\\;>]|^)([\w\-\.]{1,80}@[\w\-]+\.[\w\-\.]+[\w\-])(?=[?,\s' . $non_breaking_space . '\[\]()*\\\]|$|<br />|&nbsp;|&gt;|&lt;|&quot;|&#039;|\.(?:\.|;|&nbsp;|\s|$|<br />))~u', '[email]$1[/email]', $data);
  1587. $data = preg_replace('~(?<=<br />)([\w\-\.]{1,80}@[\w\-]+\.[\w\-\.]+[\w\-])(?=[?\.,;\s' . $non_breaking_space . '\[\]()*\\\]|$|<br />|&nbsp;|&gt;|&lt;|&quot;|&#039;)~u', '[email]$1[/email]', $data);
  1588. }
  1589. }
  1590. }
  1591. $data = strtr($data, array("\t" => '&nbsp;&nbsp;&nbsp;'));
  1592. // If it wasn't changed, no copying or other boring stuff has to happen!
  1593. if ($data != substr($message, $last_pos, $pos - $last_pos))
  1594. {
  1595. $message = substr($message, 0, $last_pos) . $data . substr($message, $pos);
  1596. // Since we changed it, look again in case we added or removed a tag. But we don't want to skip any.
  1597. $old_pos = strlen($data) + $last_pos;
  1598. $pos = strpos($message, '[', $last_pos);
  1599. $pos = $pos === false ? $old_pos : min($pos, $old_pos);
  1600. }
  1601. }
  1602. // Are we there yet? Are we there yet?
  1603. if ($pos >= strlen($message) - 1)
  1604. break;
  1605. $tags = strtolower($message[$pos + 1]);
  1606. if ($tags == '/' && !empty($open_tags))
  1607. {
  1608. $pos2 = strpos($message, ']', $pos + 1);
  1609. if ($pos2 == $pos + 2)
  1610. continue;
  1611. $look_for = strtolower(substr($message, $pos + 2, $pos2 - $pos - 2));
  1612. $to_close = array();
  1613. $block_level = null;
  1614. do
  1615. {
  1616. $tag = array_pop($open_tags);
  1617. if (!$tag)
  1618. break;
  1619. if (!empty($tag['block_level']))
  1620. {
  1621. // Only find out if we need to.
  1622. if ($block_level === false)
  1623. {
  1624. array_push($open_tags, $tag);
  1625. break;
  1626. }
  1627. // The idea is, if we are LOOKING for a block level tag, we can close them on the way.
  1628. if (strlen($look_for) > 0 && isset($bbc_codes[$look_for[0]]))
  1629. {
  1630. foreach ($bbc_codes[$look_for[0]] as $temp)
  1631. if ($temp['tag'] == $look_for)
  1632. {
  1633. $block_level = !empty($temp['block_level']);
  1634. break;
  1635. }
  1636. }
  1637. if ($block_level !== true)
  1638. {
  1639. $block_level = false;
  1640. array_push($open_tags, $tag);
  1641. break;
  1642. }
  1643. }
  1644. $to_close[] = $tag;
  1645. }
  1646. while ($tag['tag'] != $look_for);
  1647. // Did we just eat through everything and not find it?
  1648. if ((empty($open_tags) && (empty($tag) || $tag['tag'] != $look_for)))
  1649. {
  1650. $open_tags = $to_close;
  1651. continue;
  1652. }
  1653. elseif (!empty($to_close) && $tag['tag'] != $look_for)
  1654. {
  1655. if ($block_level === null && isset($look_for[0], $bbc_codes[$look_for[0]]))
  1656. {
  1657. foreach ($bbc_codes[$look_for[0]] as $temp)
  1658. if ($temp['tag'] == $look_for)
  1659. {
  1660. $block_level = !empty($temp['block_level']);
  1661. break;
  1662. }
  1663. }
  1664. // We're not looking for a block level tag (or maybe even a tag that exists...)
  1665. if (!$block_level)
  1666. {
  1667. foreach ($to_close as $tag)
  1668. array_push($open_tags, $tag);
  1669. continue;
  1670. }
  1671. }
  1672. foreach ($to_close as $tag)
  1673. {
  1674. $message = substr($message, 0, $pos) . "\n" . $tag['after'] . "\n" . substr($message, $pos2 + 1);
  1675. $pos += strlen($tag['after']) + 2;
  1676. $pos2 = $pos - 1;
  1677. // See the comment at the end of the big loop - just eating whitespace ;).
  1678. if (!empty($tag['block_level']) && substr($message, $pos, 6) == '<br />')
  1679. $message = substr($message, 0, $pos) . substr($message, $pos + 6);
  1680. if (!empty($tag['trim']) && $tag['trim'] != 'inside' && preg_match('~(<br />|&nbsp;|\s)*~', substr($message, $pos), $matches) != 0)
  1681. $message = substr($message, 0, $pos) . substr($message, $pos + strlen($matches[0]));
  1682. }
  1683. if (!empty($to_close))
  1684. {
  1685. $to_close = array();
  1686. $pos--;
  1687. }
  1688. continue;
  1689. }
  1690. // No tags for this character, so just keep going (fastest possible course.)
  1691. if (!isset($bbc_codes[$tags]))
  1692. continue;
  1693. $inside = empty($open_tags) ? null : $open_tags[count($open_tags) - 1];
  1694. $tag = null;
  1695. foreach ($bbc_codes[$tags] as $possible)
  1696. {
  1697. $pt_strlen = strlen($possible['tag']);
  1698. // Not a match?
  1699. if (strtolower(substr($message, $pos + 1, $pt_strlen)) != $possible['tag'])
  1700. continue;
  1701. $next_c = isset($message[$pos + 1 + $pt_strlen]) ? $message[$pos + 1 + $pt_strlen] : '';
  1702. // A test validation?
  1703. if (isset($possible['test']) && preg_match('~^' . $possible['test'] . '~', substr($message, $pos + 1 + $pt_strlen + 1)) === 0)
  1704. continue;
  1705. // Do we want parameters?
  1706. elseif (!empty($possible['parameters']))
  1707. {
  1708. if ($next_c != ' ')
  1709. continue;
  1710. }
  1711. elseif (isset($possible['type']))
  1712. {
  1713. // Do we need an equal sign?
  1714. if (in_array($possible['type'], array('unparsed_equals', 'unparsed_commas', 'unparsed_commas_content', 'unparsed_equals_content', 'parsed_equals')) && $next_c != '=')
  1715. continue;
  1716. // Maybe we just want a /...
  1717. if ($possible['type'] == 'closed' && $next_c != ']' && substr($message, $pos + 1 + $pt_strlen, 2) != '/]' && substr($message, $pos + 1 + $pt_strlen, 3) != ' /]')
  1718. continue;
  1719. // An immediate ]?
  1720. if ($possible['type'] == 'unparsed_content' && $next_c != ']')
  1721. continue;
  1722. }
  1723. // No type means 'parsed_content', which demands an immediate ] without parameters!
  1724. elseif ($next_c != ']')
  1725. continue;
  1726. // Check allowed tree?
  1727. if (isset($possible['require_parents']) && ($inside === null || !in_array($inside['tag'], $possible['require_parents'])))
  1728. continue;
  1729. elseif (isset($inside['require_children']) && !in_array($possible['tag'], $inside['require_children']))
  1730. continue;
  1731. // If this is in the list of disallowed child tags, don't parse it.
  1732. elseif (isset($inside['disallow_children']) && in_array($possible['tag'], $inside['disallow_children']))
  1733. continue;
  1734. $pos1 = $pos + 1 + $pt_strlen + 1;
  1735. // Quotes can have alternate styling, we do this php-side due to all the permutations of quotes.
  1736. if ($possible['tag'] == 'quote')
  1737. {
  1738. // Start with standard
  1739. $quote_alt = false;
  1740. foreach ($open_tags as $open_quote)
  1741. {
  1742. // Every parent quote this quote has flips the styling
  1743. if ($open_quote['tag'] == 'quote')
  1744. $quote_alt = !$quote_alt;
  1745. }
  1746. // Add a class to the quote to style alternating blockquotes
  1747. $possible['before'] = strtr($possible['before'], array('<blockquote>' => '<blockquote class="bbc_' . ($quote_alt ? 'alternate' : 'standard') . '_quote">'));
  1748. }
  1749. // This is long, but it makes things much easier and cleaner.
  1750. if (!empty($possible['parameters']))
  1751. {
  1752. $preg = array();
  1753. foreach ($possible['parameters'] as $p => $info)
  1754. $preg[] = '(\s+' . $p . '=' . (empty($info['quoted']) ? '' : '&quot;') . (isset($info['match']) ? $info['match'] : '(.+?)') . (empty($info['quoted']) ? '' : '&quot;') . ')' . (empty($info['optional']) ? '' : '?');
  1755. // Okay, this may look ugly and it is, but it's not going to happen much and it is the best way of allowing any order of parameters but still parsing them right.
  1756. $match = false;
  1757. $orders = permute($preg);
  1758. foreach ($orders as $p)
  1759. if (preg_match('~^' . implode('', $p) . '\]~i', substr($message, $pos1 - 1), $matches) != 0)
  1760. {
  1761. $match = true;
  1762. break;
  1763. }
  1764. // Didn't match our parameter list, try the next possible.
  1765. if (!$match)
  1766. continue;
  1767. $params = array();
  1768. for ($i = 1, $n = count($matches); $i < $n; $i += 2)
  1769. {
  1770. $key = strtok(ltrim($matches[$i]), '=');
  1771. if (isset($possible['parameters'][$key]['value']))
  1772. $params['{' . $key . '}'] = strtr($possible['parameters'][$key]['value'], array('$1' => $matches[$i + 1]));
  1773. elseif (isset($possible['parameters'][$key]['validate']))
  1774. $params['{' . $key . '}'] = $possible['parameters'][$key]['validate']($matches[$i + 1]);
  1775. else
  1776. $params['{' . $key . '}'] = $matches[$i + 1];
  1777. // Just to make sure: replace any $ or { so they can't interpolate wrongly.
  1778. $params['{' . $key . '}'] = strtr($params['{' . $key . '}'], array('$' => '&#036;', '{' => '&#123;'));
  1779. }
  1780. foreach ($possible['parameters'] as $p => $info)
  1781. {
  1782. if (!isset($params['{' . $p . '}']))
  1783. $params['{' . $p . '}'] = '';
  1784. }
  1785. $tag = $possible;
  1786. // Put the parameters into the string.
  1787. if (isset($tag['before']))
  1788. $tag['before'] = strtr($tag['before'], $params);
  1789. if (isset($tag['after']))
  1790. $tag['after'] = strtr($tag['after'], $params);
  1791. if (isset($tag['content']))
  1792. $tag['content'] = strtr($tag['content'], $params);
  1793. $pos1 += strlen($matches[0]) - 1;
  1794. }
  1795. else
  1796. $tag = $possible;
  1797. break;
  1798. }
  1799. // Item codes are complicated buggers... they are implicit [li]s and can make [list]s!
  1800. if ($smileys !== false && $tag === null && isset($itemcodes[$message[$pos + 1]]) && $message[$pos + 2] == ']' && !isset($disabled['list']) && !isset($disabled['li']))
  1801. {
  1802. if ($message[$pos + 1] == '0' && !in_array($message[$pos - 1], array(';', ' ', "\t", '>')))
  1803. continue;
  1804. $tag = $itemcodes[$message[$pos + 1]];
  1805. // First let's set up the tree: it needs to be in a list, or after an li.
  1806. if ($inside === null || ($inside['tag'] != 'list' && $inside['tag'] != 'li'))
  1807. {
  1808. $open_tags[] = array(
  1809. 'tag' => 'list',
  1810. 'after' => '</ul>',
  1811. 'block_level' => true,
  1812. 'require_children' => array('li'),
  1813. 'disallow_children' => isset($inside['disallow_children']) ? $inside['disallow_children'] : null,
  1814. );
  1815. $code = '<ul class="bbc_list">';
  1816. }
  1817. // We're in a list item already: another itemcode? Close it first.
  1818. elseif ($inside['tag'] == 'li')
  1819. {
  1820. array_pop($open_tags);
  1821. $code = '</li>';
  1822. }
  1823. else
  1824. $code = '';
  1825. // Now we open a new tag.
  1826. $open_tags[] = array(
  1827. 'tag' => 'li',
  1828. 'after' => '</li>',
  1829. 'trim' => 'outside',
  1830. 'block_level' => true,
  1831. 'disallow_children' => isset($inside['disallow_children']) ? $inside['disallow_children'] : null,
  1832. );
  1833. // First, open the tag...
  1834. $code .= '<li' . ($tag == '' ? '' : ' type="' . $tag . '"') . '>';
  1835. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos + 3);
  1836. $pos += strlen($code) - 1 + 2;
  1837. // Next, find the next break (if any.) If there's more itemcode after it, keep it going - otherwise close!
  1838. $pos2 = strpos($message, '<br />', $pos);
  1839. $pos3 = strpos($message, '[/', $pos);
  1840. if ($pos2 !== false && ($pos2 <= $pos3 || $pos3 === false))
  1841. {
  1842. preg_match('~^(<br />|&nbsp;|\s|\[)+~', substr($message, $pos2 + 6), $matches);
  1843. $message = substr($message, 0, $pos2) . "\n" . (!empty($matches[0]) && substr($matches[0], -1) == '[' ? '[/li]' : '[/li][/list]') . "\n" . substr($message, $pos2);
  1844. $open_tags[count($open_tags) - 2]['after'] = '</ul>';
  1845. }
  1846. // Tell the [list] that it needs to close specially.
  1847. else
  1848. {
  1849. // Move the li over, because we're not sure what we'll hit.
  1850. $open_tags[count($open_tags) - 1]['after'] = '';
  1851. $open_tags[count($open_tags) - 2]['after'] = '</li></ul>';
  1852. }
  1853. continue;
  1854. }
  1855. // Implicitly close lists and tables if something other than what's required is in them. This is needed for itemcode.
  1856. if ($tag === null && $inside !== null && !empty($inside['require_children']))
  1857. {
  1858. array_pop($open_tags);
  1859. $message = substr($message, 0, $pos) . "\n" . $inside['after'] . "\n" . substr($message, $pos);
  1860. $pos += strlen($inside['after']) - 1 + 2;
  1861. }
  1862. // No tag? Keep looking, then. Silly people using brackets without actual tags.
  1863. if ($tag === null)
  1864. continue;
  1865. // Propagate the list to the child (so wrapping the disallowed tag won't work either.)
  1866. if (isset($inside['disallow_children']))
  1867. $tag['disallow_children'] = isset($tag['disallow_children']) ? array_unique(array_merge($tag['disallow_children'], $inside['disallow_children'])) : $inside['disallow_children'];
  1868. // Is this tag disabled?
  1869. if (isset($disabled[$tag['tag']]))
  1870. {
  1871. if (!isset($tag['disabled_before']) && !isset($tag['disabled_after']) && !isset($tag['disabled_content']))
  1872. {
  1873. $tag['before'] = !empty($tag['block_level']) ? '<div>' : '';
  1874. $tag['after'] = !empty($tag['block_level']) ? '</div>' : '';
  1875. $tag['content'] = isset($tag['type']) && $tag['type'] == 'closed' ? '' : (!empty($tag['block_level']) ? '<div>$1</div>' : '$1');
  1876. }
  1877. elseif (isset($tag['disabled_before']) || isset($tag['disabled_after']))
  1878. {
  1879. $tag['before'] = isset($tag['disabled_before']) ? $tag['disabled_before'] : (!empty($tag['block_level']) ? '<div>' : '');
  1880. $tag['after'] = isset($tag['disabled_after']) ? $tag['disabled_after'] : (!empty($tag['block_level']) ? '</div>' : '');
  1881. }
  1882. else
  1883. $tag['content'] = $tag['disabled_content'];
  1884. }
  1885. // we use this alot
  1886. $tag_strlen = strlen($tag['tag']);
  1887. // The only special case is 'html', which doesn't need to close things.
  1888. if (!empty($tag['block_level']) && $tag['tag'] != 'html' && empty($inside['block_level']))
  1889. {
  1890. $n = count($open_tags) - 1;
  1891. while (empty($open_tags[$n]['block_level']) && $n >= 0)
  1892. $n--;
  1893. // Close all the non block level tags so this tag isn't surrounded by them.
  1894. for ($i = count($open_tags) - 1; $i > $n; $i--)
  1895. {
  1896. $message = substr($message, 0, $pos) . "\n" . $open_tags[$i]['after'] . "\n" . substr($message, $pos);
  1897. $ot_strlen = strlen($open_tags[$i]['after']);
  1898. $pos += $ot_strlen + 2;
  1899. $pos1 += $ot_strlen + 2;
  1900. // Trim or eat trailing stuff... see comment at the end of the big loop.
  1901. if (!empty($open_tags[$i]['block_level']) && substr($message, $pos, 6) == '<br />')
  1902. $message = substr($message, 0, $pos) . substr($message, $pos + 6);
  1903. if (!empty($open_tags[$i]['trim']) && $tag['trim'] != 'inside' && preg_match('~(<br />|&nbsp;|\s)*~', substr($message, $pos), $matches) != 0)
  1904. $message = substr($message, 0, $pos) . substr($message, $pos + strlen($matches[0]));
  1905. array_pop($open_tags);
  1906. }
  1907. }
  1908. // No type means 'parsed_content'.
  1909. if (!isset($tag['type']))
  1910. {
  1911. // @todo Check for end tag first, so people can say "I like that [i] tag"?
  1912. $open_tags[] = $tag;
  1913. $message = substr($message, 0, $pos) . "\n" . $tag['before'] . "\n" . substr($message, $pos1);
  1914. $pos += strlen($tag['before']) - 1 + 2;
  1915. }
  1916. // Don't parse the content, just skip it.
  1917. elseif ($tag['type'] == 'unparsed_content')
  1918. {
  1919. $pos2 = stripos($message, '[/' . substr($message, $pos + 1, $tag_strlen) . ']', $pos1);
  1920. if ($pos2 === false)
  1921. continue;
  1922. $data = substr($message, $pos1, $pos2 - $pos1);
  1923. if (!empty($tag['block_level']) && substr($data, 0, 6) == '<br />')
  1924. $data = substr($data, 6);
  1925. if (isset($tag['validate']))
  1926. $tag['validate']($tag, $data, $disabled);
  1927. $code = strtr($tag['content'], array('$1' => $data));
  1928. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos2 + 3 + $tag_strlen);
  1929. $pos += strlen($code) - 1 + 2;
  1930. $last_pos = $pos + 1;
  1931. }
  1932. // Don't parse the content, just skip it.
  1933. elseif ($tag['type'] == 'unparsed_equals_content')
  1934. {
  1935. // The value may be quoted for some tags - check.
  1936. if (isset($tag['quoted']))
  1937. {
  1938. $quoted = substr($message, $pos1, 6) == '&quot;';
  1939. if ($tag['quoted'] != 'optional' && !$quoted)
  1940. continue;
  1941. if ($quoted)
  1942. $pos1 += 6;
  1943. }
  1944. else
  1945. $quoted = false;
  1946. $pos2 = strpos($message, $quoted == false ? ']' : '&quot;]', $pos1);
  1947. if ($pos2 === false)
  1948. continue;
  1949. $pos3 = stripos($message, '[/' . substr($message, $pos + 1, $tag_strlen) . ']', $pos2);
  1950. if ($pos3 === false)
  1951. continue;
  1952. $data = array(
  1953. substr($message, $pos2 + ($quoted == false ? 1 : 7), $pos3 - ($pos2 + ($quoted == false ? 1 : 7))),
  1954. substr($message, $pos1, $pos2 - $pos1)
  1955. );
  1956. if (!empty($tag['block_level']) && substr($data[0], 0, 6) == '<br />')
  1957. $data[0] = substr($data[0], 6);
  1958. // Validation for my parking, please!
  1959. if (isset($tag['validate']))
  1960. $tag['validate']($tag, $data, $disabled);
  1961. $code = strtr($tag['content'], array('$1' => $data[0], '$2' => $data[1]));
  1962. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos3 + 3 + $tag_strlen);
  1963. $pos += strlen($code) - 1 + 2;
  1964. }
  1965. // A closed tag, with no content or value.
  1966. elseif ($tag['type'] == 'closed')
  1967. {
  1968. $pos2 = strpos($message, ']', $pos);
  1969. $message = substr($message, 0, $pos) . "\n" . $tag['content'] . "\n" . substr($message, $pos2 + 1);
  1970. $pos += strlen($tag['content']) - 1 + 2;
  1971. }
  1972. // This one is sorta ugly... :/. Unfortunately, it's needed for flash.
  1973. elseif ($tag['type'] == 'unparsed_commas_content')
  1974. {
  1975. $pos2 = strpos($message, ']', $pos1);
  1976. if ($pos2 === false)
  1977. continue;
  1978. $pos3 = stripos($message, '[/' . substr($message, $pos + 1, $tag_strlen) . ']', $pos2);
  1979. if ($pos3 === false)
  1980. continue;
  1981. // We want $1 to be the content, and the rest to be csv.
  1982. $data = explode(',', ',' . substr($message, $pos1, $pos2 - $pos1));
  1983. $data[0] = substr($message, $pos2 + 1, $pos3 - $pos2 - 1);
  1984. if (isset($tag['validate']))
  1985. $tag['validate']($tag, $data, $disabled);
  1986. $code = $tag['content'];
  1987. foreach ($data as $k => $d)
  1988. $code = strtr($code, array('$' . ($k + 1) => trim($d)));
  1989. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos3 + 3 + $tag_strlen);
  1990. $pos += strlen($code) - 1 + 2;
  1991. }
  1992. // This has parsed content, and a csv value which is unparsed.
  1993. elseif ($tag['type'] == 'unparsed_commas')
  1994. {
  1995. $pos2 = strpos($message, ']', $pos1);
  1996. if ($pos2 === false)
  1997. continue;
  1998. $data = explode(',', substr($message, $pos1, $pos2 - $pos1));
  1999. if (isset($tag['validate']))
  2000. $tag['validate']($tag, $data, $disabled);
  2001. // Fix after, for disabled code mainly.
  2002. foreach ($data as $k => $d)
  2003. $tag['after'] = strtr($tag['after'], array('$' . ($k + 1) => trim($d)));
  2004. $open_tags[] = $tag;
  2005. // Replace them out, $1, $2, $3, $4, etc.
  2006. $code = $tag['before'];
  2007. foreach ($data as $k => $d)
  2008. $code = strtr($code, array('$' . ($k + 1) => trim($d)));
  2009. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos2 + 1);
  2010. $pos += strlen($code) - 1 + 2;
  2011. }
  2012. // A tag set to a value, parsed or not.
  2013. elseif ($tag['type'] == 'unparsed_equals' || $tag['type'] == 'parsed_equals')
  2014. {
  2015. // The value may be quoted for some tags - check.
  2016. if (isset($tag['quoted']))
  2017. {
  2018. $quoted = substr($message, $pos1, 6) == '&quot;';
  2019. if ($tag['quoted'] != 'optional' && !$quoted)
  2020. continue;
  2021. if ($quoted)
  2022. $pos1 += 6;
  2023. }
  2024. else
  2025. $quoted = false;
  2026. $pos2 = strpos($message, $quoted == false ? ']' : '&quot;]', $pos1);
  2027. if ($pos2 === false)
  2028. continue;
  2029. $data = substr($message, $pos1, $pos2 - $pos1);
  2030. // Validation for my parking, please!
  2031. if (isset($tag['validate']))
  2032. $tag['validate']($tag, $data, $disabled);
  2033. // For parsed content, we must recurse to avoid security problems.
  2034. if ($tag['type'] != 'unparsed_equals')
  2035. $data = parse_bbc($data, !empty($tag['parsed_tags_allowed']) ? false : true, '', !empty($tag['parsed_tags_allowed']) ? $tag['parsed_tags_allowed'] : array());
  2036. $tag['after'] = strtr($tag['after'], array('$1' => $data));
  2037. $open_tags[] = $tag;
  2038. $code = strtr($tag['before'], array('$1' => $data));
  2039. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos2 + ($quoted == false ? 1 : 7));
  2040. $pos += strlen($code) - 1 + 2;
  2041. }
  2042. // If this is block level, eat any breaks after it.
  2043. if (!empty($tag['block_level']) && substr($message, $pos + 1, 6) == '<br />')
  2044. $message = substr($message, 0, $pos + 1) . substr($message, $pos + 7);
  2045. // Are we trimming outside this tag?
  2046. if (!empty($tag['trim']) && $tag['trim'] != 'outside' && preg_match('~(<br />|&nbsp;|\s)*~', substr($message, $pos + 1), $matches) != 0)
  2047. $message = substr($message, 0, $pos + 1) . substr($message, $pos + 1 + strlen($matches[0]));
  2048. }
  2049. // Close any remaining tags.
  2050. while ($tag = array_pop($open_tags))
  2051. $message .= "\n" . $tag['after'] . "\n";
  2052. // Parse the smileys within the parts where it can be done safely.
  2053. if ($smileys === true)
  2054. {
  2055. $message_parts = explode("\n", $message);
  2056. for ($i = 0, $n = count($message_parts); $i < $n; $i += 2)
  2057. parsesmileys($message_parts[$i]);
  2058. $message = implode('', $message_parts);
  2059. }
  2060. // No smileys, just get rid of the markers.
  2061. else
  2062. $message = strtr($message, array("\n" => ''));
  2063. if ($message[0] === ' ')
  2064. $message = '&nbsp;' . substr($message, 1);
  2065. // Cleanup whitespace.
  2066. $message = strtr($message, array(' ' => ' &nbsp;', "\r" => '', "\n" => '<br />', '<br /> ' => '<br />&nbsp;', '&#13;' => "\n"));
  2067. // Allow mods access to what parse_bbc created
  2068. call_integration_hook('integrate_post_parsebbc', array($message, $smileys, $cache_id, $parse_tags));
  2069. // Cache the output if it took some time...
  2070. if (isset($cache_key, $cache_t) && microtime(true) - $cache_t > 0.05)
  2071. cache_put_data($cache_key, $message, 240);
  2072. // If this was a force parse revert if needed.
  2073. if (!empty($parse_tags))
  2074. {
  2075. if (empty($temp_bbc))
  2076. $bbc_codes = array();
  2077. else
  2078. {
  2079. $bbc_codes = $temp_bbc;
  2080. unset($temp_bbc);
  2081. }
  2082. }
  2083. return $message;
  2084. }
  2085. /**
  2086. * Parse smileys in the passed message.
  2087. *
  2088. * The smiley parsing function which makes pretty faces appear :).
  2089. * If custom smiley sets are turned off by smiley_enable, the default set of smileys will be used.
  2090. * These are specifically not parsed in code tags [url=mailto:Dad@blah.com]
  2091. * Caches the smileys from the database or array in memory.
  2092. * Doesn't return anything, but rather modifies message directly.
  2093. *
  2094. * @param string &$message
  2095. */
  2096. function parsesmileys(&$message)
  2097. {
  2098. global $modSettings, $txt, $user_info, $context, $smcFunc;
  2099. static $smileyPregSearch = null, $smileyPregReplacements = array();
  2100. // No smiley set at all?!
  2101. if ($user_info['smiley_set'] == 'none' || trim($message) == '')
  2102. return;
  2103. // If smileyPregSearch hasn't been set, do it now.
  2104. if (empty($smileyPregSearch))
  2105. {
  2106. // Use the default smileys if it is disabled. (better for "portability" of smileys.)
  2107. if (empty($modSettings['smiley_enable']))
  2108. {
  2109. $smileysfrom = array('>:D', ':D', '::)', '>:(', ':))', ':)', ';)', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ':\'(', ':-\\', '^-^', 'O0', 'C:-)', '0:)');
  2110. $smileysto = array('evil.gif', 'cheesy.gif', 'rolleyes.gif', 'angry.gif', 'laugh.gif', 'smiley.gif', 'wink.gif', 'grin.gif', 'sad.gif', 'shocked.gif', 'cool.gif', 'tongue.gif', 'huh.gif', 'embarrassed.gif', 'lipsrsealed.gif', 'kiss.gif', 'cry.gif', 'undecided.gif', 'azn.gif', 'afro.gif', 'police.gif', 'angel.gif');
  2111. $smileysdescs = array('', $txt['icon_cheesy'], $txt['icon_rolleyes'], $txt['icon_angry'], '', $txt['icon_smiley'], $txt['icon_wink'], $txt['icon_grin'], $txt['icon_sad'], $txt['icon_shocked'], $txt['icon_cool'], $txt['icon_tongue'], $txt['icon_huh'], $txt['icon_embarrassed'], $txt['icon_lips'], $txt['icon_kiss'], $txt['icon_cry'], $txt['icon_undecided'], '', '', '', '');
  2112. }
  2113. else
  2114. {
  2115. // Load the smileys in reverse order by length so they don't get parsed wrong.
  2116. if (($temp = cache_get_data('parsing_smileys', 480)) == null)
  2117. {
  2118. $result = $smcFunc['db_query']('', '
  2119. SELECT code, filename, description
  2120. FROM {db_prefix}smileys',
  2121. array(
  2122. )
  2123. );
  2124. $smileysfrom = array();
  2125. $smileysto = array();
  2126. $smileysdescs = array();
  2127. while ($row = $smcFunc['db_fetch_assoc']($result))
  2128. {
  2129. $smileysfrom[] = $row['code'];
  2130. $smileysto[] = htmlspecialchars($row['filename']);
  2131. $smileysdescs[] = $row['description'];
  2132. }
  2133. $smcFunc['db_free_result']($result);
  2134. cache_put_data('parsing_smileys', array($smileysfrom, $smileysto, $smileysdescs), 480);
  2135. }
  2136. else
  2137. list ($smileysfrom, $smileysto, $smileysdescs) = $temp;
  2138. }
  2139. // The non-breaking-space is a complex thing...
  2140. $non_breaking_space = '\x{A0}';
  2141. // This smiley regex makes sure it doesn't parse smileys within code tags (so [url=mailto:David@bla.com] doesn't parse the :D smiley)
  2142. $smileyPregReplacements = array();
  2143. $searchParts = array();
  2144. $smileys_path = htmlspecialchars($modSettings['smileys_url'] . '/' . $user_info['smiley_set'] . '/');
  2145. for ($i = 0, $n = count($smileysfrom); $i < $n; $i++)
  2146. {
  2147. $specialChars = htmlspecialchars($smileysfrom[$i], ENT_QUOTES);
  2148. $smileyCode = '<img src="' . $smileys_path . $smileysto[$i] . '" alt="' . strtr($specialChars, array(':' => '&#58;', '(' => '&#40;', ')' => '&#41;', '$' => '&#36;', '[' => '&#091;')). '" title="' . strtr(htmlspecialchars($smileysdescs[$i]), array(':' => '&#58;', '(' => '&#40;', ')' => '&#41;', '$' => '&#36;', '[' => '&#091;')) . '" class="smiley" />';
  2149. $smileyPregReplacements[$smileysfrom[$i]] = $smileyCode;
  2150. $searchParts[] = preg_quote($smileysfrom[$i], '~');
  2151. if ($smileysfrom[$i] != $specialChars)
  2152. {
  2153. $smileyPregReplacements[$specialChars] = $smileyCode;
  2154. $searchParts[] = preg_quote($specialChars, '~');
  2155. }
  2156. }
  2157. $smileyPregSearch = '~(?<=[>:\?\.\s' . $non_breaking_space . '[\]()*\\\;]|^)(' . implode('|', $searchParts) . ')(?=[^[:alpha:]0-9]|$)~eu';
  2158. }
  2159. // Replace away!
  2160. $message = preg_replace($smileyPregSearch, '$smileyPregReplacements[\'$1\']', $message);
  2161. }
  2162. /**
  2163. * Highlight any code.
  2164. *
  2165. * Uses PHP's highlight_string() to highlight PHP syntax
  2166. * does special handling to keep the tabs in the code available.
  2167. * used to parse PHP code from inside [code] and [php] tags.
  2168. *
  2169. * @param string $code
  2170. * @return string the code with highlighted HTML.
  2171. */
  2172. function highlight_php_code($code)
  2173. {
  2174. // Remove special characters.
  2175. $code = un_htmlspecialchars(strtr($code, array('<br />' => "\n", "\t" => '___TAB();', '&#91;' => '[')));
  2176. $buffer = str_replace(array("\n", "\r"), '', @highlight_string($code, true));
  2177. // Yes, I know this is kludging it, but this is the best way to preserve tabs from PHP :P.
  2178. $buffer = preg_replace('~___TAB(?:</(?:font|span)><(?:font color|span style)="[^"]*?">)?\\(\\);~', '<pre style="display: inline;">' . "\t" . '</pre>', $buffer);
  2179. return strtr($buffer, array('\'' => '&#039;', '<code>' => '', '</code>' => ''));
  2180. }
  2181. /**
  2182. * Make sure the browser doesn't come back and repost the form data.
  2183. * Should be used whenever anything is posted.
  2184. *
  2185. * @param string $setLocation = ''
  2186. * @param bool $refresh = false
  2187. */
  2188. function redirectexit($setLocation = '', $refresh = false)
  2189. {
  2190. global $scripturl, $context, $modSettings, $db_show_debug, $db_cache;
  2191. // In case we have mail to send, better do that - as obExit doesn't always quite make it...
  2192. if (!empty($context['flush_mail']))
  2193. // @todo this relies on 'flush_mail' being only set in AddMailQueue itself... :\
  2194. AddMailQueue(true);
  2195. $add = preg_match('~^(ftp|http)[s]?://~', $setLocation) == 0 && substr($setLocation, 0, 6) != 'about:';
  2196. if ($add)
  2197. $setLocation = $scripturl . ($setLocation != '' ? '?' . $setLocation : '');
  2198. // Put the session ID in.
  2199. if (defined('SID') && SID != '')
  2200. $setLocation = preg_replace('/^' . preg_quote($scripturl, '/') . '(?!\?' . preg_quote(SID, '/') . ')\\??/', $scripturl . '?' . SID . ';', $setLocation);
  2201. // Keep that debug in their for template debugging!
  2202. elseif (isset($_GET['debug']))
  2203. $setLocation = preg_replace('/^' . preg_quote($scripturl, '/') . '\\??/', $scripturl . '?debug;', $setLocation);
  2204. if (!empty($modSettings['queryless_urls']) && (empty($context['server']['is_cgi']) || ini_get('cgi.fix_pathinfo') == 1 || @get_cfg_var('cgi.fix_pathinfo') == 1) && (!empty($context['server']['is_apache']) || !empty($context['server']['is_lighttpd']) || !empty($context['server']['is_litespeed'])))
  2205. {
  2206. if (defined('SID') && SID != '')
  2207. $setLocation = preg_replace('/^' . preg_quote($scripturl, '/') . '\?(?:' . SID . '(?:;|&|&amp;))((?:board|topic)=[^#]+?)(#[^"]*?)?$/e', "\$scripturl . '/' . strtr('\$1', '&;=', '//,') . '.html?' . SID . '\$2'", $setLocation);
  2208. else
  2209. $setLocation = preg_replace('/^' . preg_quote($scripturl, '/') . '\?((?:board|topic)=[^#"]+?)(#[^"]*?)?$/e', "\$scripturl . '/' . strtr('\$1', '&;=', '//,') . '.html\$2'", $setLocation);
  2210. }
  2211. // Maybe integrations want to change where we are heading?
  2212. call_integration_hook('integrate_redirect', array(&$setLocation, &$refresh));
  2213. // We send a Refresh header only in special cases because Location looks better. (and is quicker...)
  2214. if ($refresh)
  2215. header('Refresh: 0; URL=' . strtr($setLocation, array(' ' => '%20')));
  2216. else
  2217. header('Location: ' . str_replace(' ', '%20', $setLocation));
  2218. // Debugging.
  2219. if (isset($db_show_debug) && $db_show_debug === true)
  2220. $_SESSION['debug_redirect'] = $db_cache;
  2221. obExit(false);
  2222. }
  2223. /**
  2224. * Ends execution. Takes care of template loading and remembering the previous URL.
  2225. * @param bool $header = null
  2226. * @param bool $do_footer = null
  2227. * @param bool $from_index = false
  2228. * @param bool $from_fatal_error = false
  2229. */
  2230. function obExit($header = null, $do_footer = null, $from_index = false, $from_fatal_error = false)
  2231. {
  2232. global $context, $settings, $modSettings, $txt, $smcFunc;
  2233. static $header_done = false, $footer_done = false, $level = 0, $has_fatal_error = false;
  2234. // Attempt to prevent a recursive loop.
  2235. ++$level;
  2236. if ($level > 1 && !$from_fatal_error && !$has_fatal_error)
  2237. exit;
  2238. if ($from_fatal_error)
  2239. $has_fatal_error = true;
  2240. // Clear out the stat cache.
  2241. trackStats();
  2242. // If we have mail to send, send it.
  2243. if (!empty($context['flush_mail']))
  2244. // @todo this relies on 'flush_mail' being only set in AddMailQueue itself... :\
  2245. AddMailQueue(true);
  2246. $do_header = $header === null ? !$header_done : $header;
  2247. if ($do_footer === null)
  2248. $do_footer = $do_header;
  2249. // Has the template/header been done yet?
  2250. if ($do_header)
  2251. {
  2252. // Was the page title set last minute? Also update the HTML safe one.
  2253. if (!empty($context['page_title']) && empty($context['page_title_html_safe']))
  2254. $context['page_title_html_safe'] = $smcFunc['htmlspecialchars'](un_htmlspecialchars($context['page_title'])) . (!empty($context['current_page']) ? ' - ' . $txt['page'] . ' ' . ($context['current_page'] + 1) : '');
  2255. // Start up the session URL fixer.
  2256. ob_start('ob_sessrewrite');
  2257. if (!empty($settings['output_buffers']) && is_string($settings['output_buffers']))
  2258. $buffers = explode(',', $settings['output_buffers']);
  2259. elseif (!empty($settings['output_buffers']))
  2260. $buffers = $settings['output_buffers'];
  2261. else
  2262. $buffers = array();
  2263. if (isset($modSettings['integrate_buffer']))
  2264. $buffers = array_merge(explode(',', $modSettings['integrate_buffer']), $buffers);
  2265. if (!empty($buffers))
  2266. foreach ($buffers as $function)
  2267. {
  2268. $function = trim($function);
  2269. $call = strpos($function, '::') !== false ? explode('::', $function) : $function;
  2270. // Is it valid?
  2271. if (is_callable($call))
  2272. ob_start($call);
  2273. }
  2274. // Display the screen in the logical order.
  2275. template_header();
  2276. $header_done = true;
  2277. }
  2278. if ($do_footer)
  2279. {
  2280. // Show the footer.
  2281. loadSubTemplate(isset($context['sub_template']) ? $context['sub_template'] : 'main');
  2282. // Anything special to put out?
  2283. if (!empty($context['insert_after_template']) && !isset($_REQUEST['xml']))
  2284. echo $context['insert_after_template'];
  2285. // Just so we don't get caught in an endless loop of errors from the footer...
  2286. if (!$footer_done)
  2287. {
  2288. $footer_done = true;
  2289. template_footer();
  2290. // (since this is just debugging... it's okay that it's after </html>.)
  2291. if (!isset($_REQUEST['xml']))
  2292. displayDebug();
  2293. }
  2294. }
  2295. // Remember this URL in case someone doesn't like sending HTTP_REFERER.
  2296. if (strpos($_SERVER['REQUEST_URL'], 'action=dlattach') === false && strpos($_SERVER['REQUEST_URL'], 'action=viewadminfile') === false)
  2297. $_SESSION['old_url'] = $_SERVER['REQUEST_URL'];
  2298. // For session check verification.... don't switch browsers...
  2299. $_SESSION['USER_AGENT'] = empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'];
  2300. if (!empty($settings['strict_doctype']))
  2301. {
  2302. // The theme author wants to use the STRICT doctype (only God knows why).
  2303. $temp = ob_get_contents();
  2304. ob_clean();
  2305. echo strtr($temp, array(
  2306. 'var smf_iso_case_folding' => 'var target_blank = \'_blank\'; var smf_iso_case_folding',
  2307. 'target="_blank"' => 'onclick="this.target=target_blank"'));
  2308. }
  2309. // Hand off the output to the portal, etc. we're integrated with.
  2310. call_integration_hook('integrate_exit', array($do_footer));
  2311. // Don't exit if we're coming from index.php; that will pass through normally.
  2312. if (!$from_index)
  2313. exit;
  2314. }
  2315. /**
  2316. * Sets the class of the current topic based on is_very_hot, veryhot, hot, etc
  2317. *
  2318. * @param array &$topic_context
  2319. */
  2320. function determineTopicClass(&$topic_context)
  2321. {
  2322. // Set topic class depending on locked status and number of replies.
  2323. if ($topic_context['is_very_hot'])
  2324. $topic_context['class'] = 'veryhot';
  2325. elseif ($topic_context['is_hot'])
  2326. $topic_context['class'] = 'hot';
  2327. else
  2328. $topic_context['class'] = 'normal';
  2329. $topic_context['class'] .= $topic_context['is_poll'] ? '_poll' : '_post';
  2330. if ($topic_context['is_locked'])
  2331. $topic_context['class'] .= '_locked';
  2332. if ($topic_context['is_sticky'])
  2333. $topic_context['class'] .= '_sticky';
  2334. // This is so old themes will still work.
  2335. $topic_context['extended_class'] = &$topic_context['class'];
  2336. }
  2337. /**
  2338. * Sets up the basic theme context stuff.
  2339. * @param bool $forceload = false
  2340. */
  2341. function setupThemeContext($forceload = false)
  2342. {
  2343. global $modSettings, $user_info, $scripturl, $context, $settings, $options, $txt, $maintenance;
  2344. global $user_settings, $smcFunc;
  2345. static $loaded = false;
  2346. // Under SSI this function can be called more then once. That can cause some problems.
  2347. // So only run the function once unless we are forced to run it again.
  2348. if ($loaded && !$forceload)
  2349. return;
  2350. $loaded = true;
  2351. $context['in_maintenance'] = !empty($maintenance);
  2352. $context['current_time'] = timeformat(time(), false);
  2353. $context['current_action'] = isset($_GET['action']) ? $_GET['action'] : '';
  2354. $context['show_quick_login'] = !empty($modSettings['enableVBStyleLogin']) && $user_info['is_guest'];
  2355. // Get some news...
  2356. $context['news_lines'] = array_filter(explode("\n", str_replace("\r", '', trim(addslashes($modSettings['news'])))));
  2357. for ($i = 0, $n = count($context['news_lines']); $i < $n; $i++)
  2358. {
  2359. if (trim($context['news_lines'][$i]) == '')
  2360. continue;
  2361. // Clean it up for presentation ;).
  2362. $context['news_lines'][$i] = parse_bbc(stripslashes(trim($context['news_lines'][$i])), true, 'news' . $i);
  2363. }
  2364. if (!empty($context['news_lines']))
  2365. $context['random_news_line'] = $context['news_lines'][mt_rand(0, count($context['news_lines']) - 1)];
  2366. if (!$user_info['is_guest'])
  2367. {
  2368. $context['user']['messages'] = &$user_info['messages'];
  2369. $context['user']['unread_messages'] = &$user_info['unread_messages'];
  2370. // Personal message popup...
  2371. if ($user_info['unread_messages'] > (isset($_SESSION['unread_messages']) ? $_SESSION['unread_messages'] : 0))
  2372. $context['user']['popup_messages'] = true;
  2373. else
  2374. $context['user']['popup_messages'] = false;
  2375. $_SESSION['unread_messages'] = $user_info['unread_messages'];
  2376. if (allowedTo('moderate_forum'))
  2377. {
  2378. $context['unapproved_members'] = (!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 2) || !empty($modSettings['approveAccountDeletion']) ? $modSettings['unapprovedMembers'] : 0;
  2379. $context['unapproved_members_text'] = $context['unapproved_members'] == 1 ? sprintf($txt['approve_one_member_waiting'], $scripturl . '?action=admin;area=viewmembers;sa=browse;type=approve') : sprintf($txt['approve_many_members_waiting'], $scripturl . '?action=admin;area=viewmembers;sa=browse;type=approve', $context['unapproved_members']);
  2380. }
  2381. $context['show_open_reports'] = empty($user_settings['mod_prefs']) || $user_settings['mod_prefs'][0] == 1;
  2382. $context['user']['avatar'] = array();
  2383. // Figure out the avatar... uploaded?
  2384. if ($user_info['avatar']['url'] == '' && !empty($user_info['avatar']['id_attach']))
  2385. $context['user']['avatar']['href'] = $user_info['avatar']['custom_dir'] ? $modSettings['custom_avatar_url'] . '/' . $user_info['avatar']['filename'] : $scripturl . '?action=dlattach;attach=' . $user_info['avatar']['id_attach'] . ';type=avatar';
  2386. // Full URL?
  2387. elseif (substr($user_info['avatar']['url'], 0, 7) == 'http://')
  2388. {
  2389. $context['user']['avatar']['href'] = $user_info['avatar']['url'];
  2390. if ($modSettings['avatar_action_too_large'] == 'option_html_resize' || $modSettings['avatar_action_too_large'] == 'option_js_resize')
  2391. {
  2392. if (!empty($modSettings['avatar_max_width_external']))
  2393. $context['user']['avatar']['width'] = $modSettings['avatar_max_width_external'];
  2394. if (!empty($modSettings['avatar_max_height_external']))
  2395. $context['user']['avatar']['height'] = $modSettings['avatar_max_height_external'];
  2396. }
  2397. }
  2398. // Otherwise we assume it's server stored?
  2399. elseif ($user_info['avatar']['url'] != '')
  2400. $context['user']['avatar']['href'] = $modSettings['avatar_url'] . '/' . htmlspecialchars($user_info['avatar']['url']);
  2401. if (!empty($context['user']['avatar']))
  2402. $context['user']['avatar']['image'] = '<img src="' . $context['user']['avatar']['href'] . '"' . (isset($context['user']['avatar']['width']) ? ' width="' . $context['user']['avatar']['width'] . '"' : '') . (isset($context['user']['avatar']['height']) ? ' height="' . $context['user']['avatar']['height'] . '"' : '') . ' alt="" class="avatar" />';
  2403. // Figure out how long they've been logged in.
  2404. $context['user']['total_time_logged_in'] = array(
  2405. 'days' => floor($user_info['total_time_logged_in'] / 86400),
  2406. 'hours' => floor(($user_info['total_time_logged_in'] % 86400) / 3600),
  2407. 'minutes' => floor(($user_info['total_time_logged_in'] % 3600) / 60)
  2408. );
  2409. }
  2410. else
  2411. {
  2412. $context['user']['messages'] = 0;
  2413. $context['user']['unread_messages'] = 0;
  2414. $context['user']['avatar'] = array();
  2415. $context['user']['total_time_logged_in'] = array('days' => 0, 'hours' => 0, 'minutes' => 0);
  2416. $context['user']['popup_messages'] = false;
  2417. if (!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 1)
  2418. $txt['welcome_guest'] .= $txt['welcome_guest_activate'];
  2419. // If we've upgraded recently, go easy on the passwords.
  2420. if (!empty($modSettings['disableHashTime']) && ($modSettings['disableHashTime'] == 1 || time() < $modSettings['disableHashTime']))
  2421. $context['disable_login_hashing'] = true;
  2422. }
  2423. // Setup the main menu items.
  2424. setupMenuContext();
  2425. if (empty($settings['theme_version']))
  2426. $context['show_vBlogin'] = $context['show_quick_login'];
  2427. // This is here because old index templates might still use it.
  2428. $context['show_news'] = !empty($settings['enable_news']);
  2429. // This is done to allow theme authors to customize it as they want.
  2430. $context['show_pm_popup'] = $context['user']['popup_messages'] && !empty($options['popup_messages']) && (!isset($_REQUEST['action']) || $_REQUEST['action'] != 'pm');
  2431. // Add the PM popup here instead. Theme authors can still override it simply by editing/removing the 'fPmPopup' in the array.
  2432. if ($context['show_pm_popup'])
  2433. addInlineJavascript('
  2434. $(document).ready(function(){
  2435. new smc_Popup({
  2436. heading: ' . JavaScriptEscape($txt['show_personal_messages_heading']) . ',
  2437. content: ' . JavaScriptEscape(sprintf($txt['show_personal_messages'], $context['user']['unread_messages'], $scripturl . '?action=pm')) . ',
  2438. icon: smf_images_url + \'/im_sm_newmsg.png\'
  2439. });
  2440. });');
  2441. // Resize avatars the fancy, but non-GD requiring way.
  2442. if ($modSettings['avatar_action_too_large'] == 'option_js_resize' && (!empty($modSettings['avatar_max_width_external']) || !empty($modSettings['avatar_max_height_external'])))
  2443. {
  2444. // @todo Move this over to script.js?
  2445. addInlineJavascript('
  2446. var smf_avatarMaxWidth = ' . (int) $modSettings['avatar_max_width_external'] . ';
  2447. var smf_avatarMaxHeight = ' . (int) $modSettings['avatar_max_height_external'] . ';' . (!isBrowser('ie') ? '
  2448. window.addEventListener("load", smf_avatarResize, false);' : '
  2449. var window_oldAvatarOnload = window.onload;
  2450. window.onload = smf_avatarResize;'));
  2451. }
  2452. // This looks weird, but it's because BoardIndex.controller.php references the variable.
  2453. $context['common_stats']['latest_member'] = array(
  2454. 'id' => $modSettings['latestMember'],
  2455. 'name' => $modSettings['latestRealName'],
  2456. 'href' => $scripturl . '?action=profile;u=' . $modSettings['latestMember'],
  2457. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . '">' . $modSettings['latestRealName'] . '</a>',
  2458. );
  2459. $context['common_stats'] = array(
  2460. 'total_posts' => comma_format($modSettings['totalMessages']),
  2461. 'total_topics' => comma_format($modSettings['totalTopics']),
  2462. 'total_members' => comma_format($modSettings['totalMembers']),
  2463. 'latest_member' => $context['common_stats']['latest_member'],
  2464. );
  2465. $context['common_stats']['boardindex_total_posts'] = sprintf($txt['boardindex_total_posts'], $context['common_stats']['total_posts'], $context['common_stats']['total_topics'], $context['common_stats']['total_members']);
  2466. if (empty($settings['theme_version']))
  2467. addJavascriptVar('smf_scripturl', $scripturl);
  2468. if (!isset($context['page_title']))
  2469. $context['page_title'] = '';
  2470. // Set some specific vars.
  2471. $context['page_title_html_safe'] = $smcFunc['htmlspecialchars'](un_htmlspecialchars($context['page_title'])) . (!empty($context['current_page']) ? ' - ' . $txt['page'] . ' ' . ($context['current_page'] + 1) : '');
  2472. $context['meta_keywords'] = !empty($modSettings['meta_keywords']) ? $smcFunc['htmlspecialchars']($modSettings['meta_keywords']) : '';
  2473. }
  2474. /**
  2475. * Helper function to set the system memory to a needed value
  2476. * - If the needed memory is greater than current, will attempt to get more
  2477. * - if in_use is set to true, will also try to take the current memory usage in to account
  2478. *
  2479. * @param string $needed The amount of memory to request, if needed, like 256M
  2480. * @param bool $in_use Set to true to account for current memory usage of the script
  2481. * @return boolean, true if we have at least the needed memory
  2482. */
  2483. function setMemoryLimit($needed, $in_use = false)
  2484. {
  2485. // everything in bytes
  2486. $memory_used = 0;
  2487. $memory_current = memoryReturnBytes(ini_get('memory_limit'));
  2488. $memory_needed = memoryReturnBytes($needed);
  2489. // should we account for how much is currently being used?
  2490. if ($in_use)
  2491. $memory_needed += function_exists('memory_get_usage') ? memory_get_usage() : (2 * 1048576);
  2492. // if more is needed, request it
  2493. if ($memory_current < $memory_needed)
  2494. {
  2495. @ini_set('memory_limit', ceil($memory_needed / 1048576) . 'M');
  2496. $memory_current = memoryReturnBytes(ini_get('memory_limit'));
  2497. }
  2498. $memory_current = max($memory_current, memoryReturnBytes(get_cfg_var('memory_limit')));
  2499. // return success or not
  2500. return (bool) ($memory_current >= $memory_needed);
  2501. }
  2502. /**
  2503. * Helper function to convert memory string settings to bytes
  2504. *
  2505. * @param string $val The byte string, like 256M or 1G
  2506. * @return integer The string converted to a proper integer in bytes
  2507. */
  2508. function memoryReturnBytes($val)
  2509. {
  2510. if (is_integer($val))
  2511. return $val;
  2512. // Separate the number from the designator
  2513. $val = trim($val);
  2514. $num = intval(substr($val, 0, strlen($val) - 1));
  2515. $last = strtolower(substr($val, -1));
  2516. // convert to bytes
  2517. switch ($last)
  2518. {
  2519. case 'g':
  2520. $num *= 1024;
  2521. case 'm':
  2522. $num *= 1024;
  2523. case 'k':
  2524. $num *= 1024;
  2525. }
  2526. return $num;
  2527. }
  2528. /**
  2529. * This is the only template included in the sources.
  2530. */
  2531. function template_rawdata()
  2532. {
  2533. global $context;
  2534. echo $context['raw_data'];
  2535. }
  2536. /**
  2537. * The header template
  2538. */
  2539. function template_header()
  2540. {
  2541. global $txt, $modSettings, $context, $settings, $user_info;
  2542. setupThemeContext();
  2543. // Print stuff to prevent caching of pages (except on attachment errors, etc.)
  2544. if (empty($context['no_last_modified']))
  2545. {
  2546. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  2547. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  2548. // Are we debugging the template/html content?
  2549. if (!isset($_REQUEST['xml']) && isset($_GET['debug']) && !isBrowser('ie'))
  2550. header('Content-Type: application/xhtml+xml');
  2551. elseif (!isset($_REQUEST['xml']))
  2552. header('Content-Type: text/html; charset=UTF-8');
  2553. }
  2554. header('Content-Type: text/' . (isset($_REQUEST['xml']) ? 'xml' : 'html') . '; charset=UTF-8');
  2555. $checked_securityFiles = false;
  2556. $showed_banned = false;
  2557. foreach ($context['template_layers'] as $layer)
  2558. {
  2559. loadSubTemplate($layer . '_above', true);
  2560. // May seem contrived, but this is done in case the body and main layer aren't there...
  2561. if (in_array($layer, array('body', 'main')) && allowedTo('admin_forum') && !$user_info['is_guest'] && !$checked_securityFiles)
  2562. {
  2563. $checked_securityFiles = true;
  2564. // @todo add a hook here
  2565. $securityFiles = array('install.php', 'webinstall.php', 'upgrade.php', 'convert.php', 'repair_paths.php', 'repair_settings.php', 'Settings.php~', 'Settings_bak.php~');
  2566. foreach ($securityFiles as $i => $securityFile)
  2567. {
  2568. if (!file_exists(BOARDDIR . '/' . $securityFile))
  2569. unset($securityFiles[$i]);
  2570. }
  2571. // We are already checking so many files...just few more doesn't make any difference! :P
  2572. require_once(SUBSDIR . '/Attachments.subs.php');
  2573. $path = getAttachmentPath();
  2574. secureDirectory($path, true);
  2575. secureDirectory(CACHEDIR);
  2576. // If agreement is enabled, at least the english version shall exists
  2577. if ($modSettings['requireAgreement'])
  2578. $agreement = !file_exists(BOARDDIR . '/agreement.txt');
  2579. if (!empty($securityFiles) || (!empty($modSettings['cache_enable']) && !is_writable(CACHEDIR)) || !empty($agreement))
  2580. {
  2581. echo '
  2582. <div class="errorbox">
  2583. <p class="alert">!!</p>
  2584. <h3>', empty($securityFiles) ? $txt['generic_warning'] : $txt['security_risk'], '</h3>
  2585. <p>';
  2586. foreach ($securityFiles as $securityFile)
  2587. {
  2588. echo '
  2589. ', $txt['not_removed'], '<strong>', $securityFile, '</strong>!<br />';
  2590. if ($securityFile == 'Settings.php~' || $securityFile == 'Settings_bak.php~')
  2591. echo '
  2592. ', sprintf($txt['not_removed_extra'], $securityFile, substr($securityFile, 0, -1)), '<br />';
  2593. }
  2594. if (!empty($modSettings['cache_enable']) && !is_writable(CACHEDIR))
  2595. echo '
  2596. <strong>', $txt['cache_writable'], '</strong><br />';
  2597. if (!empty($agreement))
  2598. echo '
  2599. <strong>', $txt['agreement_missing'], '</strong><br />';
  2600. echo '
  2601. </p>
  2602. </div>';
  2603. }
  2604. }
  2605. // If the user is banned from posting inform them of it.
  2606. elseif (in_array($layer, array('main', 'body')) && isset($_SESSION['ban']['cannot_post']) && !$showed_banned)
  2607. {
  2608. $showed_banned = true;
  2609. echo '
  2610. <div class="windowbg alert" style="margin: 2ex; padding: 2ex; border: 2px dashed red;">
  2611. ', sprintf($txt['you_are_post_banned'], $user_info['is_guest'] ? $txt['guest_title'] : $user_info['name']);
  2612. if (!empty($_SESSION['ban']['cannot_post']['reason']))
  2613. echo '
  2614. <div style="padding-left: 4ex; padding-top: 1ex;">', $_SESSION['ban']['cannot_post']['reason'], '</div>';
  2615. if (!empty($_SESSION['ban']['expire_time']))
  2616. echo '
  2617. <div>', sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)), '</div>';
  2618. else
  2619. echo '
  2620. <div>', $txt['your_ban_expires_never'], '</div>';
  2621. echo '
  2622. </div>';
  2623. }
  2624. }
  2625. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  2626. {
  2627. $settings['theme_url'] = $settings['default_theme_url'];
  2628. $settings['images_url'] = $settings['default_images_url'];
  2629. $settings['theme_dir'] = $settings['default_theme_dir'];
  2630. }
  2631. }
  2632. /**
  2633. * Show the copyright.
  2634. */
  2635. function theme_copyright()
  2636. {
  2637. global $forum_copyright, $context, $boardurl, $forum_version, $txt, $modSettings;
  2638. // Don't display copyright for things like SSI.
  2639. if (!isset($forum_version))
  2640. return;
  2641. // Put in the version...
  2642. $forum_copyright = sprintf($forum_copyright, ucfirst(strtolower($forum_version)));
  2643. echo '
  2644. <span class="smalltext" style="display: inline; visibility: visible; font-family: Verdana, Arial, sans-serif;">', $forum_copyright, '
  2645. </span>';
  2646. }
  2647. /**
  2648. * The template footer
  2649. */
  2650. function template_footer()
  2651. {
  2652. global $context, $settings, $modSettings, $time_start, $db_count;
  2653. // Show the load time? (only makes sense for the footer.)
  2654. $context['show_load_time'] = !empty($modSettings['timeLoadPageEnable']);
  2655. $context['load_time'] = round(microtime(true) - $time_start, 3);
  2656. $context['load_queries'] = $db_count;
  2657. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  2658. {
  2659. $settings['theme_url'] = $settings['actual_theme_url'];
  2660. $settings['images_url'] = $settings['actual_images_url'];
  2661. $settings['theme_dir'] = $settings['actual_theme_dir'];
  2662. }
  2663. foreach (array_reverse($context['template_layers']) as $layer)
  2664. loadSubTemplate($layer . '_below', true);
  2665. }
  2666. /**
  2667. * Output the Javascript files
  2668. * - tabbing in this function is to make the HTML source look proper
  2669. * - if defered is set function will output all JS (source & inline) set to load at page end
  2670. * - if the admin option to combine files is set, will use Combiner.class
  2671. *
  2672. * @param bool $do_defered = false
  2673. */
  2674. function template_javascript($do_defered = false)
  2675. {
  2676. global $context, $modSettings, $settings;
  2677. // First up, load jquery
  2678. if (isset($modSettings['jquery_source']) && !$do_defered)
  2679. {
  2680. switch ($modSettings['jquery_source'])
  2681. {
  2682. case 'cdn':
  2683. echo '
  2684. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" id="jquery"></script>';
  2685. break;
  2686. case 'local':
  2687. echo '
  2688. <script type="text/javascript" src="', $settings['default_theme_url'], '/scripts/jquery-1.9.1.min.js" id="jquery"></script>';
  2689. break;
  2690. case 'auto':
  2691. echo '
  2692. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" id="jquery"></script>
  2693. <script type="text/javascript"><!-- // --><![CDATA[
  2694. window.jQuery || document.write(\'<script src="', $settings['default_theme_url'], '/scripts/jquery-1.9.1.min.js"><\/script>\');
  2695. // ]]></script>';
  2696. break;
  2697. }
  2698. }
  2699. // Use this hook to work with Javascript files and vars pre output
  2700. call_integration_hook('pre_javascript_output');
  2701. // Combine and minify javascript to save bandwidth and requests?
  2702. if (!empty($context['javascript_files']))
  2703. {
  2704. if (!empty($modSettings['minify_css_js']))
  2705. {
  2706. require_once(SOURCEDIR . '/Combine.class.php');
  2707. $combiner = new Site_Combiner;
  2708. $combine_name = $combiner->site_js_combine($context['javascript_files'], $do_defered);
  2709. if (!empty($combine_name))
  2710. echo '
  2711. <script type="text/javascript" src="', $combine_name, '" id="jscombined', $do_defered ? 'bottom' : 'top', '"></script>';
  2712. }
  2713. else
  2714. {
  2715. // While we have Javascript files to place in the template
  2716. foreach ($context['javascript_files'] as $id => $js_file)
  2717. {
  2718. if ((!$do_defered && empty($js_file['options']['defer'])) || ($do_defered && !empty($js_file['options']['defer'])))
  2719. echo '
  2720. <script type="text/javascript" src="', $js_file['filename'], '" id="', $id, '"', !empty($js_file['options']['async']) ? ' async="async"' : '', '></script>';
  2721. // If we are loading JQuery and we are set to 'auto' load, put in our remote success or load local check
  2722. if ($id === 'jquery' && (!isset($modSettings['jquery_source']) || $modSettings['jquery_source'] === 'auto'))
  2723. $loadjquery = true;
  2724. }
  2725. }
  2726. }
  2727. // Output the declared Javascript variables.
  2728. if (!empty($context['javascript_vars']) && !$do_defered)
  2729. {
  2730. echo '
  2731. <script type="text/javascript"><!-- // --><![CDATA[';
  2732. foreach ($context['javascript_vars'] as $key => $value)
  2733. echo '
  2734. var ', $key, ' = ', $value, ';';
  2735. echo '
  2736. // ]]></script>';
  2737. }
  2738. // Inline JavaScript - Actually useful some times!
  2739. if (!empty($context['javascript_inline']))
  2740. {
  2741. if (!empty($context['javascript_inline']['defer']) && $do_defered)
  2742. {
  2743. echo '
  2744. <script type="text/javascript"><!-- // --><![CDATA[';
  2745. foreach ($context['javascript_inline']['defer'] as $js_code)
  2746. echo $js_code;
  2747. echo'
  2748. // ]]></script>';
  2749. }
  2750. if (!empty($context['javascript_inline']['standard']) && !$do_defered)
  2751. {
  2752. echo '
  2753. <script type="text/javascript"><!-- // --><![CDATA[';
  2754. foreach ($context['javascript_inline']['standard'] as $js_code)
  2755. echo $js_code;
  2756. echo'
  2757. // ]]></script>';
  2758. }
  2759. }
  2760. }
  2761. /**
  2762. * Output the CSS files
  2763. * - if the admin option to combine files is set, will use Combiner.class
  2764. */
  2765. function template_css()
  2766. {
  2767. global $context, $modSettings;
  2768. // Use this hook to work with CSS files pre output
  2769. call_integration_hook('pre_css_output');
  2770. // Combine and minify the CSS files to save bandwidth and requests?
  2771. if (!empty($context['css_files']))
  2772. {
  2773. if (!empty($modSettings['minify_css_js']))
  2774. {
  2775. require_once(SOURCEDIR . '/Combine.class.php');
  2776. $combiner = new Site_Combiner;
  2777. $combine_name = $combiner->site_css_combine($context['css_files']);
  2778. if (!empty($combine_name))
  2779. echo '
  2780. <link rel="stylesheet" type="text/css" href="', $combine_name, '" id="csscombined" />';
  2781. }
  2782. else
  2783. {
  2784. foreach ($context['css_files'] as $id => $file)
  2785. echo '
  2786. <link rel="stylesheet" type="text/css" href="', $file['filename'], '" id="', $id,'" />';
  2787. }
  2788. }
  2789. }
  2790. /**
  2791. * Get an attachment's encrypted filename. If $new is true, won't check for file existence.
  2792. * @todo this currently returns the hash if new, and the full filename otherwise.
  2793. * Something messy like that.
  2794. * @todo and of course everything relies on this behavior and work around it. :P.
  2795. * Converters included.
  2796. *
  2797. * @param $filename
  2798. * @param $attachment_id
  2799. * @param $dir
  2800. * @param $new
  2801. * @param $file_hash
  2802. */
  2803. function getAttachmentFilename($filename, $attachment_id, $dir = null, $new = false, $file_hash = '')
  2804. {
  2805. global $modSettings, $smcFunc;
  2806. // Just make up a nice hash...
  2807. if ($new)
  2808. return sha1(md5($filename . time()) . mt_rand());
  2809. // Grab the file hash if it wasn't added.
  2810. // @todo: Locate all places that don't call a hash and fix that.
  2811. if ($file_hash === '')
  2812. {
  2813. $request = $smcFunc['db_query']('', '
  2814. SELECT file_hash
  2815. FROM {db_prefix}attachments
  2816. WHERE id_attach = {int:id_attach}',
  2817. array(
  2818. 'id_attach' => $attachment_id,
  2819. ));
  2820. if ($smcFunc['db_num_rows']($request) === 0)
  2821. return false;
  2822. list ($file_hash) = $smcFunc['db_fetch_row']($request);
  2823. $smcFunc['db_free_result']($request);
  2824. }
  2825. // In case of files from the old system, do a legacy call.
  2826. if (empty($file_hash))
  2827. return getLegacyAttachmentFilename($filename, $attachment_id, $dir, $new);
  2828. // Are we using multiple directories?
  2829. if (!empty($modSettings['currentAttachmentUploadDir']))
  2830. {
  2831. if (!is_array($modSettings['attachmentUploadDir']))
  2832. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  2833. $path = isset($modSettings['attachmentUploadDir'][$dir]) ? $modSettings['attachmentUploadDir'][$dir] : $modSettings['attachmentUploadDir'];
  2834. }
  2835. else
  2836. $path = $modSettings['attachmentUploadDir'];
  2837. return $path . '/' . $attachment_id . '_' . $file_hash;
  2838. }
  2839. /**
  2840. * Older attachments may still use this function.
  2841. *
  2842. * @param $filename
  2843. * @param $attachment_id
  2844. * @param $dir
  2845. * @param $new
  2846. */
  2847. function getLegacyAttachmentFilename($filename, $attachment_id, $dir = null, $new = false)
  2848. {
  2849. global $modSettings, $db_character_set;
  2850. $clean_name = $filename;
  2851. // Sorry, no spaces, dots, or anything else but letters allowed.
  2852. $clean_name = preg_replace(array('/\s/', '/[^\w_\.\-]/'), array('_', ''), $clean_name);
  2853. $enc_name = $attachment_id . '_' . strtr($clean_name, '.', '_') . md5($clean_name);
  2854. $clean_name = preg_replace('~\.[\.]+~', '.', $clean_name);
  2855. if ($attachment_id == false || ($new && empty($modSettings['attachmentEncryptFilenames'])))
  2856. return $clean_name;
  2857. elseif ($new)
  2858. return $enc_name;
  2859. // Are we using multiple directories?
  2860. if (!empty($modSettings['currentAttachmentUploadDir']))
  2861. {
  2862. if (!is_array($modSettings['attachmentUploadDir']))
  2863. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  2864. $path = $modSettings['attachmentUploadDir'][$dir];
  2865. }
  2866. else
  2867. $path = $modSettings['attachmentUploadDir'];
  2868. if (file_exists($path . '/' . $enc_name))
  2869. $filename = $path . '/' . $enc_name;
  2870. else
  2871. $filename = $path . '/' . $clean_name;
  2872. return $filename;
  2873. }
  2874. /**
  2875. * Convert a single IP to a ranged IP.
  2876. * internal function used to convert a user-readable format to a format suitable for the database.
  2877. *
  2878. * @param string $fullip
  2879. * @return array|string 'unknown' if the ip in the input was '255.255.255.255'
  2880. */
  2881. function ip2range($fullip)
  2882. {
  2883. // If its IPv6, validate it first.
  2884. if (isValidIPv6($fullip) !== false)
  2885. {
  2886. $ip_parts = explode(':', expandIPv6($fullip, false));
  2887. $ip_array = array();
  2888. if (count($ip_parts) != 8)
  2889. return array();
  2890. for ($i = 0; $i < 8; $i++)
  2891. {
  2892. if ($ip_parts[$i] == '*')
  2893. $ip_array[$i] = array('low' => '0', 'high' => hexdec('ffff'));
  2894. elseif (preg_match('/^([0-9A-Fa-f]{1,4})\-([0-9A-Fa-f]{1,4})$/', $ip_parts[$i], $range) == 1)
  2895. $ip_array[$i] = array('low' => hexdec($range[1]), 'high' => hexdec($range[2]));
  2896. elseif (is_numeric(hexdec($ip_parts[$i])))
  2897. $ip_array[$i] = array('low' => hexdec($ip_parts[$i]), 'high' => hexdec($ip_parts[$i]));
  2898. }
  2899. return $ip_array;
  2900. }
  2901. // Pretend that 'unknown' is 255.255.255.255. (since that can't be an IP anyway.)
  2902. if ($fullip == 'unknown')
  2903. $fullip = '255.255.255.255';
  2904. $ip_parts = explode('.', $fullip);
  2905. $ip_array = array();
  2906. if (count($ip_parts) != 4)
  2907. return array();
  2908. for ($i = 0; $i < 4; $i++)
  2909. {
  2910. if ($ip_parts[$i] == '*')
  2911. $ip_array[$i] = array('low' => '0', 'high' => '255');
  2912. elseif (preg_match('/^(\d{1,3})\-(\d{1,3})$/', $ip_parts[$i], $range) == 1)
  2913. $ip_array[$i] = array('low' => $range[1], 'high' => $range[2]);
  2914. elseif (is_numeric($ip_parts[$i]))
  2915. $ip_array[$i] = array('low' => $ip_parts[$i], 'high' => $ip_parts[$i]);
  2916. }
  2917. // Makes it simpiler to work with.
  2918. $ip_array[4] = array('low' => 0, 'high' => 0);
  2919. $ip_array[5] = array('low' => 0, 'high' => 0);
  2920. $ip_array[6] = array('low' => 0, 'high' => 0);
  2921. $ip_array[7] = array('low' => 0, 'high' => 0);
  2922. return $ip_array;
  2923. }
  2924. /**
  2925. * Lookup an IP; try shell_exec first because we can do a timeout on it.
  2926. *
  2927. * @param string $ip
  2928. */
  2929. function host_from_ip($ip)
  2930. {
  2931. global $modSettings;
  2932. if (($host = cache_get_data('hostlookup-' . $ip, 600)) !== null)
  2933. return $host;
  2934. $t = microtime(true);
  2935. // Try the Linux host command, perhaps?
  2936. if (!isset($host) && (strpos(strtolower(PHP_OS), 'win') === false || strpos(strtolower(PHP_OS), 'darwin') !== false) && mt_rand(0, 1) == 1)
  2937. {
  2938. if (!isset($modSettings['host_to_dis']))
  2939. $test = @shell_exec('host -W 1 ' . @escapeshellarg($ip));
  2940. else
  2941. $test = @shell_exec('host ' . @escapeshellarg($ip));
  2942. // Did host say it didn't find anything?
  2943. if (strpos($test, 'not found') !== false)
  2944. $host = '';
  2945. // Invalid server option?
  2946. elseif ((strpos($test, 'invalid option') || strpos($test, 'Invalid query name 1')) && !isset($modSettings['host_to_dis']))
  2947. updateSettings(array('host_to_dis' => 1));
  2948. // Maybe it found something, after all?
  2949. elseif (preg_match('~\s([^\s]+?)\.\s~', $test, $match) == 1)
  2950. $host = $match[1];
  2951. }
  2952. // This is nslookup; usually only Windows, but possibly some Unix?
  2953. if (!isset($host) && stripos(PHP_OS, 'win') !== false && strpos(strtolower(PHP_OS), 'darwin') === false && mt_rand(0, 1) == 1)
  2954. {
  2955. $test = @shell_exec('nslookup -timeout=1 ' . @escapeshellarg($ip));
  2956. if (strpos($test, 'Non-existent domain') !== false)
  2957. $host = '';
  2958. elseif (preg_match('~Name:\s+([^\s]+)~', $test, $match) == 1)
  2959. $host = $match[1];
  2960. }
  2961. // This is the last try :/.
  2962. if (!isset($host) || $host === false)
  2963. $host = @gethostbyaddr($ip);
  2964. // It took a long time, so let's cache it!
  2965. if (microtime(true) - $t > 0.5)
  2966. cache_put_data('hostlookup-' . $ip, $host, 600);
  2967. return $host;
  2968. }
  2969. /**
  2970. * Chops a string into words and prepares them to be inserted into (or searched from) the database.
  2971. *
  2972. * @param string $text
  2973. * @param int $max_chars = 20
  2974. * @param bool $encrypt = false
  2975. */
  2976. function text2words($text, $max_chars = 20, $encrypt = false)
  2977. {
  2978. global $smcFunc, $context;
  2979. // Step 1: Remove entities/things we don't consider words:
  2980. $words = preg_replace('~(?:[\x0B\0\x{A0}\t\r\s\n(){}\\[\\]<>!@$%^*.,:+=`\~\?/\\\\]+|&(?:amp|lt|gt|quot);)+~u', ' ', strtr($text, array('<br />' => ' ')));
  2981. // Step 2: Entities we left to letters, where applicable, lowercase.
  2982. $words = un_htmlspecialchars($smcFunc['strtolower']($words));
  2983. // Step 3: Ready to split apart and index!
  2984. $words = explode(' ', $words);
  2985. if ($encrypt)
  2986. {
  2987. $possible_chars = array_flip(array_merge(range(46, 57), range(65, 90), range(97, 122)));
  2988. $returned_ints = array();
  2989. foreach ($words as $word)
  2990. {
  2991. if (($word = trim($word, '-_\'')) !== '')
  2992. {
  2993. $encrypted = substr(crypt($word, 'uk'), 2, $max_chars);
  2994. $total = 0;
  2995. for ($i = 0; $i < $max_chars; $i++)
  2996. $total += $possible_chars[ord($encrypted{$i})] * pow(63, $i);
  2997. $returned_ints[] = $max_chars == 4 ? min($total, 16777215) : $total;
  2998. }
  2999. }
  3000. return array_unique($returned_ints);
  3001. }
  3002. else
  3003. {
  3004. // Trim characters before and after and add slashes for database insertion.
  3005. $returned_words = array();
  3006. foreach ($words as $word)
  3007. if (($word = trim($word, '-_\'')) !== '')
  3008. $returned_words[] = $max_chars === null ? $word : substr($word, 0, $max_chars);
  3009. // Filter out all words that occur more than once.
  3010. return array_unique($returned_words);
  3011. }
  3012. }
  3013. /**
  3014. * Creates an image/text button
  3015. *
  3016. * @param string $name
  3017. * @param string $alt
  3018. * @param string $label = ''
  3019. * @param boolean $custom = ''
  3020. * @param boolean $force_use = false
  3021. * @return string
  3022. */
  3023. function create_button($name, $alt, $label = '', $custom = '', $force_use = false)
  3024. {
  3025. global $settings, $txt, $context;
  3026. // Does the current loaded theme have this and we are not forcing the usage of this function?
  3027. if (function_exists('template_create_button') && !$force_use)
  3028. return template_create_button($name, $alt, $label = '', $custom = '');
  3029. if (!$settings['use_image_buttons'])
  3030. return $txt[$alt];
  3031. elseif (!empty($settings['use_buttons']))
  3032. return '<img src="' . $settings['images_url'] . '/buttons/' . $name . '" alt="' . $txt[$alt] . '" ' . $custom . ' />' . ($label != '' ? '&nbsp;<strong>' . $txt[$label] . '</strong>' : '');
  3033. else
  3034. return '<img src="' . $settings['lang_images_url'] . '/' . $name . '" alt="' . $txt[$alt] . '" ' . $custom . ' />';
  3035. }
  3036. /**
  3037. * Sets up all of the top menu buttons
  3038. * Saves them in the cache if it is available and on
  3039. * Places the results in $context
  3040. *
  3041. */
  3042. function setupMenuContext()
  3043. {
  3044. global $context, $modSettings, $user_info, $txt, $scripturl;
  3045. // Set up the menu privileges.
  3046. $context['allow_search'] = !empty($modSettings['allow_guestAccess']) ? allowedTo('search_posts') : (!$user_info['is_guest'] && allowedTo('search_posts'));
  3047. $context['allow_admin'] = allowedTo(array('admin_forum', 'manage_boards', 'manage_permissions', 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news', 'manage_attachments', 'manage_smileys'));
  3048. $context['allow_edit_profile'] = !$user_info['is_guest'] && allowedTo(array('profile_view_own', 'profile_view_any', 'profile_identity_own', 'profile_identity_any', 'profile_extra_own', 'profile_extra_any', 'profile_remove_own', 'profile_remove_any', 'moderate_forum', 'manage_membergroups', 'profile_title_own', 'profile_title_any'));
  3049. $context['allow_memberlist'] = allowedTo('view_mlist');
  3050. $context['allow_calendar'] = allowedTo('calendar_view') && !empty($modSettings['cal_enabled']);
  3051. $context['allow_moderation_center'] = $context['user']['can_mod'];
  3052. $context['allow_pm'] = allowedTo('pm_read');
  3053. $cacheTime = $modSettings['lastActive'] * 60;
  3054. // All the buttons we can possible want and then some, try pulling the final list of buttons from cache first.
  3055. if (($menu_buttons = cache_get_data('menu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $cacheTime)) === null || time() - $cacheTime <= $modSettings['settings_updated'])
  3056. {
  3057. $buttons = array(
  3058. 'home' => array(
  3059. 'title' => $txt['home'],
  3060. 'href' => $scripturl,
  3061. 'show' => true,
  3062. 'sub_buttons' => array(
  3063. ),
  3064. 'is_last' => $context['right_to_left'],
  3065. ),
  3066. 'help' => array(
  3067. 'title' => $txt['help'],
  3068. 'href' => $scripturl . '?action=help',
  3069. 'show' => true,
  3070. 'sub_buttons' => array(
  3071. ),
  3072. ),
  3073. 'search' => array(
  3074. 'title' => $txt['search'],
  3075. 'href' => $scripturl . '?action=search',
  3076. 'show' => $context['allow_search'],
  3077. 'sub_buttons' => array(
  3078. ),
  3079. ),
  3080. 'admin' => array(
  3081. 'title' => $txt['admin'],
  3082. 'href' => $scripturl . '?action=admin',
  3083. 'show' => $context['allow_admin'],
  3084. 'sub_buttons' => array(
  3085. 'featuresettings' => array(
  3086. 'title' => $txt['modSettings_title'],
  3087. 'href' => $scripturl . '?action=admin;area=featuresettings',
  3088. 'show' => allowedTo('admin_forum'),
  3089. ),
  3090. 'packages' => array(
  3091. 'title' => $txt['package'],
  3092. 'href' => $scripturl . '?action=admin;area=packages',
  3093. 'show' => allowedTo('admin_forum'),
  3094. ),
  3095. 'errorlog' => array(
  3096. 'title' => $txt['errlog'],
  3097. 'href' => $scripturl . '?action=admin;area=logs;sa=errorlog;desc',
  3098. 'show' => allowedTo('admin_forum') && !empty($modSettings['enableErrorLogging']),
  3099. ),
  3100. 'permissions' => array(
  3101. 'title' => $txt['edit_permissions'],
  3102. 'href' => $scripturl . '?action=admin;area=permissions',
  3103. 'show' => allowedTo('manage_permissions'),
  3104. 'is_last' => true,
  3105. ),
  3106. ),
  3107. ),
  3108. 'moderate' => array(
  3109. 'title' => $txt['moderate'],
  3110. 'href' => $scripturl . '?action=moderate',
  3111. 'show' => $context['allow_moderation_center'],
  3112. 'sub_buttons' => array(
  3113. 'modlog' => array(
  3114. 'title' => $txt['modlog_view'],
  3115. 'href' => $scripturl . '?action=moderate;area=modlog',
  3116. 'show' => !empty($modSettings['modlog_enabled']) && !empty($user_info['mod_cache']) && $user_info['mod_cache']['bq'] != '0=1',
  3117. ),
  3118. 'poststopics' => array(
  3119. 'title' => $txt['mc_unapproved_poststopics'],
  3120. 'href' => $scripturl . '?action=moderate;area=postmod;sa=posts',
  3121. 'show' => $modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap']),
  3122. ),
  3123. 'attachments' => array(
  3124. 'title' => $txt['mc_unapproved_attachments'],
  3125. 'href' => $scripturl . '?action=moderate;area=attachmod;sa=attachments',
  3126. 'show' => $modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap']),
  3127. ),
  3128. 'reports' => array(
  3129. 'title' => $txt['mc_reported_posts'],
  3130. 'href' => $scripturl . '?action=moderate;area=reports',
  3131. 'show' => !empty($user_info['mod_cache']) && $user_info['mod_cache']['bq'] != '0=1',
  3132. 'is_last' => true,
  3133. ),
  3134. ),
  3135. ),
  3136. 'profile' => array(
  3137. 'title' => $txt['profile'],
  3138. 'href' => $scripturl . '?action=profile',
  3139. 'show' => $context['allow_edit_profile'],
  3140. 'sub_buttons' => array(
  3141. 'account' => array(
  3142. 'title' => $txt['account'],
  3143. 'href' => $scripturl . '?action=profile;area=account',
  3144. 'show' => allowedTo(array('profile_identity_any', 'profile_identity_own', 'manage_membergroups')),
  3145. ),
  3146. 'profile' => array(
  3147. 'title' => $txt['forumprofile'],
  3148. 'href' => $scripturl . '?action=profile;area=forumprofile',
  3149. 'show' => allowedTo(array('profile_extra_any', 'profile_extra_own')),
  3150. 'is_last' => true,
  3151. ),
  3152. 'theme' => array(
  3153. 'title' => $txt['theme'],
  3154. 'href' => $scripturl . '?action=profile;area=theme',
  3155. 'show' => allowedTo(array('profile_extra_any', 'profile_extra_own', 'profile_extra_any')),
  3156. ),
  3157. ),
  3158. ),
  3159. 'pm' => array(
  3160. 'title' => $txt['pm_short'],
  3161. 'href' => $scripturl . '?action=pm',
  3162. 'show' => $context['allow_pm'],
  3163. 'sub_buttons' => array(
  3164. 'pm_read' => array(
  3165. 'title' => $txt['pm_menu_read'],
  3166. 'href' => $scripturl . '?action=pm',
  3167. 'show' => allowedTo('pm_read'),
  3168. ),
  3169. 'pm_send' => array(
  3170. 'title' => $txt['pm_menu_send'],
  3171. 'href' => $scripturl . '?action=pm;sa=send',
  3172. 'show' => allowedTo('pm_send'),
  3173. 'is_last' => true,
  3174. ),
  3175. ),
  3176. ),
  3177. 'calendar' => array(
  3178. 'title' => $txt['calendar'],
  3179. 'href' => $scripturl . '?action=calendar',
  3180. 'show' => $context['allow_calendar'],
  3181. 'sub_buttons' => array(
  3182. 'view' => array(
  3183. 'title' => $txt['calendar_menu'],
  3184. 'href' => $scripturl . '?action=calendar',
  3185. 'show' => allowedTo('calendar_post'),
  3186. ),
  3187. 'post' => array(
  3188. 'title' => $txt['calendar_post_event'],
  3189. 'href' => $scripturl . '?action=calendar;sa=post',
  3190. 'show' => allowedTo('calendar_post'),
  3191. 'is_last' => true,
  3192. ),
  3193. ),
  3194. ),
  3195. 'memberlist' => array(
  3196. 'title' => $txt['members_title'],
  3197. 'href' => $scripturl . '?action=memberlist',
  3198. 'show' => $context['allow_memberlist'],
  3199. 'sub_buttons' => array(
  3200. 'mlist_view' => array(
  3201. 'title' => $txt['mlist_menu_view'],
  3202. 'href' => $scripturl . '?action=memberlist',
  3203. 'show' => true,
  3204. ),
  3205. 'mlist_search' => array(
  3206. 'title' => $txt['mlist_search'],
  3207. 'href' => $scripturl . '?action=memberlist;sa=search',
  3208. 'show' => true,
  3209. 'is_last' => true,
  3210. ),
  3211. ),
  3212. ),
  3213. 'login' => array(
  3214. 'title' => $txt['login'],
  3215. 'href' => $scripturl . '?action=login',
  3216. 'show' => $user_info['is_guest'],
  3217. 'sub_buttons' => array(
  3218. ),
  3219. ),
  3220. 'register' => array(
  3221. 'title' => $txt['register'],
  3222. 'href' => $scripturl . '?action=register',
  3223. 'show' => $user_info['is_guest'] && $context['can_register'],
  3224. 'sub_buttons' => array(
  3225. ),
  3226. 'is_last' => !$context['right_to_left'],
  3227. ),
  3228. 'logout' => array(
  3229. 'title' => $txt['logout'],
  3230. 'href' => $scripturl . '?action=logout;%1$s=%2$s',
  3231. 'show' => !$user_info['is_guest'],
  3232. 'sub_buttons' => array(
  3233. ),
  3234. 'is_last' => !$context['right_to_left'],
  3235. ),
  3236. );
  3237. // Allow editing menu buttons easily.
  3238. call_integration_hook('integrate_menu_buttons', array(&$buttons));
  3239. // Now we put the buttons in the context so the theme can use them.
  3240. $menu_buttons = array();
  3241. foreach ($buttons as $act => $button)
  3242. if (!empty($button['show']))
  3243. {
  3244. $button['active_button'] = false;
  3245. // This button needs some action.
  3246. if (isset($button['action_hook']))
  3247. $needs_action_hook = true;
  3248. // Make sure the last button truely is the last button.
  3249. if (!empty($button['is_last']))
  3250. {
  3251. if (isset($last_button))
  3252. unset($menu_buttons[$last_button]['is_last']);
  3253. $last_button = $act;
  3254. }
  3255. // Go through the sub buttons if there are any.
  3256. if (!empty($button['sub_buttons']))
  3257. foreach ($button['sub_buttons'] as $key => $subbutton)
  3258. {
  3259. if (empty($subbutton['show']))
  3260. unset($button['sub_buttons'][$key]);
  3261. // 2nd level sub buttons next...
  3262. if (!empty($subbutton['sub_buttons']))
  3263. {
  3264. foreach ($subbutton['sub_buttons'] as $key2 => $sub_button2)
  3265. {
  3266. if (empty($sub_button2['show']))
  3267. unset($button['sub_buttons'][$key]['sub_buttons'][$key2]);
  3268. }
  3269. }
  3270. }
  3271. $menu_buttons[$act] = $button;
  3272. }
  3273. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  3274. cache_put_data('menu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $menu_buttons, $cacheTime);
  3275. }
  3276. $context['menu_buttons'] = $menu_buttons;
  3277. // Logging out requires the session id in the url.
  3278. if (isset($context['menu_buttons']['logout']))
  3279. $context['menu_buttons']['logout']['href'] = sprintf($context['menu_buttons']['logout']['href'], $context['session_var'], $context['session_id']);
  3280. // Figure out which action we are doing so we can set the active tab.
  3281. // Default to home.
  3282. $current_action = 'home';
  3283. if (isset($context['menu_buttons'][$context['current_action']]))
  3284. $current_action = $context['current_action'];
  3285. elseif ($context['current_action'] == 'search2')
  3286. $current_action = 'search';
  3287. elseif ($context['current_action'] == 'theme')
  3288. $current_action = isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'pick' ? 'profile' : 'admin';
  3289. elseif ($context['current_action'] == 'register2')
  3290. $current_action = 'register';
  3291. elseif ($context['current_action'] == 'login2' || ($user_info['is_guest'] && $context['current_action'] == 'reminder'))
  3292. $current_action = 'login';
  3293. elseif ($context['current_action'] == 'groups' && $context['allow_moderation_center'])
  3294. $current_action = 'moderate';
  3295. // Not all actions are simple.
  3296. if (!empty($needs_action_hook))
  3297. call_integration_hook('integrate_current_action', array($current_action));
  3298. if (isset($context['menu_buttons'][$current_action]))
  3299. $context['menu_buttons'][$current_action]['active_button'] = true;
  3300. // Update the PM menu item if they have unread messages
  3301. if (!$user_info['is_guest'] && $context['user']['unread_messages'] > 0 && isset($context['menu_buttons']['pm']))
  3302. {
  3303. $context['menu_buttons']['pm']['alttitle'] = $context['menu_buttons']['pm']['title'] . ' [' . $context['user']['unread_messages'] . ']';
  3304. $context['menu_buttons']['pm']['title'] .= ' [<strong>' . $context['user']['unread_messages'] . '</strong>]';
  3305. }
  3306. // Update the Moderation menu items with action item totals
  3307. if ($context['allow_moderation_center'])
  3308. {
  3309. // Get the numbers for the menu ...
  3310. require_once(SUBSDIR . '/Moderation.subs.php');
  3311. $mod_count = loadModeratorMenuCounts();
  3312. if (!empty($mod_count['total']))
  3313. {
  3314. $context['menu_buttons']['moderate']['alttitle'] = $context['menu_buttons']['moderate']['title'] . ' [' . $mod_count['total'] . ']';
  3315. $context['menu_buttons']['moderate']['title'] .= !empty($mod_count['total']) ? ' [<strong>' . $mod_count['total'] . '</strong>]' : '';
  3316. if (!empty($mod_count['postmod']))
  3317. {
  3318. $context['menu_buttons']['moderate']['sub_buttons']['poststopics']['alttitle'] = $context['menu_buttons']['moderate']['sub_buttons']['poststopics']['title'] . ' [' . $mod_count['postmod'] . ']';
  3319. $context['menu_buttons']['moderate']['sub_buttons']['poststopics']['title'] .= ' [<strong>' . $mod_count['postmod'] . '</strong>]';
  3320. }
  3321. if (!empty($mod_count['attachments']))
  3322. {
  3323. $context['menu_buttons']['moderate']['sub_buttons']['attachments']['alttitle'] = $context['menu_buttons']['moderate']['sub_buttons']['attachments']['title'] . ' [' . $mod_count['attachments'] . ']';
  3324. $context['menu_buttons']['moderate']['sub_buttons']['attachments']['title'] .= ' [<strong>' . $mod_count['attachments'] . '</strong>]';
  3325. }
  3326. if (!empty($mod_count['reports']))
  3327. {
  3328. $context['menu_buttons']['moderate']['sub_buttons']['reports']['alttitle'] = $context['menu_buttons']['moderate']['sub_buttons']['reports']['title'] . ' [' . $mod_count['reports'] . ']';
  3329. $context['menu_buttons']['moderate']['sub_buttons']['reports']['title'] .= ' [<strong>' . $mod_count['reports'] . '</strong>]';
  3330. }
  3331. }
  3332. }
  3333. }
  3334. /**
  3335. * Generate a random seed and ensure it's stored in settings.
  3336. */
  3337. function elk_seed_generator()
  3338. {
  3339. global $modSettings;
  3340. // Never existed?
  3341. if (empty($modSettings['rand_seed']))
  3342. {
  3343. $modSettings['rand_seed'] = microtime() * 1000000;
  3344. updateSettings(array('rand_seed' => $modSettings['rand_seed']));
  3345. }
  3346. // Change the seed.
  3347. updateSettings(array('rand_seed' => mt_rand()));
  3348. }
  3349. /**
  3350. * Process functions of an integration hook.
  3351. * calls all functions of the given hook.
  3352. * supports static class method calls.
  3353. *
  3354. * @param string $hook
  3355. * @param array $parameters = array()
  3356. * @return array the results of the functions
  3357. */
  3358. function call_integration_hook($hook, $parameters = array())
  3359. {
  3360. global $modSettings, $settings, $db_show_debug, $context;
  3361. if ($db_show_debug === true)
  3362. $context['debug']['hooks'][] = $hook;
  3363. $results = array();
  3364. if (empty($modSettings[$hook]))
  3365. return $results;
  3366. $functions = explode(',', $modSettings[$hook]);
  3367. // Loop through each function.
  3368. foreach ($functions as $function)
  3369. {
  3370. $function = trim($function);
  3371. if (strpos($function, '::') !== false)
  3372. {
  3373. $call = explode('::', $function);
  3374. if (strpos($call[1], ':') !== false)
  3375. {
  3376. list($func, $file) = explode(':', $call[1]);
  3377. if (empty($settings['theme_dir']))
  3378. $absPath = strtr(trim($file), array('BOARDDIR' => BOARDDIR, 'SOURCEDIR' => SOURCEDIR));
  3379. else
  3380. $absPath = strtr(trim($file), array('BOARDDIR' => BOARDDIR, 'SOURCEDIR' => SOURCEDIR, '$themedir' => $settings['theme_dir']));
  3381. if (file_exists($absPath))
  3382. require_once($absPath);
  3383. $call = array($call[0], $func);
  3384. }
  3385. }
  3386. else
  3387. {
  3388. $call = $function;
  3389. if (strpos($function, ':') !== false)
  3390. {
  3391. list($func, $file) = explode(':', $function);
  3392. if (empty($settings['theme_dir']))
  3393. $absPath = strtr(trim($file), array('BOARDDIR' => BOARDDIR, 'SOURCEDIR' => SOURCEDIR));
  3394. else
  3395. $absPath = strtr(trim($file), array('BOARDDIR' => BOARDDIR, 'SOURCEDIR' => SOURCEDIR, '$themedir' => $settings['theme_dir']));
  3396. if (file_exists($absPath))
  3397. require_once($absPath);
  3398. $call = $func;
  3399. }
  3400. }
  3401. // Is it valid?
  3402. if (is_callable($call))
  3403. $results[$function] = call_user_func_array($call, $parameters);
  3404. }
  3405. return $results;
  3406. }
  3407. /**
  3408. * Add a function for integration hook.
  3409. * does nothing if the function is already added.
  3410. *
  3411. * @param string $hook
  3412. * @param string $function
  3413. * @param string $file
  3414. * @param bool $permanent = true if true, updates the value in settings table
  3415. */
  3416. function add_integration_function($hook, $function, $file = '', $permanent = true)
  3417. {
  3418. global $smcFunc, $modSettings;
  3419. $integration_call = (!empty($file) && $file !== true) ? $function . ':' . $file : $function;
  3420. // Is it going to be permanent?
  3421. if ($permanent)
  3422. {
  3423. $request = $smcFunc['db_query']('', '
  3424. SELECT value
  3425. FROM {db_prefix}settings
  3426. WHERE variable = {string:variable}',
  3427. array(
  3428. 'variable' => $hook,
  3429. )
  3430. );
  3431. list($current_functions) = $smcFunc['db_fetch_row']($request);
  3432. $smcFunc['db_free_result']($request);
  3433. if (!empty($current_functions))
  3434. {
  3435. $current_functions = explode(',', $current_functions);
  3436. if (in_array($integration_call, $current_functions))
  3437. return;
  3438. $permanent_functions = array_merge($current_functions, array($integration_call));
  3439. }
  3440. else
  3441. $permanent_functions = array($integration_call);
  3442. updateSettings(array($hook => implode(',', $permanent_functions)));
  3443. }
  3444. // Make current function list usable.
  3445. $functions = empty($modSettings[$hook]) ? array() : explode(',', $modSettings[$hook]);
  3446. // Do nothing, if it's already there.
  3447. if (in_array($integration_call, $functions))
  3448. return;
  3449. $functions[] = $integration_call;
  3450. $modSettings[$hook] = implode(',', $functions);
  3451. }
  3452. /**
  3453. * Remove an integration hook function.
  3454. * Removes the given function from the given hook.
  3455. * Does nothing if the function is not available.
  3456. *
  3457. * @param string $hook
  3458. * @param string $function
  3459. * @param string $file
  3460. */
  3461. function remove_integration_function($hook, $function, $file = '')
  3462. {
  3463. global $smcFunc, $modSettings;
  3464. $integration_call = (!empty($file)) ? $function . ':' . $file : $function;
  3465. // Get the permanent functions.
  3466. $request = $smcFunc['db_query']('', '
  3467. SELECT value
  3468. FROM {db_prefix}settings
  3469. WHERE variable = {string:variable}',
  3470. array(
  3471. 'variable' => $hook,
  3472. )
  3473. );
  3474. list($current_functions) = $smcFunc['db_fetch_row']($request);
  3475. $smcFunc['db_free_result']($request);
  3476. if (!empty($current_functions))
  3477. {
  3478. $current_functions = explode(',', $current_functions);
  3479. if (in_array($integration_call, $current_functions))
  3480. updateSettings(array($hook => implode(',', array_diff($current_functions, array($integration_call)))));
  3481. }
  3482. // Turn the function list into something usable.
  3483. $functions = empty($modSettings[$hook]) ? array() : explode(',', $modSettings[$hook]);
  3484. // You can only remove it if it's available.
  3485. if (!in_array($integration_call, $functions))
  3486. return;
  3487. $functions = array_diff($functions, array($integration_call));
  3488. $modSettings[$hook] = implode(',', $functions);
  3489. }
  3490. /**
  3491. * Microsoft uses their own character set Code Page 1252 (CP1252), which is a
  3492. * superset of ISO 8859-1, defining several characters between DEC 128 and 159
  3493. * that are not normally displayable. This converts the popular ones that
  3494. * appear from a cut and paste from windows.
  3495. *
  3496. * @param string $string
  3497. * @return string $string
  3498. */
  3499. function sanitizeMSCutPaste($string)
  3500. {
  3501. global $context;
  3502. if (empty($string))
  3503. return $string;
  3504. // UTF-8 occurences of MS special characters
  3505. $findchars_utf8 = array(
  3506. "\xe2\x80\x9a", // single low-9 quotation mark
  3507. "\xe2\x80\x9e", // double low-9 quotation mark
  3508. "\xe2\x80\xa6", // horizontal ellipsis
  3509. "\xe2\x80\x98", // left single curly quote
  3510. "\xe2\x80\x99", // right single curly quote
  3511. "\xe2\x80\x9c", // left double curly quote
  3512. "\xe2\x80\x9d", // right double curly quote
  3513. "\xe2\x80\x93", // en dash
  3514. "\xe2\x80\x94", // em dash
  3515. );
  3516. // safe replacements
  3517. $replacechars = array(
  3518. ',', // &sbquo;
  3519. ',,', // &bdquo;
  3520. '...', // &hellip;
  3521. "'", // &lsquo;
  3522. "'", // &rsquo;
  3523. '"', // &ldquo;
  3524. '"', // &rdquo;
  3525. '-', // &ndash;
  3526. '--', // &mdash;
  3527. );
  3528. $string = str_replace($findchars_utf8, $replacechars, $string);
  3529. return $string;
  3530. }
  3531. /**
  3532. * Decode numeric html entities to their UTF8 equivalent character.
  3533. *
  3534. * Callback function for preg_replace_callback in subs-members
  3535. * Uses capture group 2 in the supplied array
  3536. * Does basic scan to ensure characters are inside a valid range
  3537. *
  3538. * @param array $matches
  3539. * @return string $string
  3540. */
  3541. function replaceEntities__callback($matches)
  3542. {
  3543. if (!isset($matches[2]))
  3544. return '';
  3545. $num = $matches[2][0] === 'x' ? hexdec(substr($matches[2], 1)) : (int) $matches[2];
  3546. // remove left to right / right to left overrides
  3547. if ($num === 0x202D || $num === 0x202E)
  3548. return '';
  3549. // Quote, Ampersand, Apostrophe, Less/Greater Than get html replaced
  3550. if (in_array($num, array(0x22, 0x26, 0x27, 0x3C, 0x3E)))
  3551. return '&#' . $num . ';';
  3552. // <0x20 are control characters, 0x20 is a space, > 0x10FFFF is past the end of the utf8 character set
  3553. // 0xD800 >= $num <= 0xDFFF are surrogate markers (not valid for utf8 text)
  3554. if ($num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF))
  3555. return '';
  3556. // <0x80 (or less than 128) are standard ascii characters a-z A-Z 0-9 and puncuation
  3557. elseif ($num < 0x80)
  3558. return chr($num);
  3559. // <0x800 (2048)
  3560. elseif ($num < 0x800)
  3561. return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
  3562. // < 0x10000 (65536)
  3563. elseif ($num < 0x10000)
  3564. return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  3565. // <= 0x10FFFF (1114111)
  3566. else
  3567. return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  3568. }
  3569. /**
  3570. * Converts html entities to utf8 equivalents
  3571. *
  3572. * Callback function for preg_replace_callback
  3573. * Uses capture group 1 in the supplied array
  3574. * Does basic checks to keep characters inside a viewable range.
  3575. *
  3576. * @param array $matches
  3577. * @return string $string
  3578. */
  3579. function fixchar__callback($matches)
  3580. {
  3581. if (!isset($matches[1]))
  3582. return '';
  3583. $num = $matches[1][0] === 'x' ? hexdec(substr($matches[1], 1)) : (int) $matches[1];
  3584. // <0x20 are control characters, > 0x10FFFF is past the end of the utf8 character set
  3585. // 0xD800 >= $num <= 0xDFFF are surrogate markers (not valid for utf8 text), 0x202D-E are left to right overrides
  3586. if ($num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num === 0x202D || $num === 0x202E)
  3587. return '';
  3588. // <0x80 (or less than 128) are standard ascii characters a-z A-Z 0-9 and puncuation
  3589. elseif ($num < 0x80)
  3590. return chr($num);
  3591. // <0x800 (2048)
  3592. elseif ($num < 0x800)
  3593. return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
  3594. // < 0x10000 (65536)
  3595. elseif ($num < 0x10000)
  3596. return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  3597. // <= 0x10FFFF (1114111)
  3598. else
  3599. return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  3600. }
  3601. /**
  3602. * Strips out invalid html entities, replaces others with html style &#123; codes
  3603. *
  3604. * Callback function used of preg_replace_callback in smcFunc $ent_checks, for example
  3605. * strpos, strlen, substr etc
  3606. *
  3607. * @param array $matches
  3608. * @return string $string
  3609. */
  3610. function entity_fix__callback($matches)
  3611. {
  3612. if (!isset($matches[2]))
  3613. return '';
  3614. $num = $matches[2][0] === 'x' ? hexdec(substr($matches[2], 1)) : (int) $matches[2];
  3615. // we don't allow control characters, characters out of range, byte markers, etc
  3616. if ($num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num == 0x202D || $num == 0x202E)
  3617. return '';
  3618. else
  3619. return '&#' . $num . ';';
  3620. }