Display.php 84 KB

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