Display.php 87 KB

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