Display.php 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725
  1. <?php
  2. /**
  3. * This is perhaps the most important and probably most accessed file in all
  4. * of SMF. This file controls topic, message, and attachment display.
  5. *
  6. * Simple Machines Forum (SMF)
  7. *
  8. * @package SMF
  9. * @author Simple Machines http://www.simplemachines.org
  10. * @copyright 2011 Simple Machines
  11. * @license http://www.simplemachines.org/about/smf/license.php BSD
  12. *
  13. * @version 2.1 Alpha 1
  14. */
  15. if (!defined('SMF'))
  16. die('Hacking attempt...');
  17. /**
  18. * The central part of the board - topic display.
  19. * This function loads the posts in a topic up so they can be displayed.
  20. * It supports wireless, using wap/wap2/imode and the Wireless templates.
  21. * It uses the main sub template of the Display template.
  22. * It requires a topic, and can go to the previous or next topic from it.
  23. * It jumps to the correct post depending on a number/time/IS_MSG passed.
  24. * It depends on the messages_per_page, defaultMaxMessages and enableAllMessages settings.
  25. * It is accessed by ?topic=id_topic.START.
  26. */
  27. function Display()
  28. {
  29. global $scripturl, $txt, $modSettings, $context, $settings;
  30. global $options, $sourcedir, $user_info, $board_info, $topic, $board;
  31. global $attachments, $messages_request, $topicinfo, $language, $smcFunc;
  32. // What are you gonna display if these are empty?!
  33. if (empty($topic))
  34. fatal_lang_error('no_board', false);
  35. // Load the proper template and/or sub template.
  36. if (WIRELESS)
  37. $context['sub_template'] = WIRELESS_PROTOCOL . '_display';
  38. else
  39. loadTemplate('Display');
  40. // Not only does a prefetch make things slower for the server, but it makes it impossible to know if they read it.
  41. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  42. {
  43. ob_end_clean();
  44. header('HTTP/1.1 403 Prefetch Forbidden');
  45. die;
  46. }
  47. // How much are we sticking on each page?
  48. $context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) && !WIRELESS ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
  49. // Let's do some work on what to search index.
  50. if (count($_GET) > 2)
  51. foreach ($_GET as $k => $v)
  52. {
  53. if (!in_array($k, array('topic', 'board', 'start', session_name())))
  54. $context['robot_no_index'] = true;
  55. }
  56. if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0))
  57. $context['robot_no_index'] = true;
  58. // Find the previous or next topic. Make a fuss if there are no more.
  59. if (isset($_REQUEST['prev_next']) && ($_REQUEST['prev_next'] == 'prev' || $_REQUEST['prev_next'] == 'next'))
  60. {
  61. // No use in calculating the next topic if there's only one.
  62. if ($board_info['num_topics'] > 1)
  63. {
  64. // Just prepare some variables that are used in the query.
  65. $gt_lt = $_REQUEST['prev_next'] == 'prev' ? '>' : '<';
  66. $order = $_REQUEST['prev_next'] == 'prev' ? '' : ' DESC';
  67. $request = $smcFunc['db_query']('', '
  68. SELECT t2.id_topic
  69. FROM {db_prefix}topics AS t
  70. INNER JOIN {db_prefix}topics AS t2 ON (' . (empty($modSettings['enableStickyTopics']) ? '
  71. t2.id_last_msg ' . $gt_lt . ' t.id_last_msg' : '
  72. (t2.id_last_msg ' . $gt_lt . ' t.id_last_msg AND t2.is_sticky ' . $gt_lt . '= t.is_sticky) OR t2.is_sticky ' . $gt_lt . ' t.is_sticky') . ')
  73. WHERE t.id_topic = {int:current_topic}
  74. AND t2.id_board = {int:current_board}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  75. AND (t2.approved = {int:is_approved} OR (t2.id_member_started != {int:id_member_started} AND t2.id_member_started = {int:current_member}))') . '
  76. ORDER BY' . (empty($modSettings['enableStickyTopics']) ? '' : ' t2.is_sticky' . $order . ',') . ' t2.id_last_msg' . $order . '
  77. LIMIT 1',
  78. array(
  79. 'current_board' => $board,
  80. 'current_member' => $user_info['id'],
  81. 'current_topic' => $topic,
  82. 'is_approved' => 1,
  83. 'id_member_started' => 0,
  84. )
  85. );
  86. // No more left.
  87. if ($smcFunc['db_num_rows']($request) == 0)
  88. {
  89. $smcFunc['db_free_result']($request);
  90. // Roll over - if we're going prev, get the last - otherwise the first.
  91. $request = $smcFunc['db_query']('', '
  92. SELECT id_topic
  93. FROM {db_prefix}topics
  94. WHERE id_board = {int:current_board}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  95. AND (approved = {int:is_approved} OR (id_member_started != {int:id_member_started} AND id_member_started = {int:current_member}))') . '
  96. ORDER BY' . (empty($modSettings['enableStickyTopics']) ? '' : ' is_sticky' . $order . ',') . ' id_last_msg' . $order . '
  97. LIMIT 1',
  98. array(
  99. 'current_board' => $board,
  100. 'current_member' => $user_info['id'],
  101. 'is_approved' => 1,
  102. 'id_member_started' => 0,
  103. )
  104. );
  105. }
  106. // Now you can be sure $topic is the id_topic to view.
  107. list ($topic) = $smcFunc['db_fetch_row']($request);
  108. $smcFunc['db_free_result']($request);
  109. $context['current_topic'] = $topic;
  110. }
  111. // Go to the newest message on this topic.
  112. $_REQUEST['start'] = 'new';
  113. }
  114. // Add 1 to the number of views of this topic (except for robots).
  115. if (!$user_info['possibly_robot'] && (empty($_SESSION['last_read_topic']) || $_SESSION['last_read_topic'] != $topic))
  116. {
  117. $smcFunc['db_query']('', '
  118. UPDATE {db_prefix}topics
  119. SET num_views = num_views + 1
  120. WHERE id_topic = {int:current_topic}',
  121. array(
  122. 'current_topic' => $topic,
  123. )
  124. );
  125. $_SESSION['last_read_topic'] = $topic;
  126. }
  127. // @todo Why isn't this cached?
  128. // @todo if we get id_board in this query and cache it, we can save a query on posting
  129. // Get all the important topic info.
  130. $request = $smcFunc['db_query']('', '
  131. SELECT
  132. t.num_replies, t.num_views, t.locked, ms.subject, t.is_sticky, t.id_poll,
  133. t.id_member_started, t.id_first_msg, t.id_last_msg, t.approved, t.unapproved_posts,
  134. ' . ($user_info['is_guest'] ? 't.id_last_msg + 1' : 'IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1') . ' AS new_from
  135. ' . (!empty($modSettings['recycle_board']) && $modSettings['recycle_board'] == $board ? ', id_previous_board, id_previous_topic' : '') . '
  136. FROM {db_prefix}topics AS t
  137. INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)' . ($user_info['is_guest'] ? '' : '
  138. LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = {int:current_topic} AND lt.id_member = {int:current_member})
  139. LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})') . '
  140. WHERE t.id_topic = {int:current_topic}
  141. LIMIT 1',
  142. array(
  143. 'current_member' => $user_info['id'],
  144. 'current_topic' => $topic,
  145. 'current_board' => $board,
  146. )
  147. );
  148. if ($smcFunc['db_num_rows']($request) == 0)
  149. fatal_lang_error('not_a_topic', false);
  150. $topicinfo = $smcFunc['db_fetch_assoc']($request);
  151. $smcFunc['db_free_result']($request);
  152. $context['real_num_replies'] = $context['num_replies'] = $topicinfo['num_replies'];
  153. $context['topic_first_message'] = $topicinfo['id_first_msg'];
  154. $context['topic_last_message'] = $topicinfo['id_last_msg'];
  155. // Add up unapproved replies to get real number of replies...
  156. if ($modSettings['postmod_active'] && allowedTo('approve_posts'))
  157. $context['real_num_replies'] += $topicinfo['unapproved_posts'] - ($topicinfo['approved'] ? 0 : 1);
  158. // If this topic has unapproved posts, we need to work out how many posts the user can see, for page indexing.
  159. if ($modSettings['postmod_active'] && $topicinfo['unapproved_posts'] && !$user_info['is_guest'] && !allowedTo('approve_posts'))
  160. {
  161. $request = $smcFunc['db_query']('', '
  162. SELECT COUNT(id_member) AS my_unapproved_posts
  163. FROM {db_prefix}messages
  164. WHERE id_topic = {int:current_topic}
  165. AND id_member = {int:current_member}
  166. AND approved = 0',
  167. array(
  168. 'current_topic' => $topic,
  169. 'current_member' => $user_info['id'],
  170. )
  171. );
  172. list ($myUnapprovedPosts) = $smcFunc['db_fetch_row']($request);
  173. $smcFunc['db_free_result']($request);
  174. $context['total_visible_posts'] = $context['num_replies'] + $myUnapprovedPosts + ($topicinfo['approved'] ? 1 : 0);
  175. }
  176. else
  177. $context['total_visible_posts'] = $context['num_replies'] + $topicinfo['unapproved_posts'] + ($topicinfo['approved'] ? 1 : 0);
  178. // When was the last time this topic was replied to? Should we warn them about it?
  179. $request = $smcFunc['db_query']('', '
  180. SELECT poster_time
  181. FROM {db_prefix}messages
  182. WHERE id_msg = {int:id_last_msg}
  183. LIMIT 1',
  184. array(
  185. 'id_last_msg' => $topicinfo['id_last_msg'],
  186. )
  187. );
  188. list ($lastPostTime) = $smcFunc['db_fetch_row']($request);
  189. $smcFunc['db_free_result']($request);
  190. $context['oldTopicError'] = !empty($modSettings['oldTopicDays']) && $lastPostTime + $modSettings['oldTopicDays'] * 86400 < time() && empty($topicinfo['is_sticky']);
  191. // The start isn't a number; it's information about what to do, where to go.
  192. if (!is_numeric($_REQUEST['start']))
  193. {
  194. // Redirect to the page and post with new messages, originally by Omar Bazavilvazo.
  195. if ($_REQUEST['start'] == 'new')
  196. {
  197. // Guests automatically go to the last post.
  198. if ($user_info['is_guest'])
  199. {
  200. $context['start_from'] = $context['total_visible_posts'] - 1;
  201. $_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : 0;
  202. }
  203. else
  204. {
  205. // Find the earliest unread message in the topic. (the use of topics here is just for both tables.)
  206. $request = $smcFunc['db_query']('', '
  207. SELECT IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from
  208. FROM {db_prefix}topics AS t
  209. LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = {int:current_topic} AND lt.id_member = {int:current_member})
  210. LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})
  211. WHERE t.id_topic = {int:current_topic}
  212. LIMIT 1',
  213. array(
  214. 'current_board' => $board,
  215. 'current_member' => $user_info['id'],
  216. 'current_topic' => $topic,
  217. )
  218. );
  219. list ($new_from) = $smcFunc['db_fetch_row']($request);
  220. $smcFunc['db_free_result']($request);
  221. // Fall through to the next if statement.
  222. $_REQUEST['start'] = 'msg' . $new_from;
  223. }
  224. }
  225. // Start from a certain time index, not a message.
  226. if (strpos($_REQUEST['start'], 'from') === 0)
  227. {
  228. $timestamp = (int) substr($_REQUEST['start'], 4);
  229. if ($timestamp === 0)
  230. $_REQUEST['start'] = 0;
  231. else
  232. {
  233. // Find the number of messages posted before said time...
  234. $request = $smcFunc['db_query']('', '
  235. SELECT COUNT(*)
  236. FROM {db_prefix}messages
  237. WHERE poster_time < {int:timestamp}
  238. AND id_topic = {int:current_topic}' . ($modSettings['postmod_active'] && $topicinfo['unapproved_posts'] && !allowedTo('approve_posts') ? '
  239. AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')' : ''),
  240. array(
  241. 'current_topic' => $topic,
  242. 'current_member' => $user_info['id'],
  243. 'is_approved' => 1,
  244. 'timestamp' => $timestamp,
  245. )
  246. );
  247. list ($context['start_from']) = $smcFunc['db_fetch_row']($request);
  248. $smcFunc['db_free_result']($request);
  249. // Handle view_newest_first options, and get the correct start value.
  250. $_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : $context['total_visible_posts'] - $context['start_from'] - 1;
  251. }
  252. }
  253. // Link to a message...
  254. elseif (strpos($_REQUEST['start'], 'msg') === 0)
  255. {
  256. $virtual_msg = (int) substr($_REQUEST['start'], 3);
  257. if (!$topicinfo['unapproved_posts'] && $virtual_msg >= $topicinfo['id_last_msg'])
  258. $context['start_from'] = $context['total_visible_posts'] - 1;
  259. elseif (!$topicinfo['unapproved_posts'] && $virtual_msg <= $topicinfo['id_first_msg'])
  260. $context['start_from'] = 0;
  261. else
  262. {
  263. // Find the start value for that message......
  264. $request = $smcFunc['db_query']('', '
  265. SELECT COUNT(*)
  266. FROM {db_prefix}messages
  267. WHERE id_msg < {int:virtual_msg}
  268. AND id_topic = {int:current_topic}' . ($modSettings['postmod_active'] && $topicinfo['unapproved_posts'] && !allowedTo('approve_posts') ? '
  269. AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')' : ''),
  270. array(
  271. 'current_member' => $user_info['id'],
  272. 'current_topic' => $topic,
  273. 'virtual_msg' => $virtual_msg,
  274. 'is_approved' => 1,
  275. 'no_member' => 0,
  276. )
  277. );
  278. list ($context['start_from']) = $smcFunc['db_fetch_row']($request);
  279. $smcFunc['db_free_result']($request);
  280. }
  281. // We need to reverse the start as well in this case.
  282. $_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : $context['total_visible_posts'] - $context['start_from'] - 1;
  283. }
  284. }
  285. // Create a previous next string if the selected theme has it as a selected option.
  286. $context['previous_next'] = $modSettings['enablePreviousNext'] ? '<a href="' . $scripturl . '?topic=' . $topic . '.0;prev_next=prev#new">' . $txt['previous_next_back'] . '</a> <a href="' . $scripturl . '?topic=' . $topic . '.0;prev_next=next#new">' . $txt['previous_next_forward'] . '</a>' : '';
  287. // Check if spellchecking is both enabled and actually working. (for quick reply.)
  288. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  289. // Do we need to show the visual verification image?
  290. $context['require_verification'] = !$user_info['is_mod'] && !$user_info['is_admin'] && !empty($modSettings['posts_require_captcha']) && ($user_info['posts'] < $modSettings['posts_require_captcha'] || ($user_info['is_guest'] && $modSettings['posts_require_captcha'] == -1));
  291. if ($context['require_verification'])
  292. {
  293. require_once($sourcedir . '/Subs-Editor.php');
  294. $verificationOptions = array(
  295. 'id' => 'post',
  296. );
  297. $context['require_verification'] = create_control_verification($verificationOptions);
  298. $context['visual_verification_id'] = $verificationOptions['id'];
  299. }
  300. // Are we showing signatures - or disabled fields?
  301. $context['signature_enabled'] = substr($modSettings['signature_settings'], 0, 1) == 1;
  302. $context['disabled_fields'] = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
  303. // Censor the title...
  304. censorText($topicinfo['subject']);
  305. $context['page_title'] = $topicinfo['subject'];
  306. // Is this topic sticky, or can it even be?
  307. $topicinfo['is_sticky'] = empty($modSettings['enableStickyTopics']) ? '0' : $topicinfo['is_sticky'];
  308. // Default this topic to not marked for notifications... of course...
  309. $context['is_marked_notify'] = false;
  310. // Did we report a post to a moderator just now?
  311. $context['report_sent'] = isset($_GET['reportsent']);
  312. // Let's get nosey, who is viewing this topic?
  313. if (!empty($settings['display_who_viewing']))
  314. {
  315. // Start out with no one at all viewing it.
  316. $context['view_members'] = array();
  317. $context['view_members_list'] = array();
  318. $context['view_num_hidden'] = 0;
  319. // Search for members who have this topic set in their GET data.
  320. $request = $smcFunc['db_query']('', '
  321. SELECT
  322. lo.id_member, lo.log_time, mem.real_name, mem.member_name, mem.show_online,
  323. mg.online_color, mg.id_group, mg.group_name
  324. FROM {db_prefix}log_online AS lo
  325. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lo.id_member)
  326. LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:reg_id_group} THEN mem.id_post_group ELSE mem.id_group END)
  327. WHERE INSTR(lo.url, {string:in_url_string}) > 0 OR lo.session = {string:session}',
  328. array(
  329. 'reg_id_group' => 0,
  330. 'in_url_string' => 's:5:"topic";i:' . $topic . ';',
  331. 'session' => $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id(),
  332. )
  333. );
  334. while ($row = $smcFunc['db_fetch_assoc']($request))
  335. {
  336. if (empty($row['id_member']))
  337. continue;
  338. if (!empty($row['online_color']))
  339. $link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" style="color: ' . $row['online_color'] . ';">' . $row['real_name'] . '</a>';
  340. else
  341. $link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>';
  342. $is_buddy = in_array($row['id_member'], $user_info['buddies']);
  343. if ($is_buddy)
  344. $link = '<strong>' . $link . '</strong>';
  345. // Add them both to the list and to the more detailed list.
  346. if (!empty($row['show_online']) || allowedTo('moderate_forum'))
  347. $context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '<em>' . $link . '</em>' : $link;
  348. $context['view_members'][$row['log_time'] . $row['member_name']] = array(
  349. 'id' => $row['id_member'],
  350. 'username' => $row['member_name'],
  351. 'name' => $row['real_name'],
  352. 'group' => $row['id_group'],
  353. 'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
  354. 'link' => $link,
  355. 'is_buddy' => $is_buddy,
  356. 'hidden' => empty($row['show_online']),
  357. );
  358. if (empty($row['show_online']))
  359. $context['view_num_hidden']++;
  360. }
  361. // The number of guests is equal to the rows minus the ones we actually used ;).
  362. $context['view_num_guests'] = $smcFunc['db_num_rows']($request) - count($context['view_members']);
  363. $smcFunc['db_free_result']($request);
  364. // Sort the list.
  365. krsort($context['view_members']);
  366. krsort($context['view_members_list']);
  367. }
  368. // If all is set, but not allowed... just unset it.
  369. $can_show_all = !empty($modSettings['enableAllMessages']) && $context['total_visible_posts'] > $context['messages_per_page'] && $context['total_visible_posts'] < $modSettings['enableAllMessages'];
  370. if (isset($_REQUEST['all']) && !$can_show_all)
  371. unset($_REQUEST['all']);
  372. // Otherwise, it must be allowed... so pretend start was -1.
  373. elseif (isset($_REQUEST['all']))
  374. $_REQUEST['start'] = -1;
  375. // Construct the page index, allowing for the .START method...
  376. $context['page_index'] = constructPageIndex($scripturl . '?topic=' . $topic . '.%1$d', $_REQUEST['start'], $context['total_visible_posts'], $context['messages_per_page'], true);
  377. $context['start'] = $_REQUEST['start'];
  378. // This is information about which page is current, and which page we're on - in case you don't like the constructed page index. (again, wireles..)
  379. $context['page_info'] = array(
  380. 'current_page' => $_REQUEST['start'] / $context['messages_per_page'] + 1,
  381. 'num_pages' => floor(($context['total_visible_posts'] - 1) / $context['messages_per_page']) + 1,
  382. );
  383. // Figure out all the link to the next/prev/first/last/etc. for wireless mainly.
  384. $context['links'] = array(
  385. 'first' => $_REQUEST['start'] >= $context['messages_per_page'] ? $scripturl . '?topic=' . $topic . '.0' : '',
  386. 'prev' => $_REQUEST['start'] >= $context['messages_per_page'] ? $scripturl . '?topic=' . $topic . '.' . ($_REQUEST['start'] - $context['messages_per_page']) : '',
  387. 'next' => $_REQUEST['start'] + $context['messages_per_page'] < $context['total_visible_posts'] ? $scripturl . '?topic=' . $topic. '.' . ($_REQUEST['start'] + $context['messages_per_page']) : '',
  388. 'last' => $_REQUEST['start'] + $context['messages_per_page'] < $context['total_visible_posts'] ? $scripturl . '?topic=' . $topic. '.' . (floor($context['total_visible_posts'] / $context['messages_per_page']) * $context['messages_per_page']) : '',
  389. 'up' => $scripturl . '?board=' . $board . '.0'
  390. );
  391. // If they are viewing all the posts, show all the posts, otherwise limit the number.
  392. if ($can_show_all)
  393. {
  394. if (isset($_REQUEST['all']))
  395. {
  396. // No limit! (actually, there is a limit, but...)
  397. $context['messages_per_page'] = -1;
  398. $context['page_index'] .= empty($modSettings['compactTopicPagesEnable']) ? '<strong>' . $txt['all'] . '</strong> ' : '[<strong>' . $txt['all'] . '</strong>] ';
  399. // Set start back to 0...
  400. $_REQUEST['start'] = 0;
  401. }
  402. // They aren't using it, but the *option* is there, at least.
  403. else
  404. $context['page_index'] .= '&nbsp;<a href="' . $scripturl . '?topic=' . $topic . '.0;all">' . $txt['all'] . '</a> ';
  405. }
  406. // Build the link tree.
  407. $context['linktree'][] = array(
  408. 'url' => $scripturl . '?topic=' . $topic . '.0',
  409. 'name' => $topicinfo['subject'],
  410. 'extra_before' => $settings['linktree_inline'] ? $txt['topic'] . ': ' : ''
  411. );
  412. // Build a list of this board's moderators.
  413. $context['moderators'] = &$board_info['moderators'];
  414. $context['link_moderators'] = array();
  415. if (!empty($board_info['moderators']))
  416. {
  417. // Add a link for each moderator...
  418. foreach ($board_info['moderators'] as $mod)
  419. $context['link_moderators'][] = '<a href="' . $scripturl . '?action=profile;u=' . $mod['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod['name'] . '</a>';
  420. // And show it after the board's name.
  421. $context['linktree'][count($context['linktree']) - 2]['extra_after'] = ' (' . (count($context['link_moderators']) == 1 ? $txt['moderator'] : $txt['moderators']) . ': ' . implode(', ', $context['link_moderators']) . ')';
  422. }
  423. // Information about the current topic...
  424. $context['is_locked'] = $topicinfo['locked'];
  425. $context['is_sticky'] = $topicinfo['is_sticky'];
  426. $context['is_very_hot'] = $topicinfo['num_replies'] >= $modSettings['hotTopicVeryPosts'];
  427. $context['is_hot'] = $topicinfo['num_replies'] >= $modSettings['hotTopicPosts'];
  428. $context['is_approved'] = $topicinfo['approved'];
  429. // @todo Tricks? We don't want to show the poll icon in the topic class here, so pretend it's not one.
  430. $context['is_poll'] = false;
  431. determineTopicClass($context);
  432. $context['is_poll'] = $topicinfo['id_poll'] > 0 && $modSettings['pollMode'] == '1' && allowedTo('poll_view');
  433. // Did this user start the topic or not?
  434. $context['user']['started'] = $user_info['id'] == $topicinfo['id_member_started'] && !$user_info['is_guest'];
  435. $context['topic_starter_id'] = $topicinfo['id_member_started'];
  436. // Set the topic's information for the template.
  437. $context['subject'] = $topicinfo['subject'];
  438. $context['num_views'] = $topicinfo['num_views'];
  439. $context['mark_unread_time'] = $topicinfo['new_from'];
  440. // Set a canonical URL for this page.
  441. $context['canonical_url'] = $scripturl . '?topic=' . $topic . '.' . $context['start'];
  442. // For quick reply we need a response prefix in the default forum language.
  443. if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix', 600)))
  444. {
  445. if ($language === $user_info['language'])
  446. $context['response_prefix'] = $txt['response_prefix'];
  447. else
  448. {
  449. loadLanguage('index', $language, false);
  450. $context['response_prefix'] = $txt['response_prefix'];
  451. loadLanguage('index');
  452. }
  453. cache_put_data('response_prefix', $context['response_prefix'], 600);
  454. }
  455. // If we want to show event information in the topic, prepare the data.
  456. if (allowedTo('calendar_view') && !empty($modSettings['cal_showInTopic']) && !empty($modSettings['cal_enabled']))
  457. {
  458. // First, try create a better time format, ignoring the "time" elements.
  459. if (preg_match('~%[AaBbCcDdeGghjmuYy](?:[^%]*%[AaBbCcDdeGghjmuYy])*~', $user_info['time_format'], $matches) == 0 || empty($matches[0]))
  460. $date_string = $user_info['time_format'];
  461. else
  462. $date_string = $matches[0];
  463. // Any calendar information for this topic?
  464. $request = $smcFunc['db_query']('', '
  465. SELECT cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, mem.real_name
  466. FROM {db_prefix}calendar AS cal
  467. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = cal.id_member)
  468. WHERE cal.id_topic = {int:current_topic}
  469. ORDER BY start_date',
  470. array(
  471. 'current_topic' => $topic,
  472. )
  473. );
  474. $context['linked_calendar_events'] = array();
  475. while ($row = $smcFunc['db_fetch_assoc']($request))
  476. {
  477. // Prepare the dates for being formatted.
  478. $start_date = sscanf($row['start_date'], '%04d-%02d-%02d');
  479. $start_date = mktime(12, 0, 0, $start_date[1], $start_date[2], $start_date[0]);
  480. $end_date = sscanf($row['end_date'], '%04d-%02d-%02d');
  481. $end_date = mktime(12, 0, 0, $end_date[1], $end_date[2], $end_date[0]);
  482. $context['linked_calendar_events'][] = array(
  483. 'id' => $row['id_event'],
  484. 'title' => $row['title'],
  485. 'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
  486. 'modify_href' => $scripturl . '?action=post;msg=' . $topicinfo['id_first_msg'] . ';topic=' . $topic . '.0;calendar;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
  487. 'start_date' => timeformat($start_date, $date_string, 'none'),
  488. 'start_timestamp' => $start_date,
  489. 'end_date' => timeformat($end_date, $date_string, 'none'),
  490. 'end_timestamp' => $end_date,
  491. 'is_last' => false
  492. );
  493. }
  494. $smcFunc['db_free_result']($request);
  495. if (!empty($context['linked_calendar_events']))
  496. $context['linked_calendar_events'][count($context['linked_calendar_events']) - 1]['is_last'] = true;
  497. }
  498. // Create the poll info if it exists.
  499. if ($context['is_poll'])
  500. {
  501. // Get the question and if it's locked.
  502. $request = $smcFunc['db_query']('', '
  503. SELECT
  504. p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.change_vote,
  505. p.guest_vote, p.id_member, IFNULL(mem.real_name, p.poster_name) AS poster_name, p.num_guest_voters, p.reset_poll
  506. FROM {db_prefix}polls AS p
  507. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = p.id_member)
  508. WHERE p.id_poll = {int:id_poll}
  509. LIMIT 1',
  510. array(
  511. 'id_poll' => $topicinfo['id_poll'],
  512. )
  513. );
  514. $pollinfo = $smcFunc['db_fetch_assoc']($request);
  515. $smcFunc['db_free_result']($request);
  516. $request = $smcFunc['db_query']('', '
  517. SELECT COUNT(DISTINCT id_member) AS total
  518. FROM {db_prefix}log_polls
  519. WHERE id_poll = {int:id_poll}
  520. AND id_member != {int:not_guest}',
  521. array(
  522. 'id_poll' => $topicinfo['id_poll'],
  523. 'not_guest' => 0,
  524. )
  525. );
  526. list ($pollinfo['total']) = $smcFunc['db_fetch_row']($request);
  527. $smcFunc['db_free_result']($request);
  528. // Total voters needs to include guest voters
  529. $pollinfo['total'] += $pollinfo['num_guest_voters'];
  530. // Get all the options, and calculate the total votes.
  531. $request = $smcFunc['db_query']('', '
  532. SELECT pc.id_choice, pc.label, pc.votes, IFNULL(lp.id_choice, -1) AS voted_this
  533. FROM {db_prefix}poll_choices AS pc
  534. LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_choice = pc.id_choice AND lp.id_poll = {int:id_poll} AND lp.id_member = {int:current_member} AND lp.id_member != {int:not_guest})
  535. WHERE pc.id_poll = {int:id_poll}',
  536. array(
  537. 'current_member' => $user_info['id'],
  538. 'id_poll' => $topicinfo['id_poll'],
  539. 'not_guest' => 0,
  540. )
  541. );
  542. $pollOptions = array();
  543. $realtotal = 0;
  544. $pollinfo['has_voted'] = false;
  545. while ($row = $smcFunc['db_fetch_assoc']($request))
  546. {
  547. censorText($row['label']);
  548. $pollOptions[$row['id_choice']] = $row;
  549. $realtotal += $row['votes'];
  550. $pollinfo['has_voted'] |= $row['voted_this'] != -1;
  551. }
  552. $smcFunc['db_free_result']($request);
  553. // If this is a guest we need to do our best to work out if they have voted, and what they voted for.
  554. if ($user_info['is_guest'] && $pollinfo['guest_vote'] && allowedTo('poll_vote'))
  555. {
  556. if (!empty($_COOKIE['guest_poll_vote']) && preg_match('~^[0-9,;]+$~', $_COOKIE['guest_poll_vote']) && strpos($_COOKIE['guest_poll_vote'], ';' . $topicinfo['id_poll'] . ',') !== false)
  557. {
  558. // ;id,timestamp,[vote,vote...]; etc
  559. $guestinfo = explode(';', $_COOKIE['guest_poll_vote']);
  560. // Find the poll we're after.
  561. foreach ($guestinfo as $i => $guestvoted)
  562. {
  563. $guestvoted = explode(',', $guestvoted);
  564. if ($guestvoted[0] == $topicinfo['id_poll'])
  565. break;
  566. }
  567. // Has the poll been reset since guest voted?
  568. if ($pollinfo['reset_poll'] > $guestvoted[1])
  569. {
  570. // Remove the poll info from the cookie to allow guest to vote again
  571. unset($guestinfo[$i]);
  572. if (!empty($guestinfo))
  573. $_COOKIE['guest_poll_vote'] = ';' . implode(';', $guestinfo);
  574. else
  575. unset($_COOKIE['guest_poll_vote']);
  576. }
  577. else
  578. {
  579. // What did they vote for?
  580. unset($guestvoted[0], $guestvoted[1]);
  581. foreach ($pollOptions as $choice => $details)
  582. {
  583. $pollOptions[$choice]['voted_this'] = in_array($choice, $guestvoted) ? 1 : -1;
  584. $pollinfo['has_voted'] |= $pollOptions[$choice]['voted_this'] != -1;
  585. }
  586. unset($choice, $details, $guestvoted);
  587. }
  588. unset($guestinfo, $guestvoted, $i);
  589. }
  590. }
  591. // Set up the basic poll information.
  592. $context['poll'] = array(
  593. 'id' => $topicinfo['id_poll'],
  594. 'image' => 'normal_' . (empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll'),
  595. 'question' => parse_bbc($pollinfo['question']),
  596. 'total_votes' => $pollinfo['total'],
  597. 'change_vote' => !empty($pollinfo['change_vote']),
  598. 'is_locked' => !empty($pollinfo['voting_locked']),
  599. 'options' => array(),
  600. 'lock' => allowedTo('poll_lock_any') || ($context['user']['started'] && allowedTo('poll_lock_own')),
  601. 'edit' => allowedTo('poll_edit_any') || ($context['user']['started'] && allowedTo('poll_edit_own')),
  602. 'allowed_warning' => $pollinfo['max_votes'] > 1 ? sprintf($txt['poll_options6'], min(count($pollOptions), $pollinfo['max_votes'])) : '',
  603. 'is_expired' => !empty($pollinfo['expire_time']) && $pollinfo['expire_time'] < time(),
  604. 'expire_time' => !empty($pollinfo['expire_time']) ? timeformat($pollinfo['expire_time']) : 0,
  605. 'has_voted' => !empty($pollinfo['has_voted']),
  606. 'starter' => array(
  607. 'id' => $pollinfo['id_member'],
  608. 'name' => $row['poster_name'],
  609. 'href' => $pollinfo['id_member'] == 0 ? '' : $scripturl . '?action=profile;u=' . $pollinfo['id_member'],
  610. 'link' => $pollinfo['id_member'] == 0 ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $pollinfo['id_member'] . '">' . $row['poster_name'] . '</a>'
  611. )
  612. );
  613. // Make the lock and edit permissions defined above more directly accessible.
  614. $context['allow_lock_poll'] = $context['poll']['lock'];
  615. $context['allow_edit_poll'] = $context['poll']['edit'];
  616. // You're allowed to vote if:
  617. // 1. the poll did not expire, and
  618. // 2. you're either not a guest OR guest voting is enabled... and
  619. // 3. you're not trying to view the results, and
  620. // 4. the poll is not locked, and
  621. // 5. you have the proper permissions, and
  622. // 6. you haven't already voted before.
  623. $context['allow_vote'] = !$context['poll']['is_expired'] && (!$user_info['is_guest'] || ($pollinfo['guest_vote'] && allowedTo('poll_vote'))) && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && !$context['poll']['has_voted'];
  624. // You're allowed to view the results if:
  625. // 1. you're just a super-nice-guy, or
  626. // 2. anyone can see them (hide_results == 0), or
  627. // 3. you can see them after you voted (hide_results == 1), or
  628. // 4. you've waited long enough for the poll to expire. (whether hide_results is 1 or 2.)
  629. $context['allow_poll_view'] = allowedTo('moderate_board') || $pollinfo['hide_results'] == 0 || ($pollinfo['hide_results'] == 1 && $context['poll']['has_voted']) || $context['poll']['is_expired'];
  630. $context['poll']['show_results'] = $context['allow_poll_view'] && (isset($_REQUEST['viewresults']) || isset($_REQUEST['viewResults']));
  631. $context['show_view_results_button'] = $context['allow_vote'] && (!$context['allow_poll_view'] || !$context['poll']['show_results'] || !$context['poll']['has_voted']);
  632. // You're allowed to change your vote if:
  633. // 1. the poll did not expire, and
  634. // 2. you're not a guest... and
  635. // 3. the poll is not locked, and
  636. // 4. you have the proper permissions, and
  637. // 5. you have already voted, and
  638. // 6. the poll creator has said you can!
  639. $context['allow_change_vote'] = !$context['poll']['is_expired'] && !$user_info['is_guest'] && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && $context['poll']['has_voted'] && $context['poll']['change_vote'];
  640. // You're allowed to return to voting options if:
  641. // 1. you are (still) allowed to vote.
  642. // 2. you are currently seeing the results.
  643. $context['allow_return_vote'] = $context['allow_vote'] && $context['poll']['show_results'];
  644. // Calculate the percentages and bar lengths...
  645. $divisor = $realtotal == 0 ? 1 : $realtotal;
  646. // Determine if a decimal point is needed in order for the options to add to 100%.
  647. $precision = $realtotal == 100 ? 0 : 1;
  648. // Now look through each option, and...
  649. foreach ($pollOptions as $i => $option)
  650. {
  651. // First calculate the percentage, and then the width of the bar...
  652. $bar = round(($option['votes'] * 100) / $divisor, $precision);
  653. $barWide = $bar == 0 ? 1 : floor(($bar * 8) / 3);
  654. // Now add it to the poll's contextual theme data.
  655. $context['poll']['options'][$i] = array(
  656. 'id' => 'options-' . $i,
  657. 'percent' => $bar,
  658. 'votes' => $option['votes'],
  659. 'voted_this' => $option['voted_this'] != -1,
  660. 'bar' => '<span style="white-space: nowrap;"><img src="' . $settings['images_url'] . '/poll_' . ($context['right_to_left'] ? 'right' : 'left') . '.gif" alt="" /><img src="' . $settings['images_url'] . '/poll_middle.gif" width="' . $barWide . '" height="12" alt="-" /><img src="' . $settings['images_url'] . '/poll_' . ($context['right_to_left'] ? 'left' : 'right') . '.gif" alt="" /></span>',
  661. // Note: IE < 8 requires us to set a width on the container, too.
  662. 'bar_ndt' => $bar > 0 ? '<div class="bar" style="width: ' . ($bar * 3.5 + 4) . 'px;"><div style="width: ' . $bar * 3.5 . 'px;"></div></div>' : '',
  663. 'bar_width' => $barWide,
  664. 'option' => parse_bbc($option['label']),
  665. 'vote_button' => '<input type="' . ($pollinfo['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="input_' . ($pollinfo['max_votes'] > 1 ? 'check' : 'radio') . '" />'
  666. );
  667. }
  668. }
  669. // Calculate the fastest way to get the messages!
  670. $ascending = empty($options['view_newest_first']);
  671. $start = $_REQUEST['start'];
  672. $limit = $context['messages_per_page'];
  673. $firstIndex = 0;
  674. if ($start >= $context['total_visible_posts'] / 2 && $context['messages_per_page'] != -1)
  675. {
  676. $ascending = !$ascending;
  677. $limit = $context['total_visible_posts'] <= $start + $limit ? $context['total_visible_posts'] - $start : $limit;
  678. $start = $context['total_visible_posts'] <= $start + $limit ? 0 : $context['total_visible_posts'] - $start - $limit;
  679. $firstIndex = $limit - 1;
  680. }
  681. // Get each post and poster in this topic.
  682. $request = $smcFunc['db_query']('display_get_post_poster', '
  683. SELECT id_msg, id_member, approved
  684. FROM {db_prefix}messages
  685. WHERE id_topic = {int:current_topic}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : (!empty($modSettings['db_mysql_group_by_fix']) ? '' : '
  686. GROUP BY id_msg') . '
  687. HAVING (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')') . '
  688. ORDER BY id_msg ' . ($ascending ? '' : 'DESC') . ($context['messages_per_page'] == -1 ? '' : '
  689. LIMIT ' . $start . ', ' . $limit),
  690. array(
  691. 'current_member' => $user_info['id'],
  692. 'current_topic' => $topic,
  693. 'is_approved' => 1,
  694. 'blank_id_member' => 0,
  695. )
  696. );
  697. $messages = array();
  698. $all_posters = array();
  699. while ($row = $smcFunc['db_fetch_assoc']($request))
  700. {
  701. if (!empty($row['id_member']))
  702. $all_posters[$row['id_msg']] = $row['id_member'];
  703. $messages[] = $row['id_msg'];
  704. }
  705. $smcFunc['db_free_result']($request);
  706. $posters = array_unique($all_posters);
  707. // Guests can't mark topics read or for notifications, just can't sorry.
  708. if (!$user_info['is_guest'])
  709. {
  710. $mark_at_msg = max($messages);
  711. if ($mark_at_msg >= $topicinfo['id_last_msg'])
  712. $mark_at_msg = $modSettings['maxMsgID'];
  713. if ($mark_at_msg >= $topicinfo['new_from'])
  714. {
  715. $smcFunc['db_insert']($topicinfo['new_from'] == 0 ? 'ignore' : 'replace',
  716. '{db_prefix}log_topics',
  717. array(
  718. 'id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int',
  719. ),
  720. array(
  721. $user_info['id'], $topic, $mark_at_msg,
  722. ),
  723. array('id_member', 'id_topic')
  724. );
  725. }
  726. // Check for notifications on this topic OR board.
  727. $request = $smcFunc['db_query']('', '
  728. SELECT sent, id_topic
  729. FROM {db_prefix}log_notify
  730. WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
  731. AND id_member = {int:current_member}
  732. LIMIT 2',
  733. array(
  734. 'current_board' => $board,
  735. 'current_member' => $user_info['id'],
  736. 'current_topic' => $topic,
  737. )
  738. );
  739. $do_once = true;
  740. while ($row = $smcFunc['db_fetch_assoc']($request))
  741. {
  742. // Find if this topic is marked for notification...
  743. if (!empty($row['id_topic']))
  744. $context['is_marked_notify'] = true;
  745. // Only do this once, but mark the notifications as "not sent yet" for next time.
  746. if (!empty($row['sent']) && $do_once)
  747. {
  748. $smcFunc['db_query']('', '
  749. UPDATE {db_prefix}log_notify
  750. SET sent = {int:is_not_sent}
  751. WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
  752. AND id_member = {int:current_member}',
  753. array(
  754. 'current_board' => $board,
  755. 'current_member' => $user_info['id'],
  756. 'current_topic' => $topic,
  757. 'is_not_sent' => 0,
  758. )
  759. );
  760. $do_once = false;
  761. }
  762. }
  763. // Have we recently cached the number of new topics in this board, and it's still a lot?
  764. if (isset($_REQUEST['topicseen']) && isset($_SESSION['topicseen_cache'][$board]) && $_SESSION['topicseen_cache'][$board] > 5)
  765. $_SESSION['topicseen_cache'][$board]--;
  766. // Mark board as seen if this is the only new topic.
  767. elseif (isset($_REQUEST['topicseen']))
  768. {
  769. // Use the mark read tables... and the last visit to figure out if this should be read or not.
  770. $request = $smcFunc['db_query']('', '
  771. SELECT COUNT(*)
  772. FROM {db_prefix}topics AS t
  773. LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = {int:current_board} AND lb.id_member = {int:current_member})
  774. LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
  775. WHERE t.id_board = {int:current_board}
  776. AND t.id_last_msg > IFNULL(lb.id_msg, 0)
  777. AND t.id_last_msg > IFNULL(lt.id_msg, 0)' . (empty($_SESSION['id_msg_last_visit']) ? '' : '
  778. AND t.id_last_msg > {int:id_msg_last_visit}'),
  779. array(
  780. 'current_board' => $board,
  781. 'current_member' => $user_info['id'],
  782. 'id_msg_last_visit' => (int) $_SESSION['id_msg_last_visit'],
  783. )
  784. );
  785. list ($numNewTopics) = $smcFunc['db_fetch_row']($request);
  786. $smcFunc['db_free_result']($request);
  787. // If there're no real new topics in this board, mark the board as seen.
  788. if (empty($numNewTopics))
  789. $_REQUEST['boardseen'] = true;
  790. else
  791. $_SESSION['topicseen_cache'][$board] = $numNewTopics;
  792. }
  793. // Probably one less topic - maybe not, but even if we decrease this too fast it will only make us look more often.
  794. elseif (isset($_SESSION['topicseen_cache'][$board]))
  795. $_SESSION['topicseen_cache'][$board]--;
  796. // Mark board as seen if we came using last post link from BoardIndex. (or other places...)
  797. if (isset($_REQUEST['boardseen']))
  798. {
  799. $smcFunc['db_insert']('replace',
  800. '{db_prefix}log_boards',
  801. array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
  802. array($modSettings['maxMsgID'], $user_info['id'], $board),
  803. array('id_member', 'id_board')
  804. );
  805. }
  806. }
  807. $attachments = array();
  808. // If there _are_ messages here... (probably an error otherwise :!)
  809. if (!empty($messages))
  810. {
  811. // Fetch attachments.
  812. if (!empty($modSettings['attachmentEnable']) && allowedTo('view_attachments'))
  813. {
  814. $request = $smcFunc['db_query']('', '
  815. SELECT
  816. a.id_attach, a.id_folder, a.id_msg, a.filename, a.file_hash, IFNULL(a.size, 0) AS filesize, a.downloads, a.approved,
  817. a.width, a.height' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ',
  818. IFNULL(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
  819. FROM {db_prefix}attachments AS a' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
  820. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)') . '
  821. WHERE a.id_msg IN ({array_int:message_list})
  822. AND a.attachment_type = {int:attachment_type}',
  823. array(
  824. 'message_list' => $messages,
  825. 'attachment_type' => 0,
  826. 'is_approved' => 1,
  827. )
  828. );
  829. $temp = array();
  830. while ($row = $smcFunc['db_fetch_assoc']($request))
  831. {
  832. if (!$row['approved'] && $modSettings['postmod_active'] && !allowedTo('approve_posts') && (!isset($all_posters[$row['id_msg']]) || $all_posters[$row['id_msg']] != $user_info['id']))
  833. continue;
  834. $temp[$row['id_attach']] = $row;
  835. if (!isset($attachments[$row['id_msg']]))
  836. $attachments[$row['id_msg']] = array();
  837. }
  838. $smcFunc['db_free_result']($request);
  839. // This is better than sorting it with the query...
  840. ksort($temp);
  841. foreach ($temp as $row)
  842. $attachments[$row['id_msg']][] = $row;
  843. }
  844. // What? It's not like it *couldn't* be only guests in this topic...
  845. if (!empty($posters))
  846. loadMemberData($posters);
  847. $messages_request = $smcFunc['db_query']('', '
  848. SELECT
  849. id_msg, icon, subject, poster_time, poster_ip, id_member, modified_time, modified_name, body,
  850. smileys_enabled, poster_name, poster_email, approved,
  851. id_msg_modified < {int:new_from} AS is_read
  852. FROM {db_prefix}messages
  853. WHERE id_msg IN ({array_int:message_list})
  854. ORDER BY id_msg' . (empty($options['view_newest_first']) ? '' : ' DESC'),
  855. array(
  856. 'message_list' => $messages,
  857. 'new_from' => $topicinfo['new_from'],
  858. )
  859. );
  860. // Go to the last message if the given time is beyond the time of the last message.
  861. if (isset($context['start_from']) && $context['start_from'] >= $topicinfo['num_replies'])
  862. $context['start_from'] = $topicinfo['num_replies'];
  863. // Since the anchor information is needed on the top of the page we load these variables beforehand.
  864. $context['first_message'] = isset($messages[$firstIndex]) ? $messages[$firstIndex] : $messages[0];
  865. if (empty($options['view_newest_first']))
  866. $context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $context['start_from'];
  867. else
  868. $context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $topicinfo['num_replies'] - $context['start_from'];
  869. }
  870. else
  871. {
  872. $messages_request = false;
  873. $context['first_message'] = 0;
  874. $context['first_new_message'] = false;
  875. }
  876. $context['jump_to'] = array(
  877. 'label' => addslashes(un_htmlspecialchars($txt['jump_to'])),
  878. 'board_name' => htmlspecialchars(strtr(strip_tags($board_info['name']), array('&amp;' => '&'))),
  879. 'child_level' => $board_info['child_level'],
  880. );
  881. // Set the callback. (do you REALIZE how much memory all the messages would take?!?)
  882. // This will be called from the template.
  883. $context['get_message'] = 'prepareDisplayContext';
  884. // Now set all the wonderful, wonderful permissions... like moderation ones...
  885. $common_permissions = array(
  886. 'can_approve' => 'approve_posts',
  887. 'can_ban' => 'manage_bans',
  888. 'can_sticky' => 'make_sticky',
  889. 'can_merge' => 'merge_any',
  890. 'can_split' => 'split_any',
  891. 'calendar_post' => 'calendar_post',
  892. 'can_mark_notify' => 'mark_any_notify',
  893. 'can_send_topic' => 'send_topic',
  894. 'can_send_pm' => 'pm_send',
  895. 'can_report_moderator' => 'report_any',
  896. 'can_moderate_forum' => 'moderate_forum',
  897. 'can_issue_warning' => 'issue_warning',
  898. 'can_restore_topic' => 'move_any',
  899. 'can_restore_msg' => 'move_any',
  900. );
  901. foreach ($common_permissions as $contextual => $perm)
  902. $context[$contextual] = allowedTo($perm);
  903. // Permissions with _any/_own versions. $context[YYY] => ZZZ_any/_own.
  904. $anyown_permissions = array(
  905. 'can_move' => 'move',
  906. 'can_lock' => 'lock',
  907. 'can_delete' => 'remove',
  908. 'can_add_poll' => 'poll_add',
  909. 'can_remove_poll' => 'poll_remove',
  910. 'can_reply' => 'post_reply',
  911. 'can_reply_unapproved' => 'post_unapproved_replies',
  912. );
  913. foreach ($anyown_permissions as $contextual => $perm)
  914. $context[$contextual] = allowedTo($perm . '_any') || ($context['user']['started'] && allowedTo($perm . '_own'));
  915. // Cleanup all the permissions with extra stuff...
  916. $context['can_mark_notify'] &= !$context['user']['is_guest'];
  917. $context['can_sticky'] &= !empty($modSettings['enableStickyTopics']);
  918. $context['calendar_post'] &= !empty($modSettings['cal_enabled']);
  919. $context['can_add_poll'] &= $modSettings['pollMode'] == '1' && $topicinfo['id_poll'] <= 0;
  920. $context['can_remove_poll'] &= $modSettings['pollMode'] == '1' && $topicinfo['id_poll'] > 0;
  921. $context['can_reply'] &= empty($topicinfo['locked']) || allowedTo('moderate_board');
  922. $context['can_reply_unapproved'] &= $modSettings['postmod_active'] && (empty($topicinfo['locked']) || allowedTo('moderate_board'));
  923. $context['can_issue_warning'] &= in_array('w', $context['admin_features']) && $modSettings['warning_settings'][0] == 1;
  924. // Handle approval flags...
  925. $context['can_reply_approved'] = $context['can_reply'];
  926. $context['can_reply'] |= $context['can_reply_unapproved'];
  927. $context['can_quote'] = $context['can_reply'] && (empty($modSettings['disabledBBC']) || !in_array('quote', explode(',', $modSettings['disabledBBC'])));
  928. $context['can_mark_unread'] = !$user_info['is_guest'] && $settings['show_mark_read'];
  929. $context['can_send_topic'] = (!$modSettings['postmod_active'] || $topicinfo['approved']) && allowedTo('send_topic');
  930. // Start this off for quick moderation - it will be or'd for each post.
  931. $context['can_remove_post'] = allowedTo('delete_any') || (allowedTo('delete_replies') && $context['user']['started']);
  932. // Can restore topic? That's if the topic is in the recycle board and has a previous restore state.
  933. $context['can_restore_topic'] &= !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $board && !empty($topicinfo['id_previous_board']);
  934. $context['can_restore_msg'] &= !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $board && !empty($topicinfo['id_previous_topic']);
  935. // Wireless shows a "more" if you can do anything special.
  936. if (WIRELESS && WIRELESS_PROTOCOL != 'wap')
  937. {
  938. $context['wireless_more'] = $context['can_sticky'] || $context['can_lock'] || allowedTo('modify_any');
  939. $context['wireless_moderate'] = isset($_GET['moderate']) ? ';moderate' : '';
  940. }
  941. // Load up the "double post" sequencing magic.
  942. if (!empty($options['display_quick_reply']))
  943. {
  944. checkSubmitOnce('register');
  945. $context['name'] = isset($_SESSION['guest_name']) ? $_SESSION['guest_name'] : '';
  946. $context['email'] = isset($_SESSION['guest_email']) ? $_SESSION['guest_email'] : '';
  947. }
  948. }
  949. /**
  950. * Callback for the message display.
  951. * It actually gets and prepares the message context.
  952. * This function will start over from the beginning if reset is set to true, which is
  953. * useful for showing an index before or after the posts.
  954. * @param bool $reset, default false.
  955. */
  956. function prepareDisplayContext($reset = false)
  957. {
  958. global $settings, $txt, $modSettings, $scripturl, $options, $user_info, $smcFunc;
  959. global $memberContext, $context, $messages_request, $topic, $attachments, $topicinfo;
  960. static $counter = null;
  961. // If the query returned false, bail.
  962. if ($messages_request == false)
  963. return false;
  964. // Remember which message this is. (ie. reply #83)
  965. if ($counter === null || $reset)
  966. $counter = empty($options['view_newest_first']) ? $context['start'] : $context['total_visible_posts'] - $context['start'];
  967. // Start from the beginning...
  968. if ($reset)
  969. return @$smcFunc['db_data_seek']($messages_request, 0);
  970. // Attempt to get the next message.
  971. $message = $smcFunc['db_fetch_assoc']($messages_request);
  972. if (!$message)
  973. {
  974. $smcFunc['db_free_result']($messages_request);
  975. return false;
  976. }
  977. // $context['icon_sources'] says where each icon should come from - here we set up the ones which will always exist!
  978. if (empty($context['icon_sources']))
  979. {
  980. $stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'moved', 'recycled', 'wireless', 'clip');
  981. $context['icon_sources'] = array();
  982. foreach ($stable_icons as $icon)
  983. $context['icon_sources'][$icon] = 'images_url';
  984. }
  985. // Message Icon Management... check the images exist.
  986. if (empty($modSettings['messageIconChecks_disable']))
  987. {
  988. // If the current icon isn't known, then we need to do something...
  989. if (!isset($context['icon_sources'][$message['icon']]))
  990. $context['icon_sources'][$message['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['icon'] . '.gif') ? 'images_url' : 'default_images_url';
  991. }
  992. elseif (!isset($context['icon_sources'][$message['icon']]))
  993. $context['icon_sources'][$message['icon']] = 'images_url';
  994. // If you're a lazy bum, you probably didn't give a subject...
  995. $message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
  996. // Are you allowed to remove at least a single reply?
  997. $context['can_remove_post'] |= allowedTo('delete_own') && (empty($modSettings['edit_disable_time']) || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 >= time()) && $message['id_member'] == $user_info['id'];
  998. // If it couldn't load, or the user was a guest.... someday may be done with a guest table.
  999. if (!loadMemberContext($message['id_member'], true))
  1000. {
  1001. // Notice this information isn't used anywhere else....
  1002. $memberContext[$message['id_member']]['name'] = $message['poster_name'];
  1003. $memberContext[$message['id_member']]['id'] = 0;
  1004. $memberContext[$message['id_member']]['group'] = $txt['guest_title'];
  1005. $memberContext[$message['id_member']]['link'] = $message['poster_name'];
  1006. $memberContext[$message['id_member']]['email'] = $message['poster_email'];
  1007. $memberContext[$message['id_member']]['show_email'] = showEmailAddress(true, 0);
  1008. $memberContext[$message['id_member']]['is_guest'] = true;
  1009. }
  1010. else
  1011. {
  1012. $memberContext[$message['id_member']]['can_view_profile'] = allowedTo('profile_view_any') || ($message['id_member'] == $user_info['id'] && allowedTo('profile_view_own'));
  1013. $memberContext[$message['id_member']]['is_topic_starter'] = $message['id_member'] == $context['topic_starter_id'];
  1014. $memberContext[$message['id_member']]['can_see_warning'] = !isset($context['disabled_fields']['warning_status']) && $memberContext[$message['id_member']]['warning_status'] && ($context['user']['can_mod'] || (!$user_info['is_guest'] && !empty($modSettings['warning_show']) && ($modSettings['warning_show'] > 1 || $message['id_member'] == $user_info['id'])));
  1015. }
  1016. $memberContext[$message['id_member']]['ip'] = $message['poster_ip'];
  1017. // Do the censor thang.
  1018. censorText($message['body']);
  1019. censorText($message['subject']);
  1020. // Run BBC interpreter on the message.
  1021. $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
  1022. // Compose the memory eat- I mean message array.
  1023. $output = array(
  1024. 'attachment' => loadAttachmentContext($message['id_msg']),
  1025. 'alternate' => $counter % 2,
  1026. 'id' => $message['id_msg'],
  1027. 'href' => $scripturl . '?topic=' . $topic . '.msg' . $message['id_msg'] . '#msg' . $message['id_msg'],
  1028. 'link' => '<a href="' . $scripturl . '?topic=' . $topic . '.msg' . $message['id_msg'] . '#msg' . $message['id_msg'] . '" rel="nofollow">' . $message['subject'] . '</a>',
  1029. 'member' => &$memberContext[$message['id_member']],
  1030. 'icon' => $message['icon'],
  1031. 'icon_url' => $settings[$context['icon_sources'][$message['icon']]] . '/post/' . $message['icon'] . '.gif',
  1032. 'subject' => $message['subject'],
  1033. 'time' => timeformat($message['poster_time']),
  1034. 'timestamp' => forum_time(true, $message['poster_time']),
  1035. 'counter' => $counter,
  1036. 'modified' => array(
  1037. 'time' => timeformat($message['modified_time']),
  1038. 'timestamp' => forum_time(true, $message['modified_time']),
  1039. 'name' => $message['modified_name']
  1040. ),
  1041. 'body' => $message['body'],
  1042. 'new' => empty($message['is_read']),
  1043. 'approved' => $message['approved'],
  1044. 'first_new' => isset($context['start_from']) && $context['start_from'] == $counter,
  1045. 'is_ignored' => !empty($modSettings['enable_buddylist']) && !empty($options['posts_apply_ignore_list']) && in_array($message['id_member'], $context['user']['ignoreusers']),
  1046. 'can_approve' => !$message['approved'] && $context['can_approve'],
  1047. 'can_unapprove' => $message['approved'] && $context['can_approve'],
  1048. 'can_modify' => (!$context['is_locked'] || allowedTo('moderate_board')) && (allowedTo('modify_any') || (allowedTo('modify_replies') && $context['user']['started']) || (allowedTo('modify_own') && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || !$message['approved'] || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 > time()))),
  1049. 'can_remove' => allowedTo('delete_any') || (allowedTo('delete_replies') && $context['user']['started']) || (allowedTo('delete_own') && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 > time())),
  1050. 'can_see_ip' => allowedTo('moderate_forum') || ($message['id_member'] == $user_info['id'] && !empty($user_info['id'])),
  1051. );
  1052. // Is this user the message author?
  1053. $output['is_message_author'] = $message['id_member'] == $user_info['id'];
  1054. if (empty($options['view_newest_first']))
  1055. $counter++;
  1056. else
  1057. $counter--;
  1058. return $output;
  1059. }
  1060. /**
  1061. * This downloads an attachment or avatar, and increments the downloads.
  1062. * It requires the view_attachments permission. (not for avatars!)
  1063. * It disables the session parser, and clears any previous output.
  1064. * It depends on the attachmentUploadDir setting being correct.
  1065. * It is accessed via the query string ?action=dlattach.
  1066. * Views to attachments and avatars do not increase hits and are not logged in the "Who's Online" log.
  1067. */
  1068. function Download()
  1069. {
  1070. global $txt, $modSettings, $user_info, $scripturl, $context, $sourcedir, $topic, $smcFunc;
  1071. // Some defaults that we need.
  1072. $context['character_set'] = empty($modSettings['global_character_set']) ? (empty($txt['lang_character_set']) ? 'ISO-8859-1' : $txt['lang_character_set']) : $modSettings['global_character_set'];
  1073. $context['utf8'] = $context['character_set'] === 'UTF-8' && (strpos(strtolower(PHP_OS), 'win') === false || @version_compare(PHP_VERSION, '4.2.3') != -1);
  1074. $context['no_last_modified'] = true;
  1075. // Make sure some attachment was requested!
  1076. if (!isset($_REQUEST['attach']) && !isset($_REQUEST['id']))
  1077. fatal_lang_error('no_access', false);
  1078. $_REQUEST['attach'] = isset($_REQUEST['attach']) ? (int) $_REQUEST['attach'] : (int) $_REQUEST['id'];
  1079. if (isset($_REQUEST['type']) && $_REQUEST['type'] == 'avatar')
  1080. {
  1081. $request = $smcFunc['db_query']('', '
  1082. SELECT id_folder, filename, file_hash, fileext, id_attach, attachment_type, mime_type, approved, id_member
  1083. FROM {db_prefix}attachments
  1084. WHERE id_attach = {int:id_attach}
  1085. AND id_member > {int:blank_id_member}
  1086. LIMIT 1',
  1087. array(
  1088. 'id_attach' => $_REQUEST['attach'],
  1089. 'blank_id_member' => 0,
  1090. )
  1091. );
  1092. $_REQUEST['image'] = true;
  1093. }
  1094. // This is just a regular attachment...
  1095. else
  1096. {
  1097. // This checks only the current board for $board/$topic's permissions.
  1098. isAllowedTo('view_attachments');
  1099. // Make sure this attachment is on this board.
  1100. // @todo: We must verify that $topic is the attachment's topic, or else the permission check above is broken.
  1101. $request = $smcFunc['db_query']('', '
  1102. SELECT a.id_folder, a.filename, a.file_hash, a.fileext, a.id_attach, a.attachment_type, a.mime_type, a.approved, m.id_member
  1103. FROM {db_prefix}attachments AS a
  1104. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg AND m.id_topic = {int:current_topic})
  1105. INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})
  1106. WHERE a.id_attach = {int:attach}
  1107. LIMIT 1',
  1108. array(
  1109. 'attach' => $_REQUEST['attach'],
  1110. 'current_topic' => $topic,
  1111. )
  1112. );
  1113. }
  1114. if ($smcFunc['db_num_rows']($request) == 0)
  1115. fatal_lang_error('no_access', false);
  1116. list ($id_folder, $real_filename, $file_hash, $file_ext, $id_attach, $attachment_type, $mime_type, $is_approved, $id_member) = $smcFunc['db_fetch_row']($request);
  1117. $smcFunc['db_free_result']($request);
  1118. // If it isn't yet approved, do they have permission to view it?
  1119. if (!$is_approved && ($id_member == 0 || $user_info['id'] != $id_member) && ($attachment_type == 0 || $attachment_type == 3))
  1120. isAllowedTo('approve_posts');
  1121. // Update the download counter (unless it's a thumbnail).
  1122. if ($attachment_type != 3)
  1123. $smcFunc['db_query']('attach_download_increase', '
  1124. UPDATE LOW_PRIORITY {db_prefix}attachments
  1125. SET downloads = downloads + 1
  1126. WHERE id_attach = {int:id_attach}',
  1127. array(
  1128. 'id_attach' => $id_attach,
  1129. )
  1130. );
  1131. $filename = getAttachmentFilename($real_filename, $_REQUEST['attach'], $id_folder, false, $file_hash);
  1132. // This is done to clear any output that was made before now. (would use ob_clean(), but that's PHP 4.2.0+...)
  1133. ob_end_clean();
  1134. if (!empty($modSettings['enableCompressedOutput']) && @version_compare(PHP_VERSION, '4.2.0') >= 0 && @filesize($filename) <= 4194304 && in_array($file_ext, array('txt', 'html', 'htm', 'js', 'doc', 'pdf', 'docx', 'rtf', 'css', 'php', 'log', 'xml', 'sql', 'c', 'java')))
  1135. @ob_start('ob_gzhandler');
  1136. else
  1137. {
  1138. ob_start();
  1139. header('Content-Encoding: none');
  1140. }
  1141. // No point in a nicer message, because this is supposed to be an attachment anyway...
  1142. if (!file_exists($filename))
  1143. {
  1144. loadLanguage('Errors');
  1145. header('HTTP/1.0 404 ' . $txt['attachment_not_found']);
  1146. header('Content-Type: text/plain; charset=' . (empty($context['character_set']) ? 'ISO-8859-1' : $context['character_set']));
  1147. // We need to die like this *before* we send any anti-caching headers as below.
  1148. die('404 - ' . $txt['attachment_not_found']);
  1149. }
  1150. // If it hasn't been modified since the last time this attachement was retrieved, there's no need to display it again.
  1151. if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
  1152. {
  1153. list($modified_since) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
  1154. if (strtotime($modified_since) >= filemtime($filename))
  1155. {
  1156. ob_end_clean();
  1157. // Answer the question - no, it hasn't been modified ;).
  1158. header('HTTP/1.1 304 Not Modified');
  1159. exit;
  1160. }
  1161. }
  1162. // Check whether the ETag was sent back, and cache based on that...
  1163. $eTag = '"' . substr($_REQUEST['attach'] . $real_filename . filemtime($filename), 0, 64) . '"';
  1164. if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $eTag) !== false)
  1165. {
  1166. ob_end_clean();
  1167. header('HTTP/1.1 304 Not Modified');
  1168. exit;
  1169. }
  1170. // Send the attachment headers.
  1171. header('Pragma: ');
  1172. if (!$context['browser']['is_gecko'])
  1173. header('Content-Transfer-Encoding: binary');
  1174. header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 525600 * 60) . ' GMT');
  1175. header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($filename)) . ' GMT');
  1176. header('Accept-Ranges: bytes');
  1177. header('Connection: close');
  1178. header('ETag: ' . $eTag);
  1179. // IE 6 just doesn't play nice. As dirty as this seems, it works.
  1180. if ($context['browser']['is_ie6'] && isset($_REQUEST['image']))
  1181. unset($_REQUEST['image']);
  1182. // Make sure the mime type warrants an inline display.
  1183. elseif (isset($_REQUEST['image']) && !empty($mime_type) && strpos($mime_type, 'image/') !== 0)
  1184. unset($_REQUEST['image']);
  1185. // Does this have a mime type?
  1186. elseif (!empty($mime_type) && (isset($_REQUEST['image']) || !in_array($file_ext, array('jpg', 'gif', 'jpeg', 'x-ms-bmp', 'png', 'psd', 'tiff', 'iff'))))
  1187. header('Content-Type: ' . strtr($mime_type, array('image/bmp' => 'image/x-ms-bmp')));
  1188. else
  1189. {
  1190. header('Content-Type: ' . ($context['browser']['is_ie'] || $context['browser']['is_opera'] ? 'application/octetstream' : 'application/octet-stream'));
  1191. if (isset($_REQUEST['image']))
  1192. unset($_REQUEST['image']);
  1193. }
  1194. // Convert the file to UTF-8, cuz most browsers dig that.
  1195. $utf8name = !$context['utf8'] && function_exists('iconv') ? iconv($context['character_set'], 'UTF-8', $real_filename) : (!$context['utf8'] && function_exists('mb_convert_encoding') ? mb_convert_encoding($real_filename, 'UTF-8', $context['character_set']) : $real_filename);
  1196. $fixchar = create_function('$n', '
  1197. if ($n < 32)
  1198. return \'\';
  1199. elseif ($n < 128)
  1200. return chr($n);
  1201. elseif ($n < 2048)
  1202. return chr(192 | $n >> 6) . chr(128 | $n & 63);
  1203. elseif ($n < 65536)
  1204. return chr(224 | $n >> 12) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);
  1205. else
  1206. return chr(240 | $n >> 18) . chr(128 | $n >> 12 & 63) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);');
  1207. $disposition = !isset($_REQUEST['image']) ? 'attachment' : 'inline';
  1208. // Different browsers like different standards...
  1209. if ($context['browser']['is_firefox'])
  1210. header('Content-Disposition: ' . $disposition . '; filename*=UTF-8\'\'' . rawurlencode(preg_replace('~&#(\d{3,8});~e', '$fixchar(\'$1\')', $utf8name)));
  1211. elseif ($context['browser']['is_opera'])
  1212. header('Content-Disposition: ' . $disposition . '; filename="' . preg_replace('~&#(\d{3,8});~e', '$fixchar(\'$1\')', $utf8name) . '"');
  1213. elseif ($context['browser']['is_ie'])
  1214. header('Content-Disposition: ' . $disposition . '; filename="' . urlencode(preg_replace('~&#(\d{3,8});~e', '$fixchar(\'$1\')', $utf8name)) . '"');
  1215. else
  1216. header('Content-Disposition: ' . $disposition . '; filename="' . $utf8name . '"');
  1217. // If this has an "image extension" - but isn't actually an image - then ensure it isn't cached cause of silly IE.
  1218. if (!isset($_REQUEST['image']) && in_array($file_ext, array('gif', 'jpg', 'bmp', 'png', 'jpeg', 'tiff')))
  1219. header('Cache-Control: no-cache');
  1220. else
  1221. header('Cache-Control: max-age=' . (525600 * 60) . ', private');
  1222. if (empty($modSettings['enableCompressedOutput']) || filesize($filename) > 4194304)
  1223. header('Content-Length: ' . filesize($filename));
  1224. // Try to buy some time...
  1225. @set_time_limit(600);
  1226. // Recode line endings for text files, if enabled.
  1227. if (!empty($modSettings['attachmentRecodeLineEndings']) && !isset($_REQUEST['image']) && in_array($file_ext, array('txt', 'css', 'htm', 'html', 'php', 'xml')))
  1228. {
  1229. if (strpos($_SERVER['HTTP_USER_AGENT'], 'Windows') !== false)
  1230. $callback = create_function('$buffer', 'return preg_replace(\'~[\r]?\n~\', "\r\n", $buffer);');
  1231. elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !== false)
  1232. $callback = create_function('$buffer', 'return preg_replace(\'~[\r]?\n~\', "\r", $buffer);');
  1233. else
  1234. $callback = create_function('$buffer', 'return preg_replace(\'~[\r]?\n~\', "\n", $buffer);');
  1235. }
  1236. // Since we don't do output compression for files this large...
  1237. if (filesize($filename) > 4194304)
  1238. {
  1239. // Forcibly end any output buffering going on.
  1240. if (function_exists('ob_get_level'))
  1241. {
  1242. while (@ob_get_level() > 0)
  1243. @ob_end_clean();
  1244. }
  1245. else
  1246. {
  1247. @ob_end_clean();
  1248. @ob_end_clean();
  1249. @ob_end_clean();
  1250. }
  1251. $fp = fopen($filename, 'rb');
  1252. while (!feof($fp))
  1253. {
  1254. if (isset($callback))
  1255. echo $callback(fread($fp, 8192));
  1256. else
  1257. echo fread($fp, 8192);
  1258. flush();
  1259. }
  1260. fclose($fp);
  1261. }
  1262. // On some of the less-bright hosts, readfile() is disabled. It's just a faster, more byte safe, version of what's in the if.
  1263. elseif (isset($callback) || @readfile($filename) == null)
  1264. echo isset($callback) ? $callback(file_get_contents($filename)) : file_get_contents($filename);
  1265. obExit(false);
  1266. }
  1267. /**
  1268. * This loads an attachment's contextual data including, most importantly, its size
  1269. * if it is an image.
  1270. * Pre-condition: $attachments array to have been filled with the proper attachment data, as Display() does.
  1271. * (@todo change this pre-condition, too fragile and error-prone.)
  1272. * It requires the view_attachments permission to calculate image size.
  1273. * It attempts to keep the "aspect ratio" of the posted image in line, even if it has to be resized by
  1274. * the max_image_width and max_image_height settings.
  1275. */
  1276. function loadAttachmentContext($id_msg)
  1277. {
  1278. global $attachments, $modSettings, $txt, $scripturl, $topic, $sourcedir, $smcFunc;
  1279. // Set up the attachment info - based on code by Meriadoc.
  1280. $attachmentData = array();
  1281. $have_unapproved = false;
  1282. if (isset($attachments[$id_msg]) && !empty($modSettings['attachmentEnable']))
  1283. {
  1284. foreach ($attachments[$id_msg] as $i => $attachment)
  1285. {
  1286. $attachmentData[$i] = array(
  1287. 'id' => $attachment['id_attach'],
  1288. 'name' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($attachment['filename'])),
  1289. 'downloads' => $attachment['downloads'],
  1290. 'size' => round($attachment['filesize'] / 1024, 2) . ' ' . $txt['kilobyte'],
  1291. 'byte_size' => $attachment['filesize'],
  1292. 'href' => $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['id_attach'],
  1293. 'link' => '<a href="' . $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['id_attach'] . '">' . htmlspecialchars($attachment['filename']) . '</a>',
  1294. 'is_image' => !empty($attachment['width']) && !empty($attachment['height']) && !empty($modSettings['attachmentShowImages']),
  1295. 'is_approved' => $attachment['approved'],
  1296. );
  1297. // If something is unapproved we'll note it so we can sort them.
  1298. if (!$attachment['approved'])
  1299. $have_unapproved = true;
  1300. if (!$attachmentData[$i]['is_image'])
  1301. continue;
  1302. $attachmentData[$i]['real_width'] = $attachment['width'];
  1303. $attachmentData[$i]['width'] = $attachment['width'];
  1304. $attachmentData[$i]['real_height'] = $attachment['height'];
  1305. $attachmentData[$i]['height'] = $attachment['height'];
  1306. // Let's see, do we want thumbs?
  1307. if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachment['width'] > $modSettings['attachmentThumbWidth'] || $attachment['height'] > $modSettings['attachmentThumbHeight']) && strlen($attachment['filename']) < 249)
  1308. {
  1309. // A proper thumb doesn't exist yet? Create one!
  1310. if (empty($attachment['id_thumb']) || $attachment['thumb_width'] > $modSettings['attachmentThumbWidth'] || $attachment['thumb_height'] > $modSettings['attachmentThumbHeight'] || ($attachment['thumb_width'] < $modSettings['attachmentThumbWidth'] && $attachment['thumb_height'] < $modSettings['attachmentThumbHeight']))
  1311. {
  1312. $filename = getAttachmentFilename($attachment['filename'], $attachment['id_attach'], $attachment['id_folder']);
  1313. require_once($sourcedir . '/Subs-Graphics.php');
  1314. if (createThumbnail($filename, $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight']))
  1315. {
  1316. // So what folder are we putting this image in?
  1317. if (!empty($modSettings['currentAttachmentUploadDir']))
  1318. {
  1319. if (!is_array($modSettings['attachmentUploadDir']))
  1320. $modSettings['attachmentUploadDir'] = @unserialize($modSettings['attachmentUploadDir']);
  1321. $path = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
  1322. $id_folder_thumb = $modSettings['currentAttachmentUploadDir'];
  1323. }
  1324. else
  1325. {
  1326. $path = $modSettings['attachmentUploadDir'];
  1327. $id_folder_thumb = 1;
  1328. }
  1329. // Calculate the size of the created thumbnail.
  1330. $size = @getimagesize($filename . '_thumb');
  1331. list ($attachment['thumb_width'], $attachment['thumb_height']) = $size;
  1332. $thumb_size = filesize($filename . '_thumb');
  1333. // These are the only valid image types for SMF.
  1334. $validImageTypes = array(1 => 'gif', 2 => 'jpeg', 3 => 'png', 5 => 'psd', 6 => 'bmp', 7 => 'tiff', 8 => 'tiff', 9 => 'jpeg', 14 => 'iff');
  1335. // What about the extension?
  1336. $thumb_ext = isset($validImageTypes[$size[2]]) ? $validImageTypes[$size[2]] : '';
  1337. // Figure out the mime type.
  1338. if (!empty($size['mime']))
  1339. $thumb_mime = $size['mime'];
  1340. else
  1341. $thumb_mime = 'image/' . $thumb_ext;
  1342. $thumb_filename = $attachment['filename'] . '_thumb';
  1343. $thumb_hash = getAttachmentFilename($thumb_filename, false, null, true);
  1344. // Add this beauty to the database.
  1345. $smcFunc['db_insert']('',
  1346. '{db_prefix}attachments',
  1347. array('id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'size' => 'int', 'width' => 'int', 'height' => 'int', 'fileext' => 'string', 'mime_type' => 'string'),
  1348. array($id_folder_thumb, $id_msg, 3, $thumb_filename, $thumb_hash, (int) $thumb_size, (int) $attachment['thumb_width'], (int) $attachment['thumb_height'], $thumb_ext, $thumb_mime),
  1349. array('id_attach')
  1350. );
  1351. $old_id_thumb = $attachment['id_thumb'];
  1352. $attachment['id_thumb'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
  1353. if (!empty($attachment['id_thumb']))
  1354. {
  1355. $smcFunc['db_query']('', '
  1356. UPDATE {db_prefix}attachments
  1357. SET id_thumb = {int:id_thumb}
  1358. WHERE id_attach = {int:id_attach}',
  1359. array(
  1360. 'id_thumb' => $attachment['id_thumb'],
  1361. 'id_attach' => $attachment['id_attach'],
  1362. )
  1363. );
  1364. $thumb_realname = getAttachmentFilename($thumb_filename, $attachment['id_thumb'], $id_folder_thumb, false, $thumb_hash);
  1365. rename($filename . '_thumb', $thumb_realname);
  1366. // Do we need to remove an old thumbnail?
  1367. if (!empty($old_id_thumb))
  1368. {
  1369. require_once($sourcedir . '/ManageAttachments.php');
  1370. removeAttachments(array('id_attach' => $old_id_thumb), '', false, false);
  1371. }
  1372. }
  1373. }
  1374. }
  1375. // Only adjust dimensions on successful thumbnail creation.
  1376. if (!empty($attachment['thumb_width']) && !empty($attachment['thumb_height']))
  1377. {
  1378. $attachmentData[$i]['width'] = $attachment['thumb_width'];
  1379. $attachmentData[$i]['height'] = $attachment['thumb_height'];
  1380. }
  1381. }
  1382. if (!empty($attachment['id_thumb']))
  1383. $attachmentData[$i]['thumbnail'] = array(
  1384. 'id' => $attachment['id_thumb'],
  1385. 'href' => $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['id_thumb'] . ';image',
  1386. );
  1387. $attachmentData[$i]['thumbnail']['has_thumb'] = !empty($attachment['id_thumb']);
  1388. // If thumbnails are disabled, check the maximum size of the image.
  1389. if (!$attachmentData[$i]['thumbnail']['has_thumb'] && ((!empty($modSettings['max_image_width']) && $attachment['width'] > $modSettings['max_image_width']) || (!empty($modSettings['max_image_height']) && $attachment['height'] > $modSettings['max_image_height'])))
  1390. {
  1391. if (!empty($modSettings['max_image_width']) && (empty($modSettings['max_image_height']) || $attachment['height'] * $modSettings['max_image_width'] / $attachment['width'] <= $modSettings['max_image_height']))
  1392. {
  1393. $attachmentData[$i]['width'] = $modSettings['max_image_width'];
  1394. $attachmentData[$i]['height'] = floor($attachment['height'] * $modSettings['max_image_width'] / $attachment['width']);
  1395. }
  1396. elseif (!empty($modSettings['max_image_width']))
  1397. {
  1398. $attachmentData[$i]['width'] = floor($attachment['width'] * $modSettings['max_image_height'] / $attachment['height']);
  1399. $attachmentData[$i]['height'] = $modSettings['max_image_height'];
  1400. }
  1401. }
  1402. elseif ($attachmentData[$i]['thumbnail']['has_thumb'])
  1403. {
  1404. // If the image is too large to show inline, make it a popup.
  1405. if (((!empty($modSettings['max_image_width']) && $attachmentData[$i]['real_width'] > $modSettings['max_image_width']) || (!empty($modSettings['max_image_height']) && $attachmentData[$i]['real_height'] > $modSettings['max_image_height'])))
  1406. $attachmentData[$i]['thumbnail']['javascript'] = 'return reqWin(\'' . $attachmentData[$i]['href'] . ';image\', ' . ($attachment['width'] + 20) . ', ' . ($attachment['height'] + 20) . ', true);';
  1407. else
  1408. $attachmentData[$i]['thumbnail']['javascript'] = 'return expandThumb(' . $attachment['id_attach'] . ');';
  1409. }
  1410. if (!$attachmentData[$i]['thumbnail']['has_thumb'])
  1411. $attachmentData[$i]['downloads']++;
  1412. }
  1413. }
  1414. // Do we need to instigate a sort?
  1415. if ($have_unapproved)
  1416. usort($attachmentData, 'approved_attach_sort');
  1417. return $attachmentData;
  1418. }
  1419. /**
  1420. * A sort function for putting unapproved attachments first.
  1421. * @param $a
  1422. * @param $b
  1423. * @return int, -1, 0, 1
  1424. */
  1425. function approved_attach_sort($a, $b)
  1426. {
  1427. if ($a['is_approved'] == $b['is_approved'])
  1428. return 0;
  1429. return $a['is_approved'] > $b['is_approved'] ? -1 : 1;
  1430. }
  1431. /**
  1432. * In-topic quick moderation.
  1433. */
  1434. function QuickInTopicModeration()
  1435. {
  1436. global $sourcedir, $topic, $board, $user_info, $smcFunc, $modSettings, $context;
  1437. // Check the session = get or post.
  1438. checkSession('request');
  1439. require_once($sourcedir . '/RemoveTopic.php');
  1440. if (empty($_REQUEST['msgs']))
  1441. redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
  1442. $messages = array();
  1443. foreach ($_REQUEST['msgs'] as $dummy)
  1444. $messages[] = (int) $dummy;
  1445. // We are restoring messages. We handle this in another place.
  1446. if (isset($_REQUEST['restore_selected']))
  1447. redirectexit('action=restoretopic;msgs=' . implode(',', $messages) . ';' . $context['session_var'] . '=' . $context['session_id']);
  1448. // Allowed to delete any message?
  1449. if (allowedTo('delete_any'))
  1450. $allowed_all = true;
  1451. // Allowed to delete replies to their messages?
  1452. elseif (allowedTo('delete_replies'))
  1453. {
  1454. $request = $smcFunc['db_query']('', '
  1455. SELECT id_member_started
  1456. FROM {db_prefix}topics
  1457. WHERE id_topic = {int:current_topic}
  1458. LIMIT 1',
  1459. array(
  1460. 'current_topic' => $topic,
  1461. )
  1462. );
  1463. list ($starter) = $smcFunc['db_fetch_row']($request);
  1464. $smcFunc['db_free_result']($request);
  1465. $allowed_all = $starter == $user_info['id'];
  1466. }
  1467. else
  1468. $allowed_all = false;
  1469. // Make sure they're allowed to delete their own messages, if not any.
  1470. if (!$allowed_all)
  1471. isAllowedTo('delete_own');
  1472. // Allowed to remove which messages?
  1473. $request = $smcFunc['db_query']('', '
  1474. SELECT id_msg, subject, id_member, poster_time
  1475. FROM {db_prefix}messages
  1476. WHERE id_msg IN ({array_int:message_list})
  1477. AND id_topic = {int:current_topic}' . (!$allowed_all ? '
  1478. AND id_member = {int:current_member}' : '') . '
  1479. LIMIT ' . count($messages),
  1480. array(
  1481. 'current_member' => $user_info['id'],
  1482. 'current_topic' => $topic,
  1483. 'message_list' => $messages,
  1484. )
  1485. );
  1486. $messages = array();
  1487. while ($row = $smcFunc['db_fetch_assoc']($request))
  1488. {
  1489. if (!$allowed_all && !empty($modSettings['edit_disable_time']) && $row['poster_time'] + $modSettings['edit_disable_time'] * 60 < time())
  1490. continue;
  1491. $messages[$row['id_msg']] = array($row['subject'], $row['id_member']);
  1492. }
  1493. $smcFunc['db_free_result']($request);
  1494. // Get the first message in the topic - because you can't delete that!
  1495. $request = $smcFunc['db_query']('', '
  1496. SELECT id_first_msg, id_last_msg
  1497. FROM {db_prefix}topics
  1498. WHERE id_topic = {int:current_topic}
  1499. LIMIT 1',
  1500. array(
  1501. 'current_topic' => $topic,
  1502. )
  1503. );
  1504. list ($first_message, $last_message) = $smcFunc['db_fetch_row']($request);
  1505. $smcFunc['db_free_result']($request);
  1506. // Delete all the messages we know they can delete. ($messages)
  1507. foreach ($messages as $message => $info)
  1508. {
  1509. // Just skip the first message - if it's not the last.
  1510. if ($message == $first_message && $message != $last_message)
  1511. continue;
  1512. // If the first message is going then don't bother going back to the topic as we're effectively deleting it.
  1513. elseif ($message == $first_message)
  1514. $topicGone = true;
  1515. removeMessage($message);
  1516. // Log this moderation action ;).
  1517. if (allowedTo('delete_any') && (!allowedTo('delete_own') || $info[1] != $user_info['id']))
  1518. logAction('delete', array('topic' => $topic, 'subject' => $info[0], 'member' => $info[1], 'board' => $board));
  1519. }
  1520. redirectexit(!empty($topicGone) ? 'board=' . $board : 'topic=' . $topic . '.' . $_REQUEST['start']);
  1521. }
  1522. ?>