Display.php 74 KB

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