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

/SSI.php

https://github.com/Arantor/Elkarte
PHP | 2224 lines | 1581 code | 279 blank | 364 comment | 318 complexity | c895f673599ada9447625bfc98d70822 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. */
  15. // Don't do anything if ELKARTE is already loaded.
  16. if (defined('ELKARTE'))
  17. return true;
  18. define('ELKARTE', 'SSI');
  19. // We're going to want a few globals... these are all set later.
  20. global $time_start, $maintenance, $msubject, $mmessage, $mbname, $language;
  21. global $boardurl, $webmaster_email, $cookiename;
  22. global $db_server, $db_name, $db_user, $db_prefix, $db_persist, $db_error_send, $db_last_error;
  23. global $db_connection, $modSettings, $context, $sc, $user_info, $topic, $board, $txt;
  24. global $smcFunc, $ssi_db_user, $scripturl, $ssi_db_passwd, $db_passwd;
  25. // Remember the current configuration so it can be set back.
  26. $ssi_magic_quotes_runtime = function_exists('get_magic_quotes_gpc') && get_magic_quotes_runtime();
  27. if (function_exists('set_magic_quotes_runtime'))
  28. @set_magic_quotes_runtime(0);
  29. $time_start = microtime(true);
  30. // Just being safe...
  31. foreach (array('db_character_set', 'cachedir') as $variable)
  32. if (isset($GLOBALS[$variable]))
  33. unset($GLOBALS[$variable]);
  34. // Get the forum's settings for database and file paths.
  35. require_once(dirname(__FILE__) . '/Settings.php');
  36. // Fix for using the current directory as a path.
  37. if (substr($sourcedir, 0, 1) == '.' && substr($sourcedir, 1, 1) != '.')
  38. $sourcedir = dirname(__FILE__) . substr($sourcedir, 1);
  39. // Make absolutely sure the new directories are defined.
  40. if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache'))
  41. $cachedir = $boarddir . '/cache';
  42. // Time to forget about variables and go with constants!
  43. DEFINE('BOARDDIR', $boarddir);
  44. DEFINE('CACHEDIR', $cachedir);
  45. DEFINE('EXTDIR', $extdir);
  46. DEFINE('LANGUAGEDIR', $languagedir);
  47. DEFINE('SOURCEDIR', $sourcedir);
  48. DEFINE('ADMINDIR', $sourcedir . '/admin');
  49. DEFINE('CONTROLLERDIR', $sourcedir . '/controllers');
  50. DEFINE('SUBSDIR', $sourcedir . '/subs');
  51. unset($boarddir, $cachedir, $sourcedir);
  52. $ssi_error_reporting = error_reporting(defined('E_STRICT') ? E_ALL | E_STRICT : E_ALL);
  53. /* Set this to one of three values depending on what you want to happen in the case of a fatal error.
  54. false: Default, will just load the error sub template and die - not putting any theme layers around it.
  55. true: Will load the error sub template AND put the template layers around it (Not useful if on total custom pages).
  56. string: Name of a callback function to call in the event of an error to allow you to define your own methods. Will die after function returns.
  57. */
  58. $ssi_on_error_method = false;
  59. // Don't do john didley if the forum's been shut down competely.
  60. if ($maintenance == 2 && (!isset($ssi_maintenance_off) || $ssi_maintenance_off !== true))
  61. die($mmessage);
  62. // Load the important includes.
  63. require_once(SOURCEDIR . '/QueryString.php');
  64. require_once(SOURCEDIR . '/Session.php');
  65. require_once(SOURCEDIR . '/Subs.php');
  66. require_once(SOURCEDIR . '/Errors.php');
  67. require_once(SOURCEDIR . '/Logging.php');
  68. require_once(SOURCEDIR . '/Load.php');
  69. require_once(SUBSDIR . '/Cache.subs.php');
  70. require_once(SOURCEDIR . '/Security.php');
  71. require_once(SOURCEDIR . '/BrowserDetect.class.php');
  72. // Create a variable to store some specific functions in.
  73. $smcFunc = array();
  74. // Initate the database connection and define some database functions to use.
  75. loadDatabase();
  76. // Load installed 'Mods' settings.
  77. reloadSettings();
  78. // Clean the request variables.
  79. cleanRequest();
  80. // Seed the random generator?
  81. if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69)
  82. elk_seed_generator();
  83. // Check on any hacking attempts.
  84. if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']))
  85. die('Hacking attempt...');
  86. elseif (isset($_REQUEST['ssi_theme']) && (int) $_REQUEST['ssi_theme'] == (int) $ssi_theme)
  87. die('Hacking attempt...');
  88. elseif (isset($_COOKIE['ssi_theme']) && (int) $_COOKIE['ssi_theme'] == (int) $ssi_theme)
  89. die('Hacking attempt...');
  90. elseif (isset($_REQUEST['ssi_layers'], $ssi_layers) && (@get_magic_quotes_gpc() ? stripslashes($_REQUEST['ssi_layers']) : $_REQUEST['ssi_layers']) == $ssi_layers)
  91. die('Hacking attempt...');
  92. if (isset($_REQUEST['context']))
  93. die('Hacking attempt...');
  94. // Gzip output? (because it must be boolean and true, this can't be hacked.)
  95. if (isset($ssi_gzip) && $ssi_gzip === true && ini_get('zlib.output_compression') != '1' && ini_get('output_handler') != 'ob_gzhandler' && version_compare(PHP_VERSION, '4.2.0', '>='))
  96. ob_start('ob_gzhandler');
  97. else
  98. $modSettings['enableCompressedOutput'] = '0';
  99. // Primarily, this is to fix the URLs...
  100. ob_start('ob_sessrewrite');
  101. // Start the session... known to scramble SSI includes in cases...
  102. if (!headers_sent())
  103. loadSession();
  104. else
  105. {
  106. if (isset($_COOKIE[session_name()]) || isset($_REQUEST[session_name()]))
  107. {
  108. // Make a stab at it, but ignore the E_WARNINGs generated because we can't send headers.
  109. $temp = error_reporting(error_reporting() & !E_WARNING);
  110. loadSession();
  111. error_reporting($temp);
  112. }
  113. if (!isset($_SESSION['session_value']))
  114. {
  115. $_SESSION['session_var'] = substr(md5(mt_rand() . session_id() . mt_rand()), 0, rand(7, 12));
  116. $_SESSION['session_value'] = md5(session_id() . mt_rand());
  117. }
  118. $sc = $_SESSION['session_value'];
  119. }
  120. // Get rid of $board and $topic... do stuff loadBoard would do.
  121. unset($board, $topic);
  122. $user_info['is_mod'] = false;
  123. $context['user']['is_mod'] = &$user_info['is_mod'];
  124. $context['linktree'] = array();
  125. // Load the user and their cookie, as well as their settings.
  126. loadUserSettings();
  127. // Load the current user's permissions....
  128. loadPermissions();
  129. // Load BadBehavior functions
  130. loadBadBehavior();
  131. // Load the current or SSI theme. (just use $ssi_theme = id_theme;)
  132. loadTheme(isset($ssi_theme) ? (int) $ssi_theme : 0);
  133. // @todo: probably not the best place, but somewhere it should be set...
  134. if (!headers_sent())
  135. header('Content-Type: text/html; charset=UTF-8');
  136. // Take care of any banning that needs to be done.
  137. if (isset($_REQUEST['ssi_ban']) || (isset($ssi_ban) && $ssi_ban === true))
  138. is_not_banned();
  139. // Do we allow guests in here?
  140. if (empty($ssi_guest_access) && empty($modSettings['allow_guestAccess']) && $user_info['is_guest'] && basename($_SERVER['PHP_SELF']) != 'SSI.php')
  141. {
  142. require_once(SUBSDIR . '/Auth.subs.php');
  143. KickGuest();
  144. obExit(null, true);
  145. }
  146. // Load the stuff like the menu bar, etc.
  147. if (isset($ssi_layers))
  148. {
  149. $context['template_layers'] = $ssi_layers;
  150. template_header();
  151. }
  152. else
  153. setupThemeContext();
  154. // Make sure they didn't muss around with the settings... but only if it's not cli.
  155. if (isset($_SERVER['REMOTE_ADDR']) && !isset($_SERVER['is_cli']) && session_id() == '')
  156. trigger_error($txt['ssi_session_broken'], E_USER_NOTICE);
  157. // Without visiting the forum this session variable might not be set on submit.
  158. if (!isset($_SESSION['USER_AGENT']) && (!isset($_GET['ssi_function']) || $_GET['ssi_function'] !== 'pollVote'))
  159. $_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
  160. // Have the ability to easily add functions to SSI.
  161. call_integration_hook('integrate_SSI');
  162. // Call a function passed by GET.
  163. if (isset($_GET['ssi_function']) && function_exists('ssi_' . $_GET['ssi_function']) && (!empty($modSettings['allow_guestAccess']) || !$user_info['is_guest']))
  164. {
  165. call_user_func('ssi_' . $_GET['ssi_function']);
  166. exit;
  167. }
  168. if (isset($_GET['ssi_function']))
  169. exit;
  170. // You shouldn't just access SSI.php directly by URL!!
  171. elseif (basename($_SERVER['PHP_SELF']) == 'SSI.php')
  172. die(sprintf($txt['ssi_not_direct'], $user_info['is_admin'] ? '\'' . addslashes(__FILE__) . '\'' : '\'SSI.php\''));
  173. error_reporting($ssi_error_reporting);
  174. if (function_exists('set_magic_quotes_runtime'))
  175. @set_magic_quotes_runtime($ssi_magic_quotes_runtime);
  176. return true;
  177. /**
  178. * This shuts down the SSI and shows the footer.
  179. */
  180. function ssi_shutdown()
  181. {
  182. if (!isset($_GET['ssi_function']) || $_GET['ssi_function'] != 'shutdown')
  183. template_footer();
  184. }
  185. /**
  186. * Display a welcome message, like:
  187. * "Hey, User, you have 0 messages, 0 are new."
  188. *
  189. * @param string $output_method
  190. */
  191. function ssi_welcome($output_method = 'echo')
  192. {
  193. global $context, $txt, $scripturl;
  194. if ($output_method == 'echo')
  195. {
  196. if ($context['user']['is_guest'])
  197. echo sprintf($txt[$context['can_register'] ? 'welcome_guest_register' : 'welcome_guest'], $txt['guest_title'], $scripturl . '?action=login');
  198. else
  199. echo $txt['hello_member'], ' <strong>', $context['user']['name'], '</strong>', allowedTo('pm_read') ? ', ' . (empty($context['user']['messages']) ? $txt['msg_alert_no_messages'] : (($context['user']['messages'] == 1 ? sprintf($txt['msg_alert_one_message'], $scripturl . '?action=pm') : sprintf($txt['msg_alert_many_message'], $scripturl . '?action=pm', $context['user']['messages'])) . ', ' . ($context['user']['unread_messages'] == 1 ? $txt['msg_alert_one_new'] : sprintf($txt['msg_alert_many_new'], $context['user']['unread_messages'])))) : '';
  200. }
  201. // Don't echo... then do what?!
  202. else
  203. return $context['user'];
  204. }
  205. /**
  206. * Display a menu bar, like is displayed at the top of the forum.
  207. *
  208. * @param string $output_method
  209. */
  210. function ssi_menubar($output_method = 'echo')
  211. {
  212. global $context;
  213. if ($output_method == 'echo')
  214. template_menu();
  215. // What else could this do?
  216. else
  217. return $context['menu_buttons'];
  218. }
  219. /**
  220. * Show a logout link.
  221. *
  222. * @param string $redirect_to
  223. * @param string $output_method = 'echo'
  224. */
  225. function ssi_logout($redirect_to = '', $output_method = 'echo')
  226. {
  227. global $context, $txt, $scripturl;
  228. if ($redirect_to != '')
  229. $_SESSION['logout_url'] = $redirect_to;
  230. // Guests can't log out.
  231. if ($context['user']['is_guest'])
  232. return false;
  233. $link = '<a href="' . $scripturl . '?action=logout;' . $context['session_var'] . '=' . $context['session_id'] . '">' . $txt['logout'] . '</a>';
  234. if ($output_method == 'echo')
  235. echo $link;
  236. else
  237. return $link;
  238. }
  239. /**
  240. * Recent post list:
  241. * [board] Subject by Poster Date
  242. *
  243. * @param int $num_recent
  244. * @param array $exclude_boards
  245. * @param array $include_boards
  246. * @param string $output_method
  247. * @param bool $limit_body
  248. */
  249. function ssi_recentPosts($num_recent = 8, $exclude_boards = null, $include_boards = null, $output_method = 'echo', $limit_body = true)
  250. {
  251. global $context, $settings, $scripturl, $txt, $db_prefix, $user_info;
  252. global $modSettings, $smcFunc;
  253. // Excluding certain boards...
  254. if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0)
  255. $exclude_boards = array($modSettings['recycle_board']);
  256. else
  257. $exclude_boards = empty($exclude_boards) ? array() : (is_array($exclude_boards) ? $exclude_boards : array($exclude_boards));
  258. // What about including certain boards - note we do some protection here as pre-2.0 didn't have this parameter.
  259. if (is_array($include_boards) || (int) $include_boards === $include_boards)
  260. {
  261. $include_boards = is_array($include_boards) ? $include_boards : array($include_boards);
  262. }
  263. elseif ($include_boards != null)
  264. {
  265. $include_boards = array();
  266. }
  267. // Let's restrict the query boys (and girls)
  268. $query_where = '
  269. m.id_msg >= {int:min_message_id}
  270. ' . (empty($exclude_boards) ? '' : '
  271. AND b.id_board NOT IN ({array_int:exclude_boards})') . '
  272. ' . ($include_boards === null ? '' : '
  273. AND b.id_board IN ({array_int:include_boards})') . '
  274. AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
  275. AND m.approved = {int:is_approved}' : '');
  276. $query_where_params = array(
  277. 'is_approved' => 1,
  278. 'include_boards' => $include_boards === null ? '' : $include_boards,
  279. 'exclude_boards' => empty($exclude_boards) ? '' : $exclude_boards,
  280. 'min_message_id' => $modSettings['maxMsgID'] - 25 * min($num_recent, 5),
  281. );
  282. // Past to this simpleton of a function...
  283. return ssi_queryPosts($query_where, $query_where_params, $num_recent, 'm.id_msg DESC', $output_method, $limit_body);
  284. }
  285. /**
  286. * Fetch a post with a particular ID.
  287. * By default will only show if you have permission
  288. * to the see the board in question - this can be overriden.
  289. *
  290. * @param array $post_ids
  291. * @param bool $override_permissions
  292. * @param string $output_method = 'echo'
  293. */
  294. function ssi_fetchPosts($post_ids = array(), $override_permissions = false, $output_method = 'echo')
  295. {
  296. global $user_info, $modSettings;
  297. if (empty($post_ids))
  298. return;
  299. // Allow the user to request more than one - why not?
  300. $post_ids = is_array($post_ids) ? $post_ids : array($post_ids);
  301. // Restrict the posts required...
  302. $query_where = '
  303. m.id_msg IN ({array_int:message_list})' . ($override_permissions ? '' : '
  304. AND {query_wanna_see_board}') . ($modSettings['postmod_active'] ? '
  305. AND m.approved = {int:is_approved}' : '');
  306. $query_where_params = array(
  307. 'message_list' => $post_ids,
  308. 'is_approved' => 1,
  309. );
  310. // Then make the query and dump the data.
  311. return ssi_queryPosts($query_where, $query_where_params, '', 'm.id_msg DESC', $output_method);
  312. }
  313. /**
  314. * This removes code duplication in other queries
  315. * - don't call it direct unless you really know what you're up to.
  316. *
  317. * @param string $query_where
  318. * @param array $query_where_params
  319. * @param int $query_limit
  320. * @param string $query_order
  321. * @param string $output_method = 'echo'
  322. * @param bool $limit_body
  323. * @param bool $override_permissions
  324. */
  325. function ssi_queryPosts($query_where = '', $query_where_params = array(), $query_limit = 10, $query_order = 'm.id_msg DESC', $output_method = 'echo', $limit_body = false, $override_permissions = false)
  326. {
  327. global $context, $settings, $scripturl, $txt, $db_prefix, $user_info;
  328. global $modSettings, $smcFunc;
  329. // Find all the posts. Newer ones will have higher IDs.
  330. $request = $smcFunc['db_query']('substring', '
  331. SELECT
  332. m.poster_time, m.subject, m.id_topic, m.id_member, m.id_msg, m.id_board, b.name AS board_name,
  333. IFNULL(mem.real_name, m.poster_name) AS poster_name, ' . ($user_info['is_guest'] ? '1 AS is_read, 0 AS new_from' : '
  334. IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) >= m.id_msg_modified AS is_read,
  335. IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from') . ', ' . ($limit_body ? 'SUBSTRING(m.body, 1, 384) AS body' : 'm.body') . ', m.smileys_enabled
  336. FROM {db_prefix}messages AS m
  337. INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
  338. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (!$user_info['is_guest'] ? '
  339. LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = m.id_topic AND lt.id_member = {int:current_member})
  340. LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = m.id_board AND lmr.id_member = {int:current_member})' : '') . '
  341. WHERE 1=1 ' . ($override_permissions ? '' : '
  342. AND {query_wanna_see_board}') . ($modSettings['postmod_active'] ? '
  343. AND m.approved = {int:is_approved}' : '') . '
  344. ' . (empty($query_where) ? '' : 'AND ' . $query_where) . '
  345. ORDER BY ' . $query_order . '
  346. ' . ($query_limit == '' ? '' : 'LIMIT ' . $query_limit),
  347. array_merge($query_where_params, array(
  348. 'current_member' => $user_info['id'],
  349. 'is_approved' => 1,
  350. ))
  351. );
  352. $posts = array();
  353. while ($row = $smcFunc['db_fetch_assoc']($request))
  354. {
  355. $row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
  356. // Censor it!
  357. censorText($row['subject']);
  358. censorText($row['body']);
  359. $preview = strip_tags(strtr($row['body'], array('<br />' => '&#10;')));
  360. // Build the array.
  361. $posts[] = array(
  362. 'id' => $row['id_msg'],
  363. 'board' => array(
  364. 'id' => $row['id_board'],
  365. 'name' => $row['board_name'],
  366. 'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
  367. 'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['board_name'] . '</a>'
  368. ),
  369. 'topic' => $row['id_topic'],
  370. 'poster' => array(
  371. 'id' => $row['id_member'],
  372. 'name' => $row['poster_name'],
  373. 'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
  374. 'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
  375. ),
  376. 'subject' => $row['subject'],
  377. 'short_subject' => shorten_subject($row['subject'], 25),
  378. 'preview' => $smcFunc['strlen']($preview) > 128 ? $smcFunc['substr']($preview, 0, 128) . '...' : $preview,
  379. 'body' => $row['body'],
  380. 'time' => timeformat($row['poster_time']),
  381. 'timestamp' => forum_time(true, $row['poster_time']),
  382. 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
  383. 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '" rel="nofollow">' . $row['subject'] . '</a>',
  384. 'new' => !empty($row['is_read']),
  385. 'is_new' => empty($row['is_read']),
  386. 'new_from' => $row['new_from'],
  387. );
  388. }
  389. $smcFunc['db_free_result']($request);
  390. // Just return it.
  391. if ($output_method != 'echo' || empty($posts))
  392. return $posts;
  393. echo '
  394. <table border="0" class="ssi_table">';
  395. foreach ($posts as $post)
  396. echo '
  397. <tr>
  398. <td align="right" valign="top" nowrap="nowrap">
  399. [', $post['board']['link'], ']
  400. </td>
  401. <td valign="top">
  402. <a href="', $post['href'], '">', $post['subject'], '</a>
  403. ', $txt['by'], ' ', $post['poster']['link'], '
  404. ', $post['is_new'] ? '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow"><span class="new_posts">' . $txt['new'] . '</span></a>' : '', '
  405. </td>
  406. <td align="right" nowrap="nowrap">
  407. ', $post['time'], '
  408. </td>
  409. </tr>';
  410. echo '
  411. </table>';
  412. }
  413. /**
  414. * Recent topic list:
  415. * [board] Subject by Poster Date
  416. *
  417. * @param int $num_recent
  418. * @param array $exclude_boards
  419. * @param bool $include_boards
  420. * @param string $output_method = 'echo'
  421. */
  422. function ssi_recentTopics($num_recent = 8, $exclude_boards = null, $include_boards = null, $output_method = 'echo')
  423. {
  424. global $context, $settings, $scripturl, $txt, $db_prefix, $user_info;
  425. global $modSettings, $smcFunc;
  426. if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0)
  427. $exclude_boards = array($modSettings['recycle_board']);
  428. else
  429. $exclude_boards = empty($exclude_boards) ? array() : (is_array($exclude_boards) ? $exclude_boards : array($exclude_boards));
  430. // Only some boards?.
  431. if (is_array($include_boards) || (int) $include_boards === $include_boards)
  432. {
  433. $include_boards = is_array($include_boards) ? $include_boards : array($include_boards);
  434. }
  435. elseif ($include_boards != null)
  436. {
  437. $output_method = $include_boards;
  438. $include_boards = array();
  439. }
  440. $stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'poll', 'moved', 'recycled', 'wireless');
  441. $icon_sources = array();
  442. foreach ($stable_icons as $icon)
  443. $icon_sources[$icon] = 'images_url';
  444. // Find all the posts in distinct topics. Newer ones will have higher IDs.
  445. $request = $smcFunc['db_query']('substring', '
  446. SELECT
  447. m.poster_time, ms.subject, m.id_topic, m.id_member, m.id_msg, b.id_board, b.name AS board_name, t.num_replies, t.num_views,
  448. IFNULL(mem.real_name, m.poster_name) AS poster_name, ' . ($user_info['is_guest'] ? '1 AS is_read, 0 AS new_from' : '
  449. IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) >= m.id_msg_modified AS is_read,
  450. IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from') . ', SUBSTRING(m.body, 1, 384) AS body, m.smileys_enabled, m.icon
  451. FROM {db_prefix}topics AS t
  452. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_last_msg)
  453. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  454. INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
  455. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (!$user_info['is_guest'] ? '
  456. LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
  457. LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = b.id_board AND lmr.id_member = {int:current_member})' : '') . '
  458. WHERE t.id_last_msg >= {int:min_message_id}
  459. ' . (empty($exclude_boards) ? '' : '
  460. AND b.id_board NOT IN ({array_int:exclude_boards})') . '
  461. ' . (empty($include_boards) ? '' : '
  462. AND b.id_board IN ({array_int:include_boards})') . '
  463. AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
  464. AND t.approved = {int:is_approved}
  465. AND m.approved = {int:is_approved}' : '') . '
  466. ORDER BY t.id_last_msg DESC
  467. LIMIT ' . $num_recent,
  468. array(
  469. 'current_member' => $user_info['id'],
  470. 'include_boards' => empty($include_boards) ? '' : $include_boards,
  471. 'exclude_boards' => empty($exclude_boards) ? '' : $exclude_boards,
  472. 'min_message_id' => $modSettings['maxMsgID'] - 35 * min($num_recent, 5),
  473. 'is_approved' => 1,
  474. )
  475. );
  476. $posts = array();
  477. while ($row = $smcFunc['db_fetch_assoc']($request))
  478. {
  479. $row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']), array('<br />' => '&#10;')));
  480. if ($smcFunc['strlen']($row['body']) > 128)
  481. $row['body'] = $smcFunc['substr']($row['body'], 0, 128) . '...';
  482. // Censor the subject.
  483. censorText($row['subject']);
  484. censorText($row['body']);
  485. if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
  486. $icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
  487. // Build the array.
  488. $posts[] = array(
  489. 'board' => array(
  490. 'id' => $row['id_board'],
  491. 'name' => $row['board_name'],
  492. 'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
  493. 'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['board_name'] . '</a>'
  494. ),
  495. 'topic' => $row['id_topic'],
  496. 'poster' => array(
  497. 'id' => $row['id_member'],
  498. 'name' => $row['poster_name'],
  499. 'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
  500. 'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
  501. ),
  502. 'subject' => $row['subject'],
  503. 'replies' => $row['num_replies'],
  504. 'views' => $row['num_views'],
  505. 'short_subject' => shorten_subject($row['subject'], 25),
  506. 'preview' => $row['body'],
  507. 'time' => timeformat($row['poster_time']),
  508. 'timestamp' => forum_time(true, $row['poster_time']),
  509. 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
  510. 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#new" rel="nofollow">' . $row['subject'] . '</a>',
  511. // Retained for compatibility - is technically incorrect!
  512. 'new' => !empty($row['is_read']),
  513. 'is_new' => empty($row['is_read']),
  514. 'new_from' => $row['new_from'],
  515. 'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" align="middle" alt="' . $row['icon'] . '" />',
  516. );
  517. }
  518. $smcFunc['db_free_result']($request);
  519. // Just return it.
  520. if ($output_method != 'echo' || empty($posts))
  521. return $posts;
  522. echo '
  523. <table border="0" class="ssi_table">';
  524. foreach ($posts as $post)
  525. echo '
  526. <tr>
  527. <td align="right" valign="top" nowrap="nowrap">
  528. [', $post['board']['link'], ']
  529. </td>
  530. <td valign="top">
  531. <a href="', $post['href'], '">', $post['subject'], '</a>
  532. ', $txt['by'], ' ', $post['poster']['link'], '
  533. ', !$post['is_new'] ? '' : '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow"><span class="new_posts">' . $txt['new'] . '</span></a>', '
  534. </td>
  535. <td align="right" nowrap="nowrap">
  536. ', $post['time'], '
  537. </td>
  538. </tr>';
  539. echo '
  540. </table>';
  541. }
  542. /**
  543. * Show the top poster's name and profile link.
  544. *
  545. * @param int $topNumber
  546. * @param string $output_method = 'echo'
  547. */
  548. function ssi_topPoster($topNumber = 1, $output_method = 'echo')
  549. {
  550. global $db_prefix, $scripturl, $smcFunc;
  551. // Find the latest poster.
  552. $request = $smcFunc['db_query']('', '
  553. SELECT id_member, real_name, posts
  554. FROM {db_prefix}members
  555. ORDER BY posts DESC
  556. LIMIT ' . $topNumber,
  557. array(
  558. )
  559. );
  560. $return = array();
  561. while ($row = $smcFunc['db_fetch_assoc']($request))
  562. $return[] = array(
  563. 'id' => $row['id_member'],
  564. 'name' => $row['real_name'],
  565. 'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
  566. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>',
  567. 'posts' => $row['posts']
  568. );
  569. $smcFunc['db_free_result']($request);
  570. // Just return all the top posters.
  571. if ($output_method != 'echo')
  572. return $return;
  573. // Make a quick array to list the links in.
  574. $temp_array = array();
  575. foreach ($return as $member)
  576. $temp_array[] = $member['link'];
  577. echo implode(', ', $temp_array);
  578. }
  579. /**
  580. * Show boards by activity.
  581. *
  582. * @param int $num_top
  583. * @param string $output_method = 'echo'
  584. */
  585. function ssi_topBoards($num_top = 10, $output_method = 'echo')
  586. {
  587. global $context, $settings, $db_prefix, $txt, $scripturl, $user_info, $modSettings, $smcFunc;
  588. // Find boards with lots of posts.
  589. $request = $smcFunc['db_query']('', '
  590. SELECT
  591. b.name, b.num_topics, b.num_posts, b.id_board,' . (!$user_info['is_guest'] ? ' 1 AS is_read' : '
  592. (IFNULL(lb.id_msg, 0) >= b.id_last_msg) AS is_read') . '
  593. FROM {db_prefix}boards AS b
  594. LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
  595. WHERE {query_wanna_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  596. AND b.id_board != {int:recycle_board}' : '') . '
  597. ORDER BY b.num_posts DESC
  598. LIMIT ' . $num_top,
  599. array(
  600. 'current_member' => $user_info['id'],
  601. 'recycle_board' => (int) $modSettings['recycle_board'],
  602. )
  603. );
  604. $boards = array();
  605. while ($row = $smcFunc['db_fetch_assoc']($request))
  606. $boards[] = array(
  607. 'id' => $row['id_board'],
  608. 'num_posts' => $row['num_posts'],
  609. 'num_topics' => $row['num_topics'],
  610. 'name' => $row['name'],
  611. 'new' => empty($row['is_read']),
  612. 'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
  613. 'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>'
  614. );
  615. $smcFunc['db_free_result']($request);
  616. // If we shouldn't output or have nothing to output, just jump out.
  617. if ($output_method != 'echo' || empty($boards))
  618. return $boards;
  619. echo '
  620. <table class="ssi_table">
  621. <tr>
  622. <th align="left">', $txt['board'], '</th>
  623. <th align="left">', $txt['board_topics'], '</th>
  624. <th align="left">', $txt['posts'], '</th>
  625. </tr>';
  626. foreach ($boards as $board)
  627. echo '
  628. <tr>
  629. <td>', $board['link'], $board['new'] ? ' <a href="' . $board['href'] . '"><span class="new_posts">' . $txt['new'] . '</span></a>' : '', '</td>
  630. <td align="right">', comma_format($board['num_topics']), '</td>
  631. <td align="right">', comma_format($board['num_posts']), '</td>
  632. </tr>';
  633. echo '
  634. </table>';
  635. }
  636. /**
  637. * Shows the top topics.
  638. *
  639. * @param string $type
  640. * @param 10 $num_topics
  641. * @param string $output_method = 'echo'
  642. */
  643. function ssi_topTopics($type = 'replies', $num_topics = 10, $output_method = 'echo')
  644. {
  645. global $db_prefix, $txt, $scripturl, $user_info, $modSettings, $smcFunc, $context;
  646. if ($modSettings['totalMessages'] > 100000)
  647. {
  648. // @todo Why don't we use {query(_wanna)_see_board}?
  649. $request = $smcFunc['db_query']('', '
  650. SELECT id_topic
  651. FROM {db_prefix}topics
  652. WHERE num_' . ($type != 'replies' ? 'views' : 'replies') . ' != 0' . ($modSettings['postmod_active'] ? '
  653. AND approved = {int:is_approved}' : '') . '
  654. ORDER BY num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
  655. LIMIT {int:limit}',
  656. array(
  657. 'is_approved' => 1,
  658. 'limit' => $num_topics > 100 ? ($num_topics + ($num_topics / 2)) : 100,
  659. )
  660. );
  661. $topic_ids = array();
  662. while ($row = $smcFunc['db_fetch_assoc']($request))
  663. $topic_ids[] = $row['id_topic'];
  664. $smcFunc['db_free_result']($request);
  665. }
  666. else
  667. $topic_ids = array();
  668. $request = $smcFunc['db_query']('', '
  669. SELECT m.subject, m.id_topic, t.num_views, t.num_replies
  670. FROM {db_prefix}topics AS t
  671. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  672. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  673. WHERE {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
  674. AND t.approved = {int:is_approved}' : '') . (!empty($topic_ids) ? '
  675. AND t.id_topic IN ({array_int:topic_list})' : '') . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  676. AND b.id_board != {int:recycle_enable}' : '') . '
  677. ORDER BY t.num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
  678. LIMIT {int:limit}',
  679. array(
  680. 'topic_list' => $topic_ids,
  681. 'is_approved' => 1,
  682. 'recycle_enable' => $modSettings['recycle_board'],
  683. 'limit' => $num_topics,
  684. )
  685. );
  686. $topics = array();
  687. while ($row = $smcFunc['db_fetch_assoc']($request))
  688. {
  689. censorText($row['subject']);
  690. $topics[] = array(
  691. 'id' => $row['id_topic'],
  692. 'subject' => $row['subject'],
  693. 'num_replies' => $row['num_replies'],
  694. 'num_views' => $row['num_views'],
  695. 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
  696. 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
  697. );
  698. }
  699. $smcFunc['db_free_result']($request);
  700. if ($output_method != 'echo' || empty($topics))
  701. return $topics;
  702. echo '
  703. <table class="ssi_table">
  704. <tr>
  705. <th align="left"></th>
  706. <th align="left">', $txt['views'], '</th>
  707. <th align="left">', $txt['replies'], '</th>
  708. </tr>';
  709. foreach ($topics as $topic)
  710. echo '
  711. <tr>
  712. <td align="left">
  713. ', $topic['link'], '
  714. </td>
  715. <td align="right">', comma_format($topic['num_views']), '</td>
  716. <td align="right">', comma_format($topic['num_replies']), '</td>
  717. </tr>';
  718. echo '
  719. </table>';
  720. }
  721. /**
  722. * Shows the top topics, by replies.
  723. *
  724. * @param int $num_topics = 10
  725. * @param string $output_method = 'echo'
  726. */
  727. function ssi_topTopicsReplies($num_topics = 10, $output_method = 'echo')
  728. {
  729. return ssi_topTopics('replies', $num_topics, $output_method);
  730. }
  731. /**
  732. * Shows the top topics, by views.
  733. *
  734. * @param int $num_topics = 10
  735. * @param string $output_method = 'echo'
  736. */
  737. function ssi_topTopicsViews($num_topics = 10, $output_method = 'echo')
  738. {
  739. return ssi_topTopics('views', $num_topics, $output_method);
  740. }
  741. /**
  742. * Show a link to the latest member:
  743. * Please welcome, Someone, out latest member.
  744. *
  745. * @param string $output_method = 'echo'
  746. */
  747. function ssi_latestMember($output_method = 'echo')
  748. {
  749. global $db_prefix, $txt, $scripturl, $context;
  750. if ($output_method == 'echo')
  751. echo '
  752. ', sprintf($txt['welcome_newest_member'], $context['common_stats']['latest_member']['link']), '<br />';
  753. else
  754. return $context['common_stats']['latest_member'];
  755. }
  756. /**
  757. * Fetch a random member - if type set to 'day' will only change once a day!
  758. *
  759. * @param string $random_type = ''
  760. * @param string $output_method = 'echo'
  761. */
  762. function ssi_randomMember($random_type = '', $output_method = 'echo')
  763. {
  764. global $modSettings;
  765. // If we're looking for something to stay the same each day then seed the generator.
  766. if ($random_type == 'day')
  767. {
  768. // Set the seed to change only once per day.
  769. mt_srand(floor(time() / 86400));
  770. }
  771. // Get the lowest ID we're interested in.
  772. $member_id = mt_rand(1, $modSettings['latestMember']);
  773. $where_query = '
  774. id_member >= {int:selected_member}
  775. AND is_activated = {int:is_activated}';
  776. $query_where_params = array(
  777. 'selected_member' => $member_id,
  778. 'is_activated' => 1,
  779. );
  780. $result = ssi_queryMembers($where_query, $query_where_params, 1, 'id_member ASC', $output_method);
  781. // If we got nothing do the reverse - in case of unactivated members.
  782. if (empty($result))
  783. {
  784. $where_query = '
  785. id_member <= {int:selected_member}
  786. AND is_activated = {int:is_activated}';
  787. $query_where_params = array(
  788. 'selected_member' => $member_id,
  789. 'is_activated' => 1,
  790. );
  791. $result = ssi_queryMembers($where_query, $query_where_params, 1, 'id_member DESC', $output_method);
  792. }
  793. // Just to be sure put the random generator back to something... random.
  794. if ($random_type != '')
  795. mt_srand(time());
  796. return $result;
  797. }
  798. /**
  799. * Fetch a specific member.
  800. *
  801. * @param array $member_ids = array()
  802. * @param string $output_method = 'echo'
  803. */
  804. function ssi_fetchMember($member_ids = array(), $output_method = 'echo')
  805. {
  806. if (empty($member_ids))
  807. return;
  808. // Can have more than one member if you really want...
  809. $member_ids = is_array($member_ids) ? $member_ids : array($member_ids);
  810. // Restrict it right!
  811. $query_where = '
  812. id_member IN ({array_int:member_list})';
  813. $query_where_params = array(
  814. 'member_list' => $member_ids,
  815. );
  816. // Then make the query and dump the data.
  817. return ssi_queryMembers($query_where, $query_where_params, '', 'id_member', $output_method);
  818. }
  819. /**
  820. * Fetch a specific member.
  821. *
  822. * @param null $group_id
  823. * @param string $output_method = 'echo'
  824. */
  825. function ssi_fetchGroupMembers($group_id = null, $output_method = 'echo')
  826. {
  827. if ($group_id === null)
  828. return;
  829. $query_where = '
  830. id_group = {int:id_group}
  831. OR id_post_group = {int:id_group}
  832. OR FIND_IN_SET({int:id_group}, additional_groups)';
  833. $query_where_params = array(
  834. 'id_group' => $group_id,
  835. );
  836. return ssi_queryMembers($query_where, $query_where_params, '', 'real_name', $output_method);
  837. }
  838. /**
  839. * Fetch some member data!
  840. *
  841. * @param string $query_where
  842. * @param string $query_where_params
  843. * @param string $query_limit
  844. * @param string $query_order
  845. * @param string $output_method
  846. */
  847. function ssi_queryMembers($query_where = null, $query_where_params = array(), $query_limit = '', $query_order = 'id_member DESC', $output_method = 'echo')
  848. {
  849. global $context, $settings, $scripturl, $txt, $db_prefix, $user_info;
  850. global $modSettings, $smcFunc, $memberContext;
  851. if ($query_where === null)
  852. return;
  853. // Fetch the members in question.
  854. $request = $smcFunc['db_query']('', '
  855. SELECT id_member
  856. FROM {db_prefix}members
  857. WHERE ' . $query_where . '
  858. ORDER BY ' . $query_order . '
  859. ' . ($query_limit == '' ? '' : 'LIMIT ' . $query_limit),
  860. array_merge($query_where_params, array(
  861. ))
  862. );
  863. $members = array();
  864. while ($row = $smcFunc['db_fetch_assoc']($request))
  865. $members[] = $row['id_member'];
  866. $smcFunc['db_free_result']($request);
  867. if (empty($members))
  868. return array();
  869. // Load the members.
  870. loadMemberData($members);
  871. // Draw the table!
  872. if ($output_method == 'echo')
  873. echo '
  874. <table border="0" class="ssi_table">';
  875. $query_members = array();
  876. foreach ($members as $member)
  877. {
  878. // Load their context data.
  879. if (!loadMemberContext($member))
  880. continue;
  881. // Store this member's information.
  882. $query_members[$member] = $memberContext[$member];
  883. // Only do something if we're echo'ing.
  884. if ($output_method == 'echo')
  885. echo '
  886. <tr>
  887. <td align="right" valign="top" nowrap="nowrap">
  888. ', $query_members[$member]['link'], '
  889. <br />', $query_members[$member]['blurb'], '
  890. <br />', $query_members[$member]['avatar']['image'], '
  891. </td>
  892. </tr>';
  893. }
  894. // End the table if appropriate.
  895. if ($output_method == 'echo')
  896. echo '
  897. </table>';
  898. // Send back the data.
  899. return $query_members;
  900. }
  901. /**
  902. * Show some basic stats: Total This: XXXX, etc.
  903. *
  904. * @param string $output_method
  905. */
  906. function ssi_boardStats($output_method = 'echo')
  907. {
  908. global $db_prefix, $txt, $scripturl, $modSettings, $smcFunc;
  909. if (!allowedTo('view_stats'))
  910. return;
  911. $totals = array(
  912. 'members' => $modSettings['totalMembers'],
  913. 'posts' => $modSettings['totalMessages'],
  914. 'topics' => $modSettings['totalTopics']
  915. );
  916. $result = $smcFunc['db_query']('', '
  917. SELECT COUNT(*)
  918. FROM {db_prefix}boards',
  919. array(
  920. )
  921. );
  922. list ($totals['boards']) = $smcFunc['db_fetch_row']($result);
  923. $smcFunc['db_free_result']($result);
  924. $result = $smcFunc['db_query']('', '
  925. SELECT COUNT(*)
  926. FROM {db_prefix}categories',
  927. array(
  928. )
  929. );
  930. list ($totals['categories']) = $smcFunc['db_fetch_row']($result);
  931. $smcFunc['db_free_result']($result);
  932. if ($output_method != 'echo')
  933. return $totals;
  934. echo '
  935. ', $txt['total_members'], ': <a href="', $scripturl . '?action=memberlist">', comma_format($totals['members']), '</a><br />
  936. ', $txt['total_posts'], ': ', comma_format($totals['posts']), '<br />
  937. ', $txt['total_topics'], ': ', comma_format($totals['topics']), ' <br />
  938. ', $txt['total_cats'], ': ', comma_format($totals['categories']), '<br />
  939. ', $txt['total_boards'], ': ', comma_format($totals['boards']);
  940. }
  941. /**
  942. * Shows a list of online users:
  943. * YY Guests, ZZ Users and then a list...
  944. *
  945. * @param string $output_method
  946. */
  947. function ssi_whosOnline($output_method = 'echo')
  948. {
  949. global $user_info, $txt, $settings, $modSettings;
  950. require_once(SUBSDIR . '/MembersOnline.subs.php');
  951. $membersOnlineOptions = array(
  952. 'show_hidden' => allowedTo('moderate_forum'),
  953. );
  954. $return = getMembersOnlineStats($membersOnlineOptions);
  955. // Add some redundancy for backwards compatibility reasons.
  956. if ($output_method != 'echo')
  957. return $return + array(
  958. 'users' => $return['users_online'],
  959. 'guests' => $return['num_guests'],
  960. 'hidden' => $return['num_users_hidden'],
  961. 'buddies' => $return['num_buddies'],
  962. 'num_users' => $return['num_users_online'],
  963. 'total_users' => $return['num_users_online'] + $return['num_guests'] + $return['num_spiders'],
  964. );
  965. echo '
  966. ', comma_format($return['num_guests']), ' ', $return['num_guests'] == 1 ? $txt['guest'] : $txt['guests'], ', ', comma_format($return['num_users_online']), ' ', $return['num_users_online'] == 1 ? $txt['user'] : $txt['users'];
  967. $bracketList = array();
  968. if (!empty($user_info['buddies']))
  969. $bracketList[] = comma_format($return['num_buddies']) . ' ' . ($return['num_buddies'] == 1 ? $txt['buddy'] : $txt['buddies']);
  970. if (!empty($return['num_spiders']))
  971. $bracketList[] = comma_format($return['num_spiders']) . ' ' . ($return['num_spiders'] == 1 ? $txt['spider'] : $txt['spiders']);
  972. if (!empty($return['num_users_hidden']))
  973. $bracketList[] = comma_format($return['num_users_hidden']) . ' ' . $txt['hidden'];
  974. if (!empty($bracketList))
  975. echo ' (' . implode(', ', $bracketList) . ')';
  976. echo '<br />
  977. ', implode(', ', $return['list_users_online']);
  978. // Showing membergroups?
  979. if (!empty($settings['show_group_key']) && !empty($return['membergroups']))
  980. echo '<br />
  981. [' . implode(']&nbsp;&nbsp;[', $return['membergroups']) . ']';
  982. }
  983. /**
  984. * Just like whosOnline except it also logs the online presence.
  985. *
  986. * @param string $output_method
  987. */
  988. function ssi_logOnline($output_method = 'echo')
  989. {
  990. writeLog();
  991. if ($output_method != 'echo')
  992. return ssi_whosOnline($output_method);
  993. else
  994. ssi_whosOnline($output_method);
  995. }
  996. /**
  997. * Shows a login box.
  998. *
  999. * @param string $redirect_to = ''
  1000. * @param string $output_method = 'echo'
  1001. */
  1002. function ssi_login($redirect_to = '', $output_method = 'echo')
  1003. {
  1004. global $scripturl, $txt, $user_info, $context, $modSettings;
  1005. if ($redirect_to != '')
  1006. $_SESSION['login_url'] = $redirect_to;
  1007. if ($output_method != 'echo' || !$user_info['is_guest'])
  1008. return $user_info['is_guest'];
  1009. echo '
  1010. <form action="', $scripturl, '?action=login2" method="post" accept-charset="UTF-8">
  1011. <table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
  1012. <tr>
  1013. <td align="right"><label for="user">', $txt['username'], ':</label>&nbsp;</td>
  1014. <td><input type="text" id="user" name="user" size="9" value="', $user_info['username'], '" class="input_text" /></td>
  1015. </tr><tr>
  1016. <td align="right"><label for="passwrd">', $txt['password'], ':</label>&nbsp;</td>
  1017. <td><input type="password" name="passwrd" id="passwrd" size="9" class="input_password" /></td>
  1018. </tr>';
  1019. // Open ID?
  1020. if (!empty($modSettings['enableOpenID']))
  1021. echo '<tr>
  1022. <td colspan="2" align="center"><strong>&mdash;', $txt['or'], '&mdash;</strong></td>
  1023. </tr><tr>
  1024. <td align="right"><label for="openid_url">', $txt['openid'], ':</label>&nbsp;</td>
  1025. <td><input type="text" name="openid_identifier" id="openid_url" class="input_text openid_login" size="17" /></td>
  1026. </tr>';
  1027. echo '<tr>
  1028. <td><input type="hidden" name="cookielength" value="-1" /></td>
  1029. <td><input type="submit" value="', $txt['login'], '" class="button_submit" /></td>
  1030. </tr>
  1031. </table>
  1032. </form>';
  1033. }
  1034. /**
  1035. * Show the most-voted-in poll.
  1036. *
  1037. * @param string $output_method = 'echo'
  1038. */
  1039. function ssi_topPoll($output_method = 'echo')
  1040. {
  1041. // Just use recentPoll, no need to duplicate code...
  1042. return ssi_recentPoll(true, $output_method);
  1043. }
  1044. /**
  1045. * Show the most recently posted poll.
  1046. *
  1047. * @param bool $topPollInstead = false
  1048. * @param string $output_method = string
  1049. */
  1050. function ssi_recentPoll($topPollInstead = false, $output_method = 'echo')
  1051. {
  1052. global $db_prefix, $txt, $settings, $boardurl, $user_info, $context, $smcFunc, $modSettings;
  1053. $boardsAllowed = array_intersect(boardsAllowedTo('poll_view'), boardsAllowedTo('poll_vote'));
  1054. if (empty($boardsAllowed))
  1055. return array();
  1056. $request = $smcFunc['db_query']('', '
  1057. SELECT p.id_poll, p.question, t.id_topic, p.max_votes, p.guest_vote, p.hide_results, p.expire_time
  1058. FROM {db_prefix}polls AS p
  1059. INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
  1060. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)' . ($topPollInstead ? '
  1061. INNER JOIN {db_prefix}poll_choices AS pc ON (pc.id_poll = p.id_poll)' : '') . '
  1062. LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_poll = p.id_poll AND lp.id_member > {int:no_member} AND lp.id_member = {int:current_member})
  1063. WHERE p.voting_locked = {int:voting_opened}
  1064. AND (p.expire_time = {int:no_expiration} OR {int:current_time} < p.expire_time)
  1065. AND ' . ($user_info['is_guest'] ? 'p.guest_vote = {int:guest_vote_allowed}' : 'lp.id_choice IS NULL') . '
  1066. AND {query_wanna_see_board}' . (!in_array(0, $boardsAllowed) ? '
  1067. AND b.id_board IN ({array_int:boards_allowed_list})' : '') . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  1068. AND b.id_board != {int:recycle_enable}' : '') . '
  1069. ORDER BY ' . ($topPollInstead ? 'pc.votes' : 'p.id_poll') . ' DESC
  1070. LIMIT 1',
  1071. array(
  1072. 'current_member' => $user_info['id'],
  1073. 'boards_allowed_list' => $boardsAllowed,
  1074. 'is_approved' => 1,
  1075. 'guest_vote_allowed' => 1,
  1076. 'no_member' => 0,
  1077. 'voting_opened' => 0,
  1078. 'no_expiration' => 0,
  1079. 'current_time' => time(),
  1080. 'recycle_enable' => $modSettings['recycle_board'],
  1081. )
  1082. );
  1083. $row = $smcFunc['db_fetch_assoc']($request);
  1084. $smcFunc['db_free_result']($request);
  1085. // This user has voted on all the polls.
  1086. if ($row === false)
  1087. return array();
  1088. // If this is a guest who's voted we'll through ourselves to show poll to show the results.
  1089. if ($user_info['is_guest'] && (!$row['guest_vote'] || (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))))
  1090. return ssi_showPoll($row['id_topic'], $output_method);
  1091. $request = $smcFunc['db_query']('', '
  1092. SELECT COUNT(DISTINCT id_member)
  1093. FROM {db_prefix}log_polls
  1094. WHERE id_poll = {int:current_poll}',
  1095. array(
  1096. 'current_poll' => $row['id_poll'],
  1097. )
  1098. );
  1099. list ($total) = $smcFunc['db_fetch_row']($request);
  1100. $smcFunc['db_free_result']($request);
  1101. $request = $smcFunc['db_query']('', '
  1102. SELECT id_choice, label, votes
  1103. FROM {db_prefix}poll_choices
  1104. WHERE id_poll = {int:current_poll}',
  1105. array(
  1106. 'current_poll' => $row['id_poll'],
  1107. )
  1108. );
  1109. $options = array();
  1110. while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
  1111. {
  1112. censorText($rowChoice['label']);
  1113. $options[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
  1114. }
  1115. $smcFunc['db_free_result']($request);
  1116. // Can they view it?
  1117. $is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
  1118. $allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || $is_expired;
  1119. $return = array(
  1120. 'id' => $row['id_poll'],
  1121. 'image' => 'poll',
  1122. 'question' => $row['question'],
  1123. 'total_votes' => $total,
  1124. 'is_locked' => false,
  1125. 'topic' => $row['id_topic'],
  1126. 'allow_view_results' => $allow_view_results,
  1127. 'options' => array()
  1128. );
  1129. // Calculate the percentages and bar lengths...
  1130. $divisor = $return['total_votes'] == 0 ? 1 : $return['total_votes'];
  1131. foreach ($options as $i => $option)
  1132. {
  1133. $bar = floor(($option[1] * 100) / $divisor);
  1134. $barWide = $bar == 0 ? 1 : floor(($bar * 5) / 3);
  1135. $return['options'][$i] = array(
  1136. 'id' => 'options-' . ($topPollInstead ? 'top-' : 'recent-') . $i,
  1137. 'percent' => $bar,
  1138. 'votes' => $option[1],
  1139. 'bar' => '<span style="white-space: nowrap;"><img src="' . $settings['images_url'] . '/poll_' . ($context['right_to_left'] ? 'right' : 'left') . '.png" alt="" /><img src="' . $settings['images_url'] . '/poll_middle.png" width="' . $barWide . '" height="12" alt="-" /><img src="' . $settings['images_url'] . '/poll_' . ($context['right_to_left'] ? 'left' : 'right') . '.png" alt="" /></span>',
  1140. 'option' => parse_bbc($option[0]),
  1141. 'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . ($topPollInstead ? 'top-' : 'recent-') . $i . '" value="' . $i . '" class="input_' . ($row['max_votes'] > 1 ? 'check' : 'radio') . '" />'
  1142. );
  1143. }
  1144. $return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options6'], min(count($options), $row['max_votes'])) : '';
  1145. if ($output_method != 'echo')
  1146. return $return;
  1147. if ($allow_view_results)
  1148. {
  1149. echo '
  1150. <form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="UTF-8">
  1151. <strong>', $return['question'], '</strong><br />
  1152. ', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br />' : '';
  1153. foreach ($return['options'] as $option)
  1154. echo '
  1155. <label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br />';
  1156. echo '
  1157. <input type="submit" value="', $txt['poll_vote'], '" class="button_submit" />
  1158. <input type="hidden" name="poll" value="', $return['id'], '" />
  1159. <input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
  1160. </form>';
  1161. }
  1162. else
  1163. echo $txt['poll_cannot_see'];
  1164. }
  1165. /**
  1166. * Show a poll.
  1167. *
  1168. * @param int $topic = null
  1169. * @param string $output_method = 'echo'
  1170. */
  1171. function ssi_showPoll($topic = null, $output_method = 'echo')
  1172. {
  1173. global $db_prefix, $txt, $settings, $boardurl, $user_info, $context, $smcFunc, $modSettings;
  1174. $boardsAllowed = boardsAllowedTo('poll_view');
  1175. if (empty($boardsAllowed))
  1176. return array();
  1177. if ($topic === null && isset($_REQUEST['ssi_topic']))
  1178. $topic = (int) $_REQUEST['ssi_topic'];
  1179. else
  1180. $topic = (int) $topic;
  1181. $request = $smcFunc['db_query']('', '
  1182. SELECT
  1183. p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.guest_vote, b.id_board
  1184. FROM {db_prefix}topics AS t
  1185. INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
  1186. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  1187. WHERE t.id_topic = {int:current_topic}
  1188. AND {query_see_board}' . (!in_array(0, $boardsAllowed) ? '
  1189. AND b.id_board IN ({array_int:boards_allowed_see})' : '') . ($modSettings['postmod_active'] ? '
  1190. AND t.approved = {int:is_approved}' : '') . '
  1191. LIMIT 1',
  1192. array(
  1193. 'current_topic' => $topic,
  1194. 'boards_allowed_see' => $boardsAllowed,
  1195. 'is_approved' => 1,
  1196. )
  1197. );
  1198. // Either this topic has no poll, or the user cannot view it.
  1199. if ($smcFunc['db_num_rows']($request) == 0)
  1200. return array();
  1201. $row = $smcFunc['db_fetch_assoc']($request);
  1202. $smcFunc['db_free_result']($request);
  1203. // Check if they can vote.
  1204. if (!empty($row['expire_time']) && $row['expire_time'] < time())
  1205. $allow_vote = false;
  1206. elseif ($user_info['is_guest'] && $row['guest_vote'] && (!isset($_COOKIE['guest_poll_vote']) || !in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote']))))
  1207. $allow_vote = true;
  1208. elseif ($user_info['is_guest'])
  1209. $allow_vote = false;
  1210. elseif (!empty($row['voting_locked']) || !allowedTo('poll_vote', $row['id_board']))
  1211. $allow_vote = false;
  1212. else
  1213. {
  1214. $request = $smcFunc['db_query']('', '
  1215. SELECT id_member
  1216. FROM {db_prefix}log_polls
  1217. WHERE id_poll = {int:current_poll}
  1218. AND id_member = {int:current_member}
  1219. LIMIT 1',
  1220. array(
  1221. 'current_member' => $user_info['id'],
  1222. 'current_poll' => $row['id_poll'],
  1223. )
  1224. );
  1225. $allow_vote = $smcFunc['db_num_rows']($request) == 0;
  1226. $smcFunc['db_free_result']($request);
  1227. }
  1228. // Can they view?
  1229. $is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
  1230. $allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || ($row['hide_results'] == 1 && !$allow_vote) || $is_expired;
  1231. $request = $smcFunc['db_query']('', '
  1232. SELECT COUNT(DISTINCT id_member)
  1233. FROM {db_prefix}log_polls
  1234. WHERE id_poll = {int:current_poll}',
  1235. array(
  1236. 'current_poll' => $row['id_poll'],
  1237. )
  1238. );
  1239. list ($total) = $smcFunc['db_fetch_row']($request);
  1240. $smcFunc['db_free_result']($request);
  1241. $request = $smcFunc['db_query']('', '
  1242. SELECT id_choice, label, votes
  1243. FROM {db_prefix}poll_choices
  1244. WHERE id_poll = {int:current_poll}',
  1245. array(
  1246. 'current_poll' => $row['id_poll'],
  1247. )
  1248. );
  1249. $options = array();
  1250. $total_votes = 0;
  1251. while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
  1252. {
  1253. censorText($rowChoice['label']);
  1254. $options[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
  1255. $total_votes += $rowChoice['votes'];
  1256. }
  1257. $smcFunc['db_free_result']($request);
  1258. $return = array(
  1259. 'id' => $row['id_poll'],
  1260. 'image' => empty($row['voting_locked']) ? 'poll' : 'locked_poll',
  1261. 'question' => $row['question'],
  1262. 'total_votes' => $total,
  1263. 'is_locked' => !empty($row['voting_locked']),
  1264. 'allow_…

Large files files are truncated, but you can click here to view the full file