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

/forum/Sources/Subs.php

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