Advertisement
Guest User

Untitled

a guest
Aug 14th, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 213.08 KB | None | 0 0
  1. ILS DISENT QUE C'est a la ligne 1938
  2. <?php
  3. /**
  4. * MyBB 1.8
  5. * Copyright 2014 MyBB Group, All Rights Reserved
  6. *
  7. * Website: http://www.mybb.com
  8. * License: http://www.mybb.com/about/license
  9. *
  10. */
  11.  
  12. /**
  13. * Outputs a page directly to the browser, parsing anything which needs to be parsed.
  14. *
  15. * @param string $contents The contents of the page.
  16. */
  17. function output_page($contents)
  18. {
  19. global $db, $lang, $theme, $templates, $plugins, $mybb;
  20. global $debug, $templatecache, $templatelist, $maintimer, $globaltime, $parsetime;
  21.  
  22. $contents = parse_page($contents);
  23. $totaltime = format_time_duration($maintimer->stop());
  24. $contents = $plugins->run_hooks("pre_output_page", $contents);
  25.  
  26. if($mybb->usergroup['cancp'] == 1 || $mybb->dev_mode == 1)
  27. {
  28. if($mybb->settings['extraadmininfo'] != 0)
  29. {
  30. $phptime = $maintimer->totaltime - $db->query_time;
  31. $query_time = $db->query_time;
  32.  
  33. if($maintimer->totaltime > 0)
  34. {
  35. $percentphp = number_format((($phptime/$maintimer->totaltime) * 100), 2);
  36. $percentsql = number_format((($query_time/$maintimer->totaltime) * 100), 2);
  37. }
  38. else
  39. {
  40. // if we've got a super fast script... all we can do is assume something
  41. $percentphp = 0;
  42. $percentsql = 0;
  43. }
  44.  
  45. $serverload = get_server_load();
  46.  
  47. if(my_strpos(getenv("REQUEST_URI"), "?"))
  48. {
  49. $debuglink = htmlspecialchars_uni(getenv("REQUEST_URI")) . "&amp;debug=1";
  50. }
  51. else
  52. {
  53. $debuglink = htmlspecialchars_uni(getenv("REQUEST_URI")) . "?debug=1";
  54. }
  55.  
  56. $memory_usage = get_memory_usage();
  57.  
  58. if($memory_usage)
  59. {
  60. $memory_usage = $lang->sprintf($lang->debug_memory_usage, get_friendly_size($memory_usage));
  61. }
  62. else
  63. {
  64. $memory_usage = '';
  65. }
  66. // MySQLi is still MySQL, so present it that way to the user
  67. $database_server = $db->short_title;
  68.  
  69. if($database_server == 'MySQLi')
  70. {
  71. $database_server = 'MySQL';
  72. }
  73. $generated_in = $lang->sprintf($lang->debug_generated_in, $totaltime);
  74. $debug_weight = $lang->sprintf($lang->debug_weight, $percentphp, $percentsql, $database_server);
  75. $sql_queries = $lang->sprintf($lang->debug_sql_queries, $db->query_count);
  76. $server_load = $lang->sprintf($lang->debug_server_load, $serverload);
  77.  
  78. eval("\$debugstuff = \"".$templates->get("debug_summary")."\";");
  79. $contents = str_replace("<debugstuff>", $debugstuff, $contents);
  80. }
  81.  
  82. if($mybb->debug_mode == true)
  83. {
  84. debug_page();
  85. }
  86. }
  87.  
  88. $contents = str_replace("<debugstuff>", "", $contents);
  89.  
  90. if($mybb->settings['gzipoutput'] == 1)
  91. {
  92. $contents = gzip_encode($contents, $mybb->settings['gziplevel']);
  93. }
  94.  
  95. @header("Content-type: text/html; charset={$lang->settings['charset']}");
  96.  
  97. echo $contents;
  98.  
  99. $plugins->run_hooks("post_output_page");
  100. }
  101.  
  102. /**
  103. * Adds a function or class to the list of code to run on shutdown.
  104. *
  105. * @param string|array $name The name of the function.
  106. * @param mixed $arguments Either an array of arguments for the function or one argument
  107. * @return boolean True if function exists, otherwise false.
  108. */
  109. function add_shutdown($name, $arguments=array())
  110. {
  111. global $shutdown_functions;
  112.  
  113. if(!is_array($shutdown_functions))
  114. {
  115. $shutdown_functions = array();
  116. }
  117.  
  118. if(!is_array($arguments))
  119. {
  120. $arguments = array($arguments);
  121. }
  122.  
  123. if(is_array($name) && method_exists($name[0], $name[1]))
  124. {
  125. $shutdown_functions[] = array('function' => $name, 'arguments' => $arguments);
  126. return true;
  127. }
  128. else if(!is_array($name) && function_exists($name))
  129. {
  130. $shutdown_functions[] = array('function' => $name, 'arguments' => $arguments);
  131. return true;
  132. }
  133.  
  134. return false;
  135. }
  136.  
  137. /**
  138. * Runs the shutdown items after the page has been sent to the browser.
  139. *
  140. */
  141. function run_shutdown()
  142. {
  143. global $config, $db, $cache, $plugins, $error_handler, $shutdown_functions, $shutdown_queries, $done_shutdown, $mybb;
  144.  
  145. if($done_shutdown == true || !$config || (isset($error_handler) && $error_handler->has_errors))
  146. {
  147. return;
  148. }
  149.  
  150. if(empty($shutdown_queries) && empty($shutdown_functions))
  151. {
  152. // Nothing to do
  153. return;
  154. }
  155.  
  156. // Missing the core? Build
  157. if(!is_object($mybb))
  158. {
  159. require_once MYBB_ROOT."inc/class_core.php";
  160. $mybb = new MyBB;
  161.  
  162. // Load the settings
  163. require MYBB_ROOT."inc/settings.php";
  164. $mybb->settings = &$settings;
  165. }
  166.  
  167. // If our DB has been deconstructed already (bad PHP 5.2.0), reconstruct
  168. if(!is_object($db))
  169. {
  170. if(!isset($config) || empty($config['database']['type']))
  171. {
  172. require MYBB_ROOT."inc/config.php";
  173. }
  174.  
  175. if(isset($config))
  176. {
  177. // Load DB interface
  178. require_once MYBB_ROOT."inc/db_base.php";
  179.  
  180. require_once MYBB_ROOT."inc/db_".$config['database']['type'].".php";
  181. switch($config['database']['type'])
  182. {
  183. case "sqlite":
  184. $db = new DB_SQLite;
  185. break;
  186. case "pgsql":
  187. $db = new DB_PgSQL;
  188. break;
  189. case "mysqli":
  190. $db = new DB_MySQLi;
  191. break;
  192. default:
  193. $db = new DB_MySQL;
  194. }
  195.  
  196. $db->connect($config['database']);
  197. if(!defined("TABLE_PREFIX"))
  198. {
  199. define("TABLE_PREFIX", $config['database']['table_prefix']);
  200. }
  201. $db->set_table_prefix(TABLE_PREFIX);
  202. }
  203. }
  204.  
  205. // Cache object deconstructed? reconstruct
  206. if(!is_object($cache))
  207. {
  208. require_once MYBB_ROOT."inc/class_datacache.php";
  209. $cache = new datacache;
  210. $cache->cache();
  211. }
  212.  
  213. // And finally.. plugins
  214. if(!is_object($plugins) && !defined("NO_PLUGINS") && !($mybb->settings['no_plugins'] == 1))
  215. {
  216. require_once MYBB_ROOT."inc/class_plugins.php";
  217. $plugins = new pluginSystem;
  218. $plugins->load();
  219. }
  220.  
  221. // We have some shutdown queries needing to be run
  222. if(is_array($shutdown_queries))
  223. {
  224. // Loop through and run them all
  225. foreach($shutdown_queries as $query)
  226. {
  227. $db->query($query);
  228. }
  229. }
  230.  
  231. // Run any shutdown functions if we have them
  232. if(is_array($shutdown_functions))
  233. {
  234. foreach($shutdown_functions as $function)
  235. {
  236. call_user_func_array($function['function'], $function['arguments']);
  237. }
  238. }
  239.  
  240. $done_shutdown = true;
  241. }
  242.  
  243. /**
  244. * Sends a specified amount of messages from the mail queue
  245. *
  246. * @param int $count The number of messages to send (Defaults to 10)
  247. */
  248. function send_mail_queue($count=10)
  249. {
  250. global $db, $cache, $plugins;
  251.  
  252. $plugins->run_hooks("send_mail_queue_start");
  253.  
  254. // Check to see if the mail queue has messages needing to be sent
  255. $mailcache = $cache->read("mailqueue");
  256. if($mailcache['queue_size'] > 0 && ($mailcache['locked'] == 0 || $mailcache['locked'] < TIME_NOW-300))
  257. {
  258. // Lock the queue so no other messages can be sent whilst these are (for popular boards)
  259. $cache->update_mailqueue(0, TIME_NOW);
  260.  
  261. // Fetch emails for this page view - and send them
  262. $query = $db->simple_select("mailqueue", "*", "", array("order_by" => "mid", "order_dir" => "asc", "limit_start" => 0, "limit" => $count));
  263.  
  264. while($email = $db->fetch_array($query))
  265. {
  266. // Delete the message from the queue
  267. $db->delete_query("mailqueue", "mid='{$email['mid']}'");
  268.  
  269. if($db->affected_rows() == 1)
  270. {
  271. my_mail($email['mailto'], $email['subject'], $email['message'], $email['mailfrom'], "", $email['headers'], true);
  272. }
  273. }
  274. // Update the mailqueue cache and remove the lock
  275. $cache->update_mailqueue(TIME_NOW, 0);
  276. }
  277.  
  278. $plugins->run_hooks("send_mail_queue_end");
  279. }
  280.  
  281. /**
  282. * Parses the contents of a page before outputting it.
  283. *
  284. * @param string $contents The contents of the page.
  285. * @return string The parsed page.
  286. */
  287. function parse_page($contents)
  288. {
  289. global $lang, $theme, $mybb, $htmldoctype, $archive_url, $error_handler;
  290.  
  291. $contents = str_replace('<navigation>', build_breadcrumb(), $contents);
  292. $contents = str_replace('<archive_url>', $archive_url, $contents);
  293.  
  294. if($htmldoctype)
  295. {
  296. $contents = $htmldoctype.$contents;
  297. }
  298. else
  299. {
  300. $contents = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n".$contents;
  301. }
  302.  
  303. $contents = str_replace("<html", "<html xmlns=\"http://www.w3.org/1999/xhtml\"", $contents);
  304.  
  305. if($lang->settings['rtl'] == 1)
  306. {
  307. $contents = str_replace("<html", "<html dir=\"rtl\"", $contents);
  308. }
  309.  
  310. if($lang->settings['htmllang'])
  311. {
  312. $contents = str_replace("<html", "<html xml:lang=\"".$lang->settings['htmllang']."\" lang=\"".$lang->settings['htmllang']."\"", $contents);
  313. }
  314.  
  315. if($error_handler->warnings)
  316. {
  317. $contents = str_replace("<body>", "<body>\n".$error_handler->show_warnings(), $contents);
  318. }
  319.  
  320. return $contents;
  321. }
  322.  
  323. /**
  324. * Turn a unix timestamp in to a "friendly" date/time format for the user.
  325. *
  326. * @param string $format A date format (either relative, normal or PHP's date() structure).
  327. * @param int $stamp The unix timestamp the date should be generated for.
  328. * @param int|string $offset The offset in hours that should be applied to times. (timezones) Or an empty string to determine that automatically
  329. * @param int $ty Whether or not to use today/yesterday formatting.
  330. * @param boolean $adodb Whether or not to use the adodb time class for < 1970 or > 2038 times
  331. * @return string The formatted timestamp.
  332. */
  333. function my_date($format, $stamp=0, $offset="", $ty=1, $adodb=false)
  334. {
  335. global $mybb, $lang, $mybbadmin, $plugins;
  336.  
  337. // If the stamp isn't set, use TIME_NOW
  338. if(empty($stamp))
  339. {
  340. $stamp = TIME_NOW;
  341. }
  342.  
  343. if(!$offset && $offset != '0')
  344. {
  345. if(isset($mybb->user['uid']) && $mybb->user['uid'] != 0 && array_key_exists("timezone", $mybb->user))
  346. {
  347. $offset = (float)$mybb->user['timezone'];
  348. $dstcorrection = $mybb->user['dst'];
  349. }
  350. elseif(defined("IN_ADMINCP"))
  351. {
  352. $offset = (float)$mybbadmin['timezone'];
  353. $dstcorrection = $mybbadmin['dst'];
  354. }
  355. else
  356. {
  357. $offset = (float)$mybb->settings['timezoneoffset'];
  358. $dstcorrection = $mybb->settings['dstcorrection'];
  359. }
  360.  
  361. // If DST correction is enabled, add an additional hour to the timezone.
  362. if($dstcorrection == 1)
  363. {
  364. ++$offset;
  365. if(my_substr($offset, 0, 1) != "-")
  366. {
  367. $offset = "+".$offset;
  368. }
  369. }
  370. }
  371.  
  372. if($offset == "-")
  373. {
  374. $offset = 0;
  375. }
  376.  
  377. // Using ADOdb?
  378. if($adodb == true && !function_exists('adodb_date'))
  379. {
  380. $adodb = false;
  381. }
  382.  
  383. $todaysdate = $yesterdaysdate = '';
  384. if($ty && ($format == $mybb->settings['dateformat'] || $format == 'relative' || $format == 'normal'))
  385. {
  386. $_stamp = TIME_NOW;
  387. if($adodb == true)
  388. {
  389. $date = adodb_date($mybb->settings['dateformat'], $stamp + ($offset * 3600));
  390. $todaysdate = adodb_date($mybb->settings['dateformat'], $_stamp + ($offset * 3600));
  391. $yesterdaysdate = adodb_date($mybb->settings['dateformat'], ($_stamp - 86400) + ($offset * 3600));
  392. }
  393. else
  394. {
  395. $date = gmdate($mybb->settings['dateformat'], $stamp + ($offset * 3600));
  396. $todaysdate = gmdate($mybb->settings['dateformat'], $_stamp + ($offset * 3600));
  397. $yesterdaysdate = gmdate($mybb->settings['dateformat'], ($_stamp - 86400) + ($offset * 3600));
  398. }
  399. }
  400.  
  401. if($format == 'relative')
  402. {
  403. // Relative formats both date and time
  404. $real_date = $real_time = '';
  405. if($adodb == true)
  406. {
  407. $real_date = adodb_date($mybb->settings['dateformat'], $stamp + ($offset * 3600));
  408. $real_time = $mybb->settings['datetimesep'];
  409. $real_time .= adodb_date($mybb->settings['timeformat'], $stamp + ($offset * 3600));
  410. }
  411. else
  412. {
  413. $real_date = gmdate($mybb->settings['dateformat'], $stamp + ($offset * 3600));
  414. $real_time = $mybb->settings['datetimesep'];
  415. $real_time .= gmdate($mybb->settings['timeformat'], $stamp + ($offset * 3600));
  416. }
  417.  
  418. if($ty != 2 && abs(TIME_NOW - $stamp) < 3600)
  419. {
  420. $diff = TIME_NOW - $stamp;
  421. $relative = array('prefix' => '', 'minute' => 0, 'plural' => $lang->rel_minutes_plural, 'suffix' => $lang->rel_ago);
  422.  
  423. if($diff < 0)
  424. {
  425. $diff = abs($diff);
  426. $relative['suffix'] = '';
  427. $relative['prefix'] = $lang->rel_in;
  428. }
  429.  
  430. $relative['minute'] = floor($diff / 60);
  431.  
  432. if($relative['minute'] <= 1)
  433. {
  434. $relative['minute'] = 1;
  435. $relative['plural'] = $lang->rel_minutes_single;
  436. }
  437.  
  438. if($diff <= 60)
  439. {
  440. // Less than a minute
  441. $relative['prefix'] = $lang->rel_less_than;
  442. }
  443.  
  444. $date = $lang->sprintf($lang->rel_time, $relative['prefix'], $relative['minute'], $relative['plural'], $relative['suffix'], $real_date, $real_time);
  445. }
  446. elseif($ty != 2 && abs(TIME_NOW - $stamp) < 43200)
  447. {
  448. $diff = TIME_NOW - $stamp;
  449. $relative = array('prefix' => '', 'hour' => 0, 'plural' => $lang->rel_hours_plural, 'suffix' => $lang->rel_ago);
  450.  
  451. if($diff < 0)
  452. {
  453. $diff = abs($diff);
  454. $relative['suffix'] = '';
  455. $relative['prefix'] = $lang->rel_in;
  456. }
  457.  
  458. $relative['hour'] = floor($diff / 3600);
  459.  
  460. if($relative['hour'] <= 1)
  461. {
  462. $relative['hour'] = 1;
  463. $relative['plural'] = $lang->rel_hours_single;
  464. }
  465.  
  466. $date = $lang->sprintf($lang->rel_time, $relative['prefix'], $relative['hour'], $relative['plural'], $relative['suffix'], $real_date, $real_time);
  467. }
  468. else
  469. {
  470. if($ty)
  471. {
  472. if($todaysdate == $date)
  473. {
  474. $date = $lang->sprintf($lang->today_rel, $real_date);
  475. }
  476. else if($yesterdaysdate == $date)
  477. {
  478. $date = $lang->sprintf($lang->yesterday_rel, $real_date);
  479. }
  480. }
  481.  
  482. $date .= $mybb->settings['datetimesep'];
  483. if($adodb == true)
  484. {
  485. $date .= adodb_date($mybb->settings['timeformat'], $stamp + ($offset * 3600));
  486. }
  487. else
  488. {
  489. $date .= gmdate($mybb->settings['timeformat'], $stamp + ($offset * 3600));
  490. }
  491. }
  492. }
  493. elseif($format == 'normal')
  494. {
  495. // Normal format both date and time
  496. if($ty != 2)
  497. {
  498. if($todaysdate == $date)
  499. {
  500. $date = $lang->today;
  501. }
  502. else if($yesterdaysdate == $date)
  503. {
  504. $date = $lang->yesterday;
  505. }
  506. }
  507.  
  508. $date .= $mybb->settings['datetimesep'];
  509. if($adodb == true)
  510. {
  511. $date .= adodb_date($mybb->settings['timeformat'], $stamp + ($offset * 3600));
  512. }
  513. else
  514. {
  515. $date .= gmdate($mybb->settings['timeformat'], $stamp + ($offset * 3600));
  516. }
  517. }
  518. else
  519. {
  520. if($ty && $format == $mybb->settings['dateformat'])
  521. {
  522. if($todaysdate == $date)
  523. {
  524. $date = $lang->today;
  525. }
  526. else if($yesterdaysdate == $date)
  527. {
  528. $date = $lang->yesterday;
  529. }
  530. }
  531. else
  532. {
  533. if($adodb == true)
  534. {
  535. $date = adodb_date($format, $stamp + ($offset * 3600));
  536. }
  537. else
  538. {
  539. $date = gmdate($format, $stamp + ($offset * 3600));
  540. }
  541. }
  542. }
  543.  
  544. if(is_object($plugins))
  545. {
  546. $date = $plugins->run_hooks("my_date", $date);
  547. }
  548.  
  549. return $date;
  550. }
  551.  
  552. /**
  553. * Sends an email using PHP's mail function, formatting it appropriately.
  554. *
  555. * @param string $to Address the email should be addressed to.
  556. * @param string $subject The subject of the email being sent.
  557. * @param string $message The message being sent.
  558. * @param string $from The from address of the email, if blank, the board name will be used.
  559. * @param string $charset The chracter set being used to send this email.
  560. * @param string $headers
  561. * @param boolean $keep_alive Do we wish to keep the connection to the mail server alive to send more than one message (SMTP only)
  562. * @param string $format The format of the email to be sent (text or html). text is default
  563. * @param string $message_text The text message of the email if being sent in html format, for email clients that don't support html
  564. * @param string $return_email The email address to return to. Defaults to admin return email address.
  565. * @return bool
  566. */
  567. function my_mail($to, $subject, $message, $from="", $charset="", $headers="", $keep_alive=false, $format="text", $message_text="", $return_email="")
  568. {
  569. global $mybb;
  570. static $mail;
  571.  
  572. // Does our object not exist? Create it
  573. if(!is_object($mail))
  574. {
  575. require_once MYBB_ROOT."inc/class_mailhandler.php";
  576.  
  577. if($mybb->settings['mail_handler'] == 'smtp')
  578. {
  579. require_once MYBB_ROOT."inc/mailhandlers/smtp.php";
  580. $mail = new SmtpMail();
  581. }
  582. else
  583. {
  584. require_once MYBB_ROOT."inc/mailhandlers/php.php";
  585. $mail = new PhpMail();
  586. }
  587. }
  588.  
  589. // Using SMTP based mail
  590. if($mybb->settings['mail_handler'] == 'smtp')
  591. {
  592. if($keep_alive == true)
  593. {
  594. $mail->keep_alive = true;
  595. }
  596. }
  597.  
  598. // Using PHP based mail()
  599. else
  600. {
  601. if($mybb->settings['mail_parameters'] != '')
  602. {
  603. $mail->additional_parameters = $mybb->settings['mail_parameters'];
  604. }
  605. }
  606.  
  607. // Build and send
  608. $mail->build_message($to, $subject, $message, $from, $charset, $headers, $format, $message_text, $return_email);
  609. return $mail->send();
  610. }
  611.  
  612. /**
  613. * Generates a unique code for POST requests to prevent XSS/CSRF attacks
  614. *
  615. * @return string The generated code
  616. */
  617. function generate_post_check()
  618. {
  619. global $mybb, $session;
  620. if($mybb->user['uid'])
  621. {
  622. return md5($mybb->user['loginkey'].$mybb->user['salt'].$mybb->user['regdate']);
  623. }
  624. // Guests get a special string
  625. else
  626. {
  627. return md5($session->useragent.$mybb->config['database']['username'].$mybb->settings['internal']['encryption_key']);
  628. }
  629. }
  630.  
  631. /**
  632. * Verifies a POST check code is valid, if not shows an error (silently returns false on silent parameter)
  633. *
  634. * @param string $code The incoming POST check code
  635. * @param boolean $silent Silent mode or not (silent mode will not show the error to the user but returns false)
  636. * @return bool
  637. */
  638. function verify_post_check($code, $silent=false)
  639. {
  640. global $lang;
  641. if(generate_post_check() !== $code)
  642. {
  643. if($silent == true)
  644. {
  645. return false;
  646. }
  647. else
  648. {
  649. if(defined("IN_ADMINCP"))
  650. {
  651. return false;
  652. }
  653. else
  654. {
  655. error($lang->invalid_post_code);
  656. }
  657. }
  658. }
  659. else
  660. {
  661. return true;
  662. }
  663. }
  664.  
  665. /**
  666. * Return a parent list for the specified forum.
  667. *
  668. * @param int $fid The forum id to get the parent list for.
  669. * @return string The comma-separated parent list.
  670. */
  671. function get_parent_list($fid)
  672. {
  673. global $forum_cache;
  674. static $forumarraycache;
  675.  
  676. if($forumarraycache[$fid])
  677. {
  678. return $forumarraycache[$fid]['parentlist'];
  679. }
  680. elseif($forum_cache[$fid])
  681. {
  682. return $forum_cache[$fid]['parentlist'];
  683. }
  684. else
  685. {
  686. cache_forums();
  687. return $forum_cache[$fid]['parentlist'];
  688. }
  689. }
  690.  
  691. /**
  692. * Build a parent list of a specific forum, suitable for querying
  693. *
  694. * @param int $fid The forum ID
  695. * @param string $column The column name to add to the query
  696. * @param string $joiner The joiner for each forum for querying (OR | AND | etc)
  697. * @param string $parentlist The parent list of the forum - if you have it
  698. * @return string The query string generated
  699. */
  700. function build_parent_list($fid, $column="fid", $joiner="OR", $parentlist="")
  701. {
  702. if(!$parentlist)
  703. {
  704. $parentlist = get_parent_list($fid);
  705. }
  706.  
  707. $parentsexploded = explode(",", $parentlist);
  708. $builtlist = "(";
  709. $sep = '';
  710.  
  711. foreach($parentsexploded as $key => $val)
  712. {
  713. $builtlist .= "$sep$column='$val'";
  714. $sep = " $joiner ";
  715. }
  716.  
  717. $builtlist .= ")";
  718.  
  719. return $builtlist;
  720. }
  721.  
  722. /**
  723. * Load the forum cache in to memory
  724. *
  725. * @param boolean $force True to force a reload of the cache
  726. * @return array The forum cache
  727. */
  728. function cache_forums($force=false)
  729. {
  730. global $forum_cache, $cache;
  731.  
  732. if($force == true)
  733. {
  734. $forum_cache = $cache->read("forums", 1);
  735. return $forum_cache;
  736. }
  737.  
  738. if(!$forum_cache)
  739. {
  740. $forum_cache = $cache->read("forums");
  741. if(!$forum_cache)
  742. {
  743. $cache->update_forums();
  744. $forum_cache = $cache->read("forums", 1);
  745. }
  746. }
  747. return $forum_cache;
  748. }
  749.  
  750. /**
  751. * Generate an array of all child and descendant forums for a specific forum.
  752. *
  753. * @param int $fid The forum ID
  754. * @return Array of descendants
  755. */
  756. function get_child_list($fid)
  757. {
  758. static $forums_by_parent;
  759.  
  760. $forums = array();
  761. if(!is_array($forums_by_parent))
  762. {
  763. $forum_cache = cache_forums();
  764. foreach($forum_cache as $forum)
  765. {
  766. if($forum['active'] != 0)
  767. {
  768. $forums_by_parent[$forum['pid']][$forum['fid']] = $forum;
  769. }
  770. }
  771. }
  772. if(!is_array($forums_by_parent[$fid]))
  773. {
  774. return $forums;
  775. }
  776.  
  777. foreach($forums_by_parent[$fid] as $forum)
  778. {
  779. $forums[] = $forum['fid'];
  780. $children = get_child_list($forum['fid']);
  781. if(is_array($children))
  782. {
  783. $forums = array_merge($forums, $children);
  784. }
  785. }
  786. return $forums;
  787. }
  788.  
  789. /**
  790. * Produce a friendly error message page
  791. *
  792. * @param string $error The error message to be shown
  793. * @param string $title The title of the message shown in the title of the page and the error table
  794. */
  795. function error($error="", $title="")
  796. {
  797. global $header, $footer, $theme, $headerinclude, $db, $templates, $lang, $mybb, $plugins;
  798.  
  799. $error = $plugins->run_hooks("error", $error);
  800. if(!$error)
  801. {
  802. $error = $lang->unknown_error;
  803. }
  804.  
  805. // AJAX error message?
  806. if($mybb->get_input('ajax', MyBB::INPUT_INT))
  807. {
  808. // Send our headers.
  809. @header("Content-type: application/json; charset={$lang->settings['charset']}");
  810. echo json_encode(array("errors" => array($error)));
  811. exit;
  812. }
  813.  
  814. if(!$title)
  815. {
  816. $title = $mybb->settings['bbname'];
  817. }
  818.  
  819. $timenow = my_date('relative', TIME_NOW);
  820. reset_breadcrumb();
  821. add_breadcrumb($lang->error);
  822.  
  823. eval("\$errorpage = \"".$templates->get("error")."\";");
  824. output_page($errorpage);
  825.  
  826. exit;
  827. }
  828.  
  829. /**
  830. * Produce an error message for displaying inline on a page
  831. *
  832. * @param array $errors Array of errors to be shown
  833. * @param string $title The title of the error message
  834. * @param array $json_data JSON data to be encoded (we may want to send more data; e.g. newreply.php uses this for CAPTCHA)
  835. * @return string The inline error HTML
  836. */
  837. function inline_error($errors, $title="", $json_data=array())
  838. {
  839. global $theme, $mybb, $db, $lang, $templates;
  840.  
  841. if(!$title)
  842. {
  843. $title = $lang->please_correct_errors;
  844. }
  845.  
  846. if(!is_array($errors))
  847. {
  848. $errors = array($errors);
  849. }
  850.  
  851. // AJAX error message?
  852. if($mybb->get_input('ajax', MyBB::INPUT_INT))
  853. {
  854. // Send our headers.
  855. @header("Content-type: application/json; charset={$lang->settings['charset']}");
  856.  
  857. if(empty($json_data))
  858. {
  859. echo json_encode(array("errors" => $errors));
  860. }
  861. else
  862. {
  863. echo json_encode(array_merge(array("errors" => $errors), $json_data));
  864. }
  865. exit;
  866. }
  867.  
  868. $errorlist = '';
  869.  
  870. foreach($errors as $error)
  871. {
  872. $errorlist .= "<li>".$error."</li>\n";
  873. }
  874.  
  875. eval("\$errors = \"".$templates->get("error_inline")."\";");
  876.  
  877. return $errors;
  878. }
  879.  
  880. /**
  881. * Presents the user with a "no permission" page
  882. */
  883. function error_no_permission()
  884. {
  885. global $mybb, $theme, $templates, $db, $lang, $plugins, $session;
  886.  
  887. $time = TIME_NOW;
  888. $plugins->run_hooks("no_permission");
  889.  
  890. $noperm_array = array (
  891. "nopermission" => '1',
  892. "location1" => 0,
  893. "location2" => 0
  894. );
  895.  
  896. $db->update_query("sessions", $noperm_array, "sid='{$session->sid}'");
  897.  
  898. if($mybb->get_input('ajax', MyBB::INPUT_INT))
  899. {
  900. // Send our headers.
  901. header("Content-type: application/json; charset={$lang->settings['charset']}");
  902. echo json_encode(array("errors" => array($lang->error_nopermission_user_ajax)));
  903. exit;
  904. }
  905.  
  906. if($mybb->user['uid'])
  907. {
  908. $lang->error_nopermission_user_username = $lang->sprintf($lang->error_nopermission_user_username, htmlspecialchars_uni($mybb->user['username']));
  909. eval("\$errorpage = \"".$templates->get("error_nopermission_loggedin")."\";");
  910. }
  911. else
  912. {
  913. // Redirect to where the user came from
  914. $redirect_url = $_SERVER['PHP_SELF'];
  915. if($_SERVER['QUERY_STRING'])
  916. {
  917. $redirect_url .= '?'.$_SERVER['QUERY_STRING'];
  918. }
  919.  
  920. $redirect_url = htmlspecialchars_uni($redirect_url);
  921.  
  922. switch($mybb->settings['username_method'])
  923. {
  924. case 0:
  925. $lang_username = $lang->username;
  926. break;
  927. case 1:
  928. $lang_username = $lang->username1;
  929. break;
  930. case 2:
  931. $lang_username = $lang->username2;
  932. break;
  933. default:
  934. $lang_username = $lang->username;
  935. break;
  936. }
  937. eval("\$errorpage = \"".$templates->get("error_nopermission")."\";");
  938. }
  939.  
  940. error($errorpage);
  941. }
  942.  
  943. /**
  944. * Redirect the user to a given URL with a given message
  945. *
  946. * @param string $url The URL to redirect the user to
  947. * @param string $message The redirection message to be shown
  948. * @param string $title The title of the redirection page
  949. * @param boolean $force_redirect Force the redirect page regardless of settings
  950. */
  951. function redirect($url, $message="", $title="", $force_redirect=false)
  952. {
  953. global $header, $footer, $mybb, $theme, $headerinclude, $templates, $lang, $plugins;
  954.  
  955. $redirect_args = array('url' => &$url, 'message' => &$message, 'title' => &$title);
  956.  
  957. $plugins->run_hooks("redirect", $redirect_args);
  958.  
  959. if($mybb->get_input('ajax', MyBB::INPUT_INT))
  960. {
  961. // Send our headers.
  962. //@header("Content-type: text/html; charset={$lang->settings['charset']}");
  963. $data = "<script type=\"text/javascript\">\n";
  964. if($message != "")
  965. {
  966. $data .= 'alert("'.addslashes($message).'");';
  967. }
  968. $url = str_replace("#", "&#", $url);
  969. $url = htmlspecialchars_decode($url);
  970. $url = str_replace(array("\n","\r",";"), "", $url);
  971. $data .= 'window.location = "'.addslashes($url).'";'."\n";
  972. $data .= "</script>\n";
  973. //exit;
  974.  
  975. @header("Content-type: application/json; charset={$lang->settings['charset']}");
  976. echo json_encode(array("data" => $data));
  977. exit;
  978. }
  979.  
  980. if(!$message)
  981. {
  982. $message = $lang->redirect;
  983. }
  984.  
  985. $time = TIME_NOW;
  986. $timenow = my_date('relative', $time);
  987.  
  988. if(!$title)
  989. {
  990. $title = $mybb->settings['bbname'];
  991. }
  992.  
  993. // Show redirects only if both ACP and UCP settings are enabled, or ACP is enabled, and user is a guest, or they are forced.
  994. if($force_redirect == true || ($mybb->settings['redirects'] == 1 && ($mybb->user['showredirect'] == 1 || !$mybb->user['uid'])))
  995. {
  996. $url = str_replace("&amp;", "&", $url);
  997. $url = htmlspecialchars_uni($url);
  998.  
  999. eval("\$redirectpage = \"".$templates->get("redirect")."\";");
  1000. output_page($redirectpage);
  1001. }
  1002. else
  1003. {
  1004. $url = htmlspecialchars_decode($url);
  1005. $url = str_replace(array("\n","\r",";"), "", $url);
  1006.  
  1007. run_shutdown();
  1008.  
  1009. if(!my_validate_url($url, true, true))
  1010. {
  1011. header("Location: {$mybb->settings['bburl']}/{$url}");
  1012. }
  1013. else
  1014. {
  1015. header("Location: {$url}");
  1016. }
  1017. }
  1018.  
  1019. exit;
  1020. }
  1021.  
  1022. /**
  1023. * Generate a listing of page - pagination
  1024. *
  1025. * @param int $count The number of items
  1026. * @param int $perpage The number of items to be shown per page
  1027. * @param int $page The current page number
  1028. * @param string $url The URL to have page numbers tacked on to (If {page} is specified, the value will be replaced with the page #)
  1029. * @param boolean $breadcrumb Whether or not the multipage is being shown in the navigation breadcrumb
  1030. * @return string The generated pagination
  1031. */
  1032. function multipage($count, $perpage, $page, $url, $breadcrumb=false)
  1033. {
  1034. global $theme, $templates, $lang, $mybb;
  1035.  
  1036. if($count <= $perpage)
  1037. {
  1038. return '';
  1039. }
  1040.  
  1041. $page = (int)$page;
  1042.  
  1043. $url = str_replace("&amp;", "&", $url);
  1044. $url = htmlspecialchars_uni($url);
  1045.  
  1046. $pages = ceil($count / $perpage);
  1047.  
  1048. $prevpage = '';
  1049. if($page > 1)
  1050. {
  1051. $prev = $page-1;
  1052. $page_url = fetch_page_url($url, $prev);
  1053. eval("\$prevpage = \"".$templates->get("multipage_prevpage")."\";");
  1054. }
  1055.  
  1056. // Maximum number of "page bits" to show
  1057. if(!$mybb->settings['maxmultipagelinks'])
  1058. {
  1059. $mybb->settings['maxmultipagelinks'] = 5;
  1060. }
  1061.  
  1062. $from = $page-floor($mybb->settings['maxmultipagelinks']/2);
  1063. $to = $page+floor($mybb->settings['maxmultipagelinks']/2);
  1064.  
  1065. if($from <= 0)
  1066. {
  1067. $from = 1;
  1068. $to = $from+$mybb->settings['maxmultipagelinks']-1;
  1069. }
  1070.  
  1071. if($to > $pages)
  1072. {
  1073. $to = $pages;
  1074. $from = $pages-$mybb->settings['maxmultipagelinks']+1;
  1075. if($from <= 0)
  1076. {
  1077. $from = 1;
  1078. }
  1079. }
  1080.  
  1081. if($to == 0)
  1082. {
  1083. $to = $pages;
  1084. }
  1085.  
  1086. $start = '';
  1087. if($from > 1)
  1088. {
  1089. if($from-1 == 1)
  1090. {
  1091. $lang->multipage_link_start = '';
  1092. }
  1093.  
  1094. $page_url = fetch_page_url($url, 1);
  1095. eval("\$start = \"".$templates->get("multipage_start")."\";");
  1096. }
  1097.  
  1098. $mppage = '';
  1099. for($i = $from; $i <= $to; ++$i)
  1100. {
  1101. $page_url = fetch_page_url($url, $i);
  1102. if($page == $i)
  1103. {
  1104. if($breadcrumb == true)
  1105. {
  1106. eval("\$mppage .= \"".$templates->get("multipage_page_link_current")."\";");
  1107. }
  1108. else
  1109. {
  1110. eval("\$mppage .= \"".$templates->get("multipage_page_current")."\";");
  1111. }
  1112. }
  1113. else
  1114. {
  1115. eval("\$mppage .= \"".$templates->get("multipage_page")."\";");
  1116. }
  1117. }
  1118.  
  1119. $end = '';
  1120. if($to < $pages)
  1121. {
  1122. if($to+1 == $pages)
  1123. {
  1124. $lang->multipage_link_end = '';
  1125. }
  1126.  
  1127. $page_url = fetch_page_url($url, $pages);
  1128. eval("\$end = \"".$templates->get("multipage_end")."\";");
  1129. }
  1130.  
  1131. $nextpage = '';
  1132. if($page < $pages)
  1133. {
  1134. $next = $page+1;
  1135. $page_url = fetch_page_url($url, $next);
  1136. eval("\$nextpage = \"".$templates->get("multipage_nextpage")."\";");
  1137. }
  1138.  
  1139. $jumptopage = '';
  1140. if($pages > ($mybb->settings['maxmultipagelinks']+1) && $mybb->settings['jumptopagemultipage'] == 1)
  1141. {
  1142. // When the second parameter is set to 1, fetch_page_url thinks it's the first page and removes it from the URL as it's unnecessary
  1143. $jump_url = fetch_page_url($url, 1);
  1144. eval("\$jumptopage = \"".$templates->get("multipage_jump_page")."\";");
  1145. }
  1146.  
  1147. $multipage_pages = $lang->sprintf($lang->multipage_pages, $pages);
  1148.  
  1149. if($breadcrumb == true)
  1150. {
  1151. eval("\$multipage = \"".$templates->get("multipage_breadcrumb")."\";");
  1152. }
  1153. else
  1154. {
  1155. eval("\$multipage = \"".$templates->get("multipage")."\";");
  1156. }
  1157.  
  1158. return $multipage;
  1159. }
  1160.  
  1161. /**
  1162. * Generate a page URL for use by the multipage function
  1163. *
  1164. * @param string $url The URL being passed
  1165. * @param int $page The page number
  1166. * @return string
  1167. */
  1168. function fetch_page_url($url, $page)
  1169. {
  1170. if($page <= 1)
  1171. {
  1172. $find = array(
  1173. "-page-{page}",
  1174. "&amp;page={page}",
  1175. "{page}"
  1176. );
  1177.  
  1178. // Remove "Page 1" to the defacto URL
  1179. $url = str_replace($find, array("", "", $page), $url);
  1180. return $url;
  1181. }
  1182. else if(strpos($url, "{page}") === false)
  1183. {
  1184. // If no page identifier is specified we tack it on to the end of the URL
  1185. if(strpos($url, "?") === false)
  1186. {
  1187. $url .= "?";
  1188. }
  1189. else
  1190. {
  1191. $url .= "&amp;";
  1192. }
  1193.  
  1194. $url .= "page=$page";
  1195. }
  1196. else
  1197. {
  1198. $url = str_replace("{page}", $page, $url);
  1199. }
  1200.  
  1201. return $url;
  1202. }
  1203.  
  1204. /**
  1205. * Fetch the permissions for a specific user
  1206. *
  1207. * @param int $uid The user ID, if no user ID is provided then current user's ID will be considered.
  1208. * @return array Array of user permissions for the specified user
  1209. */
  1210. function user_permissions($uid=null)
  1211. {
  1212. global $mybb, $cache, $groupscache, $user_cache;
  1213.  
  1214. // If no user id is specified, assume it is the current user
  1215. if($uid === null)
  1216. {
  1217. $uid = $mybb->user['uid'];
  1218. }
  1219.  
  1220. // Its a guest. Return the group permissions directly from cache
  1221. if($uid == 0)
  1222. {
  1223. return $groupscache[1];
  1224. }
  1225.  
  1226. // User id does not match current user, fetch permissions
  1227. if($uid != $mybb->user['uid'])
  1228. {
  1229. // We've already cached permissions for this user, return them.
  1230. if(!empty($user_cache[$uid]['permissions']))
  1231. {
  1232. return $user_cache[$uid]['permissions'];
  1233. }
  1234.  
  1235. // This user was not already cached, fetch their user information.
  1236. if(empty($user_cache[$uid]))
  1237. {
  1238. $user_cache[$uid] = get_user($uid);
  1239. }
  1240.  
  1241. // Collect group permissions.
  1242. $gid = $user_cache[$uid]['usergroup'].",".$user_cache[$uid]['additionalgroups'];
  1243. $groupperms = usergroup_permissions($gid);
  1244.  
  1245. // Store group permissions in user cache.
  1246. $user_cache[$uid]['permissions'] = $groupperms;
  1247. return $groupperms;
  1248. }
  1249. // This user is the current user, return their permissions
  1250. else
  1251. {
  1252. return $mybb->usergroup;
  1253. }
  1254. }
  1255.  
  1256. /**
  1257. * Fetch the usergroup permissions for a specific group or series of groups combined
  1258. *
  1259. * @param int|string $gid A list of groups (Can be a single integer, or a list of groups separated by a comma)
  1260. * @return array Array of permissions generated for the groups, containing also a list of comma-separated checked groups under 'all_usergroups' index
  1261. */
  1262. function usergroup_permissions($gid=0)
  1263. {
  1264. global $cache, $groupscache, $grouppermignore, $groupzerogreater;
  1265.  
  1266. if(!is_array($groupscache))
  1267. {
  1268. $groupscache = $cache->read("usergroups");
  1269. }
  1270.  
  1271. $groups = explode(",", $gid);
  1272.  
  1273. if(count($groups) == 1)
  1274. {
  1275. $groupscache[$gid]['all_usergroups'] = $gid;
  1276. return $groupscache[$gid];
  1277. }
  1278.  
  1279. $usergroup = array();
  1280. $usergroup['all_usergroups'] = $gid;
  1281.  
  1282. foreach($groups as $gid)
  1283. {
  1284. if(trim($gid) == "" || empty($groupscache[$gid]))
  1285. {
  1286. continue;
  1287. }
  1288.  
  1289. foreach($groupscache[$gid] as $perm => $access)
  1290. {
  1291. if(!in_array($perm, $grouppermignore))
  1292. {
  1293. if(isset($usergroup[$perm]))
  1294. {
  1295. $permbit = $usergroup[$perm];
  1296. }
  1297. else
  1298. {
  1299. $permbit = "";
  1300. }
  1301.  
  1302. // 0 represents unlimited for numerical group permissions (i.e. private message limit) so take that into account.
  1303. if(in_array($perm, $groupzerogreater) && ($access == 0 || $permbit === 0))
  1304. {
  1305. $usergroup[$perm] = 0;
  1306. continue;
  1307. }
  1308.  
  1309. if($access > $permbit || ($access == "yes" && $permbit == "no") || !$permbit) // Keep yes/no for compatibility?
  1310. {
  1311. $usergroup[$perm] = $access;
  1312. }
  1313. }
  1314. }
  1315. }
  1316.  
  1317. return $usergroup;
  1318. }
  1319.  
  1320. /**
  1321. * Fetch the display group properties for a specific display group
  1322. *
  1323. * @param int $gid The group ID to fetch the display properties for
  1324. * @return array Array of display properties for the group
  1325. */
  1326. function usergroup_displaygroup($gid)
  1327. {
  1328. global $cache, $groupscache, $displaygroupfields;
  1329.  
  1330. if(!is_array($groupscache))
  1331. {
  1332. $groupscache = $cache->read("usergroups");
  1333. }
  1334.  
  1335. $displaygroup = array();
  1336. $group = $groupscache[$gid];
  1337.  
  1338. foreach($displaygroupfields as $field)
  1339. {
  1340. $displaygroup[$field] = $group[$field];
  1341. }
  1342.  
  1343. return $displaygroup;
  1344. }
  1345.  
  1346. /**
  1347. * Build the forum permissions for a specific forum, user or group
  1348. *
  1349. * @param int $fid The forum ID to build permissions for (0 builds for all forums)
  1350. * @param int $uid The user to build the permissions for (0 will select the uid automatically)
  1351. * @param int $gid The group of the user to build permissions for (0 will fetch it)
  1352. * @return array Forum permissions for the specific forum or forums
  1353. */
  1354. function forum_permissions($fid=0, $uid=0, $gid=0)
  1355. {
  1356. global $db, $cache, $groupscache, $forum_cache, $fpermcache, $mybb, $cached_forum_permissions_permissions, $cached_forum_permissions;
  1357.  
  1358. if($uid == 0)
  1359. {
  1360. $uid = $mybb->user['uid'];
  1361. }
  1362.  
  1363. if(!$gid || $gid == 0) // If no group, we need to fetch it
  1364. {
  1365. if($uid != 0 && $uid != $mybb->user['uid'])
  1366. {
  1367. $user = get_user($uid);
  1368.  
  1369. $gid = $user['usergroup'].",".$user['additionalgroups'];
  1370. $groupperms = usergroup_permissions($gid);
  1371. }
  1372. else
  1373. {
  1374. $gid = $mybb->user['usergroup'];
  1375.  
  1376. if(isset($mybb->user['additionalgroups']))
  1377. {
  1378. $gid .= ",".$mybb->user['additionalgroups'];
  1379. }
  1380.  
  1381. $groupperms = $mybb->usergroup;
  1382. }
  1383. }
  1384.  
  1385. if(!is_array($forum_cache))
  1386. {
  1387. $forum_cache = cache_forums();
  1388.  
  1389. if(!$forum_cache)
  1390. {
  1391. return false;
  1392. }
  1393. }
  1394.  
  1395. if(!is_array($fpermcache))
  1396. {
  1397. $fpermcache = $cache->read("forumpermissions");
  1398. }
  1399.  
  1400. if($fid) // Fetch the permissions for a single forum
  1401. {
  1402. if(empty($cached_forum_permissions_permissions[$gid][$fid]))
  1403. {
  1404. $cached_forum_permissions_permissions[$gid][$fid] = fetch_forum_permissions($fid, $gid, $groupperms);
  1405. }
  1406. return $cached_forum_permissions_permissions[$gid][$fid];
  1407. }
  1408. else
  1409. {
  1410. if(empty($cached_forum_permissions[$gid]))
  1411. {
  1412. foreach($forum_cache as $forum)
  1413. {
  1414. $cached_forum_permissions[$gid][$forum['fid']] = fetch_forum_permissions($forum['fid'], $gid, $groupperms);
  1415. }
  1416. }
  1417. return $cached_forum_permissions[$gid];
  1418. }
  1419. }
  1420.  
  1421. /**
  1422. * Fetches the permissions for a specific forum/group applying the inheritance scheme.
  1423. * Called by forum_permissions()
  1424. *
  1425. * @param int $fid The forum ID
  1426. * @param string $gid A comma separated list of usergroups
  1427. * @param array $groupperms Group permissions
  1428. * @return array Permissions for this forum
  1429. */
  1430. function fetch_forum_permissions($fid, $gid, $groupperms)
  1431. {
  1432. global $groupscache, $forum_cache, $fpermcache, $mybb, $fpermfields;
  1433.  
  1434. $groups = explode(",", $gid);
  1435.  
  1436. if(empty($fpermcache[$fid])) // This forum has no custom or inherited permissions so lets just return the group permissions
  1437. {
  1438. return $groupperms;
  1439. }
  1440.  
  1441. $current_permissions = array();
  1442. $only_view_own_threads = 1;
  1443. $only_reply_own_threads = 1;
  1444.  
  1445. foreach($groups as $gid)
  1446. {
  1447. if(!empty($groupscache[$gid]))
  1448. {
  1449. $level_permissions = $fpermcache[$fid][$gid];
  1450.  
  1451. // If our permissions arn't inherited we need to figure them out
  1452. if(empty($fpermcache[$fid][$gid]))
  1453. {
  1454. $parents = explode(',', $forum_cache[$fid]['parentlist']);
  1455. rsort($parents);
  1456. if(!empty($parents))
  1457. {
  1458. foreach($parents as $parent_id)
  1459. {
  1460. if(!empty($fpermcache[$parent_id][$gid]))
  1461. {
  1462. $level_permissions = $fpermcache[$parent_id][$gid];
  1463. break;
  1464. }
  1465. }
  1466. }
  1467. }
  1468.  
  1469. // If we STILL don't have forum permissions we use the usergroup itself
  1470. if(empty($level_permissions))
  1471. {
  1472. $level_permissions = $groupscache[$gid];
  1473. }
  1474.  
  1475. foreach($level_permissions as $permission => $access)
  1476. {
  1477. if(empty($current_permissions[$permission]) || $access >= $current_permissions[$permission] || ($access == "yes" && $current_permissions[$permission] == "no"))
  1478. {
  1479. $current_permissions[$permission] = $access;
  1480. }
  1481. }
  1482.  
  1483. if($level_permissions["canview"] && empty($level_permissions["canonlyviewownthreads"]))
  1484. {
  1485. $only_view_own_threads = 0;
  1486. }
  1487.  
  1488. if($level_permissions["canpostreplys"] && empty($level_permissions["canonlyreplyownthreads"]))
  1489. {
  1490. $only_reply_own_threads = 0;
  1491. }
  1492. }
  1493. }
  1494.  
  1495. // Figure out if we can view more than our own threads
  1496. if($only_view_own_threads == 0)
  1497. {
  1498. $current_permissions["canonlyviewownthreads"] = 0;
  1499. }
  1500.  
  1501. // Figure out if we can reply more than our own threads
  1502. if($only_reply_own_threads == 0)
  1503. {
  1504. $current_permissions["canonlyreplyownthreads"] = 0;
  1505. }
  1506.  
  1507. if(count($current_permissions) == 0)
  1508. {
  1509. $current_permissions = $groupperms;
  1510. }
  1511. return $current_permissions;
  1512. }
  1513.  
  1514. /**
  1515. * Check the password given on a certain forum for validity
  1516. *
  1517. * @param int $fid The forum ID
  1518. * @param int $pid The Parent ID
  1519. * @param bool $return
  1520. * @return bool
  1521. */
  1522. function check_forum_password($fid, $pid=0, $return=false)
  1523. {
  1524. global $mybb, $header, $footer, $headerinclude, $theme, $templates, $lang, $forum_cache;
  1525.  
  1526. $showform = true;
  1527.  
  1528. if(!is_array($forum_cache))
  1529. {
  1530. $forum_cache = cache_forums();
  1531. if(!$forum_cache)
  1532. {
  1533. return false;
  1534. }
  1535. }
  1536.  
  1537. // Loop through each of parent forums to ensure we have a password for them too
  1538. if(isset($forum_cache[$fid]['parentlist']))
  1539. {
  1540. $parents = explode(',', $forum_cache[$fid]['parentlist']);
  1541. rsort($parents);
  1542. }
  1543. if(!empty($parents))
  1544. {
  1545. foreach($parents as $parent_id)
  1546. {
  1547. if($parent_id == $fid || $parent_id == $pid)
  1548. {
  1549. continue;
  1550. }
  1551.  
  1552. if($forum_cache[$parent_id]['password'] != "")
  1553. {
  1554. check_forum_password($parent_id, $fid);
  1555. }
  1556. }
  1557. }
  1558.  
  1559. if(!empty($forum_cache[$fid]['password']))
  1560. {
  1561. $password = $forum_cache[$fid]['password'];
  1562. if(isset($mybb->input['pwverify']) && $pid == 0)
  1563. {
  1564. if($password === $mybb->get_input('pwverify'))
  1565. {
  1566. my_setcookie("forumpass[$fid]", md5($mybb->user['uid'].$mybb->get_input('pwverify')), null, true);
  1567. $showform = false;
  1568. }
  1569. else
  1570. {
  1571. eval("\$pwnote = \"".$templates->get("forumdisplay_password_wrongpass")."\";");
  1572. $showform = true;
  1573. }
  1574. }
  1575. else
  1576. {
  1577. if(!$mybb->cookies['forumpass'][$fid] || ($mybb->cookies['forumpass'][$fid] && md5($mybb->user['uid'].$password) !== $mybb->cookies['forumpass'][$fid]))
  1578. {
  1579. $showform = true;
  1580. }
  1581. else
  1582. {
  1583. $showform = false;
  1584. }
  1585. }
  1586. }
  1587. else
  1588. {
  1589. $showform = false;
  1590. }
  1591.  
  1592. if($return)
  1593. {
  1594. return $showform;
  1595. }
  1596.  
  1597. if($showform)
  1598. {
  1599. if($pid)
  1600. {
  1601. header("Location: ".$mybb->settings['bburl']."/".get_forum_link($fid));
  1602. }
  1603. else
  1604. {
  1605. $_SERVER['REQUEST_URI'] = htmlspecialchars_uni($_SERVER['REQUEST_URI']);
  1606. eval("\$pwform = \"".$templates->get("forumdisplay_password")."\";");
  1607. output_page($pwform);
  1608. }
  1609. exit;
  1610. }
  1611. }
  1612.  
  1613. /**
  1614. * Return the permissions for a moderator in a specific forum
  1615. *
  1616. * @param int $fid The forum ID
  1617. * @param int $uid The user ID to fetch permissions for (0 assumes current logged in user)
  1618. * @param string $parentslist The parent list for the forum (if blank, will be fetched)
  1619. * @return array Array of moderator permissions for the specific forum
  1620. */
  1621. function get_moderator_permissions($fid, $uid=0, $parentslist="")
  1622. {
  1623. global $mybb, $cache, $db;
  1624. static $modpermscache;
  1625.  
  1626. if($uid < 1)
  1627. {
  1628. $uid = $mybb->user['uid'];
  1629. }
  1630.  
  1631. if($uid == 0)
  1632. {
  1633. return false;
  1634. }
  1635.  
  1636. if(isset($modpermscache[$fid][$uid]))
  1637. {
  1638. return $modpermscache[$fid][$uid];
  1639. }
  1640.  
  1641. if(!$parentslist)
  1642. {
  1643. $parentslist = explode(',', get_parent_list($fid));
  1644. }
  1645.  
  1646. // Get user groups
  1647. $perms = array();
  1648. $user = get_user($uid);
  1649.  
  1650. $groups = array($user['usergroup']);
  1651.  
  1652. if(!empty($user['additionalgroups']))
  1653. {
  1654. $extra_groups = explode(",", $user['additionalgroups']);
  1655.  
  1656. foreach($extra_groups as $extra_group)
  1657. {
  1658. $groups[] = $extra_group;
  1659. }
  1660. }
  1661.  
  1662. $mod_cache = $cache->read("moderators");
  1663.  
  1664. foreach($mod_cache as $forumid => $forum)
  1665. {
  1666. if(!is_array($forum) || !in_array($forumid, $parentslist))
  1667. {
  1668. // No perms or we're not after this forum
  1669. continue;
  1670. }
  1671.  
  1672. // User settings override usergroup settings
  1673. if(is_array($forum['users'][$uid]))
  1674. {
  1675. $perm = $forum['users'][$uid];
  1676. foreach($perm as $action => $value)
  1677. {
  1678. if(strpos($action, "can") === false)
  1679. {
  1680. continue;
  1681. }
  1682.  
  1683. // Figure out the user permissions
  1684. if($value == 0)
  1685. {
  1686. // The user doesn't have permission to set this action
  1687. $perms[$action] = 0;
  1688. }
  1689. else
  1690. {
  1691. $perms[$action] = max($perm[$action], $perms[$action]);
  1692. }
  1693. }
  1694. }
  1695.  
  1696. foreach($groups as $group)
  1697. {
  1698. if(!is_array($forum['usergroups'][$group]))
  1699. {
  1700. // There are no permissions set for this group
  1701. continue;
  1702. }
  1703.  
  1704. $perm = $forum['usergroups'][$group];
  1705. foreach($perm as $action => $value)
  1706. {
  1707. if(strpos($action, "can") === false)
  1708. {
  1709. continue;
  1710. }
  1711.  
  1712. $perms[$action] = max($perm[$action], $perms[$action]);
  1713. }
  1714. }
  1715. }
  1716.  
  1717. $modpermscache[$fid][$uid] = $perms;
  1718.  
  1719. return $perms;
  1720. }
  1721.  
  1722. /**
  1723. * Checks if a moderator has permissions to perform an action in a specific forum
  1724. *
  1725. * @param int $fid The forum ID (0 assumes global)
  1726. * @param string $action The action tyring to be performed. (blank assumes any action at all)
  1727. * @param int $uid The user ID (0 assumes current user)
  1728. * @return bool Returns true if the user has permission, false if they do not
  1729. */
  1730. function is_moderator($fid=0, $action="", $uid=0)
  1731. {
  1732. global $mybb, $cache;
  1733.  
  1734. if($uid == 0)
  1735. {
  1736. $uid = $mybb->user['uid'];
  1737. }
  1738.  
  1739. if($uid == 0)
  1740. {
  1741. return false;
  1742. }
  1743.  
  1744. $user_perms = user_permissions($uid);
  1745. if($user_perms['issupermod'] == 1)
  1746. {
  1747. if($fid)
  1748. {
  1749. $forumpermissions = forum_permissions($fid);
  1750. if($forumpermissions['canview'] && $forumpermissions['canviewthreads'] && !$forumpermissions['canonlyviewownthreads'])
  1751. {
  1752. return true;
  1753. }
  1754. return false;
  1755. }
  1756. return true;
  1757. }
  1758. else
  1759. {
  1760. if(!$fid)
  1761. {
  1762. $modcache = $cache->read('moderators');
  1763. if(!empty($modcache))
  1764. {
  1765. foreach($modcache as $modusers)
  1766. {
  1767. if(isset($modusers['users'][$uid]) && $modusers['users'][$uid]['mid'] && (!$action || !empty($modusers['users'][$uid][$action])))
  1768. {
  1769. return true;
  1770. }
  1771.  
  1772. $groups = explode(',', $user_perms['all_usergroups']);
  1773.  
  1774. foreach($groups as $group)
  1775. {
  1776. if(trim($group) != '' && isset($modusers['usergroups'][$group]) && (!$action || !empty($modusers['usergroups'][$group][$action])))
  1777. {
  1778. return true;
  1779. }
  1780. }
  1781. }
  1782. }
  1783. return false;
  1784. }
  1785. else
  1786. {
  1787. $modperms = get_moderator_permissions($fid, $uid);
  1788.  
  1789. if(!$action && $modperms)
  1790. {
  1791. return true;
  1792. }
  1793. else
  1794. {
  1795. if(isset($modperms[$action]) && $modperms[$action] == 1)
  1796. {
  1797. return true;
  1798. }
  1799. else
  1800. {
  1801. return false;
  1802. }
  1803. }
  1804. }
  1805. }
  1806. }
  1807.  
  1808. /**
  1809. * Generate a list of the posticons.
  1810. *
  1811. * @return string The template of posticons.
  1812. */
  1813. function get_post_icons()
  1814. {
  1815. global $mybb, $cache, $icon, $theme, $templates, $lang;
  1816.  
  1817. if(isset($mybb->input['icon']))
  1818. {
  1819. $icon = $mybb->get_input('icon');
  1820. }
  1821.  
  1822. $iconlist = '';
  1823. $no_icons_checked = " checked=\"checked\"";
  1824. // read post icons from cache, and sort them accordingly
  1825. $posticons_cache = (array)$cache->read("posticons");
  1826. $posticons = array();
  1827. foreach($posticons_cache as $posticon)
  1828. {
  1829. $posticons[$posticon['name']] = $posticon;
  1830. }
  1831. krsort($posticons);
  1832.  
  1833. foreach($posticons as $dbicon)
  1834. {
  1835. $dbicon['path'] = str_replace("{theme}", $theme['imgdir'], $dbicon['path']);
  1836. $dbicon['path'] = htmlspecialchars_uni($mybb->get_asset_url($dbicon['path']));
  1837. $dbicon['name'] = htmlspecialchars_uni($dbicon['name']);
  1838.  
  1839. if($icon == $dbicon['iid'])
  1840. {
  1841. $checked = " checked=\"checked\"";
  1842. $no_icons_checked = '';
  1843. }
  1844. else
  1845. {
  1846. $checked = '';
  1847. }
  1848.  
  1849. eval("\$iconlist .= \"".$templates->get("posticons_icon")."\";");
  1850. }
  1851.  
  1852. if(!empty($iconlist))
  1853. {
  1854. eval("\$posticons = \"".$templates->get("posticons")."\";");
  1855. }
  1856. else
  1857. {
  1858. $posticons = '';
  1859. }
  1860.  
  1861. return $posticons;
  1862. }
  1863.  
  1864. /**
  1865. * MyBB setcookie() wrapper.
  1866. *
  1867. * @param string $name The cookie identifier.
  1868. * @param string $value The cookie value.
  1869. * @param int|string $expires The timestamp of the expiry date.
  1870. * @param boolean $httponly True if setting a HttpOnly cookie (supported by the majority of web browsers)
  1871. * @param string $samesite The samesite attribute to prevent CSRF.
  1872. */
  1873. function my_setcookie($name, $value="", $expires="", $httponly=false, $samesite="")
  1874. {
  1875. global $mybb;
  1876.  
  1877. if(!$mybb->settings['cookiepath'])
  1878. {
  1879. $mybb->settings['cookiepath'] = "/";
  1880. }
  1881.  
  1882. if($expires == -1)
  1883. {
  1884. $expires = 0;
  1885. }
  1886. elseif($expires == "" || $expires == null)
  1887. {
  1888. $expires = TIME_NOW + (60*60*24*365); // Make the cookie expire in a years time
  1889. }
  1890. else
  1891. {
  1892. $expires = TIME_NOW + (int)$expires;
  1893. }
  1894.  
  1895. $mybb->settings['cookiepath'] = str_replace(array("\n","\r"), "", $mybb->settings['cookiepath']);
  1896. $mybb->settings['cookiedomain'] = str_replace(array("\n","\r"), "", $mybb->settings['cookiedomain']);
  1897. $mybb->settings['cookieprefix'] = str_replace(array("\n","\r", " "), "", $mybb->settings['cookieprefix']);
  1898.  
  1899. // Versions of PHP prior to 5.2 do not support HttpOnly cookies and IE is buggy when specifying a blank domain so set the cookie manually
  1900. $cookie = "Set-Cookie: {$mybb->settings['cookieprefix']}{$name}=".urlencode($value);
  1901.  
  1902. if($expires > 0)
  1903. {
  1904. $cookie .= "; expires=".@gmdate('D, d-M-Y H:i:s \\G\\M\\T', $expires);
  1905. }
  1906.  
  1907. if(!empty($mybb->settings['cookiepath']))
  1908. {
  1909. $cookie .= "; path={$mybb->settings['cookiepath']}";
  1910. }
  1911.  
  1912. if(!empty($mybb->settings['cookiedomain']))
  1913. {
  1914. $cookie .= "; domain={$mybb->settings['cookiedomain']}";
  1915. }
  1916.  
  1917. if($httponly == true)
  1918. {
  1919. $cookie .= "; HttpOnly";
  1920. }
  1921.  
  1922. if($samesite != "" && $mybb->settings['cookiesamesiteflag'])
  1923. {
  1924. $samesite = strtolower($samesite);
  1925.  
  1926. if($samesite == "lax" || $samesite == "strict")
  1927. {
  1928. $cookie .= "; SameSite=".$samesite;
  1929. }
  1930. }
  1931.  
  1932. if($mybb->settings['cookiesecureflag'])
  1933. {
  1934. $cookie .= "; Secure";
  1935. }
  1936.  
  1937. $mybb->cookies[$name] = $value;
  1938.  
  1939. header($cookie, false);
  1940. }
  1941.  
  1942. /**
  1943. * Unset a cookie set by MyBB.
  1944. *
  1945. * @param string $name The cookie identifier.
  1946. */
  1947. function my_unsetcookie($name)
  1948. {
  1949. global $mybb;
  1950.  
  1951. $expires = -3600;
  1952. my_setcookie($name, "", $expires);
  1953.  
  1954. unset($mybb->cookies[$name]);
  1955. }
  1956.  
  1957. /**
  1958. * Get the contents from a serialised cookie array.
  1959. *
  1960. * @param string $name The cookie identifier.
  1961. * @param int $id The cookie content id.
  1962. * @return array|boolean The cookie id's content array or false when non-existent.
  1963. */
  1964. function my_get_array_cookie($name, $id)
  1965. {
  1966. global $mybb;
  1967.  
  1968. if(!isset($mybb->cookies['mybb'][$name]))
  1969. {
  1970. return false;
  1971. }
  1972.  
  1973. $cookie = my_unserialize($mybb->cookies['mybb'][$name]);
  1974.  
  1975. if(is_array($cookie) && isset($cookie[$id]))
  1976. {
  1977. return $cookie[$id];
  1978. }
  1979. else
  1980. {
  1981. return 0;
  1982. }
  1983. }
  1984.  
  1985. /**
  1986. * Set a serialised cookie array.
  1987. *
  1988. * @param string $name The cookie identifier.
  1989. * @param int $id The cookie content id.
  1990. * @param string $value The value to set the cookie to.
  1991. * @param int|string $expires The timestamp of the expiry date.
  1992. */
  1993. function my_set_array_cookie($name, $id, $value, $expires="")
  1994. {
  1995. global $mybb;
  1996.  
  1997. $cookie = $mybb->cookies['mybb'];
  1998. if(isset($cookie[$name]))
  1999. {
  2000. $newcookie = my_unserialize($cookie[$name]);
  2001. }
  2002. else
  2003. {
  2004. $newcookie = array();
  2005. }
  2006.  
  2007. $newcookie[$id] = $value;
  2008. $newcookie = my_serialize($newcookie);
  2009. my_setcookie("mybb[$name]", addslashes($newcookie), $expires);
  2010.  
  2011. // Make sure our current viarables are up-to-date as well
  2012. $mybb->cookies['mybb'][$name] = $newcookie;
  2013. }
  2014.  
  2015. /*
  2016. * Arbitrary limits for _safe_unserialize()
  2017. */
  2018. define('MAX_SERIALIZED_INPUT_LENGTH', 10240);
  2019. define('MAX_SERIALIZED_ARRAY_LENGTH', 256);
  2020. define('MAX_SERIALIZED_ARRAY_DEPTH', 5);
  2021.  
  2022. /**
  2023. * Credits go to https://github.com/piwik
  2024. * Safe unserialize() replacement
  2025. * - accepts a strict subset of PHP's native my_serialized representation
  2026. * - does not unserialize objects
  2027. *
  2028. * @param string $str
  2029. * @return mixed
  2030. * @throw Exception if $str is malformed or contains unsupported types (e.g., resources, objects)
  2031. */
  2032. function _safe_unserialize($str)
  2033. {
  2034. if(strlen($str) > MAX_SERIALIZED_INPUT_LENGTH)
  2035. {
  2036. // input exceeds MAX_SERIALIZED_INPUT_LENGTH
  2037. return false;
  2038. }
  2039.  
  2040. if(empty($str) || !is_string($str))
  2041. {
  2042. return false;
  2043. }
  2044.  
  2045. $stack = array();
  2046. $expected = array();
  2047.  
  2048. /*
  2049. * states:
  2050. * 0 - initial state, expecting a single value or array
  2051. * 1 - terminal state
  2052. * 2 - in array, expecting end of array or a key
  2053. * 3 - in array, expecting value or another array
  2054. */
  2055. $state = 0;
  2056. while($state != 1)
  2057. {
  2058. $type = isset($str[0]) ? $str[0] : '';
  2059.  
  2060. if($type == '}')
  2061. {
  2062. $str = substr($str, 1);
  2063. }
  2064. else if($type == 'N' && $str[1] == ';')
  2065. {
  2066. $value = null;
  2067. $str = substr($str, 2);
  2068. }
  2069. else if($type == 'b' && preg_match('/^b:([01]);/', $str, $matches))
  2070. {
  2071. $value = $matches[1] == '1' ? true : false;
  2072. $str = substr($str, 4);
  2073. }
  2074. else if($type == 'i' && preg_match('/^i:(-?[0-9]+);(.*)/s', $str, $matches))
  2075. {
  2076. $value = (int)$matches[1];
  2077. $str = $matches[2];
  2078. }
  2079. else if($type == 'd' && preg_match('/^d:(-?[0-9]+\.?[0-9]*(E[+-][0-9]+)?);(.*)/s', $str, $matches))
  2080. {
  2081. $value = (float)$matches[1];
  2082. $str = $matches[3];
  2083. }
  2084. else if($type == 's' && preg_match('/^s:([0-9]+):"(.*)/s', $str, $matches) && substr($matches[2], (int)$matches[1], 2) == '";')
  2085. {
  2086. $value = substr($matches[2], 0, (int)$matches[1]);
  2087. $str = substr($matches[2], (int)$matches[1] + 2);
  2088. }
  2089. else if($type == 'a' && preg_match('/^a:([0-9]+):{(.*)/s', $str, $matches) && $matches[1] < MAX_SERIALIZED_ARRAY_LENGTH)
  2090. {
  2091. $expectedLength = (int)$matches[1];
  2092. $str = $matches[2];
  2093. }
  2094. else
  2095. {
  2096. // object or unknown/malformed type
  2097. return false;
  2098. }
  2099.  
  2100. switch($state)
  2101. {
  2102. case 3: // in array, expecting value or another array
  2103. if($type == 'a')
  2104. {
  2105. if(count($stack) >= MAX_SERIALIZED_ARRAY_DEPTH)
  2106. {
  2107. // array nesting exceeds MAX_SERIALIZED_ARRAY_DEPTH
  2108. return false;
  2109. }
  2110.  
  2111. $stack[] = &$list;
  2112. $list[$key] = array();
  2113. $list = &$list[$key];
  2114. $expected[] = $expectedLength;
  2115. $state = 2;
  2116. break;
  2117. }
  2118. if($type != '}')
  2119. {
  2120. $list[$key] = $value;
  2121. $state = 2;
  2122. break;
  2123. }
  2124.  
  2125. // missing array value
  2126. return false;
  2127.  
  2128. case 2: // in array, expecting end of array or a key
  2129. if($type == '}')
  2130. {
  2131. if(count($list) < end($expected))
  2132. {
  2133. // array size less than expected
  2134. return false;
  2135. }
  2136.  
  2137. unset($list);
  2138. $list = &$stack[count($stack)-1];
  2139. array_pop($stack);
  2140.  
  2141. // go to terminal state if we're at the end of the root array
  2142. array_pop($expected);
  2143. if(count($expected) == 0) {
  2144. $state = 1;
  2145. }
  2146. break;
  2147. }
  2148. if($type == 'i' || $type == 's')
  2149. {
  2150. if(count($list) >= MAX_SERIALIZED_ARRAY_LENGTH)
  2151. {
  2152. // array size exceeds MAX_SERIALIZED_ARRAY_LENGTH
  2153. return false;
  2154. }
  2155. if(count($list) >= end($expected))
  2156. {
  2157. // array size exceeds expected length
  2158. return false;
  2159. }
  2160.  
  2161. $key = $value;
  2162. $state = 3;
  2163. break;
  2164. }
  2165.  
  2166. // illegal array index type
  2167. return false;
  2168.  
  2169. case 0: // expecting array or value
  2170. if($type == 'a')
  2171. {
  2172. if(count($stack) >= MAX_SERIALIZED_ARRAY_DEPTH)
  2173. {
  2174. // array nesting exceeds MAX_SERIALIZED_ARRAY_DEPTH
  2175. return false;
  2176. }
  2177.  
  2178. $data = array();
  2179. $list = &$data;
  2180. $expected[] = $expectedLength;
  2181. $state = 2;
  2182. break;
  2183. }
  2184. if($type != '}')
  2185. {
  2186. $data = $value;
  2187. $state = 1;
  2188. break;
  2189. }
  2190.  
  2191. // not in array
  2192. return false;
  2193. }
  2194. }
  2195.  
  2196. if(!empty($str))
  2197. {
  2198. // trailing data in input
  2199. return false;
  2200. }
  2201. return $data;
  2202. }
  2203.  
  2204. /**
  2205. * Credits go to https://github.com/piwik
  2206. * Wrapper for _safe_unserialize() that handles exceptions and multibyte encoding issue
  2207. *
  2208. * @param string $str
  2209. * @return mixed
  2210. */
  2211. function my_unserialize($str)
  2212. {
  2213. // Ensure we use the byte count for strings even when strlen() is overloaded by mb_strlen()
  2214. if(function_exists('mb_internal_encoding') && (((int)ini_get('mbstring.func_overload')) & 2))
  2215. {
  2216. $mbIntEnc = mb_internal_encoding();
  2217. mb_internal_encoding('ASCII');
  2218. }
  2219.  
  2220. $out = _safe_unserialize($str);
  2221.  
  2222. if(isset($mbIntEnc))
  2223. {
  2224. mb_internal_encoding($mbIntEnc);
  2225. }
  2226.  
  2227. return $out;
  2228. }
  2229.  
  2230. /**
  2231. * Credits go to https://github.com/piwik
  2232. * Safe serialize() replacement
  2233. * - output a strict subset of PHP's native serialized representation
  2234. * - does not my_serialize objects
  2235. *
  2236. * @param mixed $value
  2237. * @return string
  2238. * @throw Exception if $value is malformed or contains unsupported types (e.g., resources, objects)
  2239. */
  2240. function _safe_serialize( $value )
  2241. {
  2242. if(is_null($value))
  2243. {
  2244. return 'N;';
  2245. }
  2246.  
  2247. if(is_bool($value))
  2248. {
  2249. return 'b:'.(int)$value.';';
  2250. }
  2251.  
  2252. if(is_int($value))
  2253. {
  2254. return 'i:'.$value.';';
  2255. }
  2256.  
  2257. if(is_float($value))
  2258. {
  2259. return 'd:'.str_replace(',', '.', $value).';';
  2260. }
  2261.  
  2262. if(is_string($value))
  2263. {
  2264. return 's:'.strlen($value).':"'.$value.'";';
  2265. }
  2266.  
  2267. if(is_array($value))
  2268. {
  2269. $out = '';
  2270. foreach($value as $k => $v)
  2271. {
  2272. $out .= _safe_serialize($k) . _safe_serialize($v);
  2273. }
  2274.  
  2275. return 'a:'.count($value).':{'.$out.'}';
  2276. }
  2277.  
  2278. // safe_serialize cannot my_serialize resources or objects
  2279. return false;
  2280. }
  2281.  
  2282. /**
  2283. * Credits go to https://github.com/piwik
  2284. * Wrapper for _safe_serialize() that handles exceptions and multibyte encoding issue
  2285. *
  2286. * @param mixed $value
  2287. * @return string
  2288. */
  2289. function my_serialize($value)
  2290. {
  2291. // ensure we use the byte count for strings even when strlen() is overloaded by mb_strlen()
  2292. if(function_exists('mb_internal_encoding') && (((int)ini_get('mbstring.func_overload')) & 2))
  2293. {
  2294. $mbIntEnc = mb_internal_encoding();
  2295. mb_internal_encoding('ASCII');
  2296. }
  2297.  
  2298. $out = _safe_serialize($value);
  2299. if(isset($mbIntEnc))
  2300. {
  2301. mb_internal_encoding($mbIntEnc);
  2302. }
  2303.  
  2304. return $out;
  2305. }
  2306.  
  2307. /**
  2308. * Returns the serverload of the system.
  2309. *
  2310. * @return int The serverload of the system.
  2311. */
  2312. function get_server_load()
  2313. {
  2314. global $mybb, $lang;
  2315.  
  2316. $serverload = array();
  2317.  
  2318. // DIRECTORY_SEPARATOR checks if running windows
  2319. if(DIRECTORY_SEPARATOR != '\\')
  2320. {
  2321. if(function_exists("sys_getloadavg"))
  2322. {
  2323. // sys_getloadavg() will return an array with [0] being load within the last minute.
  2324. $serverload = sys_getloadavg();
  2325. $serverload[0] = round($serverload[0], 4);
  2326. }
  2327. else if(@file_exists("/proc/loadavg") && $load = @file_get_contents("/proc/loadavg"))
  2328. {
  2329. $serverload = explode(" ", $load);
  2330. $serverload[0] = round($serverload[0], 4);
  2331. }
  2332. if(!is_numeric($serverload[0]))
  2333. {
  2334. if($mybb->safemode)
  2335. {
  2336. return $lang->unknown;
  2337. }
  2338.  
  2339. // Suhosin likes to throw a warning if exec is disabled then die - weird
  2340. if($func_blacklist = @ini_get('suhosin.executor.func.blacklist'))
  2341. {
  2342. if(strpos(",".$func_blacklist.",", 'exec') !== false)
  2343. {
  2344. return $lang->unknown;
  2345. }
  2346. }
  2347. // PHP disabled functions?
  2348. if($func_blacklist = @ini_get('disable_functions'))
  2349. {
  2350. if(strpos(",".$func_blacklist.",", 'exec') !== false)
  2351. {
  2352. return $lang->unknown;
  2353. }
  2354. }
  2355.  
  2356. $load = @exec("uptime");
  2357. $load = explode("load average: ", $load);
  2358. $serverload = explode(",", $load[1]);
  2359. if(!is_array($serverload))
  2360. {
  2361. return $lang->unknown;
  2362. }
  2363. }
  2364. }
  2365. else
  2366. {
  2367. return $lang->unknown;
  2368. }
  2369.  
  2370. $returnload = trim($serverload[0]);
  2371.  
  2372. return $returnload;
  2373. }
  2374.  
  2375. /**
  2376. * Returns the amount of memory allocated to the script.
  2377. *
  2378. * @return int The amount of memory allocated to the script.
  2379. */
  2380. function get_memory_usage()
  2381. {
  2382. if(function_exists('memory_get_peak_usage'))
  2383. {
  2384. return memory_get_peak_usage(true);
  2385. }
  2386. elseif(function_exists('memory_get_usage'))
  2387. {
  2388. return memory_get_usage(true);
  2389. }
  2390. return false;
  2391. }
  2392.  
  2393. /**
  2394. * Updates the forum statistics with specific values (or addition/subtraction of the previous value)
  2395. *
  2396. * @param array $changes Array of items being updated (numthreads,numposts,numusers,numunapprovedthreads,numunapprovedposts,numdeletedposts,numdeletedthreads)
  2397. * @param boolean $force Force stats update?
  2398. */
  2399. function update_stats($changes=array(), $force=false)
  2400. {
  2401. global $cache, $db;
  2402. static $stats_changes;
  2403.  
  2404. if(empty($stats_changes))
  2405. {
  2406. // Update stats after all changes are done
  2407. add_shutdown('update_stats', array(array(), true));
  2408. }
  2409.  
  2410. if(empty($stats_changes) || $stats_changes['inserted'])
  2411. {
  2412. $stats_changes = array(
  2413. 'numthreads' => '+0',
  2414. 'numposts' => '+0',
  2415. 'numusers' => '+0',
  2416. 'numunapprovedthreads' => '+0',
  2417. 'numunapprovedposts' => '+0',
  2418. 'numdeletedposts' => '+0',
  2419. 'numdeletedthreads' => '+0',
  2420. 'inserted' => false // Reset after changes are inserted into cache
  2421. );
  2422. $stats = $stats_changes;
  2423. }
  2424.  
  2425. if($force) // Force writing to cache?
  2426. {
  2427. if(!empty($changes))
  2428. {
  2429. // Calculate before writing to cache
  2430. update_stats($changes);
  2431. }
  2432. $stats = $cache->read("stats");
  2433. $changes = $stats_changes;
  2434. }
  2435. else
  2436. {
  2437. $stats = $stats_changes;
  2438. }
  2439.  
  2440. $new_stats = array();
  2441. $counters = array('numthreads', 'numunapprovedthreads', 'numposts', 'numunapprovedposts', 'numusers', 'numdeletedposts', 'numdeletedthreads');
  2442. foreach($counters as $counter)
  2443. {
  2444. if(array_key_exists($counter, $changes))
  2445. {
  2446. if(substr($changes[$counter], 0, 2) == "+-")
  2447. {
  2448. $changes[$counter] = substr($changes[$counter], 1);
  2449. }
  2450. // Adding or subtracting from previous value?
  2451. if(substr($changes[$counter], 0, 1) == "+" || substr($changes[$counter], 0, 1) == "-")
  2452. {
  2453. if((int)$changes[$counter] != 0)
  2454. {
  2455. $new_stats[$counter] = $stats[$counter] + $changes[$counter];
  2456. if(!$force && (substr($stats[$counter], 0, 1) == "+" || substr($stats[$counter], 0, 1) == "-"))
  2457. {
  2458. // We had relative values? Then it is still relative
  2459. if($new_stats[$counter] >= 0)
  2460. {
  2461. $new_stats[$counter] = "+{$new_stats[$counter]}";
  2462. }
  2463. }
  2464. // Less than 0? That's bad
  2465. elseif($new_stats[$counter] < 0)
  2466. {
  2467. $new_stats[$counter] = 0;
  2468. }
  2469. }
  2470. }
  2471. else
  2472. {
  2473. $new_stats[$counter] = $changes[$counter];
  2474. // Less than 0? That's bad
  2475. if($new_stats[$counter] < 0)
  2476. {
  2477. $new_stats[$counter] = 0;
  2478. }
  2479. }
  2480. }
  2481. }
  2482.  
  2483. if(!$force)
  2484. {
  2485. $stats_changes = array_merge($stats, $new_stats); // Overwrite changed values
  2486. return;
  2487. }
  2488.  
  2489. // Fetch latest user if the user count is changing
  2490. if(array_key_exists('numusers', $changes))
  2491. {
  2492. $query = $db->simple_select("users", "uid, username", "", array('order_by' => 'regdate', 'order_dir' => 'DESC', 'limit' => 1));
  2493. $lastmember = $db->fetch_array($query);
  2494. $new_stats['lastuid'] = $lastmember['uid'];
  2495. $new_stats['lastusername'] = $lastmember['username'] = htmlspecialchars_uni($lastmember['username']);
  2496. }
  2497.  
  2498. if(!empty($new_stats))
  2499. {
  2500. if(is_array($stats))
  2501. {
  2502. $stats = array_merge($stats, $new_stats); // Overwrite changed values
  2503. }
  2504. else
  2505. {
  2506. $stats = $new_stats;
  2507. }
  2508. }
  2509.  
  2510. // Update stats row for today in the database
  2511. $todays_stats = array(
  2512. "dateline" => mktime(0, 0, 0, date("m"), date("j"), date("Y")),
  2513. "numusers" => (int)$stats['numusers'],
  2514. "numthreads" => (int)$stats['numthreads'],
  2515. "numposts" => (int)$stats['numposts']
  2516. );
  2517. $db->replace_query("stats", $todays_stats, "dateline");
  2518.  
  2519. $cache->update("stats", $stats, "dateline");
  2520. $stats_changes['inserted'] = true;
  2521. }
  2522.  
  2523. /**
  2524. * Updates the forum counters with a specific value (or addition/subtraction of the previous value)
  2525. *
  2526. * @param int $fid The forum ID
  2527. * @param array $changes Array of items being updated (threads, posts, unapprovedthreads, unapprovedposts, deletedposts, deletedthreads) and their value (ex, 1, +1, -1)
  2528. */
  2529. function update_forum_counters($fid, $changes=array())
  2530. {
  2531. global $db;
  2532.  
  2533. $update_query = array();
  2534.  
  2535. $counters = array('threads', 'unapprovedthreads', 'posts', 'unapprovedposts', 'deletedposts', 'deletedthreads');
  2536.  
  2537. // Fetch above counters for this forum
  2538. $query = $db->simple_select("forums", implode(",", $counters), "fid='{$fid}'");
  2539. $forum = $db->fetch_array($query);
  2540.  
  2541. foreach($counters as $counter)
  2542. {
  2543. if(array_key_exists($counter, $changes))
  2544. {
  2545. if(substr($changes[$counter], 0, 2) == "+-")
  2546. {
  2547. $changes[$counter] = substr($changes[$counter], 1);
  2548. }
  2549. // Adding or subtracting from previous value?
  2550. if(substr($changes[$counter], 0, 1) == "+" || substr($changes[$counter], 0, 1) == "-")
  2551. {
  2552. if((int)$changes[$counter] != 0)
  2553. {
  2554. $update_query[$counter] = $forum[$counter] + $changes[$counter];
  2555. }
  2556. }
  2557. else
  2558. {
  2559. $update_query[$counter] = $changes[$counter];
  2560. }
  2561.  
  2562. // Less than 0? That's bad
  2563. if(isset($update_query[$counter]) && $update_query[$counter] < 0)
  2564. {
  2565. $update_query[$counter] = 0;
  2566. }
  2567. }
  2568. }
  2569.  
  2570. // Only update if we're actually doing something
  2571. if(count($update_query) > 0)
  2572. {
  2573. $db->update_query("forums", $update_query, "fid='".(int)$fid."'");
  2574. }
  2575.  
  2576. // Guess we should update the statistics too?
  2577. $new_stats = array();
  2578. if(array_key_exists('threads', $update_query))
  2579. {
  2580. $threads_diff = $update_query['threads'] - $forum['threads'];
  2581. if($threads_diff > -1)
  2582. {
  2583. $new_stats['numthreads'] = "+{$threads_diff}";
  2584. }
  2585. else
  2586. {
  2587. $new_stats['numthreads'] = "{$threads_diff}";
  2588. }
  2589. }
  2590.  
  2591. if(array_key_exists('unapprovedthreads', $update_query))
  2592. {
  2593. $unapprovedthreads_diff = $update_query['unapprovedthreads'] - $forum['unapprovedthreads'];
  2594. if($unapprovedthreads_diff > -1)
  2595. {
  2596. $new_stats['numunapprovedthreads'] = "+{$unapprovedthreads_diff}";
  2597. }
  2598. else
  2599. {
  2600. $new_stats['numunapprovedthreads'] = "{$unapprovedthreads_diff}";
  2601. }
  2602. }
  2603.  
  2604. if(array_key_exists('posts', $update_query))
  2605. {
  2606. $posts_diff = $update_query['posts'] - $forum['posts'];
  2607. if($posts_diff > -1)
  2608. {
  2609. $new_stats['numposts'] = "+{$posts_diff}";
  2610. }
  2611. else
  2612. {
  2613. $new_stats['numposts'] = "{$posts_diff}";
  2614. }
  2615. }
  2616.  
  2617. if(array_key_exists('unapprovedposts', $update_query))
  2618. {
  2619. $unapprovedposts_diff = $update_query['unapprovedposts'] - $forum['unapprovedposts'];
  2620. if($unapprovedposts_diff > -1)
  2621. {
  2622. $new_stats['numunapprovedposts'] = "+{$unapprovedposts_diff}";
  2623. }
  2624. else
  2625. {
  2626. $new_stats['numunapprovedposts'] = "{$unapprovedposts_diff}";
  2627. }
  2628. }
  2629.  
  2630. if(array_key_exists('deletedposts', $update_query))
  2631. {
  2632. $deletedposts_diff = $update_query['deletedposts'] - $forum['deletedposts'];
  2633. if($deletedposts_diff > -1)
  2634. {
  2635. $new_stats['numdeletedposts'] = "+{$deletedposts_diff}";
  2636. }
  2637. else
  2638. {
  2639. $new_stats['numdeletedposts'] = "{$deletedposts_diff}";
  2640. }
  2641. }
  2642.  
  2643. if(array_key_exists('deletedthreads', $update_query))
  2644. {
  2645. $deletedthreads_diff = $update_query['deletedthreads'] - $forum['deletedthreads'];
  2646. if($deletedthreads_diff > -1)
  2647. {
  2648. $new_stats['numdeletedthreads'] = "+{$deletedthreads_diff}";
  2649. }
  2650. else
  2651. {
  2652. $new_stats['numdeletedthreads'] = "{$deletedthreads_diff}";
  2653. }
  2654. }
  2655.  
  2656. if(!empty($new_stats))
  2657. {
  2658. update_stats($new_stats);
  2659. }
  2660. }
  2661.  
  2662. /**
  2663. * Update the last post information for a specific forum
  2664. *
  2665. * @param int $fid The forum ID
  2666. */
  2667. function update_forum_lastpost($fid)
  2668. {
  2669. global $db;
  2670.  
  2671. // Fetch the last post for this forum
  2672. $query = $db->query("
  2673. SELECT tid, lastpost, lastposter, lastposteruid, subject
  2674. FROM ".TABLE_PREFIX."threads
  2675. WHERE fid='{$fid}' AND visible='1' AND closed NOT LIKE 'moved|%'
  2676. ORDER BY lastpost DESC
  2677. LIMIT 0, 1
  2678. ");
  2679. $lastpost = $db->fetch_array($query);
  2680.  
  2681. $updated_forum = array(
  2682. "lastpost" => (int)$lastpost['lastpost'],
  2683. "lastposter" => $db->escape_string($lastpost['lastposter']),
  2684. "lastposteruid" => (int)$lastpost['lastposteruid'],
  2685. "lastposttid" => (int)$lastpost['tid'],
  2686. "lastpostsubject" => $db->escape_string($lastpost['subject'])
  2687. );
  2688.  
  2689. $db->update_query("forums", $updated_forum, "fid='{$fid}'");
  2690. }
  2691.  
  2692. /**
  2693. * Updates the thread counters with a specific value (or addition/subtraction of the previous value)
  2694. *
  2695. * @param int $tid The thread ID
  2696. * @param array $changes Array of items being updated (replies, unapprovedposts, deletedposts, attachmentcount) and their value (ex, 1, +1, -1)
  2697. */
  2698. function update_thread_counters($tid, $changes=array())
  2699. {
  2700. global $db;
  2701.  
  2702. $update_query = array();
  2703. $tid = (int)$tid;
  2704.  
  2705. $counters = array('replies', 'unapprovedposts', 'attachmentcount', 'deletedposts', 'attachmentcount');
  2706.  
  2707. // Fetch above counters for this thread
  2708. $query = $db->simple_select("threads", implode(",", $counters), "tid='{$tid}'");
  2709. $thread = $db->fetch_array($query);
  2710.  
  2711. foreach($counters as $counter)
  2712. {
  2713. if(array_key_exists($counter, $changes))
  2714. {
  2715. if(substr($changes[$counter], 0, 2) == "+-")
  2716. {
  2717. $changes[$counter] = substr($changes[$counter], 1);
  2718. }
  2719. // Adding or subtracting from previous value?
  2720. if(substr($changes[$counter], 0, 1) == "+" || substr($changes[$counter], 0, 1) == "-")
  2721. {
  2722. if((int)$changes[$counter] != 0)
  2723. {
  2724. $update_query[$counter] = $thread[$counter] + $changes[$counter];
  2725. }
  2726. }
  2727. else
  2728. {
  2729. $update_query[$counter] = $changes[$counter];
  2730. }
  2731.  
  2732. // Less than 0? That's bad
  2733. if(isset($update_query[$counter]) && $update_query[$counter] < 0)
  2734. {
  2735. $update_query[$counter] = 0;
  2736. }
  2737. }
  2738. }
  2739.  
  2740. $db->free_result($query);
  2741.  
  2742. // Only update if we're actually doing something
  2743. if(count($update_query) > 0)
  2744. {
  2745. $db->update_query("threads", $update_query, "tid='{$tid}'");
  2746. }
  2747. }
  2748.  
  2749. /**
  2750. * Update the first post and lastpost data for a specific thread
  2751. *
  2752. * @param int $tid The thread ID
  2753. */
  2754. function update_thread_data($tid)
  2755. {
  2756. global $db;
  2757.  
  2758. $thread = get_thread($tid);
  2759.  
  2760. // If this is a moved thread marker, don't update it - we need it to stay as it is
  2761. if(strpos($thread['closed'], 'moved|') !== false)
  2762. {
  2763. return;
  2764. }
  2765.  
  2766. $query = $db->query("
  2767. SELECT u.uid, u.username, p.username AS postusername, p.dateline
  2768. FROM ".TABLE_PREFIX."posts p
  2769. LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
  2770. WHERE p.tid='$tid' AND p.visible='1'
  2771. ORDER BY p.dateline DESC
  2772. LIMIT 1"
  2773. );
  2774. $lastpost = $db->fetch_array($query);
  2775.  
  2776. $db->free_result($query);
  2777.  
  2778. $query = $db->query("
  2779. SELECT u.uid, u.username, p.pid, p.username AS postusername, p.dateline
  2780. FROM ".TABLE_PREFIX."posts p
  2781. LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
  2782. WHERE p.tid='$tid'
  2783. ORDER BY p.dateline ASC
  2784. LIMIT 1
  2785. ");
  2786. $firstpost = $db->fetch_array($query);
  2787.  
  2788. $db->free_result($query);
  2789.  
  2790. if(empty($firstpost['username']))
  2791. {
  2792. $firstpost['username'] = $firstpost['postusername'];
  2793. }
  2794.  
  2795. if(empty($lastpost['username']))
  2796. {
  2797. $lastpost['username'] = $lastpost['postusername'];
  2798. }
  2799.  
  2800. if(empty($lastpost['dateline']))
  2801. {
  2802. $lastpost['username'] = $firstpost['username'];
  2803. $lastpost['uid'] = $firstpost['uid'];
  2804. $lastpost['dateline'] = $firstpost['dateline'];
  2805. }
  2806.  
  2807. $lastpost['username'] = $db->escape_string($lastpost['username']);
  2808. $firstpost['username'] = $db->escape_string($firstpost['username']);
  2809.  
  2810. $update_array = array(
  2811. 'firstpost' => (int)$firstpost['pid'],
  2812. 'username' => $firstpost['username'],
  2813. 'uid' => (int)$firstpost['uid'],
  2814. 'dateline' => (int)$firstpost['dateline'],
  2815. 'lastpost' => (int)$lastpost['dateline'],
  2816. 'lastposter' => $lastpost['username'],
  2817. 'lastposteruid' => (int)$lastpost['uid'],
  2818. );
  2819. $db->update_query("threads", $update_array, "tid='{$tid}'");
  2820. }
  2821.  
  2822. /**
  2823. * Updates the user counters with a specific value (or addition/subtraction of the previous value)
  2824. *
  2825. * @param int $uid The user ID
  2826. * @param array $changes Array of items being updated (postnum, threadnum) and their value (ex, 1, +1, -1)
  2827. */
  2828. function update_user_counters($uid, $changes=array())
  2829. {
  2830. global $db;
  2831.  
  2832. $update_query = array();
  2833.  
  2834. $counters = array('postnum', 'threadnum');
  2835. $uid = (int)$uid;
  2836.  
  2837. // Fetch above counters for this user
  2838. $query = $db->simple_select("users", implode(",", $counters), "uid='{$uid}'");
  2839. $user = $db->fetch_array($query);
  2840.  
  2841. foreach($counters as $counter)
  2842. {
  2843. if(array_key_exists($counter, $changes))
  2844. {
  2845. if(substr($changes[$counter], 0, 2) == "+-")
  2846. {
  2847. $changes[$counter] = substr($changes[$counter], 1);
  2848. }
  2849. // Adding or subtracting from previous value?
  2850. if(substr($changes[$counter], 0, 1) == "+" || substr($changes[$counter], 0, 1) == "-")
  2851. {
  2852. if((int)$changes[$counter] != 0)
  2853. {
  2854. $update_query[$counter] = $user[$counter] + $changes[$counter];
  2855. }
  2856. }
  2857. else
  2858. {
  2859. $update_query[$counter] = $changes[$counter];
  2860. }
  2861.  
  2862. // Less than 0? That's bad
  2863. if(isset($update_query[$counter]) && $update_query[$counter] < 0)
  2864. {
  2865. $update_query[$counter] = 0;
  2866. }
  2867. }
  2868. }
  2869.  
  2870. $db->free_result($query);
  2871.  
  2872. // Only update if we're actually doing something
  2873. if(count($update_query) > 0)
  2874. {
  2875. $db->update_query("users", $update_query, "uid='{$uid}'");
  2876. }
  2877. }
  2878.  
  2879. /**
  2880. * Deletes a thread from the database
  2881. *
  2882. * @param int $tid The thread ID
  2883. * @return bool
  2884. */
  2885. function delete_thread($tid)
  2886. {
  2887. global $moderation;
  2888.  
  2889. if(!is_object($moderation))
  2890. {
  2891. require_once MYBB_ROOT."inc/class_moderation.php";
  2892. $moderation = new Moderation;
  2893. }
  2894.  
  2895. return $moderation->delete_thread($tid);
  2896. }
  2897.  
  2898. /**
  2899. * Deletes a post from the database
  2900. *
  2901. * @param int $pid The thread ID
  2902. * @return bool
  2903. */
  2904. function delete_post($pid)
  2905. {
  2906. global $moderation;
  2907.  
  2908. if(!is_object($moderation))
  2909. {
  2910. require_once MYBB_ROOT."inc/class_moderation.php";
  2911. $moderation = new Moderation;
  2912. }
  2913.  
  2914. return $moderation->delete_post($pid);
  2915. }
  2916.  
  2917. /**
  2918. * Builds a forum jump menu
  2919. *
  2920. * @param int $pid The parent forum to start with
  2921. * @param int $selitem The selected item ID
  2922. * @param int $addselect If we need to add select boxes to this cal or not
  2923. * @param string $depth The current depth of forums we're at
  2924. * @param int $showextras Whether or not to show extra items such as User CP, Forum home
  2925. * @param boolean $showall Ignore the showinjump setting and show all forums (for moderation pages)
  2926. * @param mixed $permissions deprecated
  2927. * @param string $name The name of the forum jump
  2928. * @return string Forum jump items
  2929. */
  2930. function build_forum_jump($pid=0, $selitem=0, $addselect=1, $depth="", $showextras=1, $showall=false, $permissions="", $name="fid")
  2931. {
  2932. global $forum_cache, $jumpfcache, $permissioncache, $mybb, $forumjump, $forumjumpbits, $gobutton, $theme, $templates, $lang;
  2933.  
  2934. $pid = (int)$pid;
  2935.  
  2936. if(!is_array($jumpfcache))
  2937. {
  2938. if(!is_array($forum_cache))
  2939. {
  2940. cache_forums();
  2941. }
  2942.  
  2943. foreach($forum_cache as $fid => $forum)
  2944. {
  2945. if($forum['active'] != 0)
  2946. {
  2947. $jumpfcache[$forum['pid']][$forum['disporder']][$forum['fid']] = $forum;
  2948. }
  2949. }
  2950. }
  2951.  
  2952. if(!is_array($permissioncache))
  2953. {
  2954. $permissioncache = forum_permissions();
  2955. }
  2956.  
  2957. if(isset($jumpfcache[$pid]) && is_array($jumpfcache[$pid]))
  2958. {
  2959. foreach($jumpfcache[$pid] as $main)
  2960. {
  2961. foreach($main as $forum)
  2962. {
  2963. $perms = $permissioncache[$forum['fid']];
  2964.  
  2965. if($forum['fid'] != "0" && ($perms['canview'] != 0 || $mybb->settings['hideprivateforums'] == 0) && $forum['linkto'] == '' && ($forum['showinjump'] != 0 || $showall == true))
  2966. {
  2967. $optionselected = "";
  2968.  
  2969. if($selitem == $forum['fid'])
  2970. {
  2971. $optionselected = 'selected="selected"';
  2972. }
  2973.  
  2974. $forum['name'] = htmlspecialchars_uni(strip_tags($forum['name']));
  2975.  
  2976. eval("\$forumjumpbits .= \"".$templates->get("forumjump_bit")."\";");
  2977.  
  2978. if($forum_cache[$forum['fid']])
  2979. {
  2980. $newdepth = $depth."--";
  2981. $forumjumpbits .= build_forum_jump($forum['fid'], $selitem, 0, $newdepth, $showextras, $showall);
  2982. }
  2983. }
  2984. }
  2985. }
  2986. }
  2987.  
  2988. if($addselect)
  2989. {
  2990. if($showextras == 0)
  2991. {
  2992. $template = "special";
  2993. }
  2994. else
  2995. {
  2996. $template = "advanced";
  2997.  
  2998. if(strpos(FORUM_URL, '.html') !== false)
  2999. {
  3000. $forum_link = "'".str_replace('{fid}', "'+option+'", FORUM_URL)."'";
  3001. }
  3002. else
  3003. {
  3004. $forum_link = "'".str_replace('{fid}', "'+option", FORUM_URL);
  3005. }
  3006. }
  3007.  
  3008. eval("\$forumjump = \"".$templates->get("forumjump_".$template)."\";");
  3009. }
  3010.  
  3011. return $forumjump;
  3012. }
  3013.  
  3014. /**
  3015. * Returns the extension of a file.
  3016. *
  3017. * @param string $file The filename.
  3018. * @return string The extension of the file.
  3019. */
  3020. function get_extension($file)
  3021. {
  3022. return my_strtolower(my_substr(strrchr($file, "."), 1));
  3023. }
  3024.  
  3025. /**
  3026. * Generates a random string.
  3027. *
  3028. * @param int $length The length of the string to generate.
  3029. * @param bool $complex Whether to return complex string. Defaults to false
  3030. * @return string The random string.
  3031. */
  3032. function random_str($length=8, $complex=false)
  3033. {
  3034. $set = array_merge(range(0, 9), range('A', 'Z'), range('a', 'z'));
  3035. $str = array();
  3036.  
  3037. // Complex strings have always at least 3 characters, even if $length < 3
  3038. if($complex == true)
  3039. {
  3040. // At least one number
  3041. $str[] = $set[my_rand(0, 9)];
  3042.  
  3043. // At least one big letter
  3044. $str[] = $set[my_rand(10, 35)];
  3045.  
  3046. // At least one small letter
  3047. $str[] = $set[my_rand(36, 61)];
  3048.  
  3049. $length -= 3;
  3050. }
  3051.  
  3052. for($i = 0; $i < $length; ++$i)
  3053. {
  3054. $str[] = $set[my_rand(0, 61)];
  3055. }
  3056.  
  3057. // Make sure they're in random order and convert them to a string
  3058. shuffle($str);
  3059.  
  3060. return implode($str);
  3061. }
  3062.  
  3063. /**
  3064. * Formats a username based on their display group
  3065. *
  3066. * @param string $username The username
  3067. * @param int $usergroup The usergroup for the user
  3068. * @param int $displaygroup The display group for the user
  3069. * @return string The formatted username
  3070. */
  3071. function format_name($username, $usergroup, $displaygroup=0)
  3072. {
  3073. global $groupscache, $cache, $plugins;
  3074.  
  3075. static $formattednames = array();
  3076.  
  3077. if(!isset($formattednames[$username]))
  3078. {
  3079. if(!is_array($groupscache))
  3080. {
  3081. $groupscache = $cache->read("usergroups");
  3082. }
  3083.  
  3084. if($displaygroup != 0)
  3085. {
  3086. $usergroup = $displaygroup;
  3087. }
  3088.  
  3089. $format = "{username}";
  3090.  
  3091. if(isset($groupscache[$usergroup]))
  3092. {
  3093. $ugroup = $groupscache[$usergroup];
  3094.  
  3095. if(strpos($ugroup['namestyle'], "{username}") !== false)
  3096. {
  3097. $format = $ugroup['namestyle'];
  3098. }
  3099. }
  3100.  
  3101. $format = stripslashes($format);
  3102.  
  3103. $parameters = compact('username', 'usergroup', 'displaygroup', 'format');
  3104.  
  3105. $parameters = $plugins->run_hooks('format_name', $parameters);
  3106.  
  3107. $format = $parameters['format'];
  3108.  
  3109. $formattednames[$username] = str_replace("{username}", $username, $format);
  3110. }
  3111.  
  3112. return $formattednames[$username];
  3113. }
  3114.  
  3115. /**
  3116. * Formats an avatar to a certain dimension
  3117. *
  3118. * @param string $avatar The avatar file name
  3119. * @param string $dimensions Dimensions of the avatar, width x height (e.g. 44|44)
  3120. * @param string $max_dimensions The maximum dimensions of the formatted avatar
  3121. * @return array Information for the formatted avatar
  3122. */
  3123. function format_avatar($avatar, $dimensions = '', $max_dimensions = '')
  3124. {
  3125. global $mybb, $theme;
  3126. static $avatars;
  3127.  
  3128. if(!isset($avatars))
  3129. {
  3130. $avatars = array();
  3131. }
  3132.  
  3133. if(my_strpos($avatar, '://') !== false && !$mybb->settings['allowremoteavatars'])
  3134. {
  3135. // Remote avatar, but remote avatars are disallowed.
  3136. $avatar = null;
  3137. }
  3138.  
  3139. if(!$avatar)
  3140. {
  3141. // Default avatar
  3142. if(defined('IN_ADMINCP'))
  3143. {
  3144. $theme['imgdir'] = '../images';
  3145. }
  3146.  
  3147. $avatar = str_replace('{theme}', $theme['imgdir'], $mybb->settings['useravatar']);
  3148. $dimensions = $mybb->settings['useravatardims'];
  3149. }
  3150.  
  3151. if(!$max_dimensions)
  3152. {
  3153. $max_dimensions = $mybb->settings['maxavatardims'];
  3154. }
  3155.  
  3156. // An empty key wouldn't work so we need to add a fall back
  3157. $key = $dimensions;
  3158. if(empty($key))
  3159. {
  3160. $key = 'default';
  3161. }
  3162. $key2 = $max_dimensions;
  3163. if(empty($key2))
  3164. {
  3165. $key2 = 'default';
  3166. }
  3167.  
  3168. if(isset($avatars[$avatar][$key][$key2]))
  3169. {
  3170. return $avatars[$avatar][$key][$key2];
  3171. }
  3172.  
  3173. $avatar_width_height = '';
  3174.  
  3175. if($dimensions)
  3176. {
  3177. $dimensions = explode("|", $dimensions);
  3178.  
  3179. if($dimensions[0] && $dimensions[1])
  3180. {
  3181. list($max_width, $max_height) = explode('x', $max_dimensions);
  3182.  
  3183. if(!empty($max_dimensions) && ($dimensions[0] > $max_width || $dimensions[1] > $max_height))
  3184. {
  3185. require_once MYBB_ROOT."inc/functions_image.php";
  3186. $scaled_dimensions = scale_image($dimensions[0], $dimensions[1], $max_width, $max_height);
  3187. $avatar_width_height = "width=\"{$scaled_dimensions['width']}\" height=\"{$scaled_dimensions['height']}\"";
  3188. }
  3189. else
  3190. {
  3191. $avatar_width_height = "width=\"{$dimensions[0]}\" height=\"{$dimensions[1]}\"";
  3192. }
  3193. }
  3194. }
  3195.  
  3196. $avatars[$avatar][$key][$key2] = array(
  3197. 'image' => htmlspecialchars_uni($mybb->get_asset_url($avatar)),
  3198. 'width_height' => $avatar_width_height
  3199. );
  3200.  
  3201. return $avatars[$avatar][$key][$key2];
  3202. }
  3203.  
  3204. /**
  3205. * Build the javascript based MyCode inserter.
  3206. *
  3207. * @param string $bind The ID of the textarea to bind to. Defaults to "message".
  3208. * @param bool $smilies Whether to include smilies. Defaults to true.
  3209. *
  3210. * @return string The MyCode inserter
  3211. */
  3212. function build_mycode_inserter($bind="message", $smilies = true)
  3213. {
  3214. global $db, $mybb, $theme, $templates, $lang, $plugins, $smiliecache, $cache;
  3215.  
  3216. if($mybb->settings['bbcodeinserter'] != 0)
  3217. {
  3218. $editor_lang_strings = array(
  3219. "editor_bold" => "Bold",
  3220. "editor_italic" => "Italic",
  3221. "editor_underline" => "Underline",
  3222. "editor_strikethrough" => "Strikethrough",
  3223. "editor_subscript" => "Subscript",
  3224. "editor_superscript" => "Superscript",
  3225. "editor_alignleft" => "Align left",
  3226. "editor_center" => "Center",
  3227. "editor_alignright" => "Align right",
  3228. "editor_justify" => "Justify",
  3229. "editor_fontname" => "Font Name",
  3230. "editor_fontsize" => "Font Size",
  3231. "editor_fontcolor" => "Font Color",
  3232. "editor_removeformatting" => "Remove Formatting",
  3233. "editor_cut" => "Cut",
  3234. "editor_cutnosupport" => "Your browser does not allow the cut command. Please use the keyboard shortcut Ctrl/Cmd-X",
  3235. "editor_copy" => "Copy",
  3236. "editor_copynosupport" => "Your browser does not allow the copy command. Please use the keyboard shortcut Ctrl/Cmd-C",
  3237. "editor_paste" => "Paste",
  3238. "editor_pastenosupport" => "Your browser does not allow the paste command. Please use the keyboard shortcut Ctrl/Cmd-V",
  3239. "editor_pasteentertext" => "Paste your text inside the following box:",
  3240. "editor_pastetext" => "PasteText",
  3241. "editor_numlist" => "Numbered list",
  3242. "editor_bullist" => "Bullet list",
  3243. "editor_undo" => "Undo",
  3244. "editor_redo" => "Redo",
  3245. "editor_rows" => "Rows:",
  3246. "editor_cols" => "Cols:",
  3247. "editor_inserttable" => "Insert a table",
  3248. "editor_inserthr" => "Insert a horizontal rule",
  3249. "editor_code" => "Code",
  3250. "editor_width" => "Width (optional):",
  3251. "editor_height" => "Height (optional):",
  3252. "editor_insertimg" => "Insert an image",
  3253. "editor_email" => "E-mail:",
  3254. "editor_insertemail" => "Insert an email",
  3255. "editor_url" => "URL:",
  3256. "editor_insertlink" => "Insert a link",
  3257. "editor_unlink" => "Unlink",
  3258. "editor_more" => "More",
  3259. "editor_insertemoticon" => "Insert an emoticon",
  3260. "editor_videourl" => "Video URL:",
  3261. "editor_videotype" => "Video Type:",
  3262. "editor_insert" => "Insert",
  3263. "editor_insertyoutubevideo" => "Insert a YouTube video",
  3264. "editor_currentdate" => "Insert current date",
  3265. "editor_currenttime" => "Insert current time",
  3266. "editor_print" => "Print",
  3267. "editor_viewsource" => "View source",
  3268. "editor_description" => "Description (optional):",
  3269. "editor_enterimgurl" => "Enter the image URL:",
  3270. "editor_enteremail" => "Enter the e-mail address:",
  3271. "editor_enterdisplayedtext" => "Enter the displayed text:",
  3272. "editor_enterurl" => "Enter URL:",
  3273. "editor_enteryoutubeurl" => "Enter the YouTube video URL or ID:",
  3274. "editor_insertquote" => "Insert a Quote",
  3275. "editor_invalidyoutube" => "Invalid YouTube video",
  3276. "editor_dailymotion" => "Dailymotion",
  3277. "editor_metacafe" => "MetaCafe",
  3278. "editor_veoh" => "Veoh",
  3279. "editor_vimeo" => "Vimeo",
  3280. "editor_youtube" => "Youtube",
  3281. "editor_facebook" => "Facebook",
  3282. "editor_liveleak" => "LiveLeak",
  3283. "editor_insertvideo" => "Insert a video",
  3284. "editor_php" => "PHP",
  3285. "editor_maximize" => "Maximize"
  3286. );
  3287. $editor_language = "(function ($) {\n$.sceditor.locale[\"mybblang\"] = {\n";
  3288.  
  3289. $editor_lang_strings = $plugins->run_hooks("mycode_add_codebuttons", $editor_lang_strings);
  3290.  
  3291. $editor_languages_count = count($editor_lang_strings);
  3292. $i = 0;
  3293. foreach($editor_lang_strings as $lang_string => $key)
  3294. {
  3295. $i++;
  3296. $js_lang_string = str_replace("\"", "\\\"", $key);
  3297. $string = str_replace("\"", "\\\"", $lang->$lang_string);
  3298. $editor_language .= "\t\"{$js_lang_string}\": \"{$string}\"";
  3299.  
  3300. if($i < $editor_languages_count)
  3301. {
  3302. $editor_language .= ",";
  3303. }
  3304.  
  3305. $editor_language .= "\n";
  3306. }
  3307.  
  3308. $editor_language .= "}})(jQuery);";
  3309.  
  3310. if(defined("IN_ADMINCP"))
  3311. {
  3312. global $page;
  3313. $codeinsert = $page->build_codebuttons_editor($bind, $editor_language, $smilies);
  3314. }
  3315. else
  3316. {
  3317. // Smilies
  3318. $emoticon = "";
  3319. $emoticons_enabled = "false";
  3320. if($smilies)
  3321. {
  3322. if(!$smiliecache)
  3323. {
  3324. if(!isset($smilie_cache) || !is_array($smilie_cache))
  3325. {
  3326. $smilie_cache = $cache->read("smilies");
  3327. }
  3328. foreach($smilie_cache as $smilie)
  3329. {
  3330. $smilie['image'] = str_replace("{theme}", $theme['imgdir'], $smilie['image']);
  3331. $smiliecache[$smilie['sid']] = $smilie;
  3332. }
  3333. }
  3334.  
  3335. if($mybb->settings['smilieinserter'] && $mybb->settings['smilieinsertercols'] && $mybb->settings['smilieinsertertot'] && !empty($smiliecache))
  3336. {
  3337. $emoticon = ",emoticon";
  3338. }
  3339. $emoticons_enabled = "true";
  3340.  
  3341. unset($smilie);
  3342.  
  3343. if(is_array($smiliecache))
  3344. {
  3345. reset($smiliecache);
  3346.  
  3347. $dropdownsmilies = $moresmilies = $hiddensmilies = "";
  3348. $i = 0;
  3349.  
  3350. foreach($smiliecache as $smilie)
  3351. {
  3352. $finds = explode("\n", $smilie['find']);
  3353. $finds_count = count($finds);
  3354.  
  3355. // Only show the first text to replace in the box
  3356. $smilie['find'] = $finds[0];
  3357.  
  3358. $find = str_replace(array('\\', '"'), array('\\\\', '\"'), htmlspecialchars_uni($smilie['find']));
  3359. $image = htmlspecialchars_uni($mybb->get_asset_url($smilie['image']));
  3360. $image = str_replace(array('\\', '"'), array('\\\\', '\"'), $image);
  3361.  
  3362. if(!$mybb->settings['smilieinserter'] || !$mybb->settings['smilieinsertercols'] || !$mybb->settings['smilieinsertertot'] || !$smilie['showclickable'])
  3363. {
  3364. $hiddensmilies .= '"'.$find.'": "'.$image.'",';
  3365. }
  3366. elseif($i < $mybb->settings['smilieinsertertot'])
  3367. {
  3368. $dropdownsmilies .= '"'.$find.'": "'.$image.'",';
  3369. ++$i;
  3370. }
  3371. else
  3372. {
  3373. $moresmilies .= '"'.$find.'": "'.$image.'",';
  3374. }
  3375.  
  3376. for($j = 1; $j < $finds_count; ++$j)
  3377. {
  3378. $find = str_replace(array('\\', '"'), array('\\\\', '\"'), htmlspecialchars_uni($finds[$j]));
  3379. $hiddensmilies .= '"'.$find.'": "'.$image.'",';
  3380. }
  3381. }
  3382. }
  3383. }
  3384.  
  3385. $basic1 = $basic2 = $align = $font = $size = $color = $removeformat = $email = $link = $list = $code = $sourcemode = "";
  3386.  
  3387. if($mybb->settings['allowbasicmycode'] == 1)
  3388. {
  3389. $basic1 = "bold,italic,underline,strike|";
  3390. $basic2 = "horizontalrule,";
  3391. }
  3392.  
  3393. if($mybb->settings['allowalignmycode'] == 1)
  3394. {
  3395. $align = "left,center,right,justify|";
  3396. }
  3397.  
  3398. if($mybb->settings['allowfontmycode'] == 1)
  3399. {
  3400. $font = "font,";
  3401. }
  3402.  
  3403. if($mybb->settings['allowsizemycode'] == 1)
  3404. {
  3405. $size = "size,";
  3406. }
  3407.  
  3408. if($mybb->settings['allowcolormycode'] == 1)
  3409. {
  3410. $color = "color,";
  3411. }
  3412.  
  3413. if($mybb->settings['allowfontmycode'] == 1 || $mybb->settings['allowsizemycode'] == 1 || $mybb->settings['allowcolormycode'] == 1)
  3414. {
  3415. $removeformat = "removeformat|";
  3416. }
  3417.  
  3418. if($mybb->settings['allowemailmycode'] == 1)
  3419. {
  3420. $email = "email,";
  3421. }
  3422.  
  3423. if($mybb->settings['allowlinkmycode'] == 1)
  3424. {
  3425. $link = "link,unlink";
  3426. }
  3427.  
  3428. if($mybb->settings['allowlistmycode'] == 1)
  3429. {
  3430. $list = "bulletlist,orderedlist|";
  3431. }
  3432.  
  3433. if($mybb->settings['allowcodemycode'] == 1)
  3434. {
  3435. $code = "code,php,";
  3436. }
  3437.  
  3438. if($mybb->user['sourceeditor'] == 1)
  3439. {
  3440. $sourcemode = "MyBBEditor.sourceMode(true);";
  3441. }
  3442.  
  3443. eval("\$codeinsert = \"".$templates->get("codebuttons")."\";");
  3444. }
  3445. }
  3446.  
  3447. return $codeinsert;
  3448. }
  3449.  
  3450. /**
  3451. * Build the javascript clickable smilie inserter
  3452. *
  3453. * @return string The clickable smilies list
  3454. */
  3455. function build_clickable_smilies()
  3456. {
  3457. global $cache, $smiliecache, $theme, $templates, $lang, $mybb, $smiliecount;
  3458.  
  3459. if($mybb->settings['smilieinserter'] != 0 && $mybb->settings['smilieinsertercols'] && $mybb->settings['smilieinsertertot'])
  3460. {
  3461. if(!$smiliecount)
  3462. {
  3463. $smilie_cache = $cache->read("smilies");
  3464. $smiliecount = count($smilie_cache);
  3465. }
  3466.  
  3467. if(!$smiliecache)
  3468. {
  3469. if(!is_array($smilie_cache))
  3470. {
  3471. $smilie_cache = $cache->read("smilies");
  3472. }
  3473. foreach($smilie_cache as $smilie)
  3474. {
  3475. $smilie['image'] = str_replace("{theme}", $theme['imgdir'], $smilie['image']);
  3476. $smiliecache[$smilie['sid']] = $smilie;
  3477. }
  3478. }
  3479.  
  3480. unset($smilie);
  3481.  
  3482. if(is_array($smiliecache))
  3483. {
  3484. reset($smiliecache);
  3485.  
  3486. $getmore = '';
  3487. if($mybb->settings['smilieinsertertot'] >= $smiliecount)
  3488. {
  3489. $mybb->settings['smilieinsertertot'] = $smiliecount;
  3490. }
  3491. else if($mybb->settings['smilieinsertertot'] < $smiliecount)
  3492. {
  3493. $smiliecount = $mybb->settings['smilieinsertertot'];
  3494. eval("\$getmore = \"".$templates->get("smilieinsert_getmore")."\";");
  3495. }
  3496.  
  3497. $smilies = '';
  3498. $counter = 0;
  3499. $i = 0;
  3500.  
  3501. $extra_class = '';
  3502. foreach($smiliecache as $smilie)
  3503. {
  3504. if($i < $mybb->settings['smilieinsertertot'] && $smilie['showclickable'] != 0)
  3505. {
  3506. $smilie['image'] = str_replace("{theme}", $theme['imgdir'], $smilie['image']);
  3507. $smilie['image'] = htmlspecialchars_uni($mybb->get_asset_url($smilie['image']));
  3508. $smilie['name'] = htmlspecialchars_uni($smilie['name']);
  3509.  
  3510. // Only show the first text to replace in the box
  3511. $temp = explode("\n", $smilie['find']); // assign to temporary variable for php 5.3 compatibility
  3512. $smilie['find'] = $temp[0];
  3513.  
  3514. $find = str_replace(array('\\', "'"), array('\\\\', "\'"), htmlspecialchars_uni($smilie['find']));
  3515.  
  3516. $onclick = " onclick=\"MyBBEditor.insertText(' $find ');\"";
  3517. $extra_class = ' smilie_pointer';
  3518. eval('$smilie = "'.$templates->get('smilie', 1, 0).'";');
  3519. eval("\$smilie_icons .= \"".$templates->get("smilieinsert_smilie")."\";");
  3520. ++$i;
  3521. ++$counter;
  3522.  
  3523. if($counter == $mybb->settings['smilieinsertercols'])
  3524. {
  3525. $counter = 0;
  3526. eval("\$smilies .= \"".$templates->get("smilieinsert_row")."\";");
  3527. $smilie_icons = '';
  3528. }
  3529. }
  3530. }
  3531.  
  3532. if($counter != 0)
  3533. {
  3534. $colspan = $mybb->settings['smilieinsertercols'] - $counter;
  3535. eval("\$smilies .= \"".$templates->get("smilieinsert_row_empty")."\";");
  3536. }
  3537.  
  3538. eval("\$clickablesmilies = \"".$templates->get("smilieinsert")."\";");
  3539. }
  3540. else
  3541. {
  3542. $clickablesmilies = "";
  3543. }
  3544. }
  3545. else
  3546. {
  3547. $clickablesmilies = "";
  3548. }
  3549.  
  3550. return $clickablesmilies;
  3551. }
  3552.  
  3553. /**
  3554. * Builds thread prefixes and returns a selected prefix (or all)
  3555. *
  3556. * @param int $pid The prefix ID (0 to return all)
  3557. * @return array The thread prefix's values (or all thread prefixes)
  3558. */
  3559. function build_prefixes($pid=0)
  3560. {
  3561. global $cache;
  3562. static $prefixes_cache;
  3563.  
  3564. if(is_array($prefixes_cache))
  3565. {
  3566. if($pid > 0 && is_array($prefixes_cache[$pid]))
  3567. {
  3568. return $prefixes_cache[$pid];
  3569. }
  3570.  
  3571. return $prefixes_cache;
  3572. }
  3573.  
  3574. $prefix_cache = $cache->read("threadprefixes");
  3575.  
  3576. if(!is_array($prefix_cache))
  3577. {
  3578. // No cache
  3579. $prefix_cache = $cache->read("threadprefixes", true);
  3580.  
  3581. if(!is_array($prefix_cache))
  3582. {
  3583. return array();
  3584. }
  3585. }
  3586.  
  3587. $prefixes_cache = array();
  3588. foreach($prefix_cache as $prefix)
  3589. {
  3590. $prefixes_cache[$prefix['pid']] = $prefix;
  3591. }
  3592.  
  3593. if($pid != 0 && is_array($prefixes_cache[$pid]))
  3594. {
  3595. return $prefixes_cache[$pid];
  3596. }
  3597. else if(!empty($prefixes_cache))
  3598. {
  3599. return $prefixes_cache;
  3600. }
  3601.  
  3602. return false;
  3603. }
  3604.  
  3605. /**
  3606. * Build the thread prefix selection menu for the current user
  3607. *
  3608. * @param int|string $fid The forum ID (integer ID or string all)
  3609. * @param int|string $selected_pid The selected prefix ID (integer ID or string any)
  3610. * @param int $multiple Allow multiple prefix selection
  3611. * @param int $previous_pid The previously selected prefix ID
  3612. * @return string The thread prefix selection menu
  3613. */
  3614. function build_prefix_select($fid, $selected_pid=0, $multiple=0, $previous_pid=0)
  3615. {
  3616. global $cache, $db, $lang, $mybb, $templates;
  3617.  
  3618. if($fid != 'all')
  3619. {
  3620. $fid = (int)$fid;
  3621. }
  3622.  
  3623. $prefix_cache = build_prefixes(0);
  3624. if(empty($prefix_cache))
  3625. {
  3626. // We've got no prefixes to show
  3627. return '';
  3628. }
  3629.  
  3630. // Go through each of our prefixes and decide which ones we can use
  3631. $prefixes = array();
  3632. foreach($prefix_cache as $prefix)
  3633. {
  3634. if($fid != "all" && $prefix['forums'] != "-1")
  3635. {
  3636. // Decide whether this prefix can be used in our forum
  3637. $forums = explode(",", $prefix['forums']);
  3638.  
  3639. if(!in_array($fid, $forums) && $prefix['pid'] != $previous_pid)
  3640. {
  3641. // This prefix is not in our forum list
  3642. continue;
  3643. }
  3644. }
  3645.  
  3646. if(is_member($prefix['groups']) || $prefix['pid'] == $previous_pid)
  3647. {
  3648. // The current user can use this prefix
  3649. $prefixes[$prefix['pid']] = $prefix;
  3650. }
  3651. }
  3652.  
  3653. if(empty($prefixes))
  3654. {
  3655. return '';
  3656. }
  3657.  
  3658. $prefixselect = $prefixselect_prefix = '';
  3659.  
  3660. if($multiple == 1)
  3661. {
  3662. $any_selected = "";
  3663. if($selected_pid == 'any')
  3664. {
  3665. $any_selected = " selected=\"selected\"";
  3666. }
  3667. }
  3668.  
  3669. $default_selected = "";
  3670. if(((int)$selected_pid == 0) && $selected_pid != 'any')
  3671. {
  3672. $default_selected = " selected=\"selected\"";
  3673. }
  3674.  
  3675. foreach($prefixes as $prefix)
  3676. {
  3677. $selected = "";
  3678. if($prefix['pid'] == $selected_pid)
  3679. {
  3680. $selected = " selected=\"selected\"";
  3681. }
  3682.  
  3683. $prefix['prefix'] = htmlspecialchars_uni($prefix['prefix']);
  3684. eval("\$prefixselect_prefix .= \"".$templates->get("post_prefixselect_prefix")."\";");
  3685. }
  3686.  
  3687. if($multiple != 0)
  3688. {
  3689. eval("\$prefixselect = \"".$templates->get("post_prefixselect_multiple")."\";");
  3690. }
  3691. else
  3692. {
  3693. eval("\$prefixselect = \"".$templates->get("post_prefixselect_single")."\";");
  3694. }
  3695.  
  3696. return $prefixselect;
  3697. }
  3698.  
  3699. /**
  3700. * Build the thread prefix selection menu for a forum without group permission checks
  3701. *
  3702. * @param int $fid The forum ID (integer ID)
  3703. * @param int $selected_pid The selected prefix ID (integer ID)
  3704. * @return string The thread prefix selection menu
  3705. */
  3706. function build_forum_prefix_select($fid, $selected_pid=0)
  3707. {
  3708. global $cache, $db, $lang, $mybb, $templates;
  3709.  
  3710. $fid = (int)$fid;
  3711.  
  3712. $prefix_cache = build_prefixes(0);
  3713. if(empty($prefix_cache))
  3714. {
  3715. // We've got no prefixes to show
  3716. return '';
  3717. }
  3718.  
  3719. // Go through each of our prefixes and decide which ones we can use
  3720. $prefixes = array();
  3721. foreach($prefix_cache as $prefix)
  3722. {
  3723. if($prefix['forums'] != "-1")
  3724. {
  3725. // Decide whether this prefix can be used in our forum
  3726. $forums = explode(",", $prefix['forums']);
  3727.  
  3728. if(in_array($fid, $forums))
  3729. {
  3730. // This forum can use this prefix!
  3731. $prefixes[$prefix['pid']] = $prefix;
  3732. }
  3733. }
  3734. else
  3735. {
  3736. // This prefix is for anybody to use...
  3737. $prefixes[$prefix['pid']] = $prefix;
  3738. }
  3739. }
  3740.  
  3741. if(empty($prefixes))
  3742. {
  3743. return '';
  3744. }
  3745.  
  3746. $default_selected = array();
  3747. $selected_pid = (int)$selected_pid;
  3748.  
  3749. if($selected_pid == 0)
  3750. {
  3751. $default_selected['all'] = ' selected="selected"';
  3752. }
  3753. else if($selected_pid == -1)
  3754. {
  3755. $default_selected['none'] = ' selected="selected"';
  3756. }
  3757. else if($selected_pid == -2)
  3758. {
  3759. $default_selected['any'] = ' selected="selected"';
  3760. }
  3761.  
  3762. foreach($prefixes as $prefix)
  3763. {
  3764. $selected = '';
  3765. if($prefix['pid'] == $selected_pid)
  3766. {
  3767. $selected = ' selected="selected"';
  3768. }
  3769.  
  3770. $prefix['prefix'] = htmlspecialchars_uni($prefix['prefix']);
  3771. eval('$prefixselect_prefix .= "'.$templates->get("forumdisplay_threadlist_prefixes_prefix").'";');
  3772. }
  3773.  
  3774. eval('$prefixselect = "'.$templates->get("forumdisplay_threadlist_prefixes").'";');
  3775. return $prefixselect;
  3776. }
  3777.  
  3778. /**
  3779. * Gzip encodes text to a specified level
  3780. *
  3781. * @param string $contents The string to encode
  3782. * @param int $level The level (1-9) to encode at
  3783. * @return string The encoded string
  3784. */
  3785. function gzip_encode($contents, $level=1)
  3786. {
  3787. if(function_exists("gzcompress") && function_exists("crc32") && !headers_sent() && !(ini_get('output_buffering') && my_strpos(' '.ini_get('output_handler'), 'ob_gzhandler')))
  3788. {
  3789. $httpaccept_encoding = '';
  3790.  
  3791. if(isset($_SERVER['HTTP_ACCEPT_ENCODING']))
  3792. {
  3793. $httpaccept_encoding = $_SERVER['HTTP_ACCEPT_ENCODING'];
  3794. }
  3795.  
  3796. if(my_strpos(" ".$httpaccept_encoding, "x-gzip"))
  3797. {
  3798. $encoding = "x-gzip";
  3799. }
  3800.  
  3801. if(my_strpos(" ".$httpaccept_encoding, "gzip"))
  3802. {
  3803. $encoding = "gzip";
  3804. }
  3805.  
  3806. if(isset($encoding))
  3807. {
  3808. header("Content-Encoding: $encoding");
  3809.  
  3810. if(function_exists("gzencode"))
  3811. {
  3812. $contents = gzencode($contents, $level);
  3813. }
  3814. else
  3815. {
  3816. $size = strlen($contents);
  3817. $crc = crc32($contents);
  3818. $gzdata = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff";
  3819. $gzdata .= my_substr(gzcompress($contents, $level), 2, -4);
  3820. $gzdata .= pack("V", $crc);
  3821. $gzdata .= pack("V", $size);
  3822. $contents = $gzdata;
  3823. }
  3824. }
  3825. }
  3826.  
  3827. return $contents;
  3828. }
  3829.  
  3830. /**
  3831. * Log the actions of a moderator.
  3832. *
  3833. * @param array $data The data of the moderator's action.
  3834. * @param string $action The message to enter for the action the moderator performed.
  3835. */
  3836. function log_moderator_action($data, $action="")
  3837. {
  3838. global $mybb, $db, $session;
  3839.  
  3840. $fid = 0;
  3841. if(isset($data['fid']))
  3842. {
  3843. $fid = (int)$data['fid'];
  3844. unset($data['fid']);
  3845. }
  3846.  
  3847. $tid = 0;
  3848. if(isset($data['tid']))
  3849. {
  3850. $tid = (int)$data['tid'];
  3851. unset($data['tid']);
  3852. }
  3853.  
  3854. $pid = 0;
  3855. if(isset($data['pid']))
  3856. {
  3857. $pid = (int)$data['pid'];
  3858. unset($data['pid']);
  3859. }
  3860.  
  3861. $tids = array();
  3862. if(isset($data['tids']))
  3863. {
  3864. $tids = (array)$data['tids'];
  3865. unset($data['tids']);
  3866. }
  3867.  
  3868. // Any remaining extra data - we my_serialize and insert in to its own column
  3869. if(is_array($data))
  3870. {
  3871. $data = my_serialize($data);
  3872. }
  3873.  
  3874. $sql_array = array(
  3875. "uid" => (int)$mybb->user['uid'],
  3876. "dateline" => TIME_NOW,
  3877. "fid" => (int)$fid,
  3878. "tid" => $tid,
  3879. "pid" => $pid,
  3880. "action" => $db->escape_string($action),
  3881. "data" => $db->escape_string($data),
  3882. "ipaddress" => $db->escape_binary($session->packedip)
  3883. );
  3884.  
  3885. if($tids)
  3886. {
  3887. $multiple_sql_array = array();
  3888.  
  3889. foreach($tids as $tid)
  3890. {
  3891. $sql_array['tid'] = (int)$tid;
  3892. $multiple_sql_array[] = $sql_array;
  3893. }
  3894.  
  3895. $db->insert_query_multiple("moderatorlog", $multiple_sql_array);
  3896. }
  3897. else
  3898. {
  3899. $db->insert_query("moderatorlog", $sql_array);
  3900. }
  3901. }
  3902.  
  3903. /**
  3904. * Get the formatted reputation for a user.
  3905. *
  3906. * @param int $reputation The reputation value
  3907. * @param int $uid The user ID (if not specified, the generated reputation will not be a link)
  3908. * @return string The formatted repuation
  3909. */
  3910. function get_reputation($reputation, $uid=0)
  3911. {
  3912. global $theme, $templates;
  3913.  
  3914. $display_reputation = $reputation_class = '';
  3915. if($reputation < 0)
  3916. {
  3917. $reputation_class = "reputation_negative";
  3918. }
  3919. elseif($reputation > 0)
  3920. {
  3921. $reputation_class = "reputation_positive";
  3922. }
  3923. else
  3924. {
  3925. $reputation_class = "reputation_neutral";
  3926. }
  3927.  
  3928. $reputation = my_number_format($reputation);
  3929.  
  3930. if($uid != 0)
  3931. {
  3932. eval("\$display_reputation = \"".$templates->get("postbit_reputation_formatted_link")."\";");
  3933. }
  3934. else
  3935. {
  3936. eval("\$display_reputation = \"".$templates->get("postbit_reputation_formatted")."\";");
  3937. }
  3938.  
  3939. return $display_reputation;
  3940. }
  3941.  
  3942. /**
  3943. * Fetch a color coded version of a warning level (based on it's percentage)
  3944. *
  3945. * @param int $level The warning level (percentage of 100)
  3946. * @return string Formatted warning level
  3947. */
  3948. function get_colored_warning_level($level)
  3949. {
  3950. global $templates;
  3951.  
  3952. $warning_class = '';
  3953. if($level >= 80)
  3954. {
  3955. $warning_class = "high_warning";
  3956. }
  3957. else if($level >= 50)
  3958. {
  3959. $warning_class = "moderate_warning";
  3960. }
  3961. else if($level >= 25)
  3962. {
  3963. $warning_class = "low_warning";
  3964. }
  3965. else
  3966. {
  3967. $warning_class = "normal_warning";
  3968. }
  3969.  
  3970. eval("\$level = \"".$templates->get("postbit_warninglevel_formatted")."\";");
  3971. return $level;
  3972. }
  3973.  
  3974. /**
  3975. * Fetch the IP address of the current user.
  3976. *
  3977. * @return string The IP address.
  3978. */
  3979. function get_ip()
  3980. {
  3981. global $mybb, $plugins;
  3982.  
  3983. $ip = strtolower($_SERVER['REMOTE_ADDR']);
  3984.  
  3985. if($mybb->settings['ip_forwarded_check'])
  3986. {
  3987. $addresses = array();
  3988.  
  3989. if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  3990. {
  3991. $addresses = explode(',', strtolower($_SERVER['HTTP_X_FORWARDED_FOR']));
  3992. }
  3993. elseif(isset($_SERVER['HTTP_X_REAL_IP']))
  3994. {
  3995. $addresses = explode(',', strtolower($_SERVER['HTTP_X_REAL_IP']));
  3996. }
  3997.  
  3998. if(is_array($addresses))
  3999. {
  4000. foreach($addresses as $val)
  4001. {
  4002. $val = trim($val);
  4003. // Validate IP address and exclude private addresses
  4004. if(my_inet_ntop(my_inet_pton($val)) == $val && !preg_match("#^(10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.|fe80:|fe[c-f][0-f]:|f[c-d][0-f]{2}:)#", $val))
  4005. {
  4006. $ip = $val;
  4007. break;
  4008. }
  4009. }
  4010. }
  4011. }
  4012.  
  4013. if(!$ip)
  4014. {
  4015. if(isset($_SERVER['HTTP_CLIENT_IP']))
  4016. {
  4017. $ip = strtolower($_SERVER['HTTP_CLIENT_IP']);
  4018. }
  4019. }
  4020.  
  4021. if($plugins)
  4022. {
  4023. $ip_array = array("ip" => &$ip); // Used for backwards compatibility on this hook with the updated run_hooks() function.
  4024. $plugins->run_hooks("get_ip", $ip_array);
  4025. }
  4026.  
  4027. return $ip;
  4028. }
  4029.  
  4030. /**
  4031. * Fetch the friendly size (GB, MB, KB, B) for a specified file size.
  4032. *
  4033. * @param int $size The size in bytes
  4034. * @return string The friendly file size
  4035. */
  4036. function get_friendly_size($size)
  4037. {
  4038. global $lang;
  4039.  
  4040. if(!is_numeric($size))
  4041. {
  4042. return $lang->na;
  4043. }
  4044.  
  4045. // Yottabyte (1024 Zettabytes)
  4046. if($size >= 1208925819614629174706176)
  4047. {
  4048. $size = my_number_format(round(($size / 1208925819614629174706176), 2))." ".$lang->size_yb;
  4049. }
  4050. // Zetabyte (1024 Exabytes)
  4051. elseif($size >= 1180591620717411303424)
  4052. {
  4053. $size = my_number_format(round(($size / 1180591620717411303424), 2))." ".$lang->size_zb;
  4054. }
  4055. // Exabyte (1024 Petabytes)
  4056. elseif($size >= 1152921504606846976)
  4057. {
  4058. $size = my_number_format(round(($size / 1152921504606846976), 2))." ".$lang->size_eb;
  4059. }
  4060. // Petabyte (1024 Terabytes)
  4061. elseif($size >= 1125899906842624)
  4062. {
  4063. $size = my_number_format(round(($size / 1125899906842624), 2))." ".$lang->size_pb;
  4064. }
  4065. // Terabyte (1024 Gigabytes)
  4066. elseif($size >= 1099511627776)
  4067. {
  4068. $size = my_number_format(round(($size / 1099511627776), 2))." ".$lang->size_tb;
  4069. }
  4070. // Gigabyte (1024 Megabytes)
  4071. elseif($size >= 1073741824)
  4072. {
  4073. $size = my_number_format(round(($size / 1073741824), 2))." ".$lang->size_gb;
  4074. }
  4075. // Megabyte (1024 Kilobytes)
  4076. elseif($size >= 1048576)
  4077. {
  4078. $size = my_number_format(round(($size / 1048576), 2))." ".$lang->size_mb;
  4079. }
  4080. // Kilobyte (1024 bytes)
  4081. elseif($size >= 1024)
  4082. {
  4083. $size = my_number_format(round(($size / 1024), 2))." ".$lang->size_kb;
  4084. }
  4085. elseif($size == 0)
  4086. {
  4087. $size = "0 ".$lang->size_bytes;
  4088. }
  4089. else
  4090. {
  4091. $size = my_number_format($size)." ".$lang->size_bytes;
  4092. }
  4093.  
  4094. return $size;
  4095. }
  4096.  
  4097. /**
  4098. * Format a decimal number in to microseconds, milliseconds, or seconds.
  4099. *
  4100. * @param int $time The time in microseconds
  4101. * @return string The friendly time duration
  4102. */
  4103. function format_time_duration($time)
  4104. {
  4105. global $lang;
  4106.  
  4107. if(!is_numeric($time))
  4108. {
  4109. return $lang->na;
  4110. }
  4111.  
  4112. if(round(1000000 * $time, 2) < 1000)
  4113. {
  4114. $time = number_format(round(1000000 * $time, 2))." μs";
  4115. }
  4116. elseif(round(1000000 * $time, 2) >= 1000 && round(1000000 * $time, 2) < 1000000)
  4117. {
  4118. $time = number_format(round((1000 * $time), 2))." ms";
  4119. }
  4120. else
  4121. {
  4122. $time = round($time, 3)." seconds";
  4123. }
  4124.  
  4125. return $time;
  4126. }
  4127.  
  4128. /**
  4129. * Get the attachment icon for a specific file extension
  4130. *
  4131. * @param string $ext The file extension
  4132. * @return string The attachment icon
  4133. */
  4134. function get_attachment_icon($ext)
  4135. {
  4136. global $cache, $attachtypes, $theme, $templates, $lang, $mybb;
  4137.  
  4138. if(!$attachtypes)
  4139. {
  4140. $attachtypes = $cache->read("attachtypes");
  4141. }
  4142.  
  4143. $ext = my_strtolower($ext);
  4144.  
  4145. if($attachtypes[$ext]['icon'])
  4146. {
  4147. static $attach_icons_schemes = array();
  4148. if(!isset($attach_icons_schemes[$ext]))
  4149. {
  4150. $attach_icons_schemes[$ext] = parse_url($attachtypes[$ext]['icon']);
  4151. if(!empty($attach_icons_schemes[$ext]['scheme']))
  4152. {
  4153. $attach_icons_schemes[$ext] = $attachtypes[$ext]['icon'];
  4154. }
  4155. elseif(defined("IN_ADMINCP"))
  4156. {
  4157. $attach_icons_schemes[$ext] = str_replace("{theme}", "", $attachtypes[$ext]['icon']);
  4158. if(my_substr($attach_icons_schemes[$ext], 0, 1) != "/")
  4159. {
  4160. $attach_icons_schemes[$ext] = "../".$attach_icons_schemes[$ext];
  4161. }
  4162. }
  4163. elseif(defined("IN_PORTAL"))
  4164. {
  4165. global $change_dir;
  4166. $attach_icons_schemes[$ext] = $change_dir."/".str_replace("{theme}", $theme['imgdir'], $attachtypes[$ext]['icon']);
  4167. $attach_icons_schemes[$ext] = $mybb->get_asset_url($attach_icons_schemes[$ext]);
  4168. }
  4169. else
  4170. {
  4171. $attach_icons_schemes[$ext] = str_replace("{theme}", $theme['imgdir'], $attachtypes[$ext]['icon']);
  4172. $attach_icons_schemes[$ext] = $mybb->get_asset_url($attach_icons_schemes[$ext]);
  4173. }
  4174. }
  4175.  
  4176. $icon = $attach_icons_schemes[$ext];
  4177.  
  4178. $name = htmlspecialchars_uni($attachtypes[$ext]['name']);
  4179. }
  4180. else
  4181. {
  4182. if(defined("IN_ADMINCP"))
  4183. {
  4184. $theme['imgdir'] = "../images";
  4185. }
  4186. else if(defined("IN_PORTAL"))
  4187. {
  4188. global $change_dir;
  4189. $theme['imgdir'] = "{$change_dir}/images";
  4190. }
  4191.  
  4192. $icon = "{$theme['imgdir']}/attachtypes/unknown.png";
  4193.  
  4194. $name = $lang->unknown;
  4195. }
  4196.  
  4197. $icon = htmlspecialchars_uni($icon);
  4198. eval("\$attachment_icon = \"".$templates->get("attachment_icon")."\";");
  4199. return $attachment_icon;
  4200. }
  4201.  
  4202. /**
  4203. * Get a list of the unviewable forums for the current user
  4204. *
  4205. * @param boolean $only_readable_threads Set to true to only fetch those forums for which users can actually read a thread in.
  4206. * @return string Comma separated values list of the forum IDs which the user cannot view
  4207. */
  4208. function get_unviewable_forums($only_readable_threads=false)
  4209. {
  4210. global $forum_cache, $permissioncache, $mybb;
  4211.  
  4212. if(!is_array($forum_cache))
  4213. {
  4214. cache_forums();
  4215. }
  4216.  
  4217. if(!is_array($permissioncache))
  4218. {
  4219. $permissioncache = forum_permissions();
  4220. }
  4221.  
  4222. $password_forums = $unviewable = array();
  4223. foreach($forum_cache as $fid => $forum)
  4224. {
  4225. if($permissioncache[$forum['fid']])
  4226. {
  4227. $perms = $permissioncache[$forum['fid']];
  4228. }
  4229. else
  4230. {
  4231. $perms = $mybb->usergroup;
  4232. }
  4233.  
  4234. $pwverified = 1;
  4235.  
  4236. if($forum['password'] != "")
  4237. {
  4238. if($mybb->cookies['forumpass'][$forum['fid']] !== md5($mybb->user['uid'].$forum['password']))
  4239. {
  4240. $pwverified = 0;
  4241. }
  4242.  
  4243. $password_forums[$forum['fid']] = $forum['password'];
  4244. }
  4245. else
  4246. {
  4247. // Check parents for passwords
  4248. $parents = explode(",", $forum['parentlist']);
  4249. foreach($parents as $parent)
  4250. {
  4251. if(isset($password_forums[$parent]) && $mybb->cookies['forumpass'][$parent] !== md5($mybb->user['uid'].$password_forums[$parent]))
  4252. {
  4253. $pwverified = 0;
  4254. }
  4255. }
  4256. }
  4257.  
  4258. if($perms['canview'] == 0 || $pwverified == 0 || ($only_readable_threads == true && $perms['canviewthreads'] == 0))
  4259. {
  4260. $unviewable[] = $forum['fid'];
  4261. }
  4262. }
  4263.  
  4264. $unviewableforums = implode(',', $unviewable);
  4265.  
  4266. return $unviewableforums;
  4267. }
  4268.  
  4269. /**
  4270. * Fixes mktime for dates earlier than 1970
  4271. *
  4272. * @param string $format The date format to use
  4273. * @param int $year The year of the date
  4274. * @return string The correct date format
  4275. */
  4276. function fix_mktime($format, $year)
  4277. {
  4278. // Our little work around for the date < 1970 thing.
  4279. // -2 idea provided by Matt Light (http://www.mephex.com)
  4280. $format = str_replace("Y", $year, $format);
  4281. $format = str_replace("y", my_substr($year, -2), $format);
  4282.  
  4283. return $format;
  4284. }
  4285.  
  4286. /**
  4287. * Build the breadcrumb navigation trail from the specified items
  4288. *
  4289. * @return string The formatted breadcrumb navigation trail
  4290. */
  4291. function build_breadcrumb()
  4292. {
  4293. global $nav, $navbits, $templates, $theme, $lang, $mybb;
  4294.  
  4295. eval("\$navsep = \"".$templates->get("nav_sep")."\";");
  4296.  
  4297. $i = 0;
  4298. $activesep = '';
  4299.  
  4300. if(is_array($navbits))
  4301. {
  4302. reset($navbits);
  4303. foreach($navbits as $key => $navbit)
  4304. {
  4305. if(isset($navbits[$key+1]))
  4306. {
  4307. if(isset($navbits[$key+2]))
  4308. {
  4309. $sep = $navsep;
  4310. }
  4311. else
  4312. {
  4313. $sep = "";
  4314. }
  4315.  
  4316. $multipage = null;
  4317. $multipage_dropdown = null;
  4318. if(!empty($navbit['multipage']))
  4319. {
  4320. if(!$mybb->settings['threadsperpage'] || (int)$mybb->settings['threadsperpage'] < 1)
  4321. {
  4322. $mybb->settings['threadsperpage'] = 20;
  4323. }
  4324.  
  4325. $multipage = multipage($navbit['multipage']['num_threads'], $mybb->settings['threadsperpage'], $navbit['multipage']['current_page'], $navbit['multipage']['url'], true);
  4326. if($multipage)
  4327. {
  4328. ++$i;
  4329. eval("\$multipage_dropdown = \"".$templates->get("nav_dropdown")."\";");
  4330. $sep = $multipage_dropdown.$sep;
  4331. }
  4332. }
  4333.  
  4334. // Replace page 1 URLs
  4335. $navbit['url'] = str_replace("-page-1.html", ".html", $navbit['url']);
  4336. $navbit['url'] = preg_replace("/&amp;page=1$/", "", $navbit['url']);
  4337.  
  4338. eval("\$nav .= \"".$templates->get("nav_bit")."\";");
  4339. }
  4340. }
  4341. }
  4342.  
  4343. $activesep = '';
  4344. $navsize = count($navbits);
  4345. $navbit = $navbits[$navsize-1];
  4346.  
  4347. if($nav)
  4348. {
  4349. eval("\$activesep = \"".$templates->get("nav_sep_active")."\";");
  4350. }
  4351.  
  4352. eval("\$activebit = \"".$templates->get("nav_bit_active")."\";");
  4353. eval("\$donenav = \"".$templates->get("nav")."\";");
  4354.  
  4355. return $donenav;
  4356. }
  4357.  
  4358. /**
  4359. * Add a breadcrumb menu item to the list.
  4360. *
  4361. * @param string $name The name of the item to add
  4362. * @param string $url The URL of the item to add
  4363. */
  4364. function add_breadcrumb($name, $url="")
  4365. {
  4366. global $navbits;
  4367.  
  4368. $navsize = count($navbits);
  4369. $navbits[$navsize]['name'] = $name;
  4370. $navbits[$navsize]['url'] = $url;
  4371. }
  4372.  
  4373. /**
  4374. * Build the forum breadcrumb nagiation (the navigation to a specific forum including all parent forums)
  4375. *
  4376. * @param int $fid The forum ID to build the navigation for
  4377. * @param array $multipage The multipage drop down array of information
  4378. * @return int Returns 1 in every case. Kept for compatibility
  4379. */
  4380. function build_forum_breadcrumb($fid, $multipage=array())
  4381. {
  4382. global $pforumcache, $currentitem, $forum_cache, $navbits, $lang, $base_url, $archiveurl;
  4383.  
  4384. if(!$pforumcache)
  4385. {
  4386. if(!is_array($forum_cache))
  4387. {
  4388. cache_forums();
  4389. }
  4390.  
  4391. foreach($forum_cache as $key => $val)
  4392. {
  4393. $pforumcache[$val['fid']][$val['pid']] = $val;
  4394. }
  4395. }
  4396.  
  4397. if(is_array($pforumcache[$fid]))
  4398. {
  4399. foreach($pforumcache[$fid] as $key => $forumnav)
  4400. {
  4401. if($fid == $forumnav['fid'])
  4402. {
  4403. if(!empty($pforumcache[$forumnav['pid']]))
  4404. {
  4405. build_forum_breadcrumb($forumnav['pid']);
  4406. }
  4407.  
  4408. $navsize = count($navbits);
  4409. // Convert & to &amp;
  4410. $navbits[$navsize]['name'] = preg_replace("#&(?!\#[0-9]+;)#si", "&amp;", $forumnav['name']);
  4411.  
  4412. if(defined("IN_ARCHIVE"))
  4413. {
  4414. // Set up link to forum in breadcrumb.
  4415. if($pforumcache[$fid][$forumnav['pid']]['type'] == 'f' || $pforumcache[$fid][$forumnav['pid']]['type'] == 'c')
  4416. {
  4417. $navbits[$navsize]['url'] = "{$base_url}forum-".$forumnav['fid'].".html";
  4418. }
  4419. else
  4420. {
  4421. $navbits[$navsize]['url'] = $archiveurl."/index.php";
  4422. }
  4423. }
  4424. elseif(!empty($multipage))
  4425. {
  4426. $navbits[$navsize]['url'] = get_forum_link($forumnav['fid'], $multipage['current_page']);
  4427.  
  4428. $navbits[$navsize]['multipage'] = $multipage;
  4429. $navbits[$navsize]['multipage']['url'] = str_replace('{fid}', $forumnav['fid'], FORUM_URL_PAGED);
  4430. }
  4431. else
  4432. {
  4433. $navbits[$navsize]['url'] = get_forum_link($forumnav['fid']);
  4434. }
  4435. }
  4436. }
  4437. }
  4438.  
  4439. return 1;
  4440. }
  4441.  
  4442. /**
  4443. * Resets the breadcrumb navigation to the first item, and clears the rest
  4444. */
  4445. function reset_breadcrumb()
  4446. {
  4447. global $navbits;
  4448.  
  4449. $newnav[0]['name'] = $navbits[0]['name'];
  4450. $newnav[0]['url'] = $navbits[0]['url'];
  4451. if(!empty($navbits[0]['options']))
  4452. {
  4453. $newnav[0]['options'] = $navbits[0]['options'];
  4454. }
  4455.  
  4456. unset($GLOBALS['navbits']);
  4457. $GLOBALS['navbits'] = $newnav;
  4458. }
  4459.  
  4460. /**
  4461. * Builds a URL to an archive mode page
  4462. *
  4463. * @param string $type The type of page (thread|announcement|forum)
  4464. * @param int $id The ID of the item
  4465. * @return string The URL
  4466. */
  4467. function build_archive_link($type="", $id=0)
  4468. {
  4469. global $mybb;
  4470.  
  4471. // If the server OS is not Windows and not Apache or the PHP is running as a CGI or we have defined ARCHIVE_QUERY_STRINGS, use query strings - DIRECTORY_SEPARATOR checks if running windows
  4472. //if((DIRECTORY_SEPARATOR == '\\' && is_numeric(stripos($_SERVER['SERVER_SOFTWARE'], "apache")) == false) || is_numeric(stripos(SAPI_NAME, "cgi")) !== false || defined("ARCHIVE_QUERY_STRINGS"))
  4473. if($mybb->settings['seourls_archive'] == 1)
  4474. {
  4475. $base_url = $mybb->settings['bburl']."/archive/index.php/";
  4476. }
  4477. else
  4478. {
  4479. $base_url = $mybb->settings['bburl']."/archive/index.php?";
  4480. }
  4481.  
  4482. switch($type)
  4483. {
  4484. case "thread":
  4485. $url = "{$base_url}thread-{$id}.html";
  4486. break;
  4487. case "announcement":
  4488. $url = "{$base_url}announcement-{$id}.html";
  4489. break;
  4490. case "forum":
  4491. $url = "{$base_url}forum-{$id}.html";
  4492. break;
  4493. default:
  4494. $url = $mybb->settings['bburl']."/archive/index.php";
  4495. }
  4496.  
  4497. return $url;
  4498. }
  4499.  
  4500. /**
  4501. * Prints a debug information page
  4502. */
  4503. function debug_page()
  4504. {
  4505. global $db, $debug, $templates, $templatelist, $mybb, $maintimer, $globaltime, $ptimer, $parsetime, $lang, $cache;
  4506.  
  4507. $totaltime = format_time_duration($maintimer->totaltime);
  4508. $phptime = $maintimer->totaltime - $db->query_time;
  4509. $query_time = $db->query_time;
  4510. $globaltime = format_time_duration($globaltime);
  4511.  
  4512. $percentphp = number_format((($phptime/$maintimer->totaltime)*100), 2);
  4513. $percentsql = number_format((($query_time/$maintimer->totaltime)*100), 2);
  4514.  
  4515. $phptime = format_time_duration($maintimer->totaltime - $db->query_time);
  4516. $query_time = format_time_duration($db->query_time);
  4517.  
  4518. $call_time = format_time_duration($cache->call_time);
  4519.  
  4520. $phpversion = PHP_VERSION;
  4521.  
  4522. $serverload = get_server_load();
  4523.  
  4524. if($mybb->settings['gzipoutput'] != 0)
  4525. {
  4526. $gzipen = "Enabled";
  4527. }
  4528. else
  4529. {
  4530. $gzipen = "Disabled";
  4531. }
  4532.  
  4533. echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
  4534. echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">";
  4535. echo "<head>";
  4536. echo "<meta name=\"robots\" content=\"noindex\" />";
  4537. echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />";
  4538. echo "<title>MyBB Debug Information</title>";
  4539. echo "</head>";
  4540. echo "<body>";
  4541. echo "<h1>MyBB Debug Information</h1>\n";
  4542. echo "<h2>Page Generation</h2>\n";
  4543. echo "<table bgcolor=\"#666666\" width=\"95%\" cellpadding=\"4\" cellspacing=\"1\" align=\"center\">\n";
  4544. echo "<tr>\n";
  4545. echo "<td bgcolor=\"#cccccc\" colspan=\"4\"><b><span style=\"size:2;\">Page Generation Statistics</span></b></td>\n";
  4546. echo "</tr>\n";
  4547. echo "<tr>\n";
  4548. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">Page Generation Time:</span></b></td>\n";
  4549. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">$totaltime</span></td>\n";
  4550. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">No. DB Queries:</span></b></td>\n";
  4551. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">$db->query_count</span></td>\n";
  4552. echo "</tr>\n";
  4553. echo "<tr>\n";
  4554. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">PHP Processing Time:</span></b></td>\n";
  4555. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">$phptime ($percentphp%)</span></td>\n";
  4556. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">DB Processing Time:</span></b></td>\n";
  4557. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">$query_time ($percentsql%)</span></td>\n";
  4558. echo "</tr>\n";
  4559. echo "<tr>\n";
  4560. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">Extensions Used:</span></b></td>\n";
  4561. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">{$mybb->config['database']['type']}, xml</span></td>\n";
  4562. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">Global.php Processing Time:</span></b></td>\n";
  4563. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">$globaltime</span></td>\n";
  4564. echo "</tr>\n";
  4565. echo "<tr>\n";
  4566. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">PHP Version:</span></b></td>\n";
  4567. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">$phpversion</span></td>\n";
  4568. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">Server Load:</span></b></td>\n";
  4569. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">$serverload</span></td>\n";
  4570. echo "</tr>\n";
  4571. echo "<tr>\n";
  4572. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">GZip Encoding Status:</span></b></td>\n";
  4573. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">$gzipen</span></td>\n";
  4574. echo "<td bgcolor=\"#efefef\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">No. Templates Used:</span></b></td>\n";
  4575. echo "<td bgcolor=\"#fefefe\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">".count($templates->cache)." (".(int)count(explode(",", $templatelist))." Cached / ".(int)count($templates->uncached_templates)." Manually Loaded)</span></td>\n";
  4576. echo "</tr>\n";
  4577.  
  4578. $memory_usage = get_memory_usage();
  4579. if(!$memory_usage)
  4580. {
  4581. $memory_usage = $lang->unknown;
  4582. }
  4583. else
  4584. {
  4585. $memory_usage = get_friendly_size($memory_usage)." ({$memory_usage} bytes)";
  4586. }
  4587. $memory_limit = @ini_get("memory_limit");
  4588. echo "<tr>\n";
  4589. echo "<td bgcolor=\"#EFEFEF\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">Memory Usage:</span></b></td>\n";
  4590. echo "<td bgcolor=\"#FEFEFE\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">{$memory_usage}</span></td>\n";
  4591. echo "<td bgcolor=\"#EFEFEF\" width=\"25%\"><b><span style=\"font-family: tahoma; font-size: 12px;\">Memory Limit:</span></b></td>\n";
  4592. echo "<td bgcolor=\"#FEFEFE\" width=\"25%\"><span style=\"font-family: tahoma; font-size: 12px;\">{$memory_limit}</span></td>\n";
  4593. echo "</tr>\n";
  4594.  
  4595. echo "</table>\n";
  4596.  
  4597. echo "<h2>Database Connections (".count($db->connections)." Total) </h2>\n";
  4598. echo "<table style=\"background-color: #666;\" width=\"95%\" cellpadding=\"4\" cellspacing=\"1\" align=\"center\">\n";
  4599. echo "<tr>\n";
  4600. echo "<td style=\"background: #fff;\">".implode("<br />", $db->connections)."</td>\n";
  4601. echo "</tr>\n";
  4602. echo "</table>\n";
  4603. echo "<br />\n";
  4604.  
  4605. echo "<h2>Database Queries (".$db->query_count." Total) </h2>\n";
  4606. echo $db->explain;
  4607.  
  4608. if($cache->call_count > 0)
  4609. {
  4610. echo "<h2>Cache Calls (".$cache->call_count." Total, ".$call_time.") </h2>\n";
  4611. echo $cache->cache_debug;
  4612. }
  4613.  
  4614. echo "<h2>Template Statistics</h2>\n";
  4615.  
  4616. if(count($templates->cache) > 0)
  4617. {
  4618. echo "<table style=\"background-color: #666;\" width=\"95%\" cellpadding=\"4\" cellspacing=\"1\" align=\"center\">\n";
  4619. echo "<tr>\n";
  4620. echo "<td style=\"background-color: #ccc;\"><strong>Templates Used (Loaded for this Page) - ".count($templates->cache)." Total</strong></td>\n";
  4621. echo "</tr>\n";
  4622. echo "<tr>\n";
  4623. echo "<td style=\"background: #fff;\">".implode(", ", array_keys($templates->cache))."</td>\n";
  4624. echo "</tr>\n";
  4625. echo "</table>\n";
  4626. echo "<br />\n";
  4627. }
  4628.  
  4629. if(count($templates->uncached_templates) > 0)
  4630. {
  4631. echo "<table style=\"background-color: #666;\" width=\"95%\" cellpadding=\"4\" cellspacing=\"1\" align=\"center\">\n";
  4632. echo "<tr>\n";
  4633. echo "<td style=\"background-color: #ccc;\"><strong>Templates Requiring Additional Calls (Not Cached at Startup) - ".count($templates->uncached_templates)." Total</strong></td>\n";
  4634. echo "</tr>\n";
  4635. echo "<tr>\n";
  4636. echo "<td style=\"background: #fff;\">".implode(", ", $templates->uncached_templates)."</td>\n";
  4637. echo "</tr>\n";
  4638. echo "</table>\n";
  4639. echo "<br />\n";
  4640. }
  4641. echo "</body>";
  4642. echo "</html>";
  4643. exit;
  4644. }
  4645.  
  4646. /**
  4647. * Outputs the correct page headers.
  4648. */
  4649. function send_page_headers()
  4650. {
  4651. global $mybb;
  4652.  
  4653. if($mybb->settings['nocacheheaders'] == 1)
  4654. {
  4655. header("Expires: Sat, 1 Jan 2000 01:00:00 GMT");
  4656. header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
  4657. header("Cache-Control: no-cache, must-revalidate");
  4658. header("Pragma: no-cache");
  4659. }
  4660. }
  4661.  
  4662. /**
  4663. * Mark specific reported posts of a certain type as dealt with
  4664. *
  4665. * @param array|int $id An array or int of the ID numbers you're marking as dealt with
  4666. * @param string $type The type of item the above IDs are for - post, posts, thread, threads, forum, all
  4667. */
  4668. function mark_reports($id, $type="post")
  4669. {
  4670. global $db, $cache, $plugins;
  4671.  
  4672. switch($type)
  4673. {
  4674. case "posts":
  4675. if(is_array($id))
  4676. {
  4677. $rids = implode($id, "','");
  4678. $rids = "'0','$rids'";
  4679. $db->update_query("reportedcontent", array('reportstatus' => 1), "id IN($rids) AND reportstatus='0' AND (type = 'post' OR type = '')");
  4680. }
  4681. break;
  4682. case "post":
  4683. $db->update_query("reportedcontent", array('reportstatus' => 1), "id='$id' AND reportstatus='0' AND (type = 'post' OR type = '')");
  4684. break;
  4685. case "threads":
  4686. if(is_array($id))
  4687. {
  4688. $rids = implode($id, "','");
  4689. $rids = "'0','$rids'";
  4690. $db->update_query("reportedcontent", array('reportstatus' => 1), "id2 IN($rids) AND reportstatus='0' AND (type = 'post' OR type = '')");
  4691. }
  4692. break;
  4693. case "thread":
  4694. $db->update_query("reportedcontent", array('reportstatus' => 1), "id2='$id' AND reportstatus='0' AND (type = 'post' OR type = '')");
  4695. break;
  4696. case "forum":
  4697. $db->update_query("reportedcontent", array('reportstatus' => 1), "id3='$id' AND reportstatus='0' AND (type = 'post' OR type = '')");
  4698. break;
  4699. case "all":
  4700. $db->update_query("reportedcontent", array('reportstatus' => 1), "reportstatus='0' AND (type = 'post' OR type = '')");
  4701. break;
  4702. }
  4703.  
  4704. $arguments = array('id' => $id, 'type' => $type);
  4705. $plugins->run_hooks("mark_reports", $arguments);
  4706. $cache->update_reportedcontent();
  4707. }
  4708.  
  4709. /**
  4710. * Fetch a friendly x days, y months etc date stamp from a timestamp
  4711. *
  4712. * @param int $stamp The timestamp
  4713. * @param array $options Array of options
  4714. * @return string The friendly formatted timestamp
  4715. */
  4716. function nice_time($stamp, $options=array())
  4717. {
  4718. global $lang;
  4719.  
  4720. $ysecs = 365*24*60*60;
  4721. $mosecs = 31*24*60*60;
  4722. $wsecs = 7*24*60*60;
  4723. $dsecs = 24*60*60;
  4724. $hsecs = 60*60;
  4725. $msecs = 60;
  4726.  
  4727. if(isset($options['short']))
  4728. {
  4729. $lang_year = $lang->year_short;
  4730. $lang_years = $lang->years_short;
  4731. $lang_month = $lang->month_short;
  4732. $lang_months = $lang->months_short;
  4733. $lang_week = $lang->week_short;
  4734. $lang_weeks = $lang->weeks_short;
  4735. $lang_day = $lang->day_short;
  4736. $lang_days = $lang->days_short;
  4737. $lang_hour = $lang->hour_short;
  4738. $lang_hours = $lang->hours_short;
  4739. $lang_minute = $lang->minute_short;
  4740. $lang_minutes = $lang->minutes_short;
  4741. $lang_second = $lang->second_short;
  4742. $lang_seconds = $lang->seconds_short;
  4743. }
  4744. else
  4745. {
  4746. $lang_year = " ".$lang->year;
  4747. $lang_years = " ".$lang->years;
  4748. $lang_month = " ".$lang->month;
  4749. $lang_months = " ".$lang->months;
  4750. $lang_week = " ".$lang->week;
  4751. $lang_weeks = " ".$lang->weeks;
  4752. $lang_day = " ".$lang->day;
  4753. $lang_days = " ".$lang->days;
  4754. $lang_hour = " ".$lang->hour;
  4755. $lang_hours = " ".$lang->hours;
  4756. $lang_minute = " ".$lang->minute;
  4757. $lang_minutes = " ".$lang->minutes;
  4758. $lang_second = " ".$lang->second;
  4759. $lang_seconds = " ".$lang->seconds;
  4760. }
  4761.  
  4762. $years = floor($stamp/$ysecs);
  4763. $stamp %= $ysecs;
  4764. $months = floor($stamp/$mosecs);
  4765. $stamp %= $mosecs;
  4766. $weeks = floor($stamp/$wsecs);
  4767. $stamp %= $wsecs;
  4768. $days = floor($stamp/$dsecs);
  4769. $stamp %= $dsecs;
  4770. $hours = floor($stamp/$hsecs);
  4771. $stamp %= $hsecs;
  4772. $minutes = floor($stamp/$msecs);
  4773. $stamp %= $msecs;
  4774. $seconds = $stamp;
  4775.  
  4776. // Prevent gross over accuracy ($options parameter will override these)
  4777. if($years > 0)
  4778. {
  4779. $options = array_merge(array(
  4780. 'days' => false,
  4781. 'hours' => false,
  4782. 'minutes' => false,
  4783. 'seconds' => false
  4784. ), $options);
  4785. }
  4786. elseif($months > 0)
  4787. {
  4788. $options = array_merge(array(
  4789. 'hours' => false,
  4790. 'minutes' => false,
  4791. 'seconds' => false
  4792. ), $options);
  4793. }
  4794. elseif($weeks > 0)
  4795. {
  4796. $options = array_merge(array(
  4797. 'minutes' => false,
  4798. 'seconds' => false
  4799. ), $options);
  4800. }
  4801. elseif($days > 0)
  4802. {
  4803. $options = array_merge(array(
  4804. 'seconds' => false
  4805. ), $options);
  4806. }
  4807.  
  4808. if(!isset($options['years']) || $options['years'] !== false)
  4809. {
  4810. if($years == 1)
  4811. {
  4812. $nicetime['years'] = "1".$lang_year;
  4813. }
  4814. else if($years > 1)
  4815. {
  4816. $nicetime['years'] = $years.$lang_years;
  4817. }
  4818. }
  4819.  
  4820. if(!isset($options['months']) || $options['months'] !== false)
  4821. {
  4822. if($months == 1)
  4823. {
  4824. $nicetime['months'] = "1".$lang_month;
  4825. }
  4826. else if($months > 1)
  4827. {
  4828. $nicetime['months'] = $months.$lang_months;
  4829. }
  4830. }
  4831.  
  4832. if(!isset($options['weeks']) || $options['weeks'] !== false)
  4833. {
  4834. if($weeks == 1)
  4835. {
  4836. $nicetime['weeks'] = "1".$lang_week;
  4837. }
  4838. else if($weeks > 1)
  4839. {
  4840. $nicetime['weeks'] = $weeks.$lang_weeks;
  4841. }
  4842. }
  4843.  
  4844. if(!isset($options['days']) || $options['days'] !== false)
  4845. {
  4846. if($days == 1)
  4847. {
  4848. $nicetime['days'] = "1".$lang_day;
  4849. }
  4850. else if($days > 1)
  4851. {
  4852. $nicetime['days'] = $days.$lang_days;
  4853. }
  4854. }
  4855.  
  4856. if(!isset($options['hours']) || $options['hours'] !== false)
  4857. {
  4858. if($hours == 1)
  4859. {
  4860. $nicetime['hours'] = "1".$lang_hour;
  4861. }
  4862. else if($hours > 1)
  4863. {
  4864. $nicetime['hours'] = $hours.$lang_hours;
  4865. }
  4866. }
  4867.  
  4868. if(!isset($options['minutes']) || $options['minutes'] !== false)
  4869. {
  4870. if($minutes == 1)
  4871. {
  4872. $nicetime['minutes'] = "1".$lang_minute;
  4873. }
  4874. else if($minutes > 1)
  4875. {
  4876. $nicetime['minutes'] = $minutes.$lang_minutes;
  4877. }
  4878. }
  4879.  
  4880. if(!isset($options['seconds']) || $options['seconds'] !== false)
  4881. {
  4882. if($seconds == 1)
  4883. {
  4884. $nicetime['seconds'] = "1".$lang_second;
  4885. }
  4886. else if($seconds > 1)
  4887. {
  4888. $nicetime['seconds'] = $seconds.$lang_seconds;
  4889. }
  4890. }
  4891.  
  4892. if(is_array($nicetime))
  4893. {
  4894. return implode(", ", $nicetime);
  4895. }
  4896. }
  4897.  
  4898. /**
  4899. * Select an alternating row colour based on the previous call to this function
  4900. *
  4901. * @param int $reset 1 to reset the row to trow1.
  4902. * @return string trow1 or trow2 depending on the previous call
  4903. */
  4904. function alt_trow($reset=0)
  4905. {
  4906. global $alttrow;
  4907.  
  4908. if($alttrow == "trow1" && !$reset)
  4909. {
  4910. $trow = "trow2";
  4911. }
  4912. else
  4913. {
  4914. $trow = "trow1";
  4915. }
  4916.  
  4917. $alttrow = $trow;
  4918.  
  4919. return $trow;
  4920. }
  4921.  
  4922. /**
  4923. * Add a user to a specific additional user group.
  4924. *
  4925. * @param int $uid The user ID
  4926. * @param int $joingroup The user group ID to join
  4927. * @return bool
  4928. */
  4929. function join_usergroup($uid, $joingroup)
  4930. {
  4931. global $db, $mybb;
  4932.  
  4933. if($uid == $mybb->user['uid'])
  4934. {
  4935. $user = $mybb->user;
  4936. }
  4937. else
  4938. {
  4939. $query = $db->simple_select("users", "additionalgroups, usergroup", "uid='".(int)$uid."'");
  4940. $user = $db->fetch_array($query);
  4941. }
  4942.  
  4943. // Build the new list of additional groups for this user and make sure they're in the right format
  4944. $usergroups = "";
  4945. $usergroups = $user['additionalgroups'].",".$joingroup;
  4946. $groupslist = "";
  4947. $groups = explode(",", $usergroups);
  4948.  
  4949. if(is_array($groups))
  4950. {
  4951. $comma = '';
  4952. foreach($groups as $gid)
  4953. {
  4954. if(trim($gid) != "" && $gid != $user['usergroup'] && !isset($donegroup[$gid]))
  4955. {
  4956. $groupslist .= $comma.$gid;
  4957. $comma = ",";
  4958. $donegroup[$gid] = 1;
  4959. }
  4960. }
  4961. }
  4962.  
  4963. // What's the point in updating if they're the same?
  4964. if($groupslist != $user['additionalgroups'])
  4965. {
  4966. $db->update_query("users", array('additionalgroups' => $groupslist), "uid='".(int)$uid."'");
  4967. return true;
  4968. }
  4969. else
  4970. {
  4971. return false;
  4972. }
  4973. }
  4974.  
  4975. /**
  4976. * Remove a user from a specific additional user group
  4977. *
  4978. * @param int $uid The user ID
  4979. * @param int $leavegroup The user group ID
  4980. */
  4981. function leave_usergroup($uid, $leavegroup)
  4982. {
  4983. global $db, $mybb, $cache;
  4984.  
  4985. $user = get_user($uid);
  4986.  
  4987. $groupslist = $comma = '';
  4988. $usergroups = $user['additionalgroups'].",";
  4989. $donegroup = array();
  4990.  
  4991. $groups = explode(",", $user['additionalgroups']);
  4992.  
  4993. if(is_array($groups))
  4994. {
  4995. foreach($groups as $gid)
  4996. {
  4997. if(trim($gid) != "" && $leavegroup != $gid && empty($donegroup[$gid]))
  4998. {
  4999. $groupslist .= $comma.$gid;
  5000. $comma = ",";
  5001. $donegroup[$gid] = 1;
  5002. }
  5003. }
  5004. }
  5005.  
  5006. $dispupdate = "";
  5007. if($leavegroup == $user['displaygroup'])
  5008. {
  5009. $dispupdate = ", displaygroup=usergroup";
  5010. }
  5011.  
  5012. $db->write_query("
  5013. UPDATE ".TABLE_PREFIX."users
  5014. SET additionalgroups='$groupslist' $dispupdate
  5015. WHERE uid='".(int)$uid."'
  5016. ");
  5017.  
  5018. $cache->update_moderators();
  5019. }
  5020.  
  5021. /**
  5022. * Get the current location taking in to account different web serves and systems
  5023. *
  5024. * @param boolean $fields True to return as "hidden" fields
  5025. * @param array $ignore Array of fields to ignore if first argument is true
  5026. * @param boolean $quick True to skip all inputs and return only the file path part of the URL
  5027. * @return string The current URL being accessed
  5028. */
  5029. function get_current_location($fields=false, $ignore=array(), $quick=false)
  5030. {
  5031. if(defined("MYBB_LOCATION"))
  5032. {
  5033. return MYBB_LOCATION;
  5034. }
  5035.  
  5036. if(!empty($_SERVER['SCRIPT_NAME']))
  5037. {
  5038. $location = htmlspecialchars_uni($_SERVER['SCRIPT_NAME']);
  5039. }
  5040. elseif(!empty($_SERVER['PHP_SELF']))
  5041. {
  5042. $location = htmlspecialchars_uni($_SERVER['PHP_SELF']);
  5043. }
  5044. elseif(!empty($_ENV['PHP_SELF']))
  5045. {
  5046. $location = htmlspecialchars_uni($_ENV['PHP_SELF']);
  5047. }
  5048. elseif(!empty($_SERVER['PATH_INFO']))
  5049. {
  5050. $location = htmlspecialchars_uni($_SERVER['PATH_INFO']);
  5051. }
  5052. else
  5053. {
  5054. $location = htmlspecialchars_uni($_ENV['PATH_INFO']);
  5055. }
  5056.  
  5057. if($quick)
  5058. {
  5059. return $location;
  5060. }
  5061.  
  5062. if($fields == true)
  5063. {
  5064. global $mybb;
  5065.  
  5066. if(!is_array($ignore))
  5067. {
  5068. $ignore = array($ignore);
  5069. }
  5070.  
  5071. $form_html = '';
  5072. if(!empty($mybb->input))
  5073. {
  5074. foreach($mybb->input as $name => $value)
  5075. {
  5076. if(in_array($name, $ignore) || is_array($name) || is_array($value))
  5077. {
  5078. continue;
  5079. }
  5080.  
  5081. $form_html .= "<input type=\"hidden\" name=\"".htmlspecialchars_uni($name)."\" value=\"".htmlspecialchars_uni($value)."\" />\n";
  5082. }
  5083. }
  5084.  
  5085. return array('location' => $location, 'form_html' => $form_html, 'form_method' => $mybb->request_method);
  5086. }
  5087. else
  5088. {
  5089. if(isset($_SERVER['QUERY_STRING']))
  5090. {
  5091. $location .= "?".htmlspecialchars_uni($_SERVER['QUERY_STRING']);
  5092. }
  5093. else if(isset($_ENV['QUERY_STRING']))
  5094. {
  5095. $location .= "?".htmlspecialchars_uni($_ENV['QUERY_STRING']);
  5096. }
  5097.  
  5098. if((isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "POST") || (isset($_ENV['REQUEST_METHOD']) && $_ENV['REQUEST_METHOD'] == "POST"))
  5099. {
  5100. $post_array = array('action', 'fid', 'pid', 'tid', 'uid', 'eid');
  5101.  
  5102. foreach($post_array as $var)
  5103. {
  5104. if(isset($_POST[$var]))
  5105. {
  5106. $addloc[] = urlencode($var).'='.urlencode($_POST[$var]);
  5107. }
  5108. }
  5109.  
  5110. if(isset($addloc) && is_array($addloc))
  5111. {
  5112. if(strpos($location, "?") === false)
  5113. {
  5114. $location .= "?";
  5115. }
  5116. else
  5117. {
  5118. $location .= "&amp;";
  5119. }
  5120. $location .= implode("&amp;", $addloc);
  5121. }
  5122. }
  5123.  
  5124. return $location;
  5125. }
  5126. }
  5127.  
  5128. /**
  5129. * Build a theme selection menu
  5130. *
  5131. * @param string $name The name of the menu
  5132. * @param int $selected The ID of the selected theme
  5133. * @param int $tid The ID of the parent theme to select from
  5134. * @param string $depth The current selection depth
  5135. * @param boolean $usergroup_override Whether or not to override usergroup permissions (true to override)
  5136. * @param boolean $footer Whether or not theme select is in the footer (true if it is)
  5137. * @param boolean $count_override Whether or not to override output based on theme count (true to override)
  5138. * @return string The theme selection list
  5139. */
  5140. function build_theme_select($name, $selected=-1, $tid=0, $depth="", $usergroup_override=false, $footer=false, $count_override=false)
  5141. {
  5142. global $db, $themeselect, $tcache, $lang, $mybb, $limit, $templates, $num_themes, $themeselect_option;
  5143.  
  5144. if($tid == 0)
  5145. {
  5146. $tid = 1;
  5147. $num_themes = 0;
  5148. $themeselect_option = '';
  5149.  
  5150. if(!isset($lang->use_default))
  5151. {
  5152. $lang->use_default = $lang->lang_select_default;
  5153. }
  5154. }
  5155.  
  5156. if(!is_array($tcache))
  5157. {
  5158. $query = $db->simple_select('themes', 'tid, name, pid, allowedgroups', "pid!='0'");
  5159.  
  5160. while($theme = $db->fetch_array($query))
  5161. {
  5162. $tcache[$theme['pid']][$theme['tid']] = $theme;
  5163. }
  5164. }
  5165.  
  5166. if(is_array($tcache[$tid]))
  5167. {
  5168. foreach($tcache[$tid] as $theme)
  5169. {
  5170. $sel = "";
  5171. // Show theme if allowed, or if override is on
  5172. if(is_member($theme['allowedgroups']) || $theme['allowedgroups'] == "all" || $usergroup_override == true)
  5173. {
  5174. if($theme['tid'] == $selected)
  5175. {
  5176. $sel = " selected=\"selected\"";
  5177. }
  5178.  
  5179. if($theme['pid'] != 0)
  5180. {
  5181. $theme['name'] = htmlspecialchars_uni($theme['name']);
  5182. eval("\$themeselect_option .= \"".$templates->get("usercp_themeselector_option")."\";");
  5183. ++$num_themes;
  5184. $depthit = $depth."--";
  5185. }
  5186.  
  5187. if(array_key_exists($theme['tid'], $tcache))
  5188. {
  5189. build_theme_select($name, $selected, $theme['tid'], $depthit, $usergroup_override, $footer, $count_override);
  5190. }
  5191. }
  5192. }
  5193. }
  5194.  
  5195. if($tid == 1 && ($num_themes > 1 || $count_override == true))
  5196. {
  5197. if($footer == true)
  5198. {
  5199. eval("\$themeselect = \"".$templates->get("footer_themeselector")."\";");
  5200. }
  5201. else
  5202. {
  5203. eval("\$themeselect = \"".$templates->get("usercp_themeselector")."\";");
  5204. }
  5205.  
  5206. return $themeselect;
  5207. }
  5208. else
  5209. {
  5210. return false;
  5211. }
  5212. }
  5213.  
  5214. /**
  5215. * Get the theme data of a theme id.
  5216. *
  5217. * @param int $tid The theme id of the theme.
  5218. * @return boolean|array False if no valid theme, Array with the theme data otherwise
  5219. */
  5220. function get_theme($tid)
  5221. {
  5222. global $tcache, $db;
  5223.  
  5224. if(!is_array($tcache))
  5225. {
  5226. $query = $db->simple_select('themes', 'tid, name, pid, allowedgroups', "pid!='0'");
  5227.  
  5228. while($theme = $db->fetch_array($query))
  5229. {
  5230. $tcache[$theme['pid']][$theme['tid']] = $theme;
  5231. }
  5232. }
  5233.  
  5234. $s_theme = false;
  5235.  
  5236. foreach($tcache as $themes)
  5237. {
  5238. foreach($themes as $theme)
  5239. {
  5240. if($tid == $theme['tid'])
  5241. {
  5242. $s_theme = $theme;
  5243. break 2;
  5244. }
  5245. }
  5246. }
  5247.  
  5248. return $s_theme;
  5249. }
  5250.  
  5251. /**
  5252. * Custom function for htmlspecialchars which takes in to account unicode
  5253. *
  5254. * @param string $message The string to format
  5255. * @return string The string with htmlspecialchars applied
  5256. */
  5257. function htmlspecialchars_uni($message)
  5258. {
  5259. $message = preg_replace("#&(?!\#[0-9]+;)#si", "&amp;", $message); // Fix & but allow unicode
  5260. $message = str_replace("<", "&lt;", $message);
  5261. $message = str_replace(">", "&gt;", $message);
  5262. $message = str_replace("\"", "&quot;", $message);
  5263. return $message;
  5264. }
  5265.  
  5266. /**
  5267. * Custom function for formatting numbers.
  5268. *
  5269. * @param int $number The number to format.
  5270. * @return int The formatted number.
  5271. */
  5272. function my_number_format($number)
  5273. {
  5274. global $mybb;
  5275.  
  5276. if($number == "-")
  5277. {
  5278. return $number;
  5279. }
  5280.  
  5281. if(is_int($number))
  5282. {
  5283. return number_format($number, 0, $mybb->settings['decpoint'], $mybb->settings['thousandssep']);
  5284. }
  5285. else
  5286. {
  5287. $parts = explode('.', $number);
  5288.  
  5289. if(isset($parts[1]))
  5290. {
  5291. $decimals = my_strlen($parts[1]);
  5292. }
  5293. else
  5294. {
  5295. $decimals = 0;
  5296. }
  5297.  
  5298. return number_format((double)$number, $decimals, $mybb->settings['decpoint'], $mybb->settings['thousandssep']);
  5299. }
  5300. }
  5301.  
  5302. /**
  5303. * Converts a string of text to or from UTF-8.
  5304. *
  5305. * @param string $str The string of text to convert
  5306. * @param boolean $to Whether or not the string is being converted to or from UTF-8 (true if converting to)
  5307. * @return string The converted string
  5308. */
  5309. function convert_through_utf8($str, $to=true)
  5310. {
  5311. global $lang;
  5312. static $charset;
  5313. static $use_mb;
  5314. static $use_iconv;
  5315.  
  5316. if(!isset($charset))
  5317. {
  5318. $charset = my_strtolower($lang->settings['charset']);
  5319. }
  5320.  
  5321. if($charset == "utf-8")
  5322. {
  5323. return $str;
  5324. }
  5325.  
  5326. if(!isset($use_iconv))
  5327. {
  5328. $use_iconv = function_exists("iconv");
  5329. }
  5330.  
  5331. if(!isset($use_mb))
  5332. {
  5333. $use_mb = function_exists("mb_convert_encoding");
  5334. }
  5335.  
  5336. if($use_iconv || $use_mb)
  5337. {
  5338. if($to)
  5339. {
  5340. $from_charset = $lang->settings['charset'];
  5341. $to_charset = "UTF-8";
  5342. }
  5343. else
  5344. {
  5345. $from_charset = "UTF-8";
  5346. $to_charset = $lang->settings['charset'];
  5347. }
  5348. if($use_iconv)
  5349. {
  5350. return iconv($from_charset, $to_charset."//IGNORE", $str);
  5351. }
  5352. else
  5353. {
  5354. return @mb_convert_encoding($str, $to_charset, $from_charset);
  5355. }
  5356. }
  5357. elseif($charset == "iso-8859-1" && function_exists("utf8_encode"))
  5358. {
  5359. if($to)
  5360. {
  5361. return utf8_encode($str);
  5362. }
  5363. else
  5364. {
  5365. return utf8_decode($str);
  5366. }
  5367. }
  5368. else
  5369. {
  5370. return $str;
  5371. }
  5372. }
  5373.  
  5374. /**
  5375. * DEPRECATED! Please use other alternatives.
  5376. *
  5377. * @deprecated
  5378. * @param string $message
  5379. *
  5380. * @return string
  5381. */
  5382. function my_wordwrap($message)
  5383. {
  5384. return $message;
  5385. }
  5386.  
  5387. /**
  5388. * Workaround for date limitation in PHP to establish the day of a birthday (Provided by meme)
  5389. *
  5390. * @param int $month The month of the birthday
  5391. * @param int $day The day of the birthday
  5392. * @param int $year The year of the bithday
  5393. * @return int The numeric day of the week for the birthday
  5394. */
  5395. function get_weekday($month, $day, $year)
  5396. {
  5397. $h = 4;
  5398.  
  5399. for($i = 1969; $i >= $year; $i--)
  5400. {
  5401. $j = get_bdays($i);
  5402.  
  5403. for($k = 11; $k >= 0; $k--)
  5404. {
  5405. $l = ($k + 1);
  5406.  
  5407. for($m = $j[$k]; $m >= 1; $m--)
  5408. {
  5409. $h--;
  5410.  
  5411. if($i == $year && $l == $month && $m == $day)
  5412. {
  5413. return $h;
  5414. }
  5415.  
  5416. if($h == 0)
  5417. {
  5418. $h = 7;
  5419. }
  5420. }
  5421. }
  5422. }
  5423. }
  5424.  
  5425. /**
  5426. * Workaround for date limitation in PHP to establish the day of a birthday (Provided by meme)
  5427. *
  5428. * @param int $in The year.
  5429. * @return array The number of days in each month of that year
  5430. */
  5431. function get_bdays($in)
  5432. {
  5433. return array(
  5434. 31,
  5435. ($in % 4 == 0 && ($in % 100 > 0 || $in % 400 == 0) ? 29 : 28),
  5436. 31,
  5437. 30,
  5438. 31,
  5439. 30,
  5440. 31,
  5441. 31,
  5442. 30,
  5443. 31,
  5444. 30,
  5445. 31
  5446. );
  5447. }
  5448.  
  5449. /**
  5450. * DEPRECATED! Please use mktime()!
  5451. * Formats a birthday appropriately
  5452. *
  5453. * @deprecated
  5454. * @param string $display The PHP date format string
  5455. * @param int $bm The month of the birthday
  5456. * @param int $bd The day of the birthday
  5457. * @param int $by The year of the birthday
  5458. * @param int $wd The weekday of the birthday
  5459. * @return string The formatted birthday
  5460. */
  5461. function format_bdays($display, $bm, $bd, $by, $wd)
  5462. {
  5463. global $lang;
  5464.  
  5465. $bdays = array(
  5466. $lang->sunday,
  5467. $lang->monday,
  5468. $lang->tuesday,
  5469. $lang->wednesday,
  5470. $lang->thursday,
  5471. $lang->friday,
  5472. $lang->saturday
  5473. );
  5474.  
  5475. $bmonth = array(
  5476. $lang->month_1,
  5477. $lang->month_2,
  5478. $lang->month_3,
  5479. $lang->month_4,
  5480. $lang->month_5,
  5481. $lang->month_6,
  5482. $lang->month_7,
  5483. $lang->month_8,
  5484. $lang->month_9,
  5485. $lang->month_10,
  5486. $lang->month_11,
  5487. $lang->month_12
  5488. );
  5489.  
  5490. // This needs to be in this specific order
  5491. $find = array(
  5492. 'm',
  5493. 'n',
  5494. 'd',
  5495. 'D',
  5496. 'y',
  5497. 'Y',
  5498. 'j',
  5499. 'S',
  5500. 'F',
  5501. 'l',
  5502. 'M',
  5503. );
  5504.  
  5505. $html = array(
  5506. '&#109;',
  5507. '&#110;',
  5508. '&#99;',
  5509. '&#68;',
  5510. '&#121;',
  5511. '&#89;',
  5512. '&#106;',
  5513. '&#83;',
  5514. '&#70;',
  5515. '&#108;',
  5516. '&#77;',
  5517. );
  5518.  
  5519. $bdays = str_replace($find, $html, $bdays);
  5520. $bmonth = str_replace($find, $html, $bmonth);
  5521.  
  5522. $replace = array(
  5523. sprintf('%02s', $bm),
  5524. $bm,
  5525. sprintf('%02s', $bd),
  5526. ($wd == 2 ? my_substr($bdays[$wd], 0, 4) : ($wd == 4 ? my_substr($bdays[$wd], 0, 5) : my_substr($bdays[$wd], 0, 3))),
  5527. my_substr($by, 2),
  5528. $by,
  5529. ($bd[0] == 0 ? my_substr($bd, 1) : $bd),
  5530. ($bd == 1 || $bd == 21 || $bd == 31 ? 'st' : ($bd == 2 || $bd == 22 ? 'nd' : ($bd == 3 || $bd == 23 ? 'rd' : 'th'))),
  5531. $bmonth[$bm-1],
  5532. $wd,
  5533. ($bm == 9 ? my_substr($bmonth[$bm-1], 0, 4) : my_substr($bmonth[$bm-1], 0, 3)),
  5534. );
  5535.  
  5536. // Do we have the full month in our output?
  5537. // If so there's no need for the short month
  5538. if(strpos($display, 'F') !== false)
  5539. {
  5540. array_pop($find);
  5541. array_pop($replace);
  5542. }
  5543.  
  5544. return str_replace($find, $replace, $display);
  5545. }
  5546.  
  5547. /**
  5548. * Returns the age of a user with specified birthday.
  5549. *
  5550. * @param string $birthday The birthday of a user.
  5551. * @return int The age of a user with that birthday.
  5552. */
  5553. function get_age($birthday)
  5554. {
  5555. $bday = explode("-", $birthday);
  5556. if(!$bday[2])
  5557. {
  5558. return;
  5559. }
  5560.  
  5561. list($day, $month, $year) = explode("-", my_date("j-n-Y", TIME_NOW, 0, 0));
  5562.  
  5563. $age = $year-$bday[2];
  5564.  
  5565. if(($month == $bday[1] && $day < $bday[0]) || $month < $bday[1])
  5566. {
  5567. --$age;
  5568. }
  5569. return $age;
  5570. }
  5571.  
  5572. /**
  5573. * Updates the first posts in a thread.
  5574. *
  5575. * @param int $tid The thread id for which to update the first post id.
  5576. */
  5577. function update_first_post($tid)
  5578. {
  5579. global $db;
  5580.  
  5581. $query = $db->query("
  5582. SELECT u.uid, u.username, p.pid, p.username AS postusername, p.dateline
  5583. FROM ".TABLE_PREFIX."posts p
  5584. LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
  5585. WHERE p.tid='$tid'
  5586. ORDER BY p.dateline ASC
  5587. LIMIT 1
  5588. ");
  5589. $firstpost = $db->fetch_array($query);
  5590.  
  5591. if(empty($firstpost['username']))
  5592. {
  5593. $firstpost['username'] = $firstpost['postusername'];
  5594. }
  5595. $firstpost['username'] = $db->escape_string($firstpost['username']);
  5596.  
  5597. $update_array = array(
  5598. 'firstpost' => (int)$firstpost['pid'],
  5599. 'username' => $firstpost['username'],
  5600. 'uid' => (int)$firstpost['uid'],
  5601. 'dateline' => (int)$firstpost['dateline']
  5602. );
  5603. $db->update_query("threads", $update_array, "tid='{$tid}'");
  5604. }
  5605.  
  5606. /**
  5607. * Updates the last posts in a thread.
  5608. *
  5609. * @param int $tid The thread id for which to update the last post id.
  5610. */
  5611. function update_last_post($tid)
  5612. {
  5613. global $db;
  5614.  
  5615. $query = $db->query("
  5616. SELECT u.uid, u.username, p.username AS postusername, p.dateline
  5617. FROM ".TABLE_PREFIX."posts p
  5618. LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
  5619. WHERE p.tid='$tid' AND p.visible='1'
  5620. ORDER BY p.dateline DESC
  5621. LIMIT 1"
  5622. );
  5623. $lastpost = $db->fetch_array($query);
  5624.  
  5625. if(empty($lastpost['username']))
  5626. {
  5627. $lastpost['username'] = $lastpost['postusername'];
  5628. }
  5629.  
  5630. if(empty($lastpost['dateline']))
  5631. {
  5632. $query = $db->query("
  5633. SELECT u.uid, u.username, p.pid, p.username AS postusername, p.dateline
  5634. FROM ".TABLE_PREFIX."posts p
  5635. LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
  5636. WHERE p.tid='$tid'
  5637. ORDER BY p.dateline ASC
  5638. LIMIT 1
  5639. ");
  5640. $firstpost = $db->fetch_array($query);
  5641.  
  5642. $lastpost['username'] = $firstpost['username'];
  5643. $lastpost['uid'] = $firstpost['uid'];
  5644. $lastpost['dateline'] = $firstpost['dateline'];
  5645. }
  5646.  
  5647. $lastpost['username'] = $db->escape_string($lastpost['username']);
  5648.  
  5649. $update_array = array(
  5650. 'lastpost' => (int)$lastpost['dateline'],
  5651. 'lastposter' => $lastpost['username'],
  5652. 'lastposteruid' => (int)$lastpost['uid']
  5653. );
  5654. $db->update_query("threads", $update_array, "tid='{$tid}'");
  5655. }
  5656.  
  5657. /**
  5658. * Checks for the length of a string, mb strings accounted for
  5659. *
  5660. * @param string $string The string to check the length of.
  5661. * @return int The length of the string.
  5662. */
  5663. function my_strlen($string)
  5664. {
  5665. global $lang;
  5666.  
  5667. $string = preg_replace("#&\#([0-9]+);#", "-", $string);
  5668.  
  5669. if(strtolower($lang->settings['charset']) == "utf-8")
  5670. {
  5671. // Get rid of any excess RTL and LTR override for they are the workings of the devil
  5672. $string = str_replace(dec_to_utf8(8238), "", $string);
  5673. $string = str_replace(dec_to_utf8(8237), "", $string);
  5674.  
  5675. // Remove dodgy whitespaces
  5676. $string = str_replace(chr(0xCA), "", $string);
  5677. }
  5678. $string = trim($string);
  5679.  
  5680. if(function_exists("mb_strlen"))
  5681. {
  5682. $string_length = mb_strlen($string);
  5683. }
  5684. else
  5685. {
  5686. $string_length = strlen($string);
  5687. }
  5688.  
  5689. return $string_length;
  5690. }
  5691.  
  5692. /**
  5693. * Cuts a string at a specified point, mb strings accounted for
  5694. *
  5695. * @param string $string The string to cut.
  5696. * @param int $start Where to cut
  5697. * @param int $length (optional) How much to cut
  5698. * @param bool $handle_entities (optional) Properly handle HTML entities?
  5699. * @return string The cut part of the string.
  5700. */
  5701. function my_substr($string, $start, $length=null, $handle_entities = false)
  5702. {
  5703. if($handle_entities)
  5704. {
  5705. $string = unhtmlentities($string);
  5706. }
  5707. if(function_exists("mb_substr"))
  5708. {
  5709. if($length != null)
  5710. {
  5711. $cut_string = mb_substr($string, $start, $length);
  5712. }
  5713. else
  5714. {
  5715. $cut_string = mb_substr($string, $start);
  5716. }
  5717. }
  5718. else
  5719. {
  5720. if($length != null)
  5721. {
  5722. $cut_string = substr($string, $start, $length);
  5723. }
  5724. else
  5725. {
  5726. $cut_string = substr($string, $start);
  5727. }
  5728. }
  5729.  
  5730. if($handle_entities)
  5731. {
  5732. $cut_string = htmlspecialchars_uni($cut_string);
  5733. }
  5734. return $cut_string;
  5735. }
  5736.  
  5737. /**
  5738. * Lowers the case of a string, mb strings accounted for
  5739. *
  5740. * @param string $string The string to lower.
  5741. * @return string The lowered string.
  5742. */
  5743. function my_strtolower($string)
  5744. {
  5745. if(function_exists("mb_strtolower"))
  5746. {
  5747. $string = mb_strtolower($string);
  5748. }
  5749. else
  5750. {
  5751. $string = strtolower($string);
  5752. }
  5753.  
  5754. return $string;
  5755. }
  5756.  
  5757. /**
  5758. * Finds a needle in a haystack and returns it position, mb strings accounted for
  5759. *
  5760. * @param string $haystack String to look in (haystack)
  5761. * @param string $needle What to look for (needle)
  5762. * @param int $offset (optional) How much to offset
  5763. * @return int|bool false on needle not found, integer position if found
  5764. */
  5765. function my_strpos($haystack, $needle, $offset=0)
  5766. {
  5767. if($needle == '')
  5768. {
  5769. return false;
  5770. }
  5771.  
  5772. if(function_exists("mb_strpos"))
  5773. {
  5774. $position = mb_strpos($haystack, $needle, $offset);
  5775. }
  5776. else
  5777. {
  5778. $position = strpos($haystack, $needle, $offset);
  5779. }
  5780.  
  5781. return $position;
  5782. }
  5783.  
  5784. /**
  5785. * Ups the case of a string, mb strings accounted for
  5786. *
  5787. * @param string $string The string to up.
  5788. * @return string The uped string.
  5789. */
  5790. function my_strtoupper($string)
  5791. {
  5792. if(function_exists("mb_strtoupper"))
  5793. {
  5794. $string = mb_strtoupper($string);
  5795. }
  5796. else
  5797. {
  5798. $string = strtoupper($string);
  5799. }
  5800.  
  5801. return $string;
  5802. }
  5803.  
  5804. /**
  5805. * Returns any html entities to their original character
  5806. *
  5807. * @param string $string The string to un-htmlentitize.
  5808. * @return string The un-htmlentitied' string.
  5809. */
  5810. function unhtmlentities($string)
  5811. {
  5812. // Replace numeric entities
  5813. $string = preg_replace_callback('~&#x([0-9a-f]+);~i', 'unichr_callback1', $string);
  5814. $string = preg_replace_callback('~&#([0-9]+);~', 'unichr_callback2', $string);
  5815.  
  5816. // Replace literal entities
  5817. $trans_tbl = get_html_translation_table(HTML_ENTITIES);
  5818. $trans_tbl = array_flip($trans_tbl);
  5819.  
  5820. return strtr($string, $trans_tbl);
  5821. }
  5822.  
  5823. /**
  5824. * Returns any ascii to it's character (utf-8 safe).
  5825. *
  5826. * @param int $c The ascii to characterize.
  5827. * @return string|bool The characterized ascii. False on failure
  5828. */
  5829. function unichr($c)
  5830. {
  5831. if($c <= 0x7F)
  5832. {
  5833. return chr($c);
  5834. }
  5835. else if($c <= 0x7FF)
  5836. {
  5837. return chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F);
  5838. }
  5839. else if($c <= 0xFFFF)
  5840. {
  5841. return chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F)
  5842. . chr(0x80 | $c & 0x3F);
  5843. }
  5844. else if($c <= 0x10FFFF)
  5845. {
  5846. return chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F)
  5847. . chr(0x80 | $c >> 6 & 0x3F)
  5848. . chr(0x80 | $c & 0x3F);
  5849. }
  5850. else
  5851. {
  5852. return false;
  5853. }
  5854. }
  5855.  
  5856. /**
  5857. * Returns any ascii to it's character (utf-8 safe).
  5858. *
  5859. * @param array $matches Matches.
  5860. * @return string|bool The characterized ascii. False on failure
  5861. */
  5862. function unichr_callback1($matches)
  5863. {
  5864. return unichr(hexdec($matches[1]));
  5865. }
  5866.  
  5867. /**
  5868. * Returns any ascii to it's character (utf-8 safe).
  5869. *
  5870. * @param array $matches Matches.
  5871. * @return string|bool The characterized ascii. False on failure
  5872. */
  5873. function unichr_callback2($matches)
  5874. {
  5875. return unichr($matches[1]);
  5876. }
  5877.  
  5878. /**
  5879. * Get the event poster.
  5880. *
  5881. * @param array $event The event data array.
  5882. * @return string The link to the event poster.
  5883. */
  5884. function get_event_poster($event)
  5885. {
  5886. $event['username'] = htmlspecialchars_uni($event['username']);
  5887. $event['username'] = format_name($event['username'], $event['usergroup'], $event['displaygroup']);
  5888. $event_poster = build_profile_link($event['username'], $event['author']);
  5889. return $event_poster;
  5890. }
  5891.  
  5892. /**
  5893. * Get the event date.
  5894. *
  5895. * @param array $event The event data array.
  5896. * @return string The event date.
  5897. */
  5898. function get_event_date($event)
  5899. {
  5900. global $mybb;
  5901.  
  5902. $event_date = explode("-", $event['date']);
  5903. $event_date = gmmktime(0, 0, 0, $event_date[1], $event_date[0], $event_date[2]);
  5904. $event_date = my_date($mybb->settings['dateformat'], $event_date);
  5905.  
  5906. return $event_date;
  5907. }
  5908.  
  5909. /**
  5910. * Get the profile link.
  5911. *
  5912. * @param int $uid The user id of the profile.
  5913. * @return string The url to the profile.
  5914. */
  5915. function get_profile_link($uid=0)
  5916. {
  5917. $link = str_replace("{uid}", $uid, PROFILE_URL);
  5918. return htmlspecialchars_uni($link);
  5919. }
  5920.  
  5921. /**
  5922. * Get the announcement link.
  5923. *
  5924. * @param int $aid The announement id of the announcement.
  5925. * @return string The url to the announcement.
  5926. */
  5927. function get_announcement_link($aid=0)
  5928. {
  5929. $link = str_replace("{aid}", $aid, ANNOUNCEMENT_URL);
  5930. return htmlspecialchars_uni($link);
  5931. }
  5932.  
  5933. /**
  5934. * Build the profile link.
  5935. *
  5936. * @param string $username The Username of the profile.
  5937. * @param int $uid The user id of the profile.
  5938. * @param string $target The target frame
  5939. * @param string $onclick Any onclick javascript.
  5940. * @return string The complete profile link.
  5941. */
  5942. function build_profile_link($username="", $uid=0, $target="", $onclick="")
  5943. {
  5944. global $mybb, $lang;
  5945.  
  5946. if(!$username && $uid == 0)
  5947. {
  5948. // Return Guest phrase for no UID, no guest nickname
  5949. return htmlspecialchars_uni($lang->guest);
  5950. }
  5951. elseif($uid == 0)
  5952. {
  5953. // Return the guest's nickname if user is a guest but has a nickname
  5954. return $username;
  5955. }
  5956. else
  5957. {
  5958. // Build the profile link for the registered user
  5959. if(!empty($target))
  5960. {
  5961. $target = " target=\"{$target}\"";
  5962. }
  5963.  
  5964. if(!empty($onclick))
  5965. {
  5966. $onclick = " onclick=\"{$onclick}\"";
  5967. }
  5968.  
  5969. return "<a href=\"{$mybb->settings['bburl']}/".get_profile_link($uid)."\"{$target}{$onclick}>{$username}</a>";
  5970. }
  5971. }
  5972.  
  5973. /**
  5974. * Build the forum link.
  5975. *
  5976. * @param int $fid The forum id of the forum.
  5977. * @param int $page (Optional) The page number of the forum.
  5978. * @return string The url to the forum.
  5979. */
  5980. function get_forum_link($fid, $page=0)
  5981. {
  5982. if($page > 0)
  5983. {
  5984. $link = str_replace("{fid}", $fid, FORUM_URL_PAGED);
  5985. $link = str_replace("{page}", $page, $link);
  5986. return htmlspecialchars_uni($link);
  5987. }
  5988. else
  5989. {
  5990. $link = str_replace("{fid}", $fid, FORUM_URL);
  5991. return htmlspecialchars_uni($link);
  5992. }
  5993. }
  5994.  
  5995. /**
  5996. * Build the thread link.
  5997. *
  5998. * @param int $tid The thread id of the thread.
  5999. * @param int $page (Optional) The page number of the thread.
  6000. * @param string $action (Optional) The action we're performing (ex, lastpost, newpost, etc)
  6001. * @return string The url to the thread.
  6002. */
  6003. function get_thread_link($tid, $page=0, $action='')
  6004. {
  6005. if($page > 1)
  6006. {
  6007. if($action)
  6008. {
  6009. $link = THREAD_URL_ACTION;
  6010. $link = str_replace("{action}", $action, $link);
  6011. }
  6012. else
  6013. {
  6014. $link = THREAD_URL_PAGED;
  6015. }
  6016. $link = str_replace("{tid}", $tid, $link);
  6017. $link = str_replace("{page}", $page, $link);
  6018. return htmlspecialchars_uni($link);
  6019. }
  6020. else
  6021. {
  6022. if($action)
  6023. {
  6024. $link = THREAD_URL_ACTION;
  6025. $link = str_replace("{action}", $action, $link);
  6026. }
  6027. else
  6028. {
  6029. $link = THREAD_URL;
  6030. }
  6031. $link = str_replace("{tid}", $tid, $link);
  6032. return htmlspecialchars_uni($link);
  6033. }
  6034. }
  6035.  
  6036. /**
  6037. * Build the post link.
  6038. *
  6039. * @param int $pid The post ID of the post
  6040. * @param int $tid The thread id of the post.
  6041. * @return string The url to the post.
  6042. */
  6043. function get_post_link($pid, $tid=0)
  6044. {
  6045. if($tid > 0)
  6046. {
  6047. $link = str_replace("{tid}", $tid, THREAD_URL_POST);
  6048. $link = str_replace("{pid}", $pid, $link);
  6049. return htmlspecialchars_uni($link);
  6050. }
  6051. else
  6052. {
  6053. $link = str_replace("{pid}", $pid, POST_URL);
  6054. return htmlspecialchars_uni($link);
  6055. }
  6056. }
  6057.  
  6058. /**
  6059. * Build the event link.
  6060. *
  6061. * @param int $eid The event ID of the event
  6062. * @return string The URL of the event
  6063. */
  6064. function get_event_link($eid)
  6065. {
  6066. $link = str_replace("{eid}", $eid, EVENT_URL);
  6067. return htmlspecialchars_uni($link);
  6068. }
  6069.  
  6070. /**
  6071. * Build the link to a specified date on the calendar
  6072. *
  6073. * @param int $calendar The ID of the calendar
  6074. * @param int $year The year
  6075. * @param int $month The month
  6076. * @param int $day The day (optional)
  6077. * @return string The URL of the calendar
  6078. */
  6079. function get_calendar_link($calendar, $year=0, $month=0, $day=0)
  6080. {
  6081. if($day > 0)
  6082. {
  6083. $link = str_replace("{month}", $month, CALENDAR_URL_DAY);
  6084. $link = str_replace("{year}", $year, $link);
  6085. $link = str_replace("{day}", $day, $link);
  6086. $link = str_replace("{calendar}", $calendar, $link);
  6087. return htmlspecialchars_uni($link);
  6088. }
  6089. else if($month > 0)
  6090. {
  6091. $link = str_replace("{month}", $month, CALENDAR_URL_MONTH);
  6092. $link = str_replace("{year}", $year, $link);
  6093. $link = str_replace("{calendar}", $calendar, $link);
  6094. return htmlspecialchars_uni($link);
  6095. }
  6096. /* Not implemented
  6097. else if($year > 0)
  6098. {
  6099. }*/
  6100. else
  6101. {
  6102. $link = str_replace("{calendar}", $calendar, CALENDAR_URL);
  6103. return htmlspecialchars_uni($link);
  6104. }
  6105. }
  6106.  
  6107. /**
  6108. * Build the link to a specified week on the calendar
  6109. *
  6110. * @param int $calendar The ID of the calendar
  6111. * @param int $week The week
  6112. * @return string The URL of the calendar
  6113. */
  6114. function get_calendar_week_link($calendar, $week)
  6115. {
  6116. if($week < 0)
  6117. {
  6118. $week = str_replace('-', "n", $week);
  6119. }
  6120. $link = str_replace("{week}", $week, CALENDAR_URL_WEEK);
  6121. $link = str_replace("{calendar}", $calendar, $link);
  6122. return htmlspecialchars_uni($link);
  6123. }
  6124.  
  6125. /**
  6126. * Get the user data of an user id.
  6127. *
  6128. * @param int $uid The user id of the user.
  6129. * @return array The users data
  6130. */
  6131. function get_user($uid)
  6132. {
  6133. global $mybb, $db;
  6134. static $user_cache;
  6135.  
  6136. $uid = (int)$uid;
  6137.  
  6138. if(!empty($mybb->user) && $uid == $mybb->user['uid'])
  6139. {
  6140. return $mybb->user;
  6141. }
  6142. elseif(isset($user_cache[$uid]))
  6143. {
  6144. return $user_cache[$uid];
  6145. }
  6146. elseif($uid > 0)
  6147. {
  6148. $query = $db->simple_select("users", "*", "uid = '{$uid}'");
  6149. $user_cache[$uid] = $db->fetch_array($query);
  6150.  
  6151. return $user_cache[$uid];
  6152. }
  6153. return array();
  6154. }
  6155.  
  6156. /**
  6157. * Get the user data of an user username.
  6158. *
  6159. * @param string $username The user username of the user.
  6160. * @param array $options
  6161. * @return array The users data
  6162. */
  6163. function get_user_by_username($username, $options=array())
  6164. {
  6165. global $mybb, $db;
  6166.  
  6167. $username = $db->escape_string(my_strtolower($username));
  6168.  
  6169. if(!isset($options['username_method']))
  6170. {
  6171. $options['username_method'] = 0;
  6172. }
  6173.  
  6174. switch($db->type)
  6175. {
  6176. case 'mysql':
  6177. case 'mysqli':
  6178. $field = 'username';
  6179. $efield = 'email';
  6180. break;
  6181. default:
  6182. $field = 'LOWER(username)';
  6183. $efield = 'LOWER(email)';
  6184. break;
  6185. }
  6186.  
  6187. switch($options['username_method'])
  6188. {
  6189. case 1:
  6190. $sqlwhere = "{$efield}='{$username}'";
  6191. break;
  6192. case 2:
  6193. $sqlwhere = "{$field}='{$username}' OR {$efield}='{$username}'";
  6194. break;
  6195. default:
  6196. $sqlwhere = "{$field}='{$username}'";
  6197. break;
  6198. }
  6199.  
  6200. $fields = array('uid');
  6201. if(isset($options['fields']))
  6202. {
  6203. $fields = array_merge((array)$options['fields'], $fields);
  6204. }
  6205.  
  6206. $query = $db->simple_select('users', implode(',', array_unique($fields)), $sqlwhere, array('limit' => 1));
  6207.  
  6208. if(isset($options['exists']))
  6209. {
  6210. return (bool)$db->num_rows($query);
  6211. }
  6212.  
  6213. return $db->fetch_array($query);
  6214. }
  6215.  
  6216. /**
  6217. * Get the forum of a specific forum id.
  6218. *
  6219. * @param int $fid The forum id of the forum.
  6220. * @param int $active_override (Optional) If set to 1, will override the active forum status
  6221. * @return array|bool The database row of a forum. False on failure
  6222. */
  6223. function get_forum($fid, $active_override=0)
  6224. {
  6225. global $cache;
  6226. static $forum_cache;
  6227.  
  6228. if(!isset($forum_cache) || is_array($forum_cache))
  6229. {
  6230. $forum_cache = $cache->read("forums");
  6231. }
  6232.  
  6233. if(empty($forum_cache[$fid]))
  6234. {
  6235. return false;
  6236. }
  6237.  
  6238. if($active_override != 1)
  6239. {
  6240. $parents = explode(",", $forum_cache[$fid]['parentlist']);
  6241. if(is_array($parents))
  6242. {
  6243. foreach($parents as $parent)
  6244. {
  6245. if($forum_cache[$parent]['active'] == 0)
  6246. {
  6247. return false;
  6248. }
  6249. }
  6250. }
  6251. }
  6252.  
  6253. return $forum_cache[$fid];
  6254. }
  6255.  
  6256. /**
  6257. * Get the thread of a thread id.
  6258. *
  6259. * @param int $tid The thread id of the thread.
  6260. * @param boolean $recache Whether or not to recache the thread.
  6261. * @return array|bool The database row of the thread. False on failure
  6262. */
  6263. function get_thread($tid, $recache = false)
  6264. {
  6265. global $db;
  6266. static $thread_cache;
  6267.  
  6268. $tid = (int)$tid;
  6269.  
  6270. if(isset($thread_cache[$tid]) && !$recache)
  6271. {
  6272. return $thread_cache[$tid];
  6273. }
  6274. else
  6275. {
  6276. $query = $db->simple_select("threads", "*", "tid = '{$tid}'");
  6277. $thread = $db->fetch_array($query);
  6278.  
  6279. if($thread)
  6280. {
  6281. $thread_cache[$tid] = $thread;
  6282. return $thread;
  6283. }
  6284. else
  6285. {
  6286. $thread_cache[$tid] = false;
  6287. return false;
  6288. }
  6289. }
  6290. }
  6291.  
  6292. /**
  6293. * Get the post of a post id.
  6294. *
  6295. * @param int $pid The post id of the post.
  6296. * @return array|bool The database row of the post. False on failure
  6297. */
  6298. function get_post($pid)
  6299. {
  6300. global $db;
  6301. static $post_cache;
  6302.  
  6303. $pid = (int)$pid;
  6304.  
  6305. if(isset($post_cache[$pid]))
  6306. {
  6307. return $post_cache[$pid];
  6308. }
  6309. else
  6310. {
  6311. $query = $db->simple_select("posts", "*", "pid = '{$pid}'");
  6312. $post = $db->fetch_array($query);
  6313.  
  6314. if($post)
  6315. {
  6316. $post_cache[$pid] = $post;
  6317. return $post;
  6318. }
  6319. else
  6320. {
  6321. $post_cache[$pid] = false;
  6322. return false;
  6323. }
  6324. }
  6325. }
  6326.  
  6327. /**
  6328. * Get inactivate forums.
  6329. *
  6330. * @return string The comma separated values of the inactivate forum.
  6331. */
  6332. function get_inactive_forums()
  6333. {
  6334. global $forum_cache, $cache;
  6335.  
  6336. if(!$forum_cache)
  6337. {
  6338. cache_forums();
  6339. }
  6340.  
  6341. $inactive = array();
  6342.  
  6343. foreach($forum_cache as $fid => $forum)
  6344. {
  6345. if($forum['active'] == 0)
  6346. {
  6347. $inactive[] = $fid;
  6348. foreach($forum_cache as $fid1 => $forum1)
  6349. {
  6350. if(my_strpos(",".$forum1['parentlist'].",", ",".$fid.",") !== false && !in_array($fid1, $inactive))
  6351. {
  6352. $inactive[] = $fid1;
  6353. }
  6354. }
  6355. }
  6356. }
  6357.  
  6358. $inactiveforums = implode(",", $inactive);
  6359.  
  6360. return $inactiveforums;
  6361. }
  6362.  
  6363. /**
  6364. * Checks to make sure a user has not tried to login more times than permitted
  6365. *
  6366. * @param bool $fatal (Optional) Stop execution if it finds an error with the login. Default is True
  6367. * @return bool|int Number of logins when success, false if failed.
  6368. */
  6369. function login_attempt_check($uid = 0, $fatal = true)
  6370. {
  6371. global $mybb, $lang, $db;
  6372.  
  6373. $attempts = array();
  6374. $uid = (int)$uid;
  6375. $now = TIME_NOW;
  6376.  
  6377. // Get this user's login attempts and eventual lockout, if a uid is provided
  6378. if($uid > 0)
  6379. {
  6380. $query = $db->simple_select("users", "loginattempts, loginlockoutexpiry", "uid='{$uid}'", 1);
  6381. $attempts = $db->fetch_array($query);
  6382.  
  6383. if($attempts['loginattempts'] <= 0)
  6384. {
  6385. return 0;
  6386. }
  6387. }
  6388. // This user has a cookie lockout, show waiting time
  6389. elseif($mybb->cookies['lockoutexpiry'] && $mybb->cookies['lockoutexpiry'] > $now)
  6390. {
  6391. if($fatal)
  6392. {
  6393. $secsleft = (int)($mybb->cookies['lockoutexpiry'] - $now);
  6394. $hoursleft = floor($secsleft / 3600);
  6395. $minsleft = floor(($secsleft / 60) % 60);
  6396. $secsleft = floor($secsleft % 60);
  6397.  
  6398. error($lang->sprintf($lang->failed_login_wait, $hoursleft, $minsleft, $secsleft));
  6399. }
  6400.  
  6401. return false;
  6402. }
  6403.  
  6404. if($mybb->settings['failedlogincount'] > 0 && $attempts['loginattempts'] >= $mybb->settings['failedlogincount'])
  6405. {
  6406. // Set the expiry dateline if not set yet
  6407. if($attempts['loginlockoutexpiry'] == 0)
  6408. {
  6409. $attempts['loginlockoutexpiry'] = $now + ((int)$mybb->settings['failedlogintime'] * 60);
  6410.  
  6411. // Add a cookie lockout. This is used to prevent access to the login page immediately.
  6412. // A deep lockout is issued if he tries to login into a locked out account
  6413. my_setcookie('lockoutexpiry', $attempts['loginlockoutexpiry']);
  6414.  
  6415. $db->update_query("users", array(
  6416. "loginlockoutexpiry" => $attempts['loginlockoutexpiry']
  6417. ), "uid='{$uid}'");
  6418. }
  6419.  
  6420. if(empty($mybb->cookies['lockoutexpiry']))
  6421. {
  6422. $failedtime = $attempts['loginlockoutexpiry'];
  6423. }
  6424. else
  6425. {
  6426. $failedtime = $mybb->cookies['lockoutexpiry'];
  6427. }
  6428.  
  6429. // Are we still locked out?
  6430. if($attempts['loginlockoutexpiry'] > $now)
  6431. {
  6432. if($fatal)
  6433. {
  6434. $secsleft = (int)($attempts['loginlockoutexpiry'] - $now);
  6435. $hoursleft = floor($secsleft / 3600);
  6436. $minsleft = floor(($secsleft / 60) % 60);
  6437. $secsleft = floor($secsleft % 60);
  6438.  
  6439. error($lang->sprintf($lang->failed_login_wait, $hoursleft, $minsleft, $secsleft));
  6440. }
  6441.  
  6442. return false;
  6443. }
  6444. // Unlock if enough time has passed
  6445. else {
  6446.  
  6447. if($uid > 0)
  6448. {
  6449. $db->update_query("users", array(
  6450. "loginattempts" => 0,
  6451. "loginlockoutexpiry" => 0
  6452. ), "uid='{$uid}'");
  6453. }
  6454.  
  6455. // Wipe the cookie, no matter if a guest or a member
  6456. my_unsetcookie('lockoutexpiry');
  6457.  
  6458. return 0;
  6459. }
  6460. }
  6461.  
  6462. // User can attempt another login
  6463. return $attempts['loginattempts'];
  6464. }
  6465.  
  6466. /**
  6467. * Validates the format of an email address.
  6468. *
  6469. * @param string $email The string to check.
  6470. * @return boolean True when valid, false when invalid.
  6471. */
  6472. function validate_email_format($email)
  6473. {
  6474. return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
  6475. }
  6476.  
  6477. /**
  6478. * Checks to see if the email is already in use by another
  6479. *
  6480. * @param string $email The email to check.
  6481. * @param int $uid User ID of the user (updating only)
  6482. * @return boolean True when in use, false when not.
  6483. */
  6484. function email_already_in_use($email, $uid=0)
  6485. {
  6486. global $db;
  6487.  
  6488. $uid_string = "";
  6489. if($uid)
  6490. {
  6491. $uid_string = " AND uid != '".(int)$uid."'";
  6492. }
  6493. $query = $db->simple_select("users", "COUNT(email) as emails", "email = '".$db->escape_string($email)."'{$uid_string}");
  6494.  
  6495. if($db->fetch_field($query, "emails") > 0)
  6496. {
  6497. return true;
  6498. }
  6499.  
  6500. return false;
  6501. }
  6502.  
  6503. /**
  6504. * Rebuilds settings.php
  6505. *
  6506. */
  6507. function rebuild_settings()
  6508. {
  6509. global $db, $mybb;
  6510.  
  6511. $query = $db->simple_select("settings", "value, name", "", array(
  6512. 'order_by' => 'title',
  6513. 'order_dir' => 'ASC',
  6514. ));
  6515.  
  6516. $settings = '';
  6517. while($setting = $db->fetch_array($query))
  6518. {
  6519. $mybb->settings[$setting['name']] = $setting['value'];
  6520. $setting['value'] = addcslashes($setting['value'], '\\"$');
  6521. $settings .= "\$settings['{$setting['name']}'] = \"{$setting['value']}\";\n";
  6522. }
  6523.  
  6524. $settings = "<"."?php\n/*********************************\ \n DO NOT EDIT THIS FILE, PLEASE USE\n THE SETTINGS EDITOR\n\*********************************/\n\n$settings\n";
  6525.  
  6526. file_put_contents(MYBB_ROOT.'inc/settings.php', $settings, LOCK_EX);
  6527.  
  6528. $GLOBALS['settings'] = &$mybb->settings;
  6529. }
  6530.  
  6531. /**
  6532. * Build a PREG compatible array of search highlight terms to replace in posts.
  6533. *
  6534. * @param string $terms Incoming terms to highlight
  6535. * @return array PREG compatible array of terms
  6536. */
  6537. function build_highlight_array($terms)
  6538. {
  6539. global $mybb;
  6540.  
  6541. if($mybb->settings['minsearchword'] < 1)
  6542. {
  6543. $mybb->settings['minsearchword'] = 3;
  6544. }
  6545.  
  6546. if(is_array($terms))
  6547. {
  6548. $terms = implode(' ', $terms);
  6549. }
  6550.  
  6551. // Strip out any characters that shouldn't be included
  6552. $bad_characters = array(
  6553. "(",
  6554. ")",
  6555. "+",
  6556. "-",
  6557. "~"
  6558. );
  6559. $terms = str_replace($bad_characters, '', $terms);
  6560.  
  6561. // Check if this is a "series of words" - should be treated as an EXACT match
  6562. if(my_strpos($terms, "\"") !== false)
  6563. {
  6564. $inquote = false;
  6565. $terms = explode("\"", $terms);
  6566. $words = array();
  6567. foreach($terms as $phrase)
  6568. {
  6569. $phrase = htmlspecialchars_uni($phrase);
  6570. if($phrase != "")
  6571. {
  6572. if($inquote)
  6573. {
  6574. $words[] = trim($phrase);
  6575. }
  6576. else
  6577. {
  6578. $split_words = preg_split("#\s{1,}#", $phrase, -1);
  6579. if(!is_array($split_words))
  6580. {
  6581. continue;
  6582. }
  6583. foreach($split_words as $word)
  6584. {
  6585. if(!$word || strlen($word) < $mybb->settings['minsearchword'])
  6586. {
  6587. continue;
  6588. }
  6589. $words[] = trim($word);
  6590. }
  6591. }
  6592. }
  6593. $inquote = !$inquote;
  6594. }
  6595. }
  6596. // Otherwise just a simple search query with no phrases
  6597. else
  6598. {
  6599. $terms = htmlspecialchars_uni($terms);
  6600. $split_words = preg_split("#\s{1,}#", $terms, -1);
  6601. if(is_array($split_words))
  6602. {
  6603. foreach($split_words as $word)
  6604. {
  6605. if(!$word || strlen($word) < $mybb->settings['minsearchword'])
  6606. {
  6607. continue;
  6608. }
  6609. $words[] = trim($word);
  6610. }
  6611. }
  6612. }
  6613.  
  6614. if(!is_array($words))
  6615. {
  6616. return false;
  6617. }
  6618.  
  6619. // Sort the word array by length. Largest terms go first and work their way down to the smallest term.
  6620. // This resolves problems like "test tes" where "tes" will be highlighted first, then "test" can't be highlighted because of the changed html
  6621. usort($words, 'build_highlight_array_sort');
  6622.  
  6623. // Loop through our words to build the PREG compatible strings
  6624. foreach($words as $word)
  6625. {
  6626. $word = trim($word);
  6627.  
  6628. $word = my_strtolower($word);
  6629.  
  6630. // Special boolean operators should be stripped
  6631. if($word == "" || $word == "or" || $word == "not" || $word == "and")
  6632. {
  6633. continue;
  6634. }
  6635.  
  6636. // Now make PREG compatible
  6637. $find = "#(?!<.*?)(".preg_quote($word, "#").")(?![^<>]*?>)#ui";
  6638. $replacement = "<span class=\"highlight\" style=\"padding-left: 0px; padding-right: 0px;\">$1</span>";
  6639. $highlight_cache[$find] = $replacement;
  6640. }
  6641.  
  6642. return $highlight_cache;
  6643. }
  6644.  
  6645. /**
  6646. * Sort the word array by length. Largest terms go first and work their way down to the smallest term.
  6647. *
  6648. * @param string $a First word.
  6649. * @param string $b Second word.
  6650. * @return integer Result of comparison function.
  6651. */
  6652. function build_highlight_array_sort($a, $b)
  6653. {
  6654. return strlen($b) - strlen($a);
  6655. }
  6656.  
  6657. /**
  6658. * Converts a decimal reference of a character to its UTF-8 equivalent
  6659. * (Code by Anne van Kesteren, http://annevankesteren.nl/2005/05/character-references)
  6660. *
  6661. * @param int $src Decimal value of a character reference
  6662. * @return string|bool
  6663. */
  6664. function dec_to_utf8($src)
  6665. {
  6666. $dest = '';
  6667.  
  6668. if($src < 0)
  6669. {
  6670. return false;
  6671. }
  6672. elseif($src <= 0x007f)
  6673. {
  6674. $dest .= chr($src);
  6675. }
  6676. elseif($src <= 0x07ff)
  6677. {
  6678. $dest .= chr(0xc0 | ($src >> 6));
  6679. $dest .= chr(0x80 | ($src & 0x003f));
  6680. }
  6681. elseif($src <= 0xffff)
  6682. {
  6683. $dest .= chr(0xe0 | ($src >> 12));
  6684. $dest .= chr(0x80 | (($src >> 6) & 0x003f));
  6685. $dest .= chr(0x80 | ($src & 0x003f));
  6686. }
  6687. elseif($src <= 0x10ffff)
  6688. {
  6689. $dest .= chr(0xf0 | ($src >> 18));
  6690. $dest .= chr(0x80 | (($src >> 12) & 0x3f));
  6691. $dest .= chr(0x80 | (($src >> 6) & 0x3f));
  6692. $dest .= chr(0x80 | ($src & 0x3f));
  6693. }
  6694. else
  6695. {
  6696. // Out of range
  6697. return false;
  6698. }
  6699.  
  6700. return $dest;
  6701. }
  6702.  
  6703. /**
  6704. * Checks if a username has been disallowed for registration/use.
  6705. *
  6706. * @param string $username The username
  6707. * @param boolean $update_lastuse True if the 'last used' dateline should be updated if a match is found.
  6708. * @return boolean True if banned, false if not banned
  6709. */
  6710. function is_banned_username($username, $update_lastuse=false)
  6711. {
  6712. global $db;
  6713. $query = $db->simple_select('banfilters', 'filter, fid', "type='2'");
  6714. while($banned_username = $db->fetch_array($query))
  6715. {
  6716. // Make regular expression * match
  6717. $banned_username['filter'] = str_replace('\*', '(.*)', preg_quote($banned_username['filter'], '#'));
  6718. if(preg_match("#(^|\b){$banned_username['filter']}($|\b)#i", $username))
  6719. {
  6720. // Updating last use
  6721. if($update_lastuse == true)
  6722. {
  6723. $db->update_query("banfilters", array("lastuse" => TIME_NOW), "fid='{$banned_username['fid']}'");
  6724. }
  6725. return true;
  6726. }
  6727. }
  6728. // Still here - good username
  6729. return false;
  6730. }
  6731.  
  6732. /**
  6733. * Check if a specific email address has been banned.
  6734. *
  6735. * @param string $email The email address.
  6736. * @param boolean $update_lastuse True if the 'last used' dateline should be updated if a match is found.
  6737. * @return boolean True if banned, false if not banned
  6738. */
  6739. function is_banned_email($email, $update_lastuse=false)
  6740. {
  6741. global $cache, $db;
  6742.  
  6743. $banned_cache = $cache->read("bannedemails");
  6744.  
  6745. if($banned_cache === false)
  6746. {
  6747. // Failed to read cache, see if we can rebuild it
  6748. $cache->update_bannedemails();
  6749. $banned_cache = $cache->read("bannedemails");
  6750. }
  6751.  
  6752. if(is_array($banned_cache) && !empty($banned_cache))
  6753. {
  6754. foreach($banned_cache as $banned_email)
  6755. {
  6756. // Make regular expression * match
  6757. $banned_email['filter'] = str_replace('\*', '(.*)', preg_quote($banned_email['filter'], '#'));
  6758.  
  6759. if(preg_match("#{$banned_email['filter']}#i", $email))
  6760. {
  6761. // Updating last use
  6762. if($update_lastuse == true)
  6763. {
  6764. $db->update_query("banfilters", array("lastuse" => TIME_NOW), "fid='{$banned_email['fid']}'");
  6765. }
  6766. return true;
  6767. }
  6768. }
  6769. }
  6770.  
  6771. // Still here - good email
  6772. return false;
  6773. }
  6774.  
  6775. /**
  6776. * Checks if a specific IP address has been banned.
  6777. *
  6778. * @param string $ip_address The IP address.
  6779. * @param boolean $update_lastuse True if the 'last used' dateline should be updated if a match is found.
  6780. * @return boolean True if banned, false if not banned.
  6781. */
  6782. function is_banned_ip($ip_address, $update_lastuse=false)
  6783. {
  6784. global $db, $cache;
  6785.  
  6786. $banned_ips = $cache->read("bannedips");
  6787. if(!is_array($banned_ips))
  6788. {
  6789. return false;
  6790. }
  6791.  
  6792. $ip_address = my_inet_pton($ip_address);
  6793. foreach($banned_ips as $banned_ip)
  6794. {
  6795. if(!$banned_ip['filter'])
  6796. {
  6797. continue;
  6798. }
  6799.  
  6800. $banned = false;
  6801.  
  6802. $ip_range = fetch_ip_range($banned_ip['filter']);
  6803. if(is_array($ip_range))
  6804. {
  6805. if(strcmp($ip_range[0], $ip_address) <= 0 && strcmp($ip_range[1], $ip_address) >= 0)
  6806. {
  6807. $banned = true;
  6808. }
  6809. }
  6810. elseif($ip_address == $ip_range)
  6811. {
  6812. $banned = true;
  6813. }
  6814. if($banned)
  6815. {
  6816. // Updating last use
  6817. if($update_lastuse == true)
  6818. {
  6819. $db->update_query("banfilters", array("lastuse" => TIME_NOW), "fid='{$banned_ip['fid']}'");
  6820. }
  6821. return true;
  6822. }
  6823. }
  6824.  
  6825. // Still here - good ip
  6826. return false;
  6827. }
  6828.  
  6829. /**
  6830. * Returns an array of supported timezones
  6831. *
  6832. * @return string[] Key is timezone offset, Value the language description
  6833. */
  6834. function get_supported_timezones()
  6835. {
  6836. global $lang;
  6837. $timezones = array(
  6838. "-12" => $lang->timezone_gmt_minus_1200,
  6839. "-11" => $lang->timezone_gmt_minus_1100,
  6840. "-10" => $lang->timezone_gmt_minus_1000,
  6841. "-9.5" => $lang->timezone_gmt_minus_950,
  6842. "-9" => $lang->timezone_gmt_minus_900,
  6843. "-8" => $lang->timezone_gmt_minus_800,
  6844. "-7" => $lang->timezone_gmt_minus_700,
  6845. "-6" => $lang->timezone_gmt_minus_600,
  6846. "-5" => $lang->timezone_gmt_minus_500,
  6847. "-4.5" => $lang->timezone_gmt_minus_450,
  6848. "-4" => $lang->timezone_gmt_minus_400,
  6849. "-3.5" => $lang->timezone_gmt_minus_350,
  6850. "-3" => $lang->timezone_gmt_minus_300,
  6851. "-2" => $lang->timezone_gmt_minus_200,
  6852. "-1" => $lang->timezone_gmt_minus_100,
  6853. "0" => $lang->timezone_gmt,
  6854. "1" => $lang->timezone_gmt_100,
  6855. "2" => $lang->timezone_gmt_200,
  6856. "3" => $lang->timezone_gmt_300,
  6857. "3.5" => $lang->timezone_gmt_350,
  6858. "4" => $lang->timezone_gmt_400,
  6859. "4.5" => $lang->timezone_gmt_450,
  6860. "5" => $lang->timezone_gmt_500,
  6861. "5.5" => $lang->timezone_gmt_550,
  6862. "5.75" => $lang->timezone_gmt_575,
  6863. "6" => $lang->timezone_gmt_600,
  6864. "6.5" => $lang->timezone_gmt_650,
  6865. "7" => $lang->timezone_gmt_700,
  6866. "8" => $lang->timezone_gmt_800,
  6867. "8.5" => $lang->timezone_gmt_850,
  6868. "8.75" => $lang->timezone_gmt_875,
  6869. "9" => $lang->timezone_gmt_900,
  6870. "9.5" => $lang->timezone_gmt_950,
  6871. "10" => $lang->timezone_gmt_1000,
  6872. "10.5" => $lang->timezone_gmt_1050,
  6873. "11" => $lang->timezone_gmt_1100,
  6874. "11.5" => $lang->timezone_gmt_1150,
  6875. "12" => $lang->timezone_gmt_1200,
  6876. "12.75" => $lang->timezone_gmt_1275,
  6877. "13" => $lang->timezone_gmt_1300,
  6878. "14" => $lang->timezone_gmt_1400
  6879. );
  6880. return $timezones;
  6881. }
  6882.  
  6883. /**
  6884. * Build a time zone selection list.
  6885. *
  6886. * @param string $name The name of the select
  6887. * @param int $selected The selected time zone (defaults to GMT)
  6888. * @param boolean $short True to generate a "short" list with just timezone and current time
  6889. * @return string
  6890. */
  6891. function build_timezone_select($name, $selected=0, $short=false)
  6892. {
  6893. global $mybb, $lang, $templates;
  6894.  
  6895. $timezones = get_supported_timezones();
  6896.  
  6897. $selected = str_replace("+", "", $selected);
  6898. foreach($timezones as $timezone => $label)
  6899. {
  6900. $selected_add = "";
  6901. if($selected == $timezone)
  6902. {
  6903. $selected_add = " selected=\"selected\"";
  6904. }
  6905. if($short == true)
  6906. {
  6907. $label = '';
  6908. if($timezone != 0)
  6909. {
  6910. $label = $timezone;
  6911. if($timezone > 0)
  6912. {
  6913. $label = "+{$label}";
  6914. }
  6915. if(strpos($timezone, ".") !== false)
  6916. {
  6917. $label = str_replace(".", ":", $label);
  6918. $label = str_replace(":5", ":30", $label);
  6919. $label = str_replace(":75", ":45", $label);
  6920. }
  6921. else
  6922. {
  6923. $label .= ":00";
  6924. }
  6925. }
  6926. $time_in_zone = my_date($mybb->settings['timeformat'], TIME_NOW, $timezone);
  6927. $label = $lang->sprintf($lang->timezone_gmt_short, $label." ", $time_in_zone);
  6928. }
  6929.  
  6930. eval("\$timezone_option .= \"".$templates->get("usercp_options_timezone_option")."\";");
  6931. }
  6932.  
  6933. eval("\$select = \"".$templates->get("usercp_options_timezone")."\";");
  6934. return $select;
  6935. }
  6936.  
  6937. /**
  6938. * Fetch the contents of a remote file.
  6939. *
  6940. * @param string $url The URL of the remote file
  6941. * @param array $post_data The array of post data
  6942. * @param int $max_redirects Number of maximum redirects
  6943. * @return string|bool The remote file contents. False on failure
  6944. */
  6945. function fetch_remote_file($url, $post_data=array(), $max_redirects=20)
  6946. {
  6947. global $mybb, $config;
  6948.  
  6949. if(!my_validate_url($url, true))
  6950. {
  6951. return false;
  6952. }
  6953.  
  6954. $url_components = @parse_url($url);
  6955.  
  6956. if(!isset($url_components['scheme']))
  6957. {
  6958. $url_components['scheme'] = 'https';
  6959. }
  6960. if(!isset($url_components['port']))
  6961. {
  6962. $url_components['port'] = $url_components['scheme'] == 'https' ? 443 : 80;
  6963. }
  6964.  
  6965. if(
  6966. !$url_components ||
  6967. empty($url_components['host']) ||
  6968. (!empty($url_components['scheme']) && !in_array($url_components['scheme'], array('http', 'https'))) ||
  6969. (!in_array($url_components['port'], array(80, 8080, 443))) ||
  6970. (!empty($config['disallowed_remote_hosts']) && in_array($url_components['host'], $config['disallowed_remote_hosts']))
  6971. )
  6972. {
  6973. return false;
  6974. }
  6975.  
  6976. $addresses = get_ip_by_hostname($url_components['host']);
  6977. $destination_address = $addresses[0];
  6978.  
  6979. if(!empty($config['disallowed_remote_addresses']))
  6980. {
  6981. foreach($config['disallowed_remote_addresses'] as $disallowed_address)
  6982. {
  6983. $ip_range = fetch_ip_range($disallowed_address);
  6984.  
  6985. $packed_address = my_inet_pton($destination_address);
  6986.  
  6987. if(is_array($ip_range))
  6988. {
  6989. if(strcmp($ip_range[0], $packed_address) <= 0 && strcmp($ip_range[1], $packed_address) >= 0)
  6990. {
  6991. return false;
  6992. }
  6993. }
  6994. elseif($destination_address == $disallowed_address)
  6995. {
  6996. return false;
  6997. }
  6998. }
  6999. }
  7000.  
  7001. $post_body = '';
  7002. if(!empty($post_data))
  7003. {
  7004. foreach($post_data as $key => $val)
  7005. {
  7006. $post_body .= '&'.urlencode($key).'='.urlencode($val);
  7007. }
  7008. $post_body = ltrim($post_body, '&');
  7009. }
  7010.  
  7011. if(function_exists("curl_init"))
  7012. {
  7013. $fetch_header = $max_redirects > 0;
  7014.  
  7015. $ch = curl_init();
  7016.  
  7017. $curlopt = array(
  7018. CURLOPT_URL => $url,
  7019. CURLOPT_HEADER => $fetch_header,
  7020. CURLOPT_TIMEOUT => 10,
  7021. CURLOPT_RETURNTRANSFER => 1,
  7022. CURLOPT_FOLLOWLOCATION => 0,
  7023. );
  7024.  
  7025. if($ca_bundle_path = get_ca_bundle_path())
  7026. {
  7027. $curlopt[CURLOPT_SSL_VERIFYPEER] = 1;
  7028. $curlopt[CURLOPT_CAINFO] = $ca_bundle_path;
  7029. }
  7030. else
  7031. {
  7032. $curlopt[CURLOPT_SSL_VERIFYPEER] = 0;
  7033. }
  7034.  
  7035. $curl_version_info = curl_version();
  7036. $curl_version = $curl_version_info['version'];
  7037.  
  7038. if(version_compare(PHP_VERSION, '7.0.7', '>=') && version_compare($curl_version, '7.49', '>='))
  7039. {
  7040. // CURLOPT_CONNECT_TO
  7041. $curlopt[10243] = array(
  7042. $url_components['host'].':'.$url_components['port'].':'.$destination_address
  7043. );
  7044. }
  7045. elseif(version_compare(PHP_VERSION, '5.5', '>=') && version_compare($curl_version, '7.21.3', '>='))
  7046. {
  7047. // CURLOPT_RESOLVE
  7048. $curlopt[10203] = array(
  7049. $url_components['host'].':'.$url_components['port'].':'.$destination_address
  7050. );
  7051. }
  7052.  
  7053. if(!empty($post_body))
  7054. {
  7055. $curlopt[CURLOPT_POST] = 1;
  7056. $curlopt[CURLOPT_POSTFIELDS] = $post_body;
  7057. }
  7058.  
  7059. curl_setopt_array($ch, $curlopt);
  7060.  
  7061. $response = curl_exec($ch);
  7062.  
  7063. if($fetch_header)
  7064. {
  7065. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  7066. $header = substr($response, 0, $header_size);
  7067. $body = substr($response, $header_size);
  7068.  
  7069. if(in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE), array(301, 302)))
  7070. {
  7071. preg_match('/Location:(.*?)(?:\n|$)/', $header, $matches);
  7072.  
  7073. if($matches)
  7074. {
  7075. $data = fetch_remote_file(trim(array_pop($matches)), $post_data, --$max_redirects);
  7076. }
  7077. }
  7078. else
  7079. {
  7080. $data = $body;
  7081. }
  7082. }
  7083. else
  7084. {
  7085. $data = $response;
  7086. }
  7087.  
  7088. curl_close($ch);
  7089. return $data;
  7090. }
  7091. else if(function_exists("fsockopen"))
  7092. {
  7093. if(!isset($url_components['path']))
  7094. {
  7095. $url_components['path'] = "/";
  7096. }
  7097. if(isset($url_components['query']))
  7098. {
  7099. $url_components['path'] .= "?{$url_components['query']}";
  7100. }
  7101.  
  7102. $scheme = '';
  7103.  
  7104. if($url_components['scheme'] == 'https')
  7105. {
  7106. $scheme = 'ssl://';
  7107. if($url_components['port'] == 80)
  7108. {
  7109. $url_components['port'] = 443;
  7110. }
  7111. }
  7112.  
  7113. if(function_exists('stream_context_create'))
  7114. {
  7115. if($url_components['scheme'] == 'https' && $ca_bundle_path = get_ca_bundle_path())
  7116. {
  7117. $context = stream_context_create(array(
  7118. 'ssl' => array(
  7119. 'verify_peer' => true,
  7120. 'verify_peer_name' => true,
  7121. 'peer_name' => $url_components['host'],
  7122. 'cafile' => $ca_bundle_path,
  7123. ),
  7124. ));
  7125. }
  7126. else
  7127. {
  7128. $context = stream_context_create(array(
  7129. 'ssl' => array(
  7130. 'verify_peer' => false,
  7131. 'verify_peer_name' => false,
  7132. ),
  7133. ));
  7134. }
  7135.  
  7136. $fp = @stream_socket_client($scheme.$destination_address.':'.(int)$url_components['port'], $error_no, $error, 10, STREAM_CLIENT_CONNECT, $context);
  7137. }
  7138. else
  7139. {
  7140. $fp = @fsockopen($scheme.$url_components['host'], (int)$url_components['port'], $error_no, $error, 10);
  7141. }
  7142.  
  7143. @stream_set_timeout($fp, 10);
  7144. if(!$fp)
  7145. {
  7146. return false;
  7147. }
  7148. $headers = array();
  7149. if(!empty($post_body))
  7150. {
  7151. $headers[] = "POST {$url_components['path']} HTTP/1.0";
  7152. $headers[] = "Content-Length: ".strlen($post_body);
  7153. $headers[] = "Content-Type: application/x-www-form-urlencoded";
  7154. }
  7155. else
  7156. {
  7157. $headers[] = "GET {$url_components['path']} HTTP/1.0";
  7158. }
  7159.  
  7160. $headers[] = "Host: {$url_components['host']}";
  7161. $headers[] = "Connection: Close";
  7162. $headers[] = '';
  7163.  
  7164. if(!empty($post_body))
  7165. {
  7166. $headers[] = $post_body;
  7167. }
  7168. else
  7169. {
  7170. // If we have no post body, we need to add an empty element to make sure we've got \r\n\r\n before the (non-existent) body starts
  7171. $headers[] = '';
  7172. }
  7173.  
  7174. $headers = implode("\r\n", $headers);
  7175. if(!@fwrite($fp, $headers))
  7176. {
  7177. return false;
  7178. }
  7179.  
  7180. $data = null;
  7181.  
  7182. while(!feof($fp))
  7183. {
  7184. $data .= fgets($fp, 12800);
  7185. }
  7186. fclose($fp);
  7187.  
  7188. $data = explode("\r\n\r\n", $data, 2);
  7189.  
  7190. $header = $data[0];
  7191. $status_line = current(explode("\n\n", $header, 1));
  7192. $body = $data[1];
  7193.  
  7194. if($max_redirects > 0 && (strstr($status_line, ' 301 ') || strstr($status_line, ' 302 ')))
  7195. {
  7196. preg_match('/Location:(.*?)(?:\n|$)/', $header, $matches);
  7197.  
  7198. if($matches)
  7199. {
  7200. $data = fetch_remote_file(trim(array_pop($matches)), $post_data, --$max_redirects);
  7201. }
  7202. }
  7203. else
  7204. {
  7205. $data = $body;
  7206. }
  7207.  
  7208. return $data;
  7209. }
  7210. else
  7211. {
  7212. return false;
  7213. }
  7214. }
  7215.  
  7216. /**
  7217. * Resolves a hostname into a set of IP addresses.
  7218. *
  7219. * @param string $hostname The hostname to be resolved
  7220. * @return array|bool The resulting IP addresses. False on failure
  7221. */
  7222. function get_ip_by_hostname($hostname)
  7223. {
  7224. $addresses = @gethostbynamel($hostname);
  7225.  
  7226. if(!$addresses)
  7227. {
  7228. $result_set = @dns_get_record($hostname, DNS_A | DNS_AAAA);
  7229.  
  7230. if($result_set)
  7231. {
  7232. $addresses = array_column($result_set, 'ip');
  7233. }
  7234. else
  7235. {
  7236. return false;
  7237. }
  7238. }
  7239.  
  7240. return $addresses;
  7241. }
  7242.  
  7243. /**
  7244. * Returns the location of the CA bundle defined in the PHP configuration.
  7245. *
  7246. * @return string|bool The location of the CA bundle, false if not set
  7247. */
  7248. function get_ca_bundle_path()
  7249. {
  7250. if($path = ini_get('openssl.cafile'))
  7251. {
  7252. return $path;
  7253. }
  7254. if($path = ini_get('curl.cainfo'))
  7255. {
  7256. return $path;
  7257. }
  7258.  
  7259. return false;
  7260. }
  7261.  
  7262. /**
  7263. * Checks if a particular user is a super administrator.
  7264. *
  7265. * @param int $uid The user ID to check against the list of super admins
  7266. * @return boolean True if a super admin, false if not
  7267. */
  7268. function is_super_admin($uid)
  7269. {
  7270. static $super_admins;
  7271.  
  7272. if(!isset($super_admins))
  7273. {
  7274. global $mybb;
  7275. $super_admins = str_replace(" ", "", $mybb->config['super_admins']);
  7276. }
  7277.  
  7278. if(my_strpos(",{$super_admins},", ",{$uid},") === false)
  7279. {
  7280. return false;
  7281. }
  7282. else
  7283. {
  7284. return true;
  7285. }
  7286. }
  7287.  
  7288. /**
  7289. * Checks if a user is a member of a particular group
  7290. * Originates from frostschutz's PluginLibrary
  7291. * github.com/frostschutz
  7292. *
  7293. * @param array|int|string A selection of groups (as array or comma seperated) to check or -1 for any group
  7294. * @param bool|array|int False assumes the current user. Otherwise an user array or an id can be passed
  7295. * @return array Array of groups specified in the first param to which the user belongs
  7296. */
  7297. function is_member($groups, $user = false)
  7298. {
  7299. global $mybb;
  7300.  
  7301. if(empty($groups))
  7302. {
  7303. return array();
  7304. }
  7305.  
  7306. if($user == false)
  7307. {
  7308. $user = $mybb->user;
  7309. }
  7310. else if(!is_array($user))
  7311. {
  7312. // Assume it's a UID
  7313. $user = get_user($user);
  7314. }
  7315.  
  7316. $memberships = array_map('intval', explode(',', $user['additionalgroups']));
  7317. $memberships[] = $user['usergroup'];
  7318.  
  7319. if(!is_array($groups))
  7320. {
  7321. if((int)$groups == -1)
  7322. {
  7323. return $memberships;
  7324. }
  7325. else
  7326. {
  7327. if(is_string($groups))
  7328. {
  7329. $groups = explode(',', $groups);
  7330. }
  7331. else
  7332. {
  7333. $groups = (array)$groups;
  7334. }
  7335. }
  7336. }
  7337.  
  7338. $groups = array_filter(array_map('intval', $groups));
  7339.  
  7340. return array_intersect($groups, $memberships);
  7341. }
  7342.  
  7343. /**
  7344. * Split a string based on the specified delimeter, ignoring said delimeter in escaped strings.
  7345. * Ex: the "quick brown fox" jumped, could return 1 => the, 2 => quick brown fox, 3 => jumped
  7346. *
  7347. * @param string $delimeter The delimeter to split by
  7348. * @param string $string The string to split
  7349. * @param string $escape The escape character or string if we have one.
  7350. * @return array Array of split string
  7351. */
  7352. function escaped_explode($delimeter, $string, $escape="")
  7353. {
  7354. $strings = array();
  7355. $original = $string;
  7356. $in_escape = false;
  7357. if($escape)
  7358. {
  7359. if(is_array($escape))
  7360. {
  7361. function escaped_explode_escape($string)
  7362. {
  7363. return preg_quote($string, "#");
  7364. }
  7365. $escape_preg = "(".implode("|", array_map("escaped_explode_escape", $escape)).")";
  7366. }
  7367. else
  7368. {
  7369. $escape_preg = preg_quote($escape, "#");
  7370. }
  7371. $quoted_strings = preg_split("#(?<!\\\){$escape_preg}#", $string);
  7372. }
  7373. else
  7374. {
  7375. $quoted_strings = array($string);
  7376. }
  7377. foreach($quoted_strings as $string)
  7378. {
  7379. if($string != "")
  7380. {
  7381. if($in_escape)
  7382. {
  7383. $strings[] = trim($string);
  7384. }
  7385. else
  7386. {
  7387. $split_strings = explode($delimeter, $string);
  7388. foreach($split_strings as $string)
  7389. {
  7390. if($string == "") continue;
  7391. $strings[] = trim($string);
  7392. }
  7393. }
  7394. }
  7395. $in_escape = !$in_escape;
  7396. }
  7397. if(!count($strings))
  7398. {
  7399. return $original;
  7400. }
  7401. return $strings;
  7402. }
  7403.  
  7404. /**
  7405. * DEPRECATED! Please use IPv6 compatible fetch_ip_range!
  7406. * Fetch an IPv4 long formatted range for searching IPv4 IP addresses.
  7407. *
  7408. * @deprecated
  7409. * @param string $ip The IP address to convert to a range based LONG
  7410. * @return string|array If a full IP address is provided, the ip2long equivalent, otherwise an array of the upper & lower extremities of the IP
  7411. */
  7412. function fetch_longipv4_range($ip)
  7413. {
  7414. $ip_bits = explode(".", $ip);
  7415. $ip_string1 = $ip_string2 = "";
  7416.  
  7417. if($ip == "*")
  7418. {
  7419. return array(ip2long('0.0.0.0'), ip2long('255.255.255.255'));
  7420. }
  7421.  
  7422. if(strpos($ip, ".*") === false)
  7423. {
  7424. $ip = str_replace("*", "", $ip);
  7425. if(count($ip_bits) == 4)
  7426. {
  7427. return ip2long($ip);
  7428. }
  7429. else
  7430. {
  7431. return array(ip2long($ip.".0"), ip2long($ip.".255"));
  7432. }
  7433. }
  7434. // Wildcard based IP provided
  7435. else
  7436. {
  7437. $sep = "";
  7438. foreach($ip_bits as $piece)
  7439. {
  7440. if($piece == "*")
  7441. {
  7442. $ip_string1 .= $sep."0";
  7443. $ip_string2 .= $sep."255";
  7444. }
  7445. else
  7446. {
  7447. $ip_string1 .= $sep.$piece;
  7448. $ip_string2 .= $sep.$piece;
  7449. }
  7450. $sep = ".";
  7451. }
  7452. return array(ip2long($ip_string1), ip2long($ip_string2));
  7453. }
  7454. }
  7455.  
  7456. /**
  7457. * Fetch a list of ban times for a user account.
  7458. *
  7459. * @return array Array of ban times
  7460. */
  7461. function fetch_ban_times()
  7462. {
  7463. global $plugins, $lang;
  7464.  
  7465. // Days-Months-Years
  7466. $ban_times = array(
  7467. "1-0-0" => "1 {$lang->day}",
  7468. "2-0-0" => "2 {$lang->days}",
  7469. "3-0-0" => "3 {$lang->days}",
  7470. "4-0-0" => "4 {$lang->days}",
  7471. "5-0-0" => "5 {$lang->days}",
  7472. "6-0-0" => "6 {$lang->days}",
  7473. "7-0-0" => "1 {$lang->week}",
  7474. "14-0-0" => "2 {$lang->weeks}",
  7475. "21-0-0" => "3 {$lang->weeks}",
  7476. "0-1-0" => "1 {$lang->month}",
  7477. "0-2-0" => "2 {$lang->months}",
  7478. "0-3-0" => "3 {$lang->months}",
  7479. "0-4-0" => "4 {$lang->months}",
  7480. "0-5-0" => "5 {$lang->months}",
  7481. "0-6-0" => "6 {$lang->months}",
  7482. "0-0-1" => "1 {$lang->year}",
  7483. "0-0-2" => "2 {$lang->years}"
  7484. );
  7485.  
  7486. $ban_times = $plugins->run_hooks("functions_fetch_ban_times", $ban_times);
  7487.  
  7488. $ban_times['---'] = $lang->permanent;
  7489. return $ban_times;
  7490. }
  7491.  
  7492. /**
  7493. * Format a ban length in to a UNIX timestamp.
  7494. *
  7495. * @param string $date The ban length string
  7496. * @param int $stamp The optional UNIX timestamp, if 0, current time is used.
  7497. * @return int The UNIX timestamp when the ban will be lifted
  7498. */
  7499. function ban_date2timestamp($date, $stamp=0)
  7500. {
  7501. if($stamp == 0)
  7502. {
  7503. $stamp = TIME_NOW;
  7504. }
  7505. $d = explode('-', $date);
  7506. $nowdate = date("H-j-n-Y", $stamp);
  7507. $n = explode('-', $nowdate);
  7508. $n[1] += $d[0];
  7509. $n[2] += $d[1];
  7510. $n[3] += $d[2];
  7511. return mktime(date("G", $stamp), date("i", $stamp), 0, $n[2], $n[1], $n[3]);
  7512. }
  7513.  
  7514. /**
  7515. * Expire old warnings in the database.
  7516. *
  7517. * @return bool
  7518. */
  7519. function expire_warnings()
  7520. {
  7521. global $warningshandler;
  7522.  
  7523. if(!is_object($warningshandler))
  7524. {
  7525. require_once MYBB_ROOT.'inc/datahandlers/warnings.php';
  7526. $warningshandler = new WarningsHandler('update');
  7527. }
  7528.  
  7529. return $warningshandler->expire_warnings();
  7530. }
  7531.  
  7532. /**
  7533. * Custom chmod function to fix problems with hosts who's server configurations screw up umasks
  7534. *
  7535. * @param string $file The file to chmod
  7536. * @param string $mode The mode to chmod(i.e. 0666)
  7537. * @return bool
  7538. */
  7539. function my_chmod($file, $mode)
  7540. {
  7541. // Passing $mode as an octal number causes strlen and substr to return incorrect values. Instead pass as a string
  7542. if(substr($mode, 0, 1) != '0' || strlen($mode) !== 4)
  7543. {
  7544. return false;
  7545. }
  7546. $old_umask = umask(0);
  7547.  
  7548. // We convert the octal string to a decimal number because passing a octal string doesn't work with chmod
  7549. // and type casting subsequently removes the prepended 0 which is needed for octal numbers
  7550. $result = chmod($file, octdec($mode));
  7551. umask($old_umask);
  7552. return $result;
  7553. }
  7554.  
  7555. /**
  7556. * Custom rmdir function to loop through an entire directory and delete all files/folders within
  7557. *
  7558. * @param string $path The path to the directory
  7559. * @param array $ignore Any files you wish to ignore (optional)
  7560. * @return bool
  7561. */
  7562. function my_rmdir_recursive($path, $ignore=array())
  7563. {
  7564. global $orig_dir;
  7565.  
  7566. if(!isset($orig_dir))
  7567. {
  7568. $orig_dir = $path;
  7569. }
  7570.  
  7571. if(@is_dir($path) && !@is_link($path))
  7572. {
  7573. if($dh = @opendir($path))
  7574. {
  7575. while(($file = @readdir($dh)) !== false)
  7576. {
  7577. if($file == '.' || $file == '..' || $file == '.svn' || in_array($path.'/'.$file, $ignore) || !my_rmdir_recursive($path.'/'.$file))
  7578. {
  7579. continue;
  7580. }
  7581. }
  7582. @closedir($dh);
  7583. }
  7584.  
  7585. // Are we done? Don't delete the main folder too and return true
  7586. if($path == $orig_dir)
  7587. {
  7588. return true;
  7589. }
  7590.  
  7591. return @rmdir($path);
  7592. }
  7593.  
  7594. return @unlink($path);
  7595. }
  7596.  
  7597. /**
  7598. * Counts the number of subforums in a array([pid][disporder][fid]) starting from the pid
  7599. *
  7600. * @param array $array The array of forums
  7601. * @return integer The number of sub forums
  7602. */
  7603. function subforums_count($array)
  7604. {
  7605. $count = 0;
  7606. foreach($array as $array2)
  7607. {
  7608. $count += count($array2);
  7609. }
  7610.  
  7611. return $count;
  7612. }
  7613.  
  7614. /**
  7615. * DEPRECATED! Please use IPv6 compatible my_inet_pton!
  7616. * Fix for PHP's ip2long to guarantee a 32-bit signed integer value is produced (this is aimed
  7617. * at 64-bit versions of PHP)
  7618. *
  7619. * @deprecated
  7620. * @param string $ip The IP to convert
  7621. * @return integer IP in 32-bit signed format
  7622. */
  7623. function my_ip2long($ip)
  7624. {
  7625. $ip_long = ip2long($ip);
  7626.  
  7627. if(!$ip_long)
  7628. {
  7629. $ip_long = sprintf("%u", ip2long($ip));
  7630.  
  7631. if(!$ip_long)
  7632. {
  7633. return 0;
  7634. }
  7635. }
  7636.  
  7637. if($ip_long >= 2147483648) // Won't occur on 32-bit PHP
  7638. {
  7639. $ip_long -= 4294967296;
  7640. }
  7641.  
  7642. return $ip_long;
  7643. }
  7644.  
  7645. /**
  7646. * DEPRECATED! Please use IPv6 compatible my_inet_ntop!
  7647. * As above, fix for PHP's long2ip on 64-bit versions
  7648. *
  7649. * @deprecated
  7650. * @param integer $long The IP to convert (will accept 64-bit IPs as well)
  7651. * @return string IP in IPv4 format
  7652. */
  7653. function my_long2ip($long)
  7654. {
  7655. // On 64-bit machines is_int will return true. On 32-bit it will return false
  7656. if($long < 0 && is_int(2147483648))
  7657. {
  7658. // We have a 64-bit system
  7659. $long += 4294967296;
  7660. }
  7661. return long2ip($long);
  7662. }
  7663.  
  7664. /**
  7665. * Converts a human readable IP address to its packed in_addr representation
  7666. *
  7667. * @param string $ip The IP to convert
  7668. * @return string IP in 32bit or 128bit binary format
  7669. */
  7670. function my_inet_pton($ip)
  7671. {
  7672. if(function_exists('inet_pton'))
  7673. {
  7674. return @inet_pton($ip);
  7675. }
  7676. else
  7677. {
  7678. /**
  7679. * Replace inet_pton()
  7680. *
  7681. * @category PHP
  7682. * @package PHP_Compat
  7683. * @license LGPL - http://www.gnu.org/licenses/lgpl.html
  7684. * @copyright 2004-2007 Aidan Lister <aidan@php.net>, Arpad Ray <arpad@php.net>
  7685. * @link http://php.net/inet_pton
  7686. * @author Arpad Ray <arpad@php.net>
  7687. * @version $Revision: 269597 $
  7688. */
  7689. $r = ip2long($ip);
  7690. if($r !== false && $r != -1)
  7691. {
  7692. return pack('N', $r);
  7693. }
  7694.  
  7695. $delim_count = substr_count($ip, ':');
  7696. if($delim_count < 1 || $delim_count > 7)
  7697. {
  7698. return false;
  7699. }
  7700.  
  7701. $r = explode(':', $ip);
  7702. $rcount = count($r);
  7703. if(($doub = array_search('', $r, 1)) !== false)
  7704. {
  7705. $length = (!$doub || $doub == $rcount - 1 ? 2 : 1);
  7706. array_splice($r, $doub, $length, array_fill(0, 8 + $length - $rcount, 0));
  7707. }
  7708.  
  7709. $r = array_map('hexdec', $r);
  7710. array_unshift($r, 'n*');
  7711. $r = call_user_func_array('pack', $r);
  7712.  
  7713. return $r;
  7714. }
  7715. }
  7716.  
  7717. /**
  7718. * Converts a packed internet address to a human readable representation
  7719. *
  7720. * @param string $ip IP in 32bit or 128bit binary format
  7721. * @return string IP in human readable format
  7722. */
  7723. function my_inet_ntop($ip)
  7724. {
  7725. if(function_exists('inet_ntop'))
  7726. {
  7727. return @inet_ntop($ip);
  7728. }
  7729. else
  7730. {
  7731. /**
  7732. * Replace inet_ntop()
  7733. *
  7734. * @category PHP
  7735. * @package PHP_Compat
  7736. * @license LGPL - http://www.gnu.org/licenses/lgpl.html
  7737. * @copyright 2004-2007 Aidan Lister <aidan@php.net>, Arpad Ray <arpad@php.net>
  7738. * @link http://php.net/inet_ntop
  7739. * @author Arpad Ray <arpad@php.net>
  7740. * @version $Revision: 269597 $
  7741. */
  7742. switch(strlen($ip))
  7743. {
  7744. case 4:
  7745. list(,$r) = unpack('N', $ip);
  7746. return long2ip($r);
  7747. case 16:
  7748. $r = substr(chunk_split(bin2hex($ip), 4, ':'), 0, -1);
  7749. $r = preg_replace(
  7750. array('/(?::?\b0+\b:?){2,}/', '/\b0+([^0])/e'),
  7751. array('::', '(int)"$1"?"$1":"0$1"'),
  7752. $r);
  7753. return $r;
  7754. }
  7755. return false;
  7756. }
  7757. }
  7758.  
  7759. /**
  7760. * Fetch an binary formatted range for searching IPv4 and IPv6 IP addresses.
  7761. *
  7762. * @param string $ipaddress The IP address to convert to a range
  7763. * @return string|array|bool If a full IP address is provided, the in_addr representation, otherwise an array of the upper & lower extremities of the IP. False on failure
  7764. */
  7765. function fetch_ip_range($ipaddress)
  7766. {
  7767. // Wildcard
  7768. if(strpos($ipaddress, '*') !== false)
  7769. {
  7770. if(strpos($ipaddress, ':') !== false)
  7771. {
  7772. // IPv6
  7773. $upper = str_replace('*', 'ffff', $ipaddress);
  7774. $lower = str_replace('*', '0', $ipaddress);
  7775. }
  7776. else
  7777. {
  7778. // IPv4
  7779. $ip_bits = count(explode('.', $ipaddress));
  7780. if($ip_bits < 4)
  7781. {
  7782. // Support for 127.0.*
  7783. $replacement = str_repeat('.*', 4-$ip_bits);
  7784. $ipaddress = substr_replace($ipaddress, $replacement, strrpos($ipaddress, '*')+1, 0);
  7785. }
  7786. $upper = str_replace('*', '255', $ipaddress);
  7787. $lower = str_replace('*', '0', $ipaddress);
  7788. }
  7789. $upper = my_inet_pton($upper);
  7790. $lower = my_inet_pton($lower);
  7791. if($upper === false || $lower === false)
  7792. {
  7793. return false;
  7794. }
  7795. return array($lower, $upper);
  7796. }
  7797. // CIDR notation
  7798. elseif(strpos($ipaddress, '/') !== false)
  7799. {
  7800. $ipaddress = explode('/', $ipaddress);
  7801. $ip_address = $ipaddress[0];
  7802. $ip_range = (int)$ipaddress[1];
  7803.  
  7804. if(empty($ip_address) || empty($ip_range))
  7805. {
  7806. // Invalid input
  7807. return false;
  7808. }
  7809. else
  7810. {
  7811. $ip_address = my_inet_pton($ip_address);
  7812.  
  7813. if(!$ip_address)
  7814. {
  7815. // Invalid IP address
  7816. return false;
  7817. }
  7818. }
  7819.  
  7820. /**
  7821. * Taken from: https://github.com/NewEraCracker/php_work/blob/master/ipRangeCalculate.php
  7822. * Author: NewEraCracker
  7823. * License: Public Domain
  7824. */
  7825.  
  7826. // Pack IP, Set some vars
  7827. $ip_pack = $ip_address;
  7828. $ip_pack_size = strlen($ip_pack);
  7829. $ip_bits_size = $ip_pack_size*8;
  7830.  
  7831. // IP bits (lots of 0's and 1's)
  7832. $ip_bits = '';
  7833. for($i = 0; $i < $ip_pack_size; $i = $i+1)
  7834. {
  7835. $bit = decbin(ord($ip_pack[$i]));
  7836. $bit = str_pad($bit, 8, '0', STR_PAD_LEFT);
  7837. $ip_bits .= $bit;
  7838. }
  7839.  
  7840. // Significative bits (from the ip range)
  7841. $ip_bits = substr($ip_bits, 0, $ip_range);
  7842.  
  7843. // Some calculations
  7844. $ip_lower_bits = str_pad($ip_bits, $ip_bits_size, '0', STR_PAD_RIGHT);
  7845. $ip_higher_bits = str_pad($ip_bits, $ip_bits_size, '1', STR_PAD_RIGHT);
  7846.  
  7847. // Lower IP
  7848. $ip_lower_pack = '';
  7849. for($i=0; $i < $ip_bits_size; $i=$i+8)
  7850. {
  7851. $chr = substr($ip_lower_bits, $i, 8);
  7852. $chr = chr(bindec($chr));
  7853. $ip_lower_pack .= $chr;
  7854. }
  7855.  
  7856. // Higher IP
  7857. $ip_higher_pack = '';
  7858. for($i=0; $i < $ip_bits_size; $i=$i+8)
  7859. {
  7860. $chr = substr($ip_higher_bits, $i, 8);
  7861. $chr = chr( bindec($chr) );
  7862. $ip_higher_pack .= $chr;
  7863. }
  7864.  
  7865. return array($ip_lower_pack, $ip_higher_pack);
  7866. }
  7867. // Just on IP address
  7868. else
  7869. {
  7870. return my_inet_pton($ipaddress);
  7871. }
  7872. }
  7873.  
  7874. /**
  7875. * Time how long it takes for a particular piece of code to run. Place calls above & below the block of code.
  7876. *
  7877. * @return float The time taken
  7878. */
  7879. function get_execution_time()
  7880. {
  7881. static $time_start;
  7882.  
  7883. $time = microtime(true);
  7884.  
  7885. // Just starting timer, init and return
  7886. if(!$time_start)
  7887. {
  7888. $time_start = $time;
  7889. return;
  7890. }
  7891. // Timer has run, return execution time
  7892. else
  7893. {
  7894. $total = $time-$time_start;
  7895. if($total < 0) $total = 0;
  7896. $time_start = 0;
  7897. return $total;
  7898. }
  7899. }
  7900.  
  7901. /**
  7902. * Processes a checksum list on MyBB files and returns a result set
  7903. *
  7904. * @param string $path The base path
  7905. * @param int $count The count of files
  7906. * @return array The bad files
  7907. */
  7908. function verify_files($path=MYBB_ROOT, $count=0)
  7909. {
  7910. global $mybb, $checksums, $bad_verify_files;
  7911.  
  7912. // We don't need to check these types of files
  7913. $ignore = array(".", "..", ".svn", "config.php", "settings.php", "Thumb.db", "config.default.php", "lock", "htaccess.txt", "htaccess-nginx.txt", "logo.gif", "logo.png");
  7914. $ignore_ext = array("attach");
  7915.  
  7916. if(substr($path, -1, 1) == "/")
  7917. {
  7918. $path = substr($path, 0, -1);
  7919. }
  7920.  
  7921. if(!is_array($bad_verify_files))
  7922. {
  7923. $bad_verify_files = array();
  7924. }
  7925.  
  7926. // Make sure that we're in a directory and it's not a symbolic link
  7927. if(@is_dir($path) && !@is_link($path))
  7928. {
  7929. if($dh = @opendir($path))
  7930. {
  7931. // Loop through all the files/directories in this directory
  7932. while(($file = @readdir($dh)) !== false)
  7933. {
  7934. if(in_array($file, $ignore) || in_array(get_extension($file), $ignore_ext))
  7935. {
  7936. continue;
  7937. }
  7938.  
  7939. // Recurse through the directory tree
  7940. if(is_dir($path."/".$file))
  7941. {
  7942. verify_files($path."/".$file, ($count+1));
  7943. continue;
  7944. }
  7945.  
  7946. // We only need the last part of the path (from the MyBB directory to the file. i.e. inc/functions.php)
  7947. $file_path = ".".str_replace(substr(MYBB_ROOT, 0, -1), "", $path)."/".$file;
  7948.  
  7949. // Does this file even exist in our official list? Perhaps it's a plugin
  7950. if(array_key_exists($file_path, $checksums))
  7951. {
  7952. $filename = $path."/".$file;
  7953. $handle = fopen($filename, "rb");
  7954. $hashingContext = hash_init('sha512');
  7955. while(!feof($handle))
  7956. {
  7957. hash_update($hashingContext, fread($handle, 8192));
  7958. }
  7959. fclose($handle);
  7960.  
  7961. $checksum = hash_final($hashingContext);
  7962.  
  7963. // Does it match any of our hashes (unix/windows new lines taken into consideration with the hashes)
  7964. if(!in_array($checksum, $checksums[$file_path]))
  7965. {
  7966. $bad_verify_files[] = array("status" => "changed", "path" => $file_path);
  7967. }
  7968. }
  7969. unset($checksums[$file_path]);
  7970. }
  7971. @closedir($dh);
  7972. }
  7973. }
  7974.  
  7975. if($count == 0)
  7976. {
  7977. if(!empty($checksums))
  7978. {
  7979. foreach($checksums as $file_path => $hashes)
  7980. {
  7981. if(in_array(basename($file_path), $ignore))
  7982. {
  7983. continue;
  7984. }
  7985. $bad_verify_files[] = array("status" => "missing", "path" => $file_path);
  7986. }
  7987. }
  7988. }
  7989.  
  7990. // uh oh
  7991. if($count == 0)
  7992. {
  7993. return $bad_verify_files;
  7994. }
  7995. }
  7996.  
  7997. /**
  7998. * Returns a signed value equal to an integer
  7999. *
  8000. * @param int $int The integer
  8001. * @return string The signed equivalent
  8002. */
  8003. function signed($int)
  8004. {
  8005. if($int < 0)
  8006. {
  8007. return "$int";
  8008. }
  8009. else
  8010. {
  8011. return "+$int";
  8012. }
  8013. }
  8014.  
  8015. /**
  8016. * Returns a securely generated seed
  8017. *
  8018. * @return string A secure binary seed
  8019. */
  8020. function secure_binary_seed_rng($bytes)
  8021. {
  8022. $output = null;
  8023.  
  8024. if(version_compare(PHP_VERSION, '7.0', '>='))
  8025. {
  8026. try
  8027. {
  8028. $output = random_bytes($bytes);
  8029. } catch (Exception $e) {
  8030. }
  8031. }
  8032.  
  8033. if(strlen($output) < $bytes)
  8034. {
  8035. if(@is_readable('/dev/urandom') && ($handle = @fopen('/dev/urandom', 'rb')))
  8036. {
  8037. $output = @fread($handle, $bytes);
  8038. @fclose($handle);
  8039. }
  8040. }
  8041. else
  8042. {
  8043. return $output;
  8044. }
  8045.  
  8046. if(strlen($output) < $bytes)
  8047. {
  8048. if(function_exists('mcrypt_create_iv'))
  8049. {
  8050. if (DIRECTORY_SEPARATOR == '/')
  8051. {
  8052. $source = MCRYPT_DEV_URANDOM;
  8053. }
  8054. else
  8055. {
  8056. $source = MCRYPT_RAND;
  8057. }
  8058.  
  8059. $output = @mcrypt_create_iv($bytes, $source);
  8060. }
  8061. }
  8062. else
  8063. {
  8064. return $output;
  8065. }
  8066.  
  8067. if(strlen($output) < $bytes)
  8068. {
  8069. if(function_exists('openssl_random_pseudo_bytes'))
  8070. {
  8071. // PHP <5.3.4 had a bug which makes that function unusable on Windows
  8072. if ((DIRECTORY_SEPARATOR == '/') || version_compare(PHP_VERSION, '5.3.4', '>='))
  8073. {
  8074. $output = openssl_random_pseudo_bytes($bytes, $crypto_strong);
  8075. if ($crypto_strong == false)
  8076. {
  8077. $output = null;
  8078. }
  8079. }
  8080. }
  8081. }
  8082. else
  8083. {
  8084. return $output;
  8085. }
  8086.  
  8087. if(strlen($output) < $bytes)
  8088. {
  8089. if(class_exists('COM'))
  8090. {
  8091. try
  8092. {
  8093. $CAPI_Util = new COM('CAPICOM.Utilities.1');
  8094. if(is_callable(array($CAPI_Util, 'GetRandom')))
  8095. {
  8096. $output = $CAPI_Util->GetRandom($bytes, 0);
  8097. }
  8098. } catch (Exception $e) {
  8099. }
  8100. }
  8101. }
  8102. else
  8103. {
  8104. return $output;
  8105. }
  8106.  
  8107. if(strlen($output) < $bytes)
  8108. {
  8109. // Close to what PHP basically uses internally to seed, but not quite.
  8110. $unique_state = microtime().@getmypid();
  8111.  
  8112. $rounds = ceil($bytes / 16);
  8113.  
  8114. for($i = 0; $i < $rounds; $i++)
  8115. {
  8116. $unique_state = md5(microtime().$unique_state);
  8117. $output .= md5($unique_state);
  8118. }
  8119.  
  8120. $output = substr($output, 0, ($bytes * 2));
  8121.  
  8122. $output = pack('H*', $output);
  8123.  
  8124. return $output;
  8125. }
  8126. else
  8127. {
  8128. return $output;
  8129. }
  8130. }
  8131.  
  8132. /**
  8133. * Returns a securely generated seed integer
  8134. *
  8135. * @return int An integer equivalent of a secure hexadecimal seed
  8136. */
  8137. function secure_seed_rng()
  8138. {
  8139. $bytes = PHP_INT_SIZE;
  8140.  
  8141. do
  8142. {
  8143.  
  8144. $output = secure_binary_seed_rng($bytes);
  8145.  
  8146. // convert binary data to a decimal number
  8147. if ($bytes == 4)
  8148. {
  8149. $elements = unpack('i', $output);
  8150. $output = abs($elements[1]);
  8151. }
  8152. else
  8153. {
  8154. $elements = unpack('N2', $output);
  8155. $output = abs($elements[1] << 32 | $elements[2]);
  8156. }
  8157.  
  8158. } while($output > PHP_INT_MAX);
  8159.  
  8160. return $output;
  8161. }
  8162.  
  8163. /**
  8164. * Generates a cryptographically secure random number.
  8165. *
  8166. * @param int $min Optional lowest value to be returned (default: 0)
  8167. * @param int $max Optional highest value to be returned (default: PHP_INT_MAX)
  8168. */
  8169. function my_rand($min=0, $max=PHP_INT_MAX)
  8170. {
  8171. // backward compatibility
  8172. if($min === null || $max === null || $max < $min)
  8173. {
  8174. $min = 0;
  8175. $max = PHP_INT_MAX;
  8176. }
  8177.  
  8178. if(version_compare(PHP_VERSION, '7.0', '>='))
  8179. {
  8180. try
  8181. {
  8182. $result = random_int($min, $max);
  8183. } catch (Exception $e) {
  8184. }
  8185.  
  8186. if(isset($result))
  8187. {
  8188. return $result;
  8189. }
  8190. }
  8191.  
  8192. $seed = secure_seed_rng();
  8193.  
  8194. $distance = $max - $min;
  8195. return $min + floor($distance * ($seed / PHP_INT_MAX) );
  8196. }
  8197.  
  8198. /**
  8199. * More robust version of PHP's trim() function. It includes a list of UTF-8 blank characters
  8200. * from http://kb.mozillazine.org/Network.IDN.blacklist_chars
  8201. *
  8202. * @param string $string The string to trim from
  8203. * @param string $charlist Optional. The stripped characters can also be specified using the charlist parameter
  8204. * @return string The trimmed string
  8205. */
  8206. function trim_blank_chrs($string, $charlist="")
  8207. {
  8208. $hex_chrs = array(
  8209. 0x09 => 1, // \x{0009}
  8210. 0x0A => 1, // \x{000A}
  8211. 0x0B => 1, // \x{000B}
  8212. 0x0D => 1, // \x{000D}
  8213. 0x20 => 1, // \x{0020}
  8214. 0xC2 => array(0x81 => 1, 0x8D => 1, 0x90 => 1, 0x9D => 1, 0xA0 => 1, 0xAD => 1), // \x{0081}, \x{008D}, \x{0090}, \x{009D}, \x{00A0}, \x{00AD}
  8215. 0xCC => array(0xB7 => 1, 0xB8 => 1), // \x{0337}, \x{0338}
  8216. 0xE1 => array(0x85 => array(0x9F => 1, 0xA0 => 1), 0x9A => array(0x80 => 1), 0xA0 => array(0x8E => 1)), // \x{115F}, \x{1160}, \x{1680}, \x{180E}
  8217. 0xE2 => array(0x80 => array(0x80 => 1, 0x81 => 1, 0x82 => 1, 0x83 => 1, 0x84 => 1, 0x85 => 1, 0x86 => 1, 0x87 => 1, 0x88 => 1, 0x89 => 1, 0x8A => 1, 0x8B => 1, 0x8C => 1, 0x8D => 1, 0x8E => 1, 0x8F => 1, // \x{2000} - \x{200F}
  8218. 0xA8 => 1, 0xA9 => 1, 0xAA => 1, 0xAB => 1, 0xAC => 1, 0xAD => 1, 0xAE => 1, 0xAF => 1), // \x{2028} - \x{202F}
  8219. 0x81 => array(0x9F => 1)), // \x{205F}
  8220. 0xE3 => array(0x80 => array(0x80 => 1), // \x{3000}
  8221. 0x85 => array(0xA4 => 1)), // \x{3164}
  8222. 0xEF => array(0xBB => array(0xBF => 1), // \x{FEFF}
  8223. 0xBE => array(0xA0 => 1), // \x{FFA0}
  8224. 0xBF => array(0xB9 => 1, 0xBA => 1, 0xBB => 1)), // \x{FFF9} - \x{FFFB}
  8225. );
  8226.  
  8227. $hex_chrs_rev = array(
  8228. 0x09 => 1, // \x{0009}
  8229. 0x0A => 1, // \x{000A}
  8230. 0x0B => 1, // \x{000B}
  8231. 0x0D => 1, // \x{000D}
  8232. 0x20 => 1, // \x{0020}
  8233. 0x81 => array(0xC2 => 1, 0x80 => array(0xE2 => 1)), // \x{0081}, \x{2001}
  8234. 0x8D => array(0xC2 => 1, 0x80 => array(0xE2 => 1)), // \x{008D}, \x{200D}
  8235. 0x90 => array(0xC2 => 1), // \x{0090}
  8236. 0x9D => array(0xC2 => 1), // \x{009D}
  8237. 0xA0 => array(0xC2 => 1, 0x85 => array(0xE1 => 1), 0x81 => array(0xE2 => 1), 0xBE => array(0xEF => 1)), // \x{00A0}, \x{1160}, \x{2060}, \x{FFA0}
  8238. 0xAD => array(0xC2 => 1, 0x80 => array(0xE2 => 1)), // \x{00AD}, \x{202D}
  8239. 0xB8 => array(0xCC => 1), // \x{0338}
  8240. 0xB7 => array(0xCC => 1), // \x{0337}
  8241. 0x9F => array(0x85 => array(0xE1 => 1), 0x81 => array(0xE2 => 1)), // \x{115F}, \x{205F}
  8242. 0x80 => array(0x9A => array(0xE1 => 1), 0x80 => array(0xE2 => 1, 0xE3 => 1)), // \x{1680}, \x{2000}, \x{3000}
  8243. 0x8E => array(0xA0 => array(0xE1 => 1), 0x80 => array(0xE2 => 1)), // \x{180E}, \x{200E}
  8244. 0x82 => array(0x80 => array(0xE2 => 1)), // \x{2002}
  8245. 0x83 => array(0x80 => array(0xE2 => 1)), // \x{2003}
  8246. 0x84 => array(0x80 => array(0xE2 => 1)), // \x{2004}
  8247. 0x85 => array(0x80 => array(0xE2 => 1)), // \x{2005}
  8248. 0x86 => array(0x80 => array(0xE2 => 1)), // \x{2006}
  8249. 0x87 => array(0x80 => array(0xE2 => 1)), // \x{2007}
  8250. 0x88 => array(0x80 => array(0xE2 => 1)), // \x{2008}
  8251. 0x89 => array(0x80 => array(0xE2 => 1)), // \x{2009}
  8252. 0x8A => array(0x80 => array(0xE2 => 1)), // \x{200A}
  8253. 0x8B => array(0x80 => array(0xE2 => 1)), // \x{200B}
  8254. 0x8C => array(0x80 => array(0xE2 => 1)), // \x{200C}
  8255. 0x8F => array(0x80 => array(0xE2 => 1)), // \x{200F}
  8256. 0xA8 => array(0x80 => array(0xE2 => 1)), // \x{2028}
  8257. 0xA9 => array(0x80 => array(0xE2 => 1)), // \x{2029}
  8258. 0xAA => array(0x80 => array(0xE2 => 1)), // \x{202A}
  8259. 0xAB => array(0x80 => array(0xE2 => 1)), // \x{202B}
  8260. 0xAC => array(0x80 => array(0xE2 => 1)), // \x{202C}
  8261. 0xAE => array(0x80 => array(0xE2 => 1)), // \x{202E}
  8262. 0xAF => array(0x80 => array(0xE2 => 1)), // \x{202F}
  8263. 0xA4 => array(0x85 => array(0xE3 => 1)), // \x{3164}
  8264. 0xBF => array(0xBB => array(0xEF => 1)), // \x{FEFF}
  8265. 0xB9 => array(0xBF => array(0xEF => 1)), // \x{FFF9}
  8266. 0xBA => array(0xBF => array(0xEF => 1)), // \x{FFFA}
  8267. 0xBB => array(0xBF => array(0xEF => 1)), // \x{FFFB}
  8268. );
  8269.  
  8270. // Start from the beginning and work our way in
  8271. do
  8272. {
  8273. // Check to see if we have matched a first character in our utf-8 array
  8274. $offset = match_sequence($string, $hex_chrs);
  8275. if(!$offset)
  8276. {
  8277. // If not, then we must have a "good" character and we don't need to do anymore processing
  8278. break;
  8279. }
  8280. $string = substr($string, $offset);
  8281. }
  8282. while(++$i);
  8283.  
  8284. // Start from the end and work our way in
  8285. $string = strrev($string);
  8286. do
  8287. {
  8288. // Check to see if we have matched a first character in our utf-8 array
  8289. $offset = match_sequence($string, $hex_chrs_rev);
  8290. if(!$offset)
  8291. {
  8292. // If not, then we must have a "good" character and we don't need to do anymore processing
  8293. break;
  8294. }
  8295. $string = substr($string, $offset);
  8296. }
  8297. while(++$i);
  8298. $string = strrev($string);
  8299.  
  8300. if($charlist)
  8301. {
  8302. $string = trim($string, $charlist);
  8303. }
  8304. else
  8305. {
  8306. $string = trim($string);
  8307. }
  8308.  
  8309. return $string;
  8310. }
  8311.  
  8312. /**
  8313. * Match a sequence
  8314. *
  8315. * @param string $string The string to match from
  8316. * @param array $array The array to match from
  8317. * @param int $i Number in the string
  8318. * @param int $n Number of matches
  8319. * @return int The number matched
  8320. */
  8321. function match_sequence($string, $array, $i=0, $n=0)
  8322. {
  8323. if($string === "")
  8324. {
  8325. return 0;
  8326. }
  8327.  
  8328. $ord = ord($string[$i]);
  8329. if(array_key_exists($ord, $array))
  8330. {
  8331. $level = $array[$ord];
  8332. ++$n;
  8333. if(is_array($level))
  8334. {
  8335. ++$i;
  8336. return match_sequence($string, $level, $i, $n);
  8337. }
  8338. return $n;
  8339. }
  8340.  
  8341. return 0;
  8342. }
  8343.  
  8344. /**
  8345. * Obtain the version of GD installed.
  8346. *
  8347. * @return float Version of GD
  8348. */
  8349. function gd_version()
  8350. {
  8351. static $gd_version;
  8352.  
  8353. if($gd_version)
  8354. {
  8355. return $gd_version;
  8356. }
  8357. if(!extension_loaded('gd'))
  8358. {
  8359. return;
  8360. }
  8361.  
  8362. if(function_exists("gd_info"))
  8363. {
  8364. $gd_info = gd_info();
  8365. preg_match('/\d/', $gd_info['GD Version'], $gd);
  8366. $gd_version = $gd[0];
  8367. }
  8368. else
  8369. {
  8370. ob_start();
  8371. phpinfo(8);
  8372. $info = ob_get_contents();
  8373. ob_end_clean();
  8374. $info = stristr($info, 'gd version');
  8375. preg_match('/\d/', $info, $gd);
  8376. $gd_version = $gd[0];
  8377. }
  8378.  
  8379. return $gd_version;
  8380. }
  8381.  
  8382. /*
  8383. * Validates an UTF-8 string.
  8384. *
  8385. * @param string $input The string to be checked
  8386. * @param boolean $allow_mb4 Allow 4 byte UTF-8 characters?
  8387. * @param boolean $return Return the cleaned string?
  8388. * @return string|boolean Cleaned string or boolean
  8389. */
  8390. function validate_utf8_string($input, $allow_mb4=true, $return=true)
  8391. {
  8392. // Valid UTF-8 sequence?
  8393. if(!preg_match('##u', $input))
  8394. {
  8395. $string = '';
  8396. $len = strlen($input);
  8397. for($i = 0; $i < $len; $i++)
  8398. {
  8399. $c = ord($input[$i]);
  8400. if($c > 128)
  8401. {
  8402. if($c > 247 || $c <= 191)
  8403. {
  8404. if($return)
  8405. {
  8406. $string .= '?';
  8407. continue;
  8408. }
  8409. else
  8410. {
  8411. return false;
  8412. }
  8413. }
  8414. elseif($c > 239)
  8415. {
  8416. $bytes = 4;
  8417. }
  8418. elseif($c > 223)
  8419. {
  8420. $bytes = 3;
  8421. }
  8422. elseif($c > 191)
  8423. {
  8424. $bytes = 2;
  8425. }
  8426. if(($i + $bytes) > $len)
  8427. {
  8428. if($return)
  8429. {
  8430. $string .= '?';
  8431. break;
  8432. }
  8433. else
  8434. {
  8435. return false;
  8436. }
  8437. }
  8438. $valid = true;
  8439. $multibytes = $input[$i];
  8440. while($bytes > 1)
  8441. {
  8442. $i++;
  8443. $b = ord($input[$i]);
  8444. if($b < 128 || $b > 191)
  8445. {
  8446. if($return)
  8447. {
  8448. $valid = false;
  8449. $string .= '?';
  8450. break;
  8451. }
  8452. else
  8453. {
  8454. return false;
  8455. }
  8456. }
  8457. else
  8458. {
  8459. $multibytes .= $input[$i];
  8460. }
  8461. $bytes--;
  8462. }
  8463. if($valid)
  8464. {
  8465. $string .= $multibytes;
  8466. }
  8467. }
  8468. else
  8469. {
  8470. $string .= $input[$i];
  8471. }
  8472. }
  8473. $input = $string;
  8474. }
  8475. if($return)
  8476. {
  8477. if($allow_mb4)
  8478. {
  8479. return $input;
  8480. }
  8481. else
  8482. {
  8483. return preg_replace("#[^\\x00-\\x7F][\\x80-\\xBF]{3,}#", '?', $input);
  8484. }
  8485. }
  8486. else
  8487. {
  8488. if($allow_mb4)
  8489. {
  8490. return true;
  8491. }
  8492. else
  8493. {
  8494. return !preg_match("#[^\\x00-\\x7F][\\x80-\\xBF]{3,}#", $input);
  8495. }
  8496. }
  8497. }
  8498.  
  8499. /**
  8500. * Send a Private Message to a user.
  8501. *
  8502. * @param array $pm Array containing: 'subject', 'message', 'touid' and 'receivepms' (the latter should reflect the value found in the users table: receivepms and receivefrombuddy)
  8503. * @param int $fromid Sender UID (0 if you want to use $mybb->user['uid'] or -1 to use MyBB Engine)
  8504. * @param bool $admin_override Whether or not do override user defined options for receiving PMs
  8505. * @return bool True if PM sent
  8506. */
  8507. function send_pm($pm, $fromid = 0, $admin_override=false)
  8508. {
  8509. global $lang, $mybb, $db, $session;
  8510.  
  8511. if($mybb->settings['enablepms'] == 0)
  8512. {
  8513. return false;
  8514. }
  8515.  
  8516. if(!is_array($pm))
  8517. {
  8518. return false;
  8519. }
  8520.  
  8521. if(isset($pm['language']))
  8522. {
  8523. if($pm['language'] != $mybb->user['language'] && $lang->language_exists($pm['language']))
  8524. {
  8525. // Load user language
  8526. $lang->set_language($pm['language']);
  8527. $lang->load($pm['language_file']);
  8528.  
  8529. $revert = true;
  8530. }
  8531.  
  8532. foreach(array('subject', 'message') as $key)
  8533. {
  8534. if(is_array($pm[$key]))
  8535. {
  8536. $lang_string = $lang->{$pm[$key][0]};
  8537. $num_args = count($pm[$key]);
  8538.  
  8539. for($i = 1; $i < $num_args; $i++)
  8540. {
  8541. $lang_string = str_replace('{'.$i.'}', $pm[$key][$i], $lang_string);
  8542. }
  8543. }
  8544. else
  8545. {
  8546. $lang_string = $lang->{$pm[$key]};
  8547. }
  8548.  
  8549. $pm[$key] = $lang_string;
  8550. }
  8551.  
  8552. if(isset($revert))
  8553. {
  8554. // Revert language
  8555. $lang->set_language($mybb->user['language']);
  8556. $lang->load($pm['language_file']);
  8557. }
  8558. }
  8559.  
  8560. if(!$pm['subject'] ||!$pm['message'] || !$pm['touid'] || (!$pm['receivepms'] && !$admin_override))
  8561. {
  8562. return false;
  8563. }
  8564.  
  8565. require_once MYBB_ROOT."inc/datahandlers/pm.php";
  8566.  
  8567. $pmhandler = new PMDataHandler();
  8568.  
  8569. $subject = $pm['subject'];
  8570. $message = $pm['message'];
  8571. $toid = $pm['touid'];
  8572.  
  8573. // Our recipients
  8574. if(is_array($toid))
  8575. {
  8576. $recipients_to = $toid;
  8577. }
  8578. else
  8579. {
  8580. $recipients_to = array($toid);
  8581. }
  8582.  
  8583. $recipients_bcc = array();
  8584.  
  8585. // Determine user ID
  8586. if((int)$fromid == 0)
  8587. {
  8588. $fromid = (int)$mybb->user['uid'];
  8589. }
  8590. elseif((int)$fromid < 0)
  8591. {
  8592. $fromid = 0;
  8593. }
  8594.  
  8595. // Build our final PM array
  8596. $pm = array(
  8597. "subject" => $subject,
  8598. "message" => $message,
  8599. "icon" => -1,
  8600. "fromid" => $fromid,
  8601. "toid" => $recipients_to,
  8602. "bccid" => $recipients_bcc,
  8603. "do" => '',
  8604. "pmid" => ''
  8605. );
  8606.  
  8607. if(isset($session))
  8608. {
  8609. $pm['ipaddress'] = $session->packedip;
  8610. }
  8611.  
  8612. $pm['options'] = array(
  8613. "disablesmilies" => 0,
  8614. "savecopy" => 0,
  8615. "readreceipt" => 0
  8616. );
  8617.  
  8618. $pm['saveasdraft'] = 0;
  8619.  
  8620. // Admin override
  8621. $pmhandler->admin_override = (int)$admin_override;
  8622.  
  8623. $pmhandler->set_data($pm);
  8624.  
  8625. if($pmhandler->validate_pm())
  8626. {
  8627. $pmhandler->insert_pm();
  8628. return true;
  8629. }
  8630.  
  8631. return false;
  8632. }
  8633.  
  8634. /**
  8635. * Log a user spam block from StopForumSpam (or other spam service providers...)
  8636. *
  8637. * @param string $username The username that the user was using.
  8638. * @param string $email The email address the user was using.
  8639. * @param string $ip_address The IP addres of the user.
  8640. * @param array $data An array of extra data to go with the block (eg: confidence rating).
  8641. * @return bool Whether the action was logged successfully.
  8642. */
  8643. function log_spam_block($username = '', $email = '', $ip_address = '', $data = array())
  8644. {
  8645. global $db, $session;
  8646.  
  8647. if(!is_array($data))
  8648. {
  8649. $data = array($data);
  8650. }
  8651.  
  8652. if(!$ip_address)
  8653. {
  8654. $ip_address = get_ip();
  8655. }
  8656.  
  8657. $ip_address = my_inet_pton($ip_address);
  8658.  
  8659. $insert_array = array(
  8660. 'username' => $db->escape_string($username),
  8661. 'email' => $db->escape_string($email),
  8662. 'ipaddress' => $db->escape_binary($ip_address),
  8663. 'dateline' => (int)TIME_NOW,
  8664. 'data' => $db->escape_string(@my_serialize($data)),
  8665. );
  8666.  
  8667. return (bool)$db->insert_query('spamlog', $insert_array);
  8668. }
  8669.  
  8670. /**
  8671. * Copy a file to the CDN.
  8672. *
  8673. * @param string $file_path The path to the file to upload to the CDN.
  8674. *
  8675. * @param string $uploaded_path The path the file was uploaded to, reference parameter for when this may be needed.
  8676. *
  8677. * @return bool Whether the file was copied successfully.
  8678. */
  8679. function copy_file_to_cdn($file_path = '', &$uploaded_path = null)
  8680. {
  8681. global $mybb, $plugins;
  8682.  
  8683. $success = false;
  8684.  
  8685. $file_path = (string)$file_path;
  8686.  
  8687. $real_file_path = realpath($file_path);
  8688.  
  8689. $file_dir_path = dirname($real_file_path);
  8690. $file_dir_path = str_replace(MYBB_ROOT, '', $file_dir_path);
  8691. $file_dir_path = ltrim($file_dir_path, './\\');
  8692.  
  8693. $file_name = basename($real_file_path);
  8694.  
  8695. if(file_exists($file_path))
  8696. {
  8697. if($mybb->settings['usecdn'] && !empty($mybb->settings['cdnpath']))
  8698. {
  8699. $cdn_path = rtrim($mybb->settings['cdnpath'], '/\\');
  8700.  
  8701. if(substr($file_dir_path, 0, my_strlen(MYBB_ROOT)) == MYBB_ROOT)
  8702. {
  8703. $file_dir_path = str_replace(MYBB_ROOT, '', $file_dir_path);
  8704. }
  8705.  
  8706. $cdn_upload_path = $cdn_path . DIRECTORY_SEPARATOR . $file_dir_path;
  8707.  
  8708. if(!($dir_exists = is_dir($cdn_upload_path)))
  8709. {
  8710. $dir_exists = @mkdir($cdn_upload_path, 0777, true);
  8711. }
  8712.  
  8713. if($dir_exists)
  8714. {
  8715. if(($cdn_upload_path = realpath($cdn_upload_path)) !== false)
  8716. {
  8717. $success = @copy($file_path, $cdn_upload_path.DIRECTORY_SEPARATOR.$file_name);
  8718.  
  8719. if($success)
  8720. {
  8721. $uploaded_path = $cdn_upload_path;
  8722. }
  8723. }
  8724. }
  8725. }
  8726.  
  8727. if(is_object($plugins))
  8728. {
  8729. $hook_args = array(
  8730. 'file_path' => &$file_path,
  8731. 'real_file_path' => &$real_file_path,
  8732. 'file_name' => &$file_name,
  8733. 'uploaded_path' => &$uploaded_path,
  8734. 'success' => &$success,
  8735. );
  8736.  
  8737. $plugins->run_hooks('copy_file_to_cdn_end', $hook_args);
  8738. }
  8739. }
  8740.  
  8741. return $success;
  8742. }
  8743.  
  8744. /**
  8745. * Validate an url
  8746. *
  8747. * @param string $url The url to validate.
  8748. * @param bool $relative_path Whether or not the url could be a relative path.
  8749. * @param bool $allow_local Whether or not the url could be pointing to local networks.
  8750. *
  8751. * @return bool Whether this is a valid url.
  8752. */
  8753. function my_validate_url($url, $relative_path=false, $allow_local=false)
  8754. {
  8755. if($allow_local)
  8756. {
  8757. $regex = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:localhost|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]-*)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]-*)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,}))\.?))(?::\d{2,5})?(?:[/?#]\S*)?$_iuS';
  8758. }
  8759. else
  8760. {
  8761. $regex = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]-*)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]-*)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$_iuS';
  8762. }
  8763.  
  8764. if($relative_path && my_substr($url, 0, 1) == '/' || preg_match($regex, $url))
  8765. {
  8766. return true;
  8767. }
  8768. return false;
  8769. }
  8770.  
  8771. /**
  8772. * Strip html tags from string, also removes <script> and <style> contents.
  8773. *
  8774. * @deprecated
  8775. * @param string $string String to stripe
  8776. * @param string $allowable_tags Allowed html tags
  8777. *
  8778. * @return string Striped string
  8779. */
  8780. function my_strip_tags($string, $allowable_tags = '')
  8781. {
  8782. $pattern = array(
  8783. '@(&lt;)style[^(&gt;)]*?(&gt;).*?(&lt;)/style(&gt;)@siu',
  8784. '@(&lt;)script[^(&gt;)]*?.*?(&lt;)/script(&gt;)@siu',
  8785. '@<style[^>]*?>.*?</style>@siu',
  8786. '@<script[^>]*?.*?</script>@siu',
  8787. );
  8788. $string = preg_replace($pattern, '', $string);
  8789. return strip_tags($string, $allowable_tags);
  8790. }
  8791.  
  8792. /**
  8793. * Escapes a RFC 4180-compliant CSV string.
  8794. * Based on https://github.com/Automattic/camptix/blob/f80725094440bf09861383b8f11e96c177c45789/camptix.php#L2867
  8795. *
  8796. * @param string $string The string to be escaped
  8797. * @param boolean $escape_active_content Whether or not to escape active content trigger characters
  8798. * @return string The escaped string
  8799. */
  8800. function my_escape_csv($string, $escape_active_content=true)
  8801. {
  8802. if($escape_active_content)
  8803. {
  8804. $active_content_triggers = array('=', '+', '-', '@');
  8805. $delimiters = array(',', ';', ':', '|', '^', "\n", "\t", " ");
  8806.  
  8807. $first_character = mb_substr($string, 0, 1);
  8808.  
  8809. if(
  8810. in_array($first_character, $active_content_triggers, true) ||
  8811. in_array($first_character, $delimiters, true)
  8812. )
  8813. {
  8814. $string = "'".$string;
  8815. }
  8816.  
  8817. foreach($delimiters as $delimiter)
  8818. {
  8819. foreach($active_content_triggers as $trigger)
  8820. {
  8821. $string = str_replace($delimiter.$trigger, $delimiter."'".$trigger, $string);
  8822. }
  8823. }
  8824. }
  8825.  
  8826. $string = str_replace('"', '""', $string);
  8827.  
  8828. return $string;
  8829. }
  8830. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement