Display.php 74 KB

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