Display.php 85 KB

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