PersonalMessage.php 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649
  1. <?php
  2. /**
  3. * This file is mainly meant for controlling the actions related to personal
  4. * messages. It allows viewing, sending, deleting, and marking personal
  5. * messages. For compatibility reasons, they are often called "instant messages".
  6. *
  7. * Simple Machines Forum (SMF)
  8. *
  9. * @package SMF
  10. * @author Simple Machines http://www.simplemachines.org
  11. * @copyright 2011 Simple Machines
  12. * @license http://www.simplemachines.org/about/smf/license.php BSD
  13. *
  14. * @version 2.1 Alpha 1
  15. */
  16. if (!defined('SMF'))
  17. die('Hacking attempt...');
  18. /**
  19. * This helps organize things...
  20. * @todo this should be a simple dispatcher....
  21. */
  22. function MessageMain()
  23. {
  24. global $txt, $scripturl, $sourcedir, $context, $user_info, $user_settings, $smcFunc, $modSettings;
  25. // No guests!
  26. is_not_guest();
  27. // You're not supposed to be here at all, if you can't even read PMs.
  28. isAllowedTo('pm_read');
  29. // This file contains the basic functions for sending a PM.
  30. require_once($sourcedir . '/Subs-Post.php');
  31. loadLanguage('PersonalMessage');
  32. if (WIRELESS && WIRELESS_PROTOCOL == 'wap')
  33. fatal_lang_error('wireless_error_notyet', false);
  34. elseif (WIRELESS)
  35. $context['sub_template'] = WIRELESS_PROTOCOL . '_pm';
  36. elseif (!isset($_REQUEST['xml']))
  37. loadTemplate('PersonalMessage');
  38. // Load up the members maximum message capacity.
  39. if ($user_info['is_admin'])
  40. $context['message_limit'] = 0;
  41. elseif (($context['message_limit'] = cache_get_data('msgLimit:' . $user_info['id'], 360)) === null)
  42. {
  43. // @todo Why do we do this? It seems like if they have any limit we should use it.
  44. $request = $smcFunc['db_query']('', '
  45. SELECT MAX(max_messages) AS top_limit, MIN(max_messages) AS bottom_limit
  46. FROM {db_prefix}membergroups
  47. WHERE id_group IN ({array_int:users_groups})',
  48. array(
  49. 'users_groups' => $user_info['groups'],
  50. )
  51. );
  52. list ($maxMessage, $minMessage) = $smcFunc['db_fetch_row']($request);
  53. $smcFunc['db_free_result']($request);
  54. $context['message_limit'] = $minMessage == 0 ? 0 : $maxMessage;
  55. // Save us doing it again!
  56. cache_put_data('msgLimit:' . $user_info['id'], $context['message_limit'], 360);
  57. }
  58. // Prepare the context for the capacity bar.
  59. if (!empty($context['message_limit']))
  60. {
  61. $bar = ($user_info['messages'] * 100) / $context['message_limit'];
  62. $context['limit_bar'] = array(
  63. 'messages' => $user_info['messages'],
  64. 'allowed' => $context['message_limit'],
  65. 'percent' => $bar,
  66. 'bar' => min(100, (int) $bar),
  67. 'text' => sprintf($txt['pm_currently_using'], $user_info['messages'], round($bar, 1)),
  68. );
  69. }
  70. // a previous message was sent successfully? show a small indication.
  71. if (isset($_GET['done']) && ($_GET['done'] == 'sent'))
  72. $context['pm_sent'] = true;
  73. // Now we have the labels, and assuming we have unsorted mail, apply our rules!
  74. if ($user_settings['new_pm'])
  75. {
  76. $context['labels'] = $user_settings['message_labels'] == '' ? array() : explode(',', $user_settings['message_labels']);
  77. foreach ($context['labels'] as $id_label => $label_name)
  78. $context['labels'][(int) $id_label] = array(
  79. 'id' => $id_label,
  80. 'name' => trim($label_name),
  81. 'messages' => 0,
  82. 'unread_messages' => 0,
  83. );
  84. $context['labels'][-1] = array(
  85. 'id' => -1,
  86. 'name' => $txt['pm_msg_label_inbox'],
  87. 'messages' => 0,
  88. 'unread_messages' => 0,
  89. );
  90. ApplyRules();
  91. updateMemberData($user_info['id'], array('new_pm' => 0));
  92. $smcFunc['db_query']('', '
  93. UPDATE {db_prefix}pm_recipients
  94. SET is_new = {int:not_new}
  95. WHERE id_member = {int:current_member}',
  96. array(
  97. 'current_member' => $user_info['id'],
  98. 'not_new' => 0,
  99. )
  100. );
  101. }
  102. // Load the label data.
  103. if ($user_settings['new_pm'] || ($context['labels'] = cache_get_data('labelCounts:' . $user_info['id'], 720)) === null)
  104. {
  105. $context['labels'] = $user_settings['message_labels'] == '' ? array() : explode(',', $user_settings['message_labels']);
  106. foreach ($context['labels'] as $id_label => $label_name)
  107. $context['labels'][(int) $id_label] = array(
  108. 'id' => $id_label,
  109. 'name' => trim($label_name),
  110. 'messages' => 0,
  111. 'unread_messages' => 0,
  112. );
  113. $context['labels'][-1] = array(
  114. 'id' => -1,
  115. 'name' => $txt['pm_msg_label_inbox'],
  116. 'messages' => 0,
  117. 'unread_messages' => 0,
  118. );
  119. // Looks like we need to reseek!
  120. $result = $smcFunc['db_query']('', '
  121. SELECT labels, is_read, COUNT(*) AS num
  122. FROM {db_prefix}pm_recipients
  123. WHERE id_member = {int:current_member}
  124. AND deleted = {int:not_deleted}
  125. GROUP BY labels, is_read',
  126. array(
  127. 'current_member' => $user_info['id'],
  128. 'not_deleted' => 0,
  129. )
  130. );
  131. while ($row = $smcFunc['db_fetch_assoc']($result))
  132. {
  133. $this_labels = explode(',', $row['labels']);
  134. foreach ($this_labels as $this_label)
  135. {
  136. $context['labels'][(int) $this_label]['messages'] += $row['num'];
  137. if (!($row['is_read'] & 1))
  138. $context['labels'][(int) $this_label]['unread_messages'] += $row['num'];
  139. }
  140. }
  141. $smcFunc['db_free_result']($result);
  142. // Store it please!
  143. cache_put_data('labelCounts:' . $user_info['id'], $context['labels'], 720);
  144. }
  145. // This determines if we have more labels than just the standard inbox.
  146. $context['currently_using_labels'] = count($context['labels']) > 1 ? 1 : 0;
  147. // Some stuff for the labels...
  148. $context['current_label_id'] = isset($_REQUEST['l']) && isset($context['labels'][(int) $_REQUEST['l']]) ? (int) $_REQUEST['l'] : -1;
  149. $context['current_label'] = &$context['labels'][(int) $context['current_label_id']]['name'];
  150. $context['folder'] = !isset($_REQUEST['f']) || $_REQUEST['f'] != 'sent' ? 'inbox' : 'sent';
  151. // This is convenient. Do you know how annoying it is to do this every time?!
  152. $context['current_label_redirect'] = 'action=pm;f=' . $context['folder'] . (isset($_GET['start']) ? ';start=' . $_GET['start'] : '') . (isset($_REQUEST['l']) ? ';l=' . $_REQUEST['l'] : '');
  153. $context['can_issue_warning'] = in_array('w', $context['admin_features']) && allowedTo('issue_warning') && $modSettings['warning_settings'][0] == 1;
  154. // Build the linktree for all the actions...
  155. $context['linktree'][] = array(
  156. 'url' => $scripturl . '?action=pm',
  157. 'name' => $txt['personal_messages']
  158. );
  159. // Preferences...
  160. $context['display_mode'] = WIRELESS ? 0 : $user_settings['pm_prefs'] & 3;
  161. $subActions = array(
  162. 'addbuddy' => 'WirelessAddBuddy',
  163. 'manlabels' => 'ManageLabels',
  164. 'manrules' => 'ManageRules',
  165. 'pmactions' => 'MessageActionsApply',
  166. 'prune' => 'MessagePrune',
  167. 'removeall' => 'MessageKillAllQuery',
  168. 'removeall2' => 'MessageKillAll',
  169. 'report' => 'ReportMessage',
  170. 'search' => 'MessageSearch',
  171. 'search2' => 'MessageSearch2',
  172. 'send' => 'MessagePost',
  173. 'send2' => 'MessagePost2',
  174. 'settings' => 'MessageSettings',
  175. );
  176. if (!isset($_REQUEST['sa']) || !isset($subActions[$_REQUEST['sa']]))
  177. MessageFolder();
  178. else
  179. {
  180. if (!isset($_REQUEST['xml']))
  181. messageIndexBar($_REQUEST['sa']);
  182. $subActions[$_REQUEST['sa']]();
  183. }
  184. }
  185. /**
  186. * A sidebar to easily access different areas of the section
  187. *
  188. * @param string $area
  189. */
  190. function messageIndexBar($area)
  191. {
  192. global $txt, $context, $scripturl, $sourcedir, $sc, $modSettings, $settings, $user_info, $options;
  193. $pm_areas = array(
  194. 'folders' => array(
  195. 'title' => $txt['pm_messages'],
  196. 'areas' => array(
  197. 'send' => array(
  198. 'label' => $txt['new_message'],
  199. 'custom_url' => $scripturl . '?action=pm;sa=send',
  200. 'permission' => allowedTo('pm_send'),
  201. ),
  202. 'inbox' => array(
  203. 'label' => $txt['inbox'],
  204. 'custom_url' => $scripturl . '?action=pm',
  205. ),
  206. 'sent' => array(
  207. 'label' => $txt['sent_items'],
  208. 'custom_url' => $scripturl . '?action=pm;f=sent',
  209. ),
  210. ),
  211. ),
  212. 'labels' => array(
  213. 'title' => $txt['pm_labels'],
  214. 'areas' => array(),
  215. ),
  216. 'actions' => array(
  217. 'title' => $txt['pm_actions'],
  218. 'areas' => array(
  219. 'search' => array(
  220. 'label' => $txt['pm_search_bar_title'],
  221. 'custom_url' => $scripturl . '?action=pm;sa=search',
  222. ),
  223. 'prune' => array(
  224. 'label' => $txt['pm_prune'],
  225. 'custom_url' => $scripturl . '?action=pm;sa=prune'
  226. ),
  227. ),
  228. ),
  229. 'pref' => array(
  230. 'title' => $txt['pm_preferences'],
  231. 'areas' => array(
  232. 'manlabels' => array(
  233. 'label' => $txt['pm_manage_labels'],
  234. 'custom_url' => $scripturl . '?action=pm;sa=manlabels',
  235. ),
  236. 'manrules' => array(
  237. 'label' => $txt['pm_manage_rules'],
  238. 'custom_url' => $scripturl . '?action=pm;sa=manrules',
  239. ),
  240. 'settings' => array(
  241. 'label' => $txt['pm_settings'],
  242. 'custom_url' => $scripturl . '?action=pm;sa=settings',
  243. ),
  244. ),
  245. ),
  246. );
  247. // Handle labels.
  248. if (empty($context['currently_using_labels']))
  249. unset($pm_areas['labels']);
  250. else
  251. {
  252. // Note we send labels by id as it will have less problems in the querystring.
  253. $unread_in_labels = 0;
  254. foreach ($context['labels'] as $label)
  255. {
  256. if ($label['id'] == -1)
  257. continue;
  258. // Count the amount of unread items in labels.
  259. $unread_in_labels += $label['unread_messages'];
  260. // Add the label to the menu.
  261. $pm_areas['labels']['areas']['label' . $label['id']] = array(
  262. 'label' => $label['name'] . (!empty($label['unread_messages']) ? ' (<strong>' . $label['unread_messages'] . '</strong>)' : ''),
  263. 'custom_url' => $scripturl . '?action=pm;l=' . $label['id'],
  264. 'unread_messages' => $label['unread_messages'],
  265. 'messages' => $label['messages'],
  266. );
  267. }
  268. if (!empty($unread_in_labels))
  269. $pm_areas['labels']['title'] .= ' (' . $unread_in_labels . ')';
  270. }
  271. $pm_areas['folders']['areas']['inbox']['unread_messages'] = &$context['labels'][-1]['unread_messages'];
  272. $pm_areas['folders']['areas']['inbox']['messages'] = &$context['labels'][-1]['messages'];
  273. if (!empty($context['labels'][-1]['unread_messages']))
  274. {
  275. $pm_areas['folders']['areas']['inbox']['label'] .= ' (<strong>' . $context['labels'][-1]['unread_messages'] . '</strong>)';
  276. $pm_areas['folders']['title'] .= ' (' . $context['labels'][-1]['unread_messages'] . ')';
  277. }
  278. // Do we have a limit on the amount of messages we can keep?
  279. if (!empty($context['message_limit']))
  280. {
  281. $bar = round(($user_info['messages'] * 100) / $context['message_limit'], 1);
  282. $context['limit_bar'] = array(
  283. 'messages' => $user_info['messages'],
  284. 'allowed' => $context['message_limit'],
  285. 'percent' => $bar,
  286. 'bar' => $bar > 100 ? 100 : (int) $bar,
  287. 'text' => sprintf($txt['pm_currently_using'], $user_info['messages'], $bar)
  288. );
  289. }
  290. require_once($sourcedir . '/Subs-Menu.php');
  291. // What page is this, again?
  292. $current_page = $scripturl . '?action=pm' . (!empty($_REQUEST['sa']) ? ';sa=' . $_REQUEST['sa'] : '') . (!empty($context['folder']) ? ';f=' . $context['folder'] : '') . (!empty($context['current_label_id']) ? ';l=' . $context['current_label_id'] : '');
  293. // Set a few options for the menu.
  294. $menuOptions = array(
  295. 'current_area' => $area,
  296. 'disable_url_session_check' => true,
  297. 'toggle_url' => $current_page . ';togglebar',
  298. 'toggle_redirect_url' => $current_page,
  299. );
  300. // Actually create the menu!
  301. $pm_include_data = createMenu($pm_areas, $menuOptions);
  302. unset($pm_areas);
  303. // Make a note of the Unique ID for this menu.
  304. $context['pm_menu_id'] = $context['max_menu_id'];
  305. $context['pm_menu_name'] = 'menu_data_' . $context['pm_menu_id'];
  306. // Set the selected item.
  307. $context['menu_item_selected'] = $pm_include_data['current_area'];
  308. // obExit will know what to do!
  309. if (!WIRELESS && !isset($_REQUEST['xml']))
  310. $context['template_layers'][] = 'pm';
  311. }
  312. /**
  313. * A folder, ie. inbox/sent etc.
  314. */
  315. function MessageFolder()
  316. {
  317. global $txt, $scripturl, $modSettings, $context, $subjects_request;
  318. global $messages_request, $user_info, $recipients, $options, $smcFunc, $memberContext, $user_settings;
  319. // Changing view?
  320. if (isset($_GET['view']))
  321. {
  322. $context['display_mode'] = $context['display_mode'] > 1 ? 0 : $context['display_mode'] + 1;
  323. updateMemberData($user_info['id'], array('pm_prefs' => ($user_settings['pm_prefs'] & 252) | $context['display_mode']));
  324. }
  325. // Make sure the starting location is valid.
  326. if (isset($_GET['start']) && $_GET['start'] != 'new')
  327. $_GET['start'] = (int) $_GET['start'];
  328. elseif (!isset($_GET['start']) && !empty($options['view_newest_pm_first']))
  329. $_GET['start'] = 0;
  330. else
  331. $_GET['start'] = 'new';
  332. // Set up some basic theme stuff.
  333. $context['from_or_to'] = $context['folder'] != 'sent' ? 'from' : 'to';
  334. $context['get_pmessage'] = 'prepareMessageContext';
  335. $context['signature_enabled'] = substr($modSettings['signature_settings'], 0, 1) == 1;
  336. $labelQuery = $context['folder'] != 'sent' ? '
  337. AND FIND_IN_SET(' . $context['current_label_id'] . ', pmr.labels) != 0' : '';
  338. // Set the index bar correct!
  339. messageIndexBar($context['current_label_id'] == -1 ? $context['folder'] : 'label' . $context['current_label_id']);
  340. // Sorting the folder.
  341. $sort_methods = array(
  342. 'date' => 'pm.id_pm',
  343. 'name' => 'IFNULL(mem.real_name, \'\')',
  344. 'subject' => 'pm.subject',
  345. );
  346. // They didn't pick one, use the forum default.
  347. if (!isset($_GET['sort']) || !isset($sort_methods[$_GET['sort']]))
  348. {
  349. $context['sort_by'] = 'date';
  350. $_GET['sort'] = 'pm.id_pm';
  351. // An overriding setting?
  352. $descending = !empty($options['view_newest_pm_first']);
  353. }
  354. // Otherwise use the defaults: ascending, by date.
  355. else
  356. {
  357. $context['sort_by'] = $_GET['sort'];
  358. $_GET['sort'] = $sort_methods[$_GET['sort']];
  359. $descending = isset($_GET['desc']);
  360. }
  361. $context['sort_direction'] = $descending ? 'down' : 'up';
  362. // Why would you want access to your sent items if you're not allowed to send anything?
  363. if ($context['folder'] == 'sent')
  364. isAllowedTo('pm_send');
  365. // Set the text to resemble the current folder.
  366. $pmbox = $context['folder'] != 'sent' ? $txt['inbox'] : $txt['sent_items'];
  367. $txt['delete_all'] = str_replace('PMBOX', $pmbox, $txt['delete_all']);
  368. // Now, build the link tree!
  369. if ($context['current_label_id'] == -1)
  370. $context['linktree'][] = array(
  371. 'url' => $scripturl . '?action=pm;f=' . $context['folder'],
  372. 'name' => $pmbox
  373. );
  374. // Build it further for a label.
  375. if ($context['current_label_id'] != -1)
  376. $context['linktree'][] = array(
  377. 'url' => $scripturl . '?action=pm;f=' . $context['folder'] . ';l=' . $context['current_label_id'],
  378. 'name' => $txt['pm_current_label'] . ': ' . $context['current_label']
  379. );
  380. // Figure out how many messages there are.
  381. if ($context['folder'] == 'sent')
  382. $request = $smcFunc['db_query']('', '
  383. SELECT COUNT(' . ($context['display_mode'] == 2 ? 'DISTINCT pm.id_pm_head' : '*') . ')
  384. FROM {db_prefix}personal_messages AS pm
  385. WHERE pm.id_member_from = {int:current_member}
  386. AND pm.deleted_by_sender = {int:not_deleted}',
  387. array(
  388. 'current_member' => $user_info['id'],
  389. 'not_deleted' => 0,
  390. )
  391. );
  392. else
  393. $request = $smcFunc['db_query']('', '
  394. SELECT COUNT(' . ($context['display_mode'] == 2 ? 'DISTINCT pm.id_pm_head' : '*') . ')
  395. FROM {db_prefix}pm_recipients AS pmr' . ($context['display_mode'] == 2 ? '
  396. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)' : '') . '
  397. WHERE pmr.id_member = {int:current_member}
  398. AND pmr.deleted = {int:not_deleted}' . $labelQuery,
  399. array(
  400. 'current_member' => $user_info['id'],
  401. 'not_deleted' => 0,
  402. )
  403. );
  404. list ($max_messages) = $smcFunc['db_fetch_row']($request);
  405. $smcFunc['db_free_result']($request);
  406. // Only show the button if there are messages to delete.
  407. $context['show_delete'] = $max_messages > 0;
  408. // Start on the last page.
  409. if (!is_numeric($_GET['start']) || $_GET['start'] >= $max_messages)
  410. $_GET['start'] = ($max_messages - 1) - (($max_messages - 1) % $modSettings['defaultMaxMessages']);
  411. elseif ($_GET['start'] < 0)
  412. $_GET['start'] = 0;
  413. // ... but wait - what if we want to start from a specific message?
  414. if (isset($_GET['pmid']))
  415. {
  416. $pmID = (int) $_GET['pmid'];
  417. // Make sure you have access to this PM.
  418. if (!isAccessiblePM($pmID, $context['folder'] == 'sent' ? 'outbox' : 'inbox'))
  419. fatal_lang_error('no_access', false);
  420. $context['current_pm'] = $pmID;
  421. // With only one page of PM's we're gonna want page 1.
  422. if ($max_messages <= $modSettings['defaultMaxMessages'])
  423. $_GET['start'] = 0;
  424. // If we pass kstart we assume we're in the right place.
  425. elseif (!isset($_GET['kstart']))
  426. {
  427. if ($context['folder'] == 'sent')
  428. $request = $smcFunc['db_query']('', '
  429. SELECT COUNT(' . ($context['display_mode'] == 2 ? 'DISTINCT pm.id_pm_head' : '*') . ')
  430. FROM {db_prefix}personal_messages
  431. WHERE id_member_from = {int:current_member}
  432. AND deleted_by_sender = {int:not_deleted}
  433. AND id_pm ' . ($descending ? '>' : '<') . ' {int:id_pm}',
  434. array(
  435. 'current_member' => $user_info['id'],
  436. 'not_deleted' => 0,
  437. 'id_pm' => $pmID,
  438. )
  439. );
  440. else
  441. $request = $smcFunc['db_query']('', '
  442. SELECT COUNT(' . ($context['display_mode'] == 2 ? 'DISTINCT pm.id_pm_head' : '*') . ')
  443. FROM {db_prefix}pm_recipients AS pmr' . ($context['display_mode'] == 2 ? '
  444. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)' : '') . '
  445. WHERE pmr.id_member = {int:current_member}
  446. AND pmr.deleted = {int:not_deleted}' . $labelQuery . '
  447. AND pmr.id_pm ' . ($descending ? '>' : '<') . ' {int:id_pm}',
  448. array(
  449. 'current_member' => $user_info['id'],
  450. 'not_deleted' => 0,
  451. 'id_pm' => $pmID,
  452. )
  453. );
  454. list ($_GET['start']) = $smcFunc['db_fetch_row']($request);
  455. $smcFunc['db_free_result']($request);
  456. // To stop the page index's being abnormal, start the page on the page the message would normally be located on...
  457. $_GET['start'] = $modSettings['defaultMaxMessages'] * (int) ($_GET['start'] / $modSettings['defaultMaxMessages']);
  458. }
  459. }
  460. // Sanitize and validate pmsg variable if set.
  461. if (isset($_GET['pmsg']))
  462. {
  463. $pmsg = (int) $_GET['pmsg'];
  464. if (!isAccessiblePM($pmsg, $context['folder'] == 'sent' ? 'outbox' : 'inbox'))
  465. fatal_lang_error('no_access', false);
  466. }
  467. // Set up the page index.
  468. $context['page_index'] = constructPageIndex($scripturl . '?action=pm;f=' . $context['folder'] . (isset($_REQUEST['l']) ? ';l=' . (int) $_REQUEST['l'] : '') . ';sort=' . $context['sort_by'] . ($descending ? ';desc' : ''), $_GET['start'], $max_messages, $modSettings['defaultMaxMessages']);
  469. $context['start'] = $_GET['start'];
  470. // Determine the navigation context (especially useful for the wireless template).
  471. $context['links'] = array(
  472. 'first' => $_GET['start'] >= $modSettings['defaultMaxMessages'] ? $scripturl . '?action=pm;start=0' : '',
  473. 'prev' => $_GET['start'] >= $modSettings['defaultMaxMessages'] ? $scripturl . '?action=pm;start=' . ($_GET['start'] - $modSettings['defaultMaxMessages']) : '',
  474. 'next' => $_GET['start'] + $modSettings['defaultMaxMessages'] < $max_messages ? $scripturl . '?action=pm;start=' . ($_GET['start'] + $modSettings['defaultMaxMessages']) : '',
  475. 'last' => $_GET['start'] + $modSettings['defaultMaxMessages'] < $max_messages ? $scripturl . '?action=pm;start=' . (floor(($max_messages - 1) / $modSettings['defaultMaxMessages']) * $modSettings['defaultMaxMessages']) : '',
  476. 'up' => $scripturl,
  477. );
  478. $context['page_info'] = array(
  479. 'current_page' => $_GET['start'] / $modSettings['defaultMaxMessages'] + 1,
  480. 'num_pages' => floor(($max_messages - 1) / $modSettings['defaultMaxMessages']) + 1
  481. );
  482. // First work out what messages we need to see - if grouped is a little trickier...
  483. if ($context['display_mode'] == 2)
  484. {
  485. // On a non-default sort due to PostgreSQL we have to do a harder sort.
  486. if ($smcFunc['db_title'] == 'PostgreSQL' && $_GET['sort'] != 'pm.id_pm')
  487. {
  488. $sub_request = $smcFunc['db_query']('', '
  489. SELECT MAX({raw:sort}) AS sort_param, pm.id_pm_head
  490. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? ($context['sort_by'] == 'name' ? '
  491. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') : '
  492. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm
  493. AND pmr.id_member = {int:current_member}
  494. AND pmr.deleted = {int:not_deleted}
  495. ' . $labelQuery . ')') . ($context['sort_by'] == 'name' ? ( '
  496. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:id_member})') : '') . '
  497. WHERE ' . ($context['folder'] == 'sent' ? 'pm.id_member_from = {int:current_member}
  498. AND pm.deleted_by_sender = {int:not_deleted}' : '1=1') . (empty($pmsg) ? '' : '
  499. AND pm.id_pm = {int:id_pm}') . '
  500. GROUP BY pm.id_pm_head
  501. ORDER BY sort_param' . ($descending ? ' DESC' : ' ASC') . (empty($pmsg) ? '
  502. LIMIT ' . $_GET['start'] . ', ' . $modSettings['defaultMaxMessages'] : ''),
  503. array(
  504. 'current_member' => $user_info['id'],
  505. 'not_deleted' => 0,
  506. 'id_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  507. 'id_pm' => isset($pmsg) ? $pmsg : '0',
  508. 'sort' => $_GET['sort'],
  509. )
  510. );
  511. $sub_pms = array();
  512. while ($row = $smcFunc['db_fetch_assoc']($sub_request))
  513. $sub_pms[$row['id_pm_head']] = $row['sort_param'];
  514. $smcFunc['db_free_result']($sub_request);
  515. $request = $smcFunc['db_query']('', '
  516. SELECT pm.id_pm AS id_pm, pm.id_pm_head
  517. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? ($context['sort_by'] == 'name' ? '
  518. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') : '
  519. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm
  520. AND pmr.id_member = {int:current_member}
  521. AND pmr.deleted = {int:not_deleted}
  522. ' . $labelQuery . ')') . ($context['sort_by'] == 'name' ? ( '
  523. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:id_member})') : '') . '
  524. WHERE ' . (empty($sub_pms) ? '0=1' : 'pm.id_pm IN ({array_int:pm_list})') . '
  525. ORDER BY ' . ($_GET['sort'] == 'pm.id_pm' && $context['folder'] != 'sent' ? 'id_pm' : '{raw:sort}') . ($descending ? ' DESC' : ' ASC') . (empty($pmsg) ? '
  526. LIMIT ' . $_GET['start'] . ', ' . $modSettings['defaultMaxMessages'] : ''),
  527. array(
  528. 'current_member' => $user_info['id'],
  529. 'pm_list' => array_keys($sub_pms),
  530. 'not_deleted' => 0,
  531. 'sort' => $_GET['sort'],
  532. 'id_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  533. )
  534. );
  535. }
  536. else
  537. {
  538. $request = $smcFunc['db_query']('pm_conversation_list', '
  539. SELECT MAX(pm.id_pm) AS id_pm, pm.id_pm_head
  540. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? ($context['sort_by'] == 'name' ? '
  541. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') : '
  542. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm
  543. AND pmr.id_member = {int:current_member}
  544. AND pmr.deleted = {int:deleted_by}
  545. ' . $labelQuery . ')') . ($context['sort_by'] == 'name' ? ( '
  546. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:pm_member})') : '') . '
  547. WHERE ' . ($context['folder'] == 'sent' ? 'pm.id_member_from = {int:current_member}
  548. AND pm.deleted_by_sender = {int:deleted_by}' : '1=1') . (empty($pmsg) ? '' : '
  549. AND pm.id_pm = {int:pmsg}') . '
  550. GROUP BY pm.id_pm_head
  551. ORDER BY ' . ($_GET['sort'] == 'pm.id_pm' && $context['folder'] != 'sent' ? 'id_pm' : '{raw:sort}') . ($descending ? ' DESC' : ' ASC') . (empty($_GET['pmsg']) ? '
  552. LIMIT ' . $_GET['start'] . ', ' . $modSettings['defaultMaxMessages'] : ''),
  553. array(
  554. 'current_member' => $user_info['id'],
  555. 'deleted_by' => 0,
  556. 'sort' => $_GET['sort'],
  557. 'pm_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  558. 'pmsg' => isset($pmsg) ? (int) $pmsg : 0,
  559. )
  560. );
  561. }
  562. }
  563. // This is kinda simple!
  564. else
  565. {
  566. // @todo SLOW This query uses a filesort. (inbox only.)
  567. $request = $smcFunc['db_query']('', '
  568. SELECT pm.id_pm, pm.id_pm_head, pm.id_member_from
  569. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? '' . ($context['sort_by'] == 'name' ? '
  570. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') : '
  571. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm
  572. AND pmr.id_member = {int:current_member}
  573. AND pmr.deleted = {int:is_deleted}
  574. ' . $labelQuery . ')') . ($context['sort_by'] == 'name' ? ( '
  575. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:pm_member})') : '') . '
  576. WHERE ' . ($context['folder'] == 'sent' ? 'pm.id_member_from = {raw:current_member}
  577. AND pm.deleted_by_sender = {int:is_deleted}' : '1=1') . (empty($pmsg) ? '' : '
  578. AND pm.id_pm = {int:pmsg}') . '
  579. ORDER BY ' . ($_GET['sort'] == 'pm.id_pm' && $context['folder'] != 'sent' ? 'pmr.id_pm' : '{raw:sort}') . ($descending ? ' DESC' : ' ASC') . (empty($pmsg) ? '
  580. LIMIT ' . $_GET['start'] . ', ' . $modSettings['defaultMaxMessages'] : ''),
  581. array(
  582. 'current_member' => $user_info['id'],
  583. 'is_deleted' => 0,
  584. 'sort' => $_GET['sort'],
  585. 'pm_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  586. 'pmsg' => isset($pmsg) ? (int) $pmsg : 0,
  587. )
  588. );
  589. }
  590. // Load the id_pms and initialize recipients.
  591. $pms = array();
  592. $lastData = array();
  593. $posters = $context['folder'] == 'sent' ? array($user_info['id']) : array();
  594. $recipients = array();
  595. while ($row = $smcFunc['db_fetch_assoc']($request))
  596. {
  597. if (!isset($recipients[$row['id_pm']]))
  598. {
  599. if (isset($row['id_member_from']))
  600. $posters[$row['id_pm']] = $row['id_member_from'];
  601. $pms[$row['id_pm']] = $row['id_pm'];
  602. $recipients[$row['id_pm']] = array(
  603. 'to' => array(),
  604. 'bcc' => array()
  605. );
  606. }
  607. // Keep track of the last message so we know what the head is without another query!
  608. if ((empty($pmID) && (empty($options['view_newest_pm_first']) || !isset($lastData))) || empty($lastData) || (!empty($pmID) && $pmID == $row['id_pm']))
  609. $lastData = array(
  610. 'id' => $row['id_pm'],
  611. 'head' => $row['id_pm_head'],
  612. );
  613. }
  614. $smcFunc['db_free_result']($request);
  615. // Make sure that we have been given a correct head pm id!
  616. if ($context['display_mode'] == 2 && !empty($pmID) && $pmID != $lastData['id'])
  617. fatal_lang_error('no_access', false);
  618. if (!empty($pms))
  619. {
  620. // Select the correct current message.
  621. if (empty($pmID))
  622. $context['current_pm'] = $lastData['id'];
  623. // This is a list of the pm's that are used for "full" display.
  624. if ($context['display_mode'] == 0)
  625. $display_pms = $pms;
  626. else
  627. $display_pms = array($context['current_pm']);
  628. // At this point we know the main id_pm's. But - if we are looking at conversations we need the others!
  629. if ($context['display_mode'] == 2)
  630. {
  631. $request = $smcFunc['db_query']('', '
  632. SELECT pm.id_pm, pm.id_member_from, pm.deleted_by_sender, pmr.id_member, pmr.deleted
  633. FROM {db_prefix}personal_messages AS pm
  634. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)
  635. WHERE pm.id_pm_head = {int:id_pm_head}
  636. AND ((pm.id_member_from = {int:current_member} AND pm.deleted_by_sender = {int:not_deleted})
  637. OR (pmr.id_member = {int:current_member} AND pmr.deleted = {int:not_deleted}))
  638. ORDER BY pm.id_pm',
  639. array(
  640. 'current_member' => $user_info['id'],
  641. 'id_pm_head' => $lastData['head'],
  642. 'not_deleted' => 0,
  643. )
  644. );
  645. while ($row = $smcFunc['db_fetch_assoc']($request))
  646. {
  647. // This is, frankly, a joke. We will put in a workaround for people sending to themselves - yawn!
  648. if ($context['folder'] == 'sent' && $row['id_member_from'] == $user_info['id'] && $row['deleted_by_sender'] == 1)
  649. continue;
  650. elseif ($row['id_member'] == $user_info['id'] & $row['deleted'] == 1)
  651. continue;
  652. if (!isset($recipients[$row['id_pm']]))
  653. $recipients[$row['id_pm']] = array(
  654. 'to' => array(),
  655. 'bcc' => array()
  656. );
  657. $display_pms[] = $row['id_pm'];
  658. $posters[$row['id_pm']] = $row['id_member_from'];
  659. }
  660. $smcFunc['db_free_result']($request);
  661. }
  662. // This is pretty much EVERY pm!
  663. $all_pms = array_merge($pms, $display_pms);
  664. $all_pms = array_unique($all_pms);
  665. // Get recipients (don't include bcc-recipients for your inbox, you're not supposed to know :P).
  666. $request = $smcFunc['db_query']('', '
  667. SELECT pmr.id_pm, mem_to.id_member AS id_member_to, mem_to.real_name AS to_name, pmr.bcc, pmr.labels, pmr.is_read
  668. FROM {db_prefix}pm_recipients AS pmr
  669. LEFT JOIN {db_prefix}members AS mem_to ON (mem_to.id_member = pmr.id_member)
  670. WHERE pmr.id_pm IN ({array_int:pm_list})',
  671. array(
  672. 'pm_list' => $all_pms,
  673. )
  674. );
  675. $context['message_labels'] = array();
  676. $context['message_replied'] = array();
  677. $context['message_unread'] = array();
  678. while ($row = $smcFunc['db_fetch_assoc']($request))
  679. {
  680. if ($context['folder'] == 'sent' || empty($row['bcc']))
  681. $recipients[$row['id_pm']][empty($row['bcc']) ? 'to' : 'bcc'][] = empty($row['id_member_to']) ? $txt['guest_title'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_to'] . '">' . $row['to_name'] . '</a>';
  682. if ($row['id_member_to'] == $user_info['id'] && $context['folder'] != 'sent')
  683. {
  684. $context['message_replied'][$row['id_pm']] = $row['is_read'] & 2;
  685. $context['message_unread'][$row['id_pm']] = $row['is_read'] == 0;
  686. $row['labels'] = $row['labels'] == '' ? array() : explode(',', $row['labels']);
  687. foreach ($row['labels'] as $v)
  688. {
  689. if (isset($context['labels'][(int) $v]))
  690. $context['message_labels'][$row['id_pm']][(int) $v] = array('id' => $v, 'name' => $context['labels'][(int) $v]['name']);
  691. }
  692. }
  693. }
  694. $smcFunc['db_free_result']($request);
  695. // Make sure we don't load unnecessary data.
  696. if ($context['display_mode'] == 1)
  697. {
  698. foreach ($posters as $k => $v)
  699. if (!in_array($k, $display_pms))
  700. unset($posters[$k]);
  701. }
  702. // Load any users....
  703. $posters = array_unique($posters);
  704. if (!empty($posters))
  705. loadMemberData($posters);
  706. // If we're on grouped/restricted view get a restricted list of messages.
  707. if ($context['display_mode'] != 0)
  708. {
  709. // Get the order right.
  710. $orderBy = array();
  711. foreach (array_reverse($pms) as $pm)
  712. $orderBy[] = 'pm.id_pm = ' . $pm;
  713. // Seperate query for these bits!
  714. $subjects_request = $smcFunc['db_query']('', '
  715. SELECT pm.id_pm, pm.subject, pm.id_member_from, pm.msgtime, IFNULL(mem.real_name, pm.from_name) AS from_name,
  716. IFNULL(mem.id_member, 0) AS not_guest
  717. FROM {db_prefix}personal_messages AS pm
  718. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = pm.id_member_from)
  719. WHERE pm.id_pm IN ({array_int:pm_list})
  720. ORDER BY ' . implode(', ', $orderBy) . '
  721. LIMIT ' . count($pms),
  722. array(
  723. 'pm_list' => $pms,
  724. )
  725. );
  726. }
  727. // Execute the query!
  728. $messages_request = $smcFunc['db_query']('', '
  729. SELECT pm.id_pm, pm.subject, pm.id_member_from, pm.body, pm.msgtime, pm.from_name
  730. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? '
  731. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') . ($context['sort_by'] == 'name' ? '
  732. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:id_member})' : '') . '
  733. WHERE pm.id_pm IN ({array_int:display_pms})' . ($context['folder'] == 'sent' ? '
  734. GROUP BY pm.id_pm, pm.subject, pm.id_member_from, pm.body, pm.msgtime, pm.from_name' : '') . '
  735. ORDER BY ' . ($context['display_mode'] == 2 ? 'pm.id_pm' : $_GET['sort']) . ($descending ? ' DESC' : ' ASC') . '
  736. LIMIT ' . count($display_pms),
  737. array(
  738. 'display_pms' => $display_pms,
  739. 'id_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  740. )
  741. );
  742. }
  743. else
  744. $messages_request = false;
  745. $context['can_send_pm'] = allowedTo('pm_send');
  746. if (!WIRELESS)
  747. $context['sub_template'] = 'folder';
  748. $context['page_title'] = $txt['pm_inbox'];
  749. // Finally mark the relevant messages as read.
  750. if ($context['folder'] != 'sent' && !empty($context['labels'][(int) $context['current_label_id']]['unread_messages']))
  751. {
  752. // If the display mode is "old sk00l" do them all...
  753. if ($context['display_mode'] == 0)
  754. markMessages(null, $context['current_label_id']);
  755. // Otherwise do just the current one!
  756. elseif (!empty($context['current_pm']))
  757. markMessages($display_pms, $context['current_label_id']);
  758. }
  759. }
  760. /**
  761. * Get a personal message for the theme. (used to save memory.)
  762. *
  763. * @param $type
  764. * @param $reset
  765. */
  766. function prepareMessageContext($type = 'subject', $reset = false)
  767. {
  768. global $txt, $scripturl, $modSettings, $context, $messages_request, $memberContext, $recipients, $smcFunc;
  769. global $user_info, $subjects_request;
  770. // Count the current message number....
  771. static $counter = null;
  772. if ($counter === null || $reset)
  773. $counter = $context['start'];
  774. static $temp_pm_selected = null;
  775. if ($temp_pm_selected === null)
  776. {
  777. $temp_pm_selected = isset($_SESSION['pm_selected']) ? $_SESSION['pm_selected'] : array();
  778. $_SESSION['pm_selected'] = array();
  779. }
  780. // If we're in non-boring view do something exciting!
  781. if ($context['display_mode'] != 0 && $subjects_request && $type == 'subject')
  782. {
  783. $subject = $smcFunc['db_fetch_assoc']($subjects_request);
  784. if (!$subject)
  785. {
  786. $smcFunc['db_free_result']($subjects_request);
  787. return false;
  788. }
  789. $subject['subject'] = $subject['subject'] == '' ? $txt['no_subject'] : $subject['subject'];
  790. censorText($subject['subject']);
  791. $output = array(
  792. 'id' => $subject['id_pm'],
  793. 'member' => array(
  794. 'id' => $subject['id_member_from'],
  795. 'name' => $subject['from_name'],
  796. 'link' => $subject['not_guest'] ? '<a href="' . $scripturl . '?action=profile;u=' . $subject['id_member_from'] . '">' . $subject['from_name'] . '</a>' : $subject['from_name'],
  797. ),
  798. 'recipients' => &$recipients[$subject['id_pm']],
  799. 'subject' => $subject['subject'],
  800. 'time' => timeformat($subject['msgtime']),
  801. 'timestamp' => forum_time(true, $subject['msgtime']),
  802. 'number_recipients' => count($recipients[$subject['id_pm']]['to']),
  803. 'labels' => &$context['message_labels'][$subject['id_pm']],
  804. 'fully_labeled' => count($context['message_labels'][$subject['id_pm']]) == count($context['labels']),
  805. 'is_replied_to' => &$context['message_replied'][$subject['id_pm']],
  806. 'is_unread' => &$context['message_unread'][$subject['id_pm']],
  807. 'is_selected' => !empty($temp_pm_selected) && in_array($subject['id_pm'], $temp_pm_selected),
  808. );
  809. return $output;
  810. }
  811. // Bail if it's false, ie. no messages.
  812. if ($messages_request == false)
  813. return false;
  814. // Reset the data?
  815. if ($reset == true)
  816. return @$smcFunc['db_data_seek']($messages_request, 0);
  817. // Get the next one... bail if anything goes wrong.
  818. $message = $smcFunc['db_fetch_assoc']($messages_request);
  819. if (!$message)
  820. {
  821. if ($type != 'subject')
  822. $smcFunc['db_free_result']($messages_request);
  823. return false;
  824. }
  825. // Use '(no subject)' if none was specified.
  826. $message['subject'] = $message['subject'] == '' ? $txt['no_subject'] : $message['subject'];
  827. // Load the message's information - if it's not there, load the guest information.
  828. if (!loadMemberContext($message['id_member_from'], true))
  829. {
  830. $memberContext[$message['id_member_from']]['name'] = $message['from_name'];
  831. $memberContext[$message['id_member_from']]['id'] = 0;
  832. // Sometimes the forum sends messages itself (Warnings are an example) - in this case don't label it from a guest.
  833. $memberContext[$message['id_member_from']]['group'] = $message['from_name'] == $context['forum_name'] ? '' : $txt['guest_title'];
  834. $memberContext[$message['id_member_from']]['link'] = $message['from_name'];
  835. $memberContext[$message['id_member_from']]['email'] = '';
  836. $memberContext[$message['id_member_from']]['show_email'] = showEmailAddress(true, 0);
  837. $memberContext[$message['id_member_from']]['is_guest'] = true;
  838. }
  839. else
  840. {
  841. $memberContext[$message['id_member_from']]['can_view_profile'] = allowedTo('profile_view_any') || ($message['id_member_from'] == $user_info['id'] && allowedTo('profile_view_own'));
  842. $memberContext[$message['id_member_from']]['can_see_warning'] = !isset($context['disabled_fields']['warning_status']) && $memberContext[$message['id_member_from']]['warning_status'] && ($context['user']['can_mod'] || (!empty($modSettings['warning_show']) && ($modSettings['warning_show'] > 1 || $message['id_member_from'] == $user_info['id'])));
  843. }
  844. // Censor all the important text...
  845. censorText($message['body']);
  846. censorText($message['subject']);
  847. // Run UBBC interpreter on the message.
  848. $message['body'] = parse_bbc($message['body'], true, 'pm' . $message['id_pm']);
  849. // Send the array.
  850. $output = array(
  851. 'alternate' => $counter % 2,
  852. 'id' => $message['id_pm'],
  853. 'member' => &$memberContext[$message['id_member_from']],
  854. 'subject' => $message['subject'],
  855. 'time' => timeformat($message['msgtime']),
  856. 'timestamp' => forum_time(true, $message['msgtime']),
  857. 'counter' => $counter,
  858. 'body' => $message['body'],
  859. 'recipients' => &$recipients[$message['id_pm']],
  860. 'number_recipients' => count($recipients[$message['id_pm']]['to']),
  861. 'labels' => &$context['message_labels'][$message['id_pm']],
  862. 'fully_labeled' => count($context['message_labels'][$message['id_pm']]) == count($context['labels']),
  863. 'is_replied_to' => &$context['message_replied'][$message['id_pm']],
  864. 'is_unread' => &$context['message_unread'][$message['id_pm']],
  865. 'is_selected' => !empty($temp_pm_selected) && in_array($message['id_pm'], $temp_pm_selected),
  866. );
  867. $counter++;
  868. return $output;
  869. }
  870. /**
  871. * Allows to search through personal messages.
  872. */
  873. function MessageSearch()
  874. {
  875. global $context, $txt, $scripturl, $modSettings, $smcFunc;
  876. if (isset($_REQUEST['params']))
  877. {
  878. $temp_params = explode('|"|', base64_decode(strtr($_REQUEST['params'], array(' ' => '+'))));
  879. $context['search_params'] = array();
  880. foreach ($temp_params as $i => $data)
  881. {
  882. @list ($k, $v) = explode('|\'|', $data);
  883. $context['search_params'][$k] = $v;
  884. }
  885. }
  886. if (isset($_REQUEST['search']))
  887. $context['search_params']['search'] = un_htmlspecialchars($_REQUEST['search']);
  888. if (isset($context['search_params']['search']))
  889. $context['search_params']['search'] = htmlspecialchars($context['search_params']['search']);
  890. if (isset($context['search_params']['userspec']))
  891. $context['search_params']['userspec'] = htmlspecialchars($context['search_params']['userspec']);
  892. if (!empty($context['search_params']['searchtype']))
  893. $context['search_params']['searchtype'] = 2;
  894. if (!empty($context['search_params']['minage']))
  895. $context['search_params']['minage'] = (int) $context['search_params']['minage'];
  896. if (!empty($context['search_params']['maxage']))
  897. $context['search_params']['maxage'] = (int) $context['search_params']['maxage'];
  898. $context['search_params']['subject_only'] = !empty($context['search_params']['subject_only']);
  899. $context['search_params']['show_complete'] = !empty($context['search_params']['show_complete']);
  900. // Create the array of labels to be searched.
  901. $context['search_labels'] = array();
  902. $searchedLabels = isset($context['search_params']['labels']) && $context['search_params']['labels'] != '' ? explode(',', $context['search_params']['labels']) : array();
  903. foreach ($context['labels'] as $label)
  904. {
  905. $context['search_labels'][] = array(
  906. 'id' => $label['id'],
  907. 'name' => $label['name'],
  908. 'checked' => !empty($searchedLabels) ? in_array($label['id'], $searchedLabels) : true,
  909. );
  910. }
  911. // Are all the labels checked?
  912. $context['check_all'] = empty($searchedLabels) || count($context['search_labels']) == count($searchedLabels);
  913. // Load the error text strings if there were errors in the search.
  914. if (!empty($context['search_errors']))
  915. {
  916. loadLanguage('Errors');
  917. $context['search_errors']['messages'] = array();
  918. foreach ($context['search_errors'] as $search_error => $dummy)
  919. {
  920. if ($search_error == 'messages')
  921. continue;
  922. $context['search_errors']['messages'][] = $txt['error_' . $search_error];
  923. }
  924. }
  925. $context['simple_search'] = isset($context['search_params']['advanced']) ? empty($context['search_params']['advanced']) : !empty($modSettings['simpleSearch']) && !isset($_REQUEST['advanced']);
  926. $context['page_title'] = $txt['pm_search_title'];
  927. $context['sub_template'] = 'search';
  928. $context['linktree'][] = array(
  929. 'url' => $scripturl . '?action=pm;sa=search',
  930. 'name' => $txt['pm_search_bar_title'],
  931. );
  932. }
  933. /**
  934. * Actually do the search of personal messages.
  935. */
  936. function MessageSearch2()
  937. {
  938. global $scripturl, $modSettings, $user_info, $context, $txt;
  939. global $memberContext, $smcFunc;
  940. if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
  941. fatal_lang_error('loadavg_search_disabled', false);
  942. /**
  943. * @todo For the moment force the folder to the inbox.
  944. * @todo Maybe set the inbox based on a cookie or theme setting?
  945. */
  946. $context['folder'] = 'inbox';
  947. // Some useful general permissions.
  948. $context['can_send_pm'] = allowedTo('pm_send');
  949. // Some hardcoded veriables that can be tweaked if required.
  950. $maxMembersToSearch = 500;
  951. // Extract all the search parameters.
  952. $search_params = array();
  953. if (isset($_REQUEST['params']))
  954. {
  955. $temp_params = explode('|"|', base64_decode(strtr($_REQUEST['params'], array(' ' => '+'))));
  956. foreach ($temp_params as $i => $data)
  957. {
  958. @list ($k, $v) = explode('|\'|', $data);
  959. $search_params[$k] = $v;
  960. }
  961. }
  962. $context['start'] = isset($_GET['start']) ? (int) $_GET['start'] : 0;
  963. // Store whether simple search was used (needed if the user wants to do another query).
  964. if (!isset($search_params['advanced']))
  965. $search_params['advanced'] = empty($_REQUEST['advanced']) ? 0 : 1;
  966. // 1 => 'allwords' (default, don't set as param) / 2 => 'anywords'.
  967. if (!empty($search_params['searchtype']) || (!empty($_REQUEST['searchtype']) && $_REQUEST['searchtype'] == 2))
  968. $search_params['searchtype'] = 2;
  969. // Minimum age of messages. Default to zero (don't set param in that case).
  970. if (!empty($search_params['minage']) || (!empty($_REQUEST['minage']) && $_REQUEST['minage'] > 0))
  971. $search_params['minage'] = !empty($search_params['minage']) ? (int) $search_params['minage'] : (int) $_REQUEST['minage'];
  972. // Maximum age of messages. Default to infinite (9999 days: param not set).
  973. if (!empty($search_params['maxage']) || (!empty($_REQUEST['maxage']) && $_REQUEST['maxage'] != 9999))
  974. $search_params['maxage'] = !empty($search_params['maxage']) ? (int) $search_params['maxage'] : (int) $_REQUEST['maxage'];
  975. $search_params['subject_only'] = !empty($search_params['subject_only']) || !empty($_REQUEST['subject_only']);
  976. $search_params['show_complete'] = !empty($search_params['show_complete']) || !empty($_REQUEST['show_complete']);
  977. // Default the user name to a wildcard matching every user (*).
  978. if (!empty($search_params['user_spec']) || (!empty($_REQUEST['userspec']) && $_REQUEST['userspec'] != '*'))
  979. $search_params['userspec'] = isset($search_params['userspec']) ? $search_params['userspec'] : $_REQUEST['userspec'];
  980. // This will be full of all kinds of parameters!
  981. $searchq_parameters = array();
  982. // If there's no specific user, then don't mention it in the main query.
  983. if (empty($search_params['userspec']))
  984. $userQuery = '';
  985. else
  986. {
  987. $userString = strtr($smcFunc['htmlspecialchars']($search_params['userspec'], ENT_QUOTES), array('&quot;' => '"'));
  988. $userString = strtr($userString, array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_'));
  989. preg_match_all('~"([^"]+)"~', $userString, $matches);
  990. $possible_users = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $userString)));
  991. for ($k = 0, $n = count($possible_users); $k < $n; $k++)
  992. {
  993. $possible_users[$k] = trim($possible_users[$k]);
  994. if (strlen($possible_users[$k]) == 0)
  995. unset($possible_users[$k]);
  996. }
  997. // Who matches those criteria?
  998. // @todo This doesn't support sent item searching.
  999. $request = $smcFunc['db_query']('', '
  1000. SELECT id_member
  1001. FROM {db_prefix}members
  1002. WHERE real_name LIKE {raw:real_name_implode}',
  1003. array(
  1004. 'real_name_implode' => '\'' . implode('\' OR real_name LIKE \'', $possible_users) . '\'',
  1005. )
  1006. );
  1007. // Simply do nothing if there're too many members matching the criteria.
  1008. if ($smcFunc['db_num_rows']($request) > $maxMembersToSearch)
  1009. $userQuery = '';
  1010. elseif ($smcFunc['db_num_rows']($request) == 0)
  1011. {
  1012. $userQuery = 'AND pm.id_member_from = 0 AND (pm.from_name LIKE {raw:guest_user_name_implode})';
  1013. $searchq_parameters['guest_user_name_implode'] = '\'' . implode('\' OR pm.from_name LIKE \'', $possible_users) . '\'';
  1014. }
  1015. else
  1016. {
  1017. $memberlist = array();
  1018. while ($row = $smcFunc['db_fetch_assoc']($request))
  1019. $memberlist[] = $row['id_member'];
  1020. $userQuery = 'AND (pm.id_member_from IN ({array_int:member_list}) OR (pm.id_member_from = 0 AND (pm.from_name LIKE {raw:guest_user_name_implode})))';
  1021. $searchq_parameters['guest_user_name_implode'] = '\'' . implode('\' OR pm.from_name LIKE \'', $possible_users) . '\'';
  1022. $searchq_parameters['member_list'] = $memberlist;
  1023. }
  1024. $smcFunc['db_free_result']($request);
  1025. }
  1026. // Setup the sorting variables...
  1027. // @todo Add more in here!
  1028. $sort_columns = array(
  1029. 'pm.id_pm',
  1030. );
  1031. if (empty($search_params['sort']) && !empty($_REQUEST['sort']))
  1032. list ($search_params['sort'], $search_params['sort_dir']) = array_pad(explode('|', $_REQUEST['sort']), 2, '');
  1033. $search_params['sort'] = !empty($search_params['sort']) && in_array($search_params['sort'], $sort_columns) ? $search_params['sort'] : 'pm.id_pm';
  1034. $search_params['sort_dir'] = !empty($search_params['sort_dir']) && $search_params['sort_dir'] == 'asc' ? 'asc' : 'desc';
  1035. // Sort out any labels we may be searching by.
  1036. $labelQuery = '';
  1037. if ($context['folder'] == 'inbox' && !empty($search_params['advanced']) && $context['currently_using_labels'])
  1038. {
  1039. // Came here from pagination? Put them back into $_REQUEST for sanitization.
  1040. if (isset($search_params['labels']))
  1041. $_REQUEST['searchlabel'] = explode(',', $search_params['labels']);
  1042. // Assuming we have some labels - make them all integers.
  1043. if (!empty($_REQUEST['searchlabel']) && is_array($_REQUEST['searchlabel']))
  1044. {
  1045. foreach ($_REQUEST['searchlabel'] as $key => $id)
  1046. $_REQUEST['searchlabel'][$key] = (int) $id;
  1047. }
  1048. else
  1049. $_REQUEST['searchlabel'] = array();
  1050. // Now that everything is cleaned up a bit, make the labels a param.
  1051. $search_params['labels'] = implode(',', $_REQUEST['searchlabel']);
  1052. // No labels selected? That must be an error!
  1053. if (empty($_REQUEST['searchlabel']))
  1054. $context['search_errors']['no_labels_selected'] = true;
  1055. // Otherwise prepare the query!
  1056. elseif (count($_REQUEST['searchlabel']) != count($context['labels']))
  1057. {
  1058. $labelQuery = '
  1059. AND {raw:label_implode}';
  1060. $labelStatements = array();
  1061. foreach ($_REQUEST['searchlabel'] as $label)
  1062. $labelStatements[] = $smcFunc['db_quote']('FIND_IN_SET({string:label}, pmr.labels) != 0', array(
  1063. 'label' => $label,
  1064. ));
  1065. $searchq_parameters['label_implode'] = '(' . implode(' OR ', $labelStatements) . ')';
  1066. }
  1067. }
  1068. // What are we actually searching for?
  1069. $search_params['search'] = !empty($search_params['search']) ? $search_params['search'] : (isset($_REQUEST['search']) ? $_REQUEST['search'] : '');
  1070. // If we ain't got nothing - we should error!
  1071. if (!isset($search_params['search']) || $search_params['search'] == '')
  1072. $context['search_errors']['invalid_search_string'] = true;
  1073. // Extract phrase parts first (e.g. some words "this is a phrase" some more words.)
  1074. preg_match_all('~(?:^|\s)([-]?)"([^"]+)"(?:$|\s)~' . ($context['utf8'] ? 'u' : ''), $search_params['search'], $matches, PREG_PATTERN_ORDER);
  1075. $searchArray = $matches[2];
  1076. // Remove the phrase parts and extract the words.
  1077. $tempSearch = explode(' ', preg_replace('~(?:^|\s)(?:[-]?)"(?:[^"]+)"(?:$|\s)~' . ($context['utf8'] ? 'u' : ''), ' ', $search_params['search']));
  1078. // A minus sign in front of a word excludes the word.... so...
  1079. $excludedWords = array();
  1080. // .. first, we check for things like -"some words", but not "-some words".
  1081. foreach ($matches[1] as $index => $word)
  1082. if ($word == '-')
  1083. {
  1084. $word = $smcFunc['strtolower'](trim($searchArray[$index]));
  1085. if (strlen($word) > 0)
  1086. $excludedWords[] = $word;
  1087. unset($searchArray[$index]);
  1088. }
  1089. // Now we look for -test, etc.... normaller.
  1090. foreach ($tempSearch as $index => $word)
  1091. {
  1092. if (strpos(trim($word), '-') === 0)
  1093. {
  1094. $word = substr($smcFunc['strtolower']($word), 1);
  1095. if (strlen($word) > 0)
  1096. $excludedWords[] = $word;
  1097. unset($tempSearch[$index]);
  1098. }
  1099. }
  1100. $searchArray = array_merge($searchArray, $tempSearch);
  1101. // Trim everything and make sure there are no words that are the same.
  1102. foreach ($searchArray as $index => $value)
  1103. {
  1104. $searchArray[$index] = $smcFunc['strtolower'](trim($value));
  1105. if ($searchArray[$index] == '')
  1106. unset($searchArray[$index]);
  1107. else
  1108. {
  1109. // Sort out entities first.
  1110. $searchArray[$index] = $smcFunc['htmlspecialchars']($searchArray[$index]);
  1111. }
  1112. }
  1113. $searchArray = array_unique($searchArray);
  1114. // Create an array of replacements for highlighting.
  1115. $context['mark'] = array();
  1116. foreach ($searchArray as $word)
  1117. $context['mark'][$word] = '<strong class="highlight">' . $word . '</strong>';
  1118. // This contains *everything*
  1119. $searchWords = array_merge($searchArray, $excludedWords);
  1120. // Make sure at least one word is being searched for.
  1121. if (empty($searchArray))
  1122. $context['search_errors']['invalid_search_string'] = true;
  1123. // Sort out the search query so the user can edit it - if they want.
  1124. $context['search_params'] = $search_params;
  1125. if (isset($context['search_params']['search']))
  1126. $context['search_params']['search'] = htmlspecialchars($context['search_params']['search']);
  1127. if (isset($context['search_params']['userspec']))
  1128. $context['search_params']['userspec'] = htmlspecialchars($context['search_params']['userspec']);
  1129. // Now we have all the parameters, combine them together for pagination and the like...
  1130. $context['params'] = array();
  1131. foreach ($search_params as $k => $v)
  1132. $context['params'][] = $k . '|\'|' . $v;
  1133. $context['params'] = base64_encode(implode('|"|', $context['params']));
  1134. // Compile the subject query part.
  1135. $andQueryParts = array();
  1136. foreach ($searchWords as $index => $word)
  1137. {
  1138. if ($word == '')
  1139. continue;
  1140. if ($search_params['subject_only'])
  1141. $andQueryParts[] = 'pm.subject' . (in_array($word, $excludedWords) ? ' NOT' : '') . ' LIKE {string:search_' . $index . '}';
  1142. else
  1143. $andQueryParts[] = '(pm.subject' . (in_array($word, $excludedWords) ? ' NOT' : '') . ' LIKE {string:search_' . $index . '} ' . (in_array($word, $excludedWords) ? 'AND pm.body NOT' : 'OR pm.body') . ' LIKE {string:search_' . $index . '})';
  1144. $searchq_parameters['search_' . $index] = '%' . strtr($word, array('_' => '\\_', '%' => '\\%')) . '%';
  1145. }
  1146. $searchQuery = ' 1=1';
  1147. if (!empty($andQueryParts))
  1148. $searchQuery = implode(!empty($search_params['searchtype']) && $search_params['searchtype'] == 2 ? ' OR ' : ' AND ', $andQueryParts);
  1149. // Age limits?
  1150. $timeQuery = '';
  1151. if (!empty($search_params['minage']))
  1152. $timeQuery .= ' AND pm.msgtime < ' . (time() - $search_params['minage'] * 86400);
  1153. if (!empty($search_params['maxage']))
  1154. $timeQuery .= ' AND pm.msgtime > ' . (time() - $search_params['maxage'] * 86400);
  1155. // If we have errors - return back to the first screen...
  1156. if (!empty($context['search_errors']))
  1157. {
  1158. $_REQUEST['params'] = $context['params'];
  1159. return MessageSearch();
  1160. }
  1161. // Get the amount of results.
  1162. $request = $smcFunc['db_query']('', '
  1163. SELECT COUNT(*)
  1164. FROM {db_prefix}pm_recipients AS pmr
  1165. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)
  1166. WHERE ' . ($context['folder'] == 'inbox' ? '
  1167. pmr.id_member = {int:current_member}
  1168. AND pmr.deleted = {int:not_deleted}' : '
  1169. pm.id_member_from = {int:current_member}
  1170. AND pm.deleted_by_sender = {int:not_deleted}') . '
  1171. ' . $userQuery . $labelQuery . $timeQuery . '
  1172. AND (' . $searchQuery . ')',
  1173. array_merge($searchq_parameters, array(
  1174. 'current_member' => $user_info['id'],
  1175. 'not_deleted' => 0,
  1176. ))
  1177. );
  1178. list ($numResults) = $smcFunc['db_fetch_row']($request);
  1179. $smcFunc['db_free_result']($request);
  1180. // Get all the matching messages... using standard search only (No caching and the like!)
  1181. // @todo This doesn't support sent item searching yet.
  1182. $request = $smcFunc['db_query']('', '
  1183. SELECT pm.id_pm, pm.id_pm_head, pm.id_member_from
  1184. FROM {db_prefix}pm_recipients AS pmr
  1185. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)
  1186. WHERE ' . ($context['folder'] == 'inbox' ? '
  1187. pmr.id_member = {int:current_member}
  1188. AND pmr.deleted = {int:not_deleted}' : '
  1189. pm.id_member_from = {int:current_member}
  1190. AND pm.deleted_by_sender = {int:not_deleted}') . '
  1191. ' . $userQuery . $labelQuery . $timeQuery . '
  1192. AND (' . $searchQuery . ')
  1193. ORDER BY ' . $search_params['sort'] . ' ' . $search_params['sort_dir'] . '
  1194. LIMIT ' . $context['start'] . ', ' . $modSettings['search_results_per_page'],
  1195. array_merge($searchq_parameters, array(
  1196. 'current_member' => $user_info['id'],
  1197. 'not_deleted' => 0,
  1198. ))
  1199. );
  1200. $foundMessages = array();
  1201. $posters = array();
  1202. $head_pms = array();
  1203. while ($row = $smcFunc['db_fetch_assoc']($request))
  1204. {
  1205. $foundMessages[] = $row['id_pm'];
  1206. $posters[] = $row['id_member_from'];
  1207. $head_pms[$row['id_pm']] = $row['id_pm_head'];
  1208. }
  1209. $smcFunc['db_free_result']($request);
  1210. // Find the real head pms!
  1211. if ($context['display_mode'] == 2 && !empty($head_pms))
  1212. {
  1213. $request = $smcFunc['db_query']('', '
  1214. SELECT MAX(pm.id_pm) AS id_pm, pm.id_pm_head
  1215. FROM {db_prefix}personal_messages AS pm
  1216. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)
  1217. WHERE pm.id_pm_head IN ({array_int:head_pms})
  1218. AND pmr.id_member = {int:current_member}
  1219. AND pmr.deleted = {int:not_deleted}
  1220. GROUP BY pm.id_pm_head
  1221. LIMIT {int:limit}',
  1222. array(
  1223. 'head_pms' => array_unique($head_pms),
  1224. 'current_member' => $user_info['id'],
  1225. 'not_deleted' => 0,
  1226. 'limit' => count($head_pms),
  1227. )
  1228. );
  1229. $real_pm_ids = array();
  1230. while ($row = $smcFunc['db_fetch_assoc']($request))
  1231. $real_pm_ids[$row['id_pm_head']] = $row['id_pm'];
  1232. $smcFunc['db_free_result']($request);
  1233. }
  1234. // Load the users...
  1235. $posters = array_unique($posters);
  1236. if (!empty($posters))
  1237. loadMemberData($posters);
  1238. // Sort out the page index.
  1239. $context['page_index'] = constructPageIndex($scripturl . '?action=pm;sa=search2;params=' . $context['params'], $_GET['start'], $numResults, $modSettings['search_results_per_page'], false);
  1240. $context['message_labels'] = array();
  1241. $context['message_replied'] = array();
  1242. $context['personal_messages'] = array();
  1243. if (!empty($foundMessages))
  1244. {
  1245. // Now get recipients (but don't include bcc-recipients for your inbox, you're not supposed to know :P!)
  1246. $request = $smcFunc['db_query']('', '
  1247. SELECT
  1248. pmr.id_pm, mem_to.id_member AS id_member_to, mem_to.real_name AS to_name,
  1249. pmr.bcc, pmr.labels, pmr.is_read
  1250. FROM {db_prefix}pm_recipients AS pmr
  1251. LEFT JOIN {db_prefix}members AS mem_to ON (mem_to.id_member = pmr.id_member)
  1252. WHERE pmr.id_pm IN ({array_int:message_list})',
  1253. array(
  1254. 'message_list' => $foundMessages,
  1255. )
  1256. );
  1257. while ($row = $smcFunc['db_fetch_assoc']($request))
  1258. {
  1259. if ($context['folder'] == 'sent' || empty($row['bcc']))
  1260. $recipients[$row['id_pm']][empty($row['bcc']) ? 'to' : 'bcc'][] = empty($row['id_member_to']) ? $txt['guest_title'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_to'] . '">' . $row['to_name'] . '</a>';
  1261. if ($row['id_member_to'] == $user_info['id'] && $context['folder'] != 'sent')
  1262. {
  1263. $context['message_replied'][$row['id_pm']] = $row['is_read'] & 2;
  1264. $row['labels'] = $row['labels'] == '' ? array() : explode(',', $row['labels']);
  1265. // This is a special need for linking to messages.
  1266. foreach ($row['labels'] as $v)
  1267. {
  1268. if (isset($context['labels'][(int) $v]))
  1269. $context['message_labels'][$row['id_pm']][(int) $v] = array('id' => $v, 'name' => $context['labels'][(int) $v]['name']);
  1270. // Here we find the first label on a message - for linking to posts in results
  1271. if (!isset($context['first_label'][$row['id_pm']]) && !in_array('-1', $row['labels']))
  1272. $context['first_label'][$row['id_pm']] = (int) $v;
  1273. }
  1274. }
  1275. }
  1276. // Prepare the query for the callback!
  1277. $request = $smcFunc['db_query']('', '
  1278. SELECT pm.id_pm, pm.subject, pm.id_member_from, pm.body, pm.msgtime, pm.from_name
  1279. FROM {db_prefix}personal_messages AS pm
  1280. WHERE pm.id_pm IN ({array_int:message_list})
  1281. ORDER BY ' . $search_params['sort'] . ' ' . $search_params['sort_dir'] . '
  1282. LIMIT ' . count($foundMessages),
  1283. array(
  1284. 'message_list' => $foundMessages,
  1285. )
  1286. );
  1287. $counter = 0;
  1288. while ($row = $smcFunc['db_fetch_assoc']($request))
  1289. {
  1290. // If there's no message subject, use the default.
  1291. $row['subject'] = $row['subject'] == '' ? $txt['no_subject'] : $row['subject'];
  1292. // Load this posters context info, if it ain't there then fill in the essentials...
  1293. if (!loadMemberContext($row['id_member_from'], true))
  1294. {
  1295. $memberContext[$row['id_member_from']]['name'] = $row['from_name'];
  1296. $memberContext[$row['id_member_from']]['id'] = 0;
  1297. $memberContext[$row['id_member_from']]['group'] = $txt['guest_title'];
  1298. $memberContext[$row['id_member_from']]['link'] = $row['from_name'];
  1299. $memberContext[$row['id_member_from']]['email'] = '';
  1300. $memberContext[$row['id_member_from']]['show_email'] = showEmailAddress(true, 0);
  1301. $memberContext[$row['id_member_from']]['is_guest'] = true;
  1302. }
  1303. // Censor anything we don't want to see...
  1304. censorText($row['body']);
  1305. censorText($row['subject']);
  1306. // Parse out any BBC...
  1307. $row['body'] = parse_bbc($row['body'], true, 'pm' . $row['id_pm']);
  1308. $href = $scripturl . '?action=pm;f=' . $context['folder'] . (isset($context['first_label'][$row['id_pm']]) ? ';l=' . $context['first_label'][$row['id_pm']] : '') . ';pmid=' . ($context['display_mode'] == 2 && isset($real_pm_ids[$head_pms[$row['id_pm']]]) ? $real_pm_ids[$head_pms[$row['id_pm']]] : $row['id_pm']) . '#msg' . $row['id_pm'];
  1309. $context['personal_messages'][] = array(
  1310. 'id' => $row['id_pm'],
  1311. 'member' => &$memberContext[$row['id_member_from']],
  1312. 'subject' => $row['subject'],
  1313. 'body' => $row['body'],
  1314. 'time' => timeformat($row['msgtime']),
  1315. 'recipients' => &$recipients[$row['id_pm']],
  1316. 'labels' => &$context['message_labels'][$row['id_pm']],
  1317. 'fully_labeled' => count($context['message_labels'][$row['id_pm']]) == count($context['labels']),
  1318. 'is_replied_to' => &$context['message_replied'][$row['id_pm']],
  1319. 'href' => $href,
  1320. 'link' => '<a href="' . $href . '">' . $row['subject'] . '</a>',
  1321. 'counter' => ++$counter,
  1322. );
  1323. }
  1324. $smcFunc['db_free_result']($request);
  1325. }
  1326. // Finish off the context.
  1327. $context['page_title'] = $txt['pm_search_title'];
  1328. $context['sub_template'] = 'search_results';
  1329. $context['menu_data_' . $context['pm_menu_id']]['current_area'] = 'search';
  1330. $context['linktree'][] = array(
  1331. 'url' => $scripturl . '?action=pm;sa=search',
  1332. 'name' => $txt['pm_search_bar_title'],
  1333. );
  1334. }
  1335. /**
  1336. * Send a new message?
  1337. */
  1338. function MessagePost()
  1339. {
  1340. global $txt, $sourcedir, $scripturl, $modSettings;
  1341. global $context, $options, $smcFunc, $language, $user_info;
  1342. isAllowedTo('pm_send');
  1343. loadLanguage('PersonalMessage');
  1344. // Just in case it was loaded from somewhere else.
  1345. if (!WIRELESS)
  1346. {
  1347. loadTemplate('PersonalMessage');
  1348. $context['sub_template'] = 'send';
  1349. }
  1350. // Extract out the spam settings - cause it's neat.
  1351. list ($modSettings['max_pm_recipients'], $modSettings['pm_posts_verification'], $modSettings['pm_posts_per_hour']) = explode(',', $modSettings['pm_spam_settings']);
  1352. // Set the title...
  1353. $context['page_title'] = $txt['send_message'];
  1354. $context['reply'] = isset($_REQUEST['pmsg']) || isset($_REQUEST['quote']);
  1355. // Check whether we've gone over the limit of messages we can send per hour.
  1356. if (!empty($modSettings['pm_posts_per_hour']) && !allowedTo(array('admin_forum', 'moderate_forum', 'send_mail')) && $user_info['mod_cache']['bq'] == '0=1' && $user_info['mod_cache']['gq'] == '0=1')
  1357. {
  1358. // How many messages have they sent this last hour?
  1359. $request = $smcFunc['db_query']('', '
  1360. SELECT COUNT(pr.id_pm) AS post_count
  1361. FROM {db_prefix}personal_messages AS pm
  1362. INNER JOIN {db_prefix}pm_recipients AS pr ON (pr.id_pm = pm.id_pm)
  1363. WHERE pm.id_member_from = {int:current_member}
  1364. AND pm.msgtime > {int:msgtime}',
  1365. array(
  1366. 'current_member' => $user_info['id'],
  1367. 'msgtime' => time() - 3600,
  1368. )
  1369. );
  1370. list ($postCount) = $smcFunc['db_fetch_row']($request);
  1371. $smcFunc['db_free_result']($request);
  1372. if (!empty($postCount) && $postCount >= $modSettings['pm_posts_per_hour'])
  1373. fatal_lang_error('pm_too_many_per_hour', true, array($modSettings['pm_posts_per_hour']));
  1374. }
  1375. // Quoting/Replying to a message?
  1376. if (!empty($_REQUEST['pmsg']))
  1377. {
  1378. $pmsg = (int) $_REQUEST['pmsg'];
  1379. // Make sure this is yours.
  1380. if (!isAccessiblePM($pmsg))
  1381. fatal_lang_error('no_access', false);
  1382. // Work out whether this is one you've received?
  1383. $request = $smcFunc['db_query']('', '
  1384. SELECT
  1385. id_pm
  1386. FROM {db_prefix}pm_recipients
  1387. WHERE id_pm = {int:id_pm}
  1388. AND id_member = {int:current_member}
  1389. LIMIT 1',
  1390. array(
  1391. 'current_member' => $user_info['id'],
  1392. 'id_pm' => $pmsg,
  1393. )
  1394. );
  1395. $isReceived = $smcFunc['db_num_rows']($request) != 0;
  1396. $smcFunc['db_free_result']($request);
  1397. // Get the quoted message (and make sure you're allowed to see this quote!).
  1398. $request = $smcFunc['db_query']('', '
  1399. SELECT
  1400. pm.id_pm, CASE WHEN pm.id_pm_head = {int:id_pm_head_empty} THEN pm.id_pm ELSE pm.id_pm_head END AS pm_head,
  1401. pm.body, pm.subject, pm.msgtime, mem.member_name, IFNULL(mem.id_member, 0) AS id_member,
  1402. IFNULL(mem.real_name, pm.from_name) AS real_name
  1403. FROM {db_prefix}personal_messages AS pm' . (!$isReceived ? '' : '
  1404. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = {int:id_pm})') . '
  1405. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = pm.id_member_from)
  1406. WHERE pm.id_pm = {int:id_pm}' . (!$isReceived ? '
  1407. AND pm.id_member_from = {int:current_member}' : '
  1408. AND pmr.id_member = {int:current_member}') . '
  1409. LIMIT 1',
  1410. array(
  1411. 'current_member' => $user_info['id'],
  1412. 'id_pm_head_empty' => 0,
  1413. 'id_pm' => $pmsg,
  1414. )
  1415. );
  1416. if ($smcFunc['db_num_rows']($request) == 0)
  1417. fatal_lang_error('pm_not_yours', false);
  1418. $row_quoted = $smcFunc['db_fetch_assoc']($request);
  1419. $smcFunc['db_free_result']($request);
  1420. // Censor the message.
  1421. censorText($row_quoted['subject']);
  1422. censorText($row_quoted['body']);
  1423. // Add 'Re: ' to it....
  1424. if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix')))
  1425. {
  1426. if ($language === $user_info['language'])
  1427. $context['response_prefix'] = $txt['response_prefix'];
  1428. else
  1429. {
  1430. loadLanguage('index', $language, false);
  1431. $context['response_prefix'] = $txt['response_prefix'];
  1432. loadLanguage('index');
  1433. }
  1434. cache_put_data('response_prefix', $context['response_prefix'], 600);
  1435. }
  1436. $form_subject = $row_quoted['subject'];
  1437. if ($context['reply'] && trim($context['response_prefix']) != '' && $smcFunc['strpos']($form_subject, trim($context['response_prefix'])) !== 0)
  1438. $form_subject = $context['response_prefix'] . $form_subject;
  1439. if (isset($_REQUEST['quote']))
  1440. {
  1441. // Remove any nested quotes and <br />...
  1442. $form_message = preg_replace('~<br ?/?' . '>~i', "\n", $row_quoted['body']);
  1443. if (!empty($modSettings['removeNestedQuotes']))
  1444. $form_message = preg_replace(array('~\n?\[quote.*?\].+?\[/quote\]\n?~is', '~^\n~', '~\[/quote\]~'), '', $form_message);
  1445. if (empty($row_quoted['id_member']))
  1446. $form_message = '[quote author=&quot;' . $row_quoted['real_name'] . '&quot;]' . "\n" . $form_message . "\n" . '[/quote]';
  1447. else
  1448. $form_message = '[quote author=' . $row_quoted['real_name'] . ' link=action=profile;u=' . $row_quoted['id_member'] . ' date=' . $row_quoted['msgtime'] . ']' . "\n" . $form_message . "\n" . '[/quote]';
  1449. }
  1450. else
  1451. $form_message = '';
  1452. // Do the BBC thang on the message.
  1453. $row_quoted['body'] = parse_bbc($row_quoted['body'], true, 'pm' . $row_quoted['id_pm']);
  1454. // Set up the quoted message array.
  1455. $context['quoted_message'] = array(
  1456. 'id' => $row_quoted['id_pm'],
  1457. 'pm_head' => $row_quoted['pm_head'],
  1458. 'member' => array(
  1459. 'name' => $row_quoted['real_name'],
  1460. 'username' => $row_quoted['member_name'],
  1461. 'id' => $row_quoted['id_member'],
  1462. 'href' => !empty($row_quoted['id_member']) ? $scripturl . '?action=profile;u=' . $row_quoted['id_member'] : '',
  1463. 'link' => !empty($row_quoted['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row_quoted['id_member'] . '">' . $row_quoted['real_name'] . '</a>' : $row_quoted['real_name'],
  1464. ),
  1465. 'subject' => $row_quoted['subject'],
  1466. 'time' => timeformat($row_quoted['msgtime']),
  1467. 'timestamp' => forum_time(true, $row_quoted['msgtime']),
  1468. 'body' => $row_quoted['body']
  1469. );
  1470. }
  1471. else
  1472. {
  1473. $context['quoted_message'] = false;
  1474. $form_subject = '';
  1475. $form_message = '';
  1476. }
  1477. $context['recipients'] = array(
  1478. 'to' => array(),
  1479. 'bcc' => array(),
  1480. );
  1481. // Sending by ID? Replying to all? Fetch the real_name(s).
  1482. if (isset($_REQUEST['u']))
  1483. {
  1484. // If the user is replying to all, get all the other members this was sent to..
  1485. if ($_REQUEST['u'] == 'all' && isset($row_quoted))
  1486. {
  1487. // Firstly, to reply to all we clearly already have $row_quoted - so have the original member from.
  1488. if ($row_quoted['id_member'] != $user_info['id'])
  1489. $context['recipients']['to'][] = array(
  1490. 'id' => $row_quoted['id_member'],
  1491. 'name' => htmlspecialchars($row_quoted['real_name']),
  1492. );
  1493. // Now to get the others.
  1494. $request = $smcFunc['db_query']('', '
  1495. SELECT mem.id_member, mem.real_name
  1496. FROM {db_prefix}pm_recipients AS pmr
  1497. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = pmr.id_member)
  1498. WHERE pmr.id_pm = {int:id_pm}
  1499. AND pmr.id_member != {int:current_member}
  1500. AND pmr.bcc = {int:not_bcc}',
  1501. array(
  1502. 'current_member' => $user_info['id'],
  1503. 'id_pm' => $pmsg,
  1504. 'not_bcc' => 0,
  1505. )
  1506. );
  1507. while ($row = $smcFunc['db_fetch_assoc']($request))
  1508. $context['recipients']['to'][] = array(
  1509. 'id' => $row['id_member'],
  1510. 'name' => $row['real_name'],
  1511. );
  1512. $smcFunc['db_free_result']($request);
  1513. }
  1514. else
  1515. {
  1516. $_REQUEST['u'] = explode(',', $_REQUEST['u']);
  1517. foreach ($_REQUEST['u'] as $key => $uID)
  1518. $_REQUEST['u'][$key] = (int) $uID;
  1519. $_REQUEST['u'] = array_unique($_REQUEST['u']);
  1520. $request = $smcFunc['db_query']('', '
  1521. SELECT id_member, real_name
  1522. FROM {db_prefix}members
  1523. WHERE id_member IN ({array_int:member_list})
  1524. LIMIT ' . count($_REQUEST['u']),
  1525. array(
  1526. 'member_list' => $_REQUEST['u'],
  1527. )
  1528. );
  1529. while ($row = $smcFunc['db_fetch_assoc']($request))
  1530. $context['recipients']['to'][] = array(
  1531. 'id' => $row['id_member'],
  1532. 'name' => $row['real_name'],
  1533. );
  1534. $smcFunc['db_free_result']($request);
  1535. }
  1536. // Get a literal name list in case the user has JavaScript disabled.
  1537. $names = array();
  1538. foreach ($context['recipients']['to'] as $to)
  1539. $names[] = $to['name'];
  1540. $context['to_value'] = empty($names) ? '' : '&quot;' . implode('&quot;, &quot;', $names) . '&quot;';
  1541. }
  1542. else
  1543. $context['to_value'] = '';
  1544. // Set the defaults...
  1545. $context['subject'] = $form_subject != '' ? $form_subject : $txt['no_subject'];
  1546. $context['message'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $form_message);
  1547. $context['post_error'] = array();
  1548. $context['copy_to_outbox'] = !empty($options['copy_to_outbox']);
  1549. // And build the link tree.
  1550. $context['linktree'][] = array(
  1551. 'url' => $scripturl . '?action=pm;sa=send',
  1552. 'name' => $txt['new_message']
  1553. );
  1554. $modSettings['disable_wysiwyg'] = !empty($modSettings['disable_wysiwyg']) || empty($modSettings['enableBBC']);
  1555. // Needed for the WYSIWYG editor.
  1556. require_once($sourcedir . '/Subs-Editor.php');
  1557. // Now create the editor.
  1558. $editorOptions = array(
  1559. 'id' => 'message',
  1560. 'value' => $context['message'],
  1561. 'height' => '175px',
  1562. 'width' => '100%',
  1563. 'labels' => array(
  1564. 'post_button' => $txt['send_message'],
  1565. ),
  1566. 'preview_type' => 2,
  1567. );
  1568. create_control_richedit($editorOptions);
  1569. // Store the ID for old compatibility.
  1570. $context['post_box_name'] = $editorOptions['id'];
  1571. $context['bcc_value'] = '';
  1572. $context['require_verification'] = !$user_info['is_admin'] && !empty($modSettings['pm_posts_verification']) && $user_info['posts'] < $modSettings['pm_posts_verification'];
  1573. if ($context['require_verification'])
  1574. {
  1575. $verificationOptions = array(
  1576. 'id' => 'pm',
  1577. );
  1578. $context['require_verification'] = create_control_verification($verificationOptions);
  1579. $context['visual_verification_id'] = $verificationOptions['id'];
  1580. }
  1581. // Register this form and get a sequence number in $context.
  1582. checkSubmitOnce('register');
  1583. }
  1584. /**
  1585. * An error in the message...
  1586. *
  1587. * @param $error_types
  1588. * @param $named_recipients
  1589. * @param $recipient_ids
  1590. */
  1591. function messagePostError($error_types, $named_recipients, $recipient_ids = array())
  1592. {
  1593. global $txt, $context, $scripturl, $modSettings;
  1594. global $smcFunc, $user_info, $sourcedir;
  1595. if (!isset($_REQUEST['xml']))
  1596. $context['menu_data_' . $context['pm_menu_id']]['current_area'] = 'send';
  1597. if (!WIRELESS && !isset($_REQUEST['xml']))
  1598. $context['sub_template'] = 'send';
  1599. elseif (isset($_REQUEST['xml']))
  1600. $context['sub_template'] = 'pm';
  1601. $context['page_title'] = $txt['send_message'];
  1602. // Got some known members?
  1603. $context['recipients'] = array(
  1604. 'to' => array(),
  1605. 'bcc' => array(),
  1606. );
  1607. if (!empty($recipient_ids['to']) || !empty($recipient_ids['bcc']))
  1608. {
  1609. $allRecipients = array_merge($recipient_ids['to'], $recipient_ids['bcc']);
  1610. $request = $smcFunc['db_query']('', '
  1611. SELECT id_member, real_name
  1612. FROM {db_prefix}members
  1613. WHERE id_member IN ({array_int:member_list})',
  1614. array(
  1615. 'member_list' => $allRecipients,
  1616. )
  1617. );
  1618. while ($row = $smcFunc['db_fetch_assoc']($request))
  1619. {
  1620. $recipientType = in_array($row['id_member'], $recipient_ids['bcc']) ? 'bcc' : 'to';
  1621. $context['recipients'][$recipientType][] = array(
  1622. 'id' => $row['id_member'],
  1623. 'name' => $row['real_name'],
  1624. );
  1625. }
  1626. $smcFunc['db_free_result']($request);
  1627. }
  1628. // Set everything up like before....
  1629. $context['subject'] = isset($_REQUEST['subject']) ? $smcFunc['htmlspecialchars']($_REQUEST['subject']) : '';
  1630. $context['message'] = isset($_REQUEST['message']) ? str_replace(array(' '), array('&nbsp; '), $smcFunc['htmlspecialchars']($_REQUEST['message'])) : '';
  1631. $context['copy_to_outbox'] = !empty($_REQUEST['outbox']);
  1632. $context['reply'] = !empty($_REQUEST['replied_to']);
  1633. if ($context['reply'])
  1634. {
  1635. $_REQUEST['replied_to'] = (int) $_REQUEST['replied_to'];
  1636. $request = $smcFunc['db_query']('', '
  1637. SELECT
  1638. pm.id_pm, CASE WHEN pm.id_pm_head = {int:no_id_pm_head} THEN pm.id_pm ELSE pm.id_pm_head END AS pm_head,
  1639. pm.body, pm.subject, pm.msgtime, mem.member_name, IFNULL(mem.id_member, 0) AS id_member,
  1640. IFNULL(mem.real_name, pm.from_name) AS real_name
  1641. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? '' : '
  1642. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = {int:replied_to})') . '
  1643. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = pm.id_member_from)
  1644. WHERE pm.id_pm = {int:replied_to}' . ($context['folder'] == 'sent' ? '
  1645. AND pm.id_member_from = {int:current_member}' : '
  1646. AND pmr.id_member = {int:current_member}') . '
  1647. LIMIT 1',
  1648. array(
  1649. 'current_member' => $user_info['id'],
  1650. 'no_id_pm_head' => 0,
  1651. 'replied_to' => $_REQUEST['replied_to'],
  1652. )
  1653. );
  1654. if ($smcFunc['db_num_rows']($request) == 0)
  1655. {
  1656. if (!isset($_REQUEST['xml']))
  1657. fatal_lang_error('pm_not_yours', false);
  1658. else
  1659. $error_types[] = 'pm_not_yours';
  1660. }
  1661. $row_quoted = $smcFunc['db_fetch_assoc']($request);
  1662. $smcFunc['db_free_result']($request);
  1663. censorText($row_quoted['subject']);
  1664. censorText($row_quoted['body']);
  1665. $context['quoted_message'] = array(
  1666. 'id' => $row_quoted['id_pm'],
  1667. 'pm_head' => $row_quoted['pm_head'],
  1668. 'member' => array(
  1669. 'name' => $row_quoted['real_name'],
  1670. 'username' => $row_quoted['member_name'],
  1671. 'id' => $row_quoted['id_member'],
  1672. 'href' => !empty($row_quoted['id_member']) ? $scripturl . '?action=profile;u=' . $row_quoted['id_member'] : '',
  1673. 'link' => !empty($row_quoted['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row_quoted['id_member'] . '">' . $row_quoted['real_name'] . '</a>' : $row_quoted['real_name'],
  1674. ),
  1675. 'subject' => $row_quoted['subject'],
  1676. 'time' => timeformat($row_quoted['msgtime']),
  1677. 'timestamp' => forum_time(true, $row_quoted['msgtime']),
  1678. 'body' => parse_bbc($row_quoted['body'], true, 'pm' . $row_quoted['id_pm']),
  1679. );
  1680. }
  1681. // Build the link tree....
  1682. $context['linktree'][] = array(
  1683. 'url' => $scripturl . '?action=pm;sa=send',
  1684. 'name' => $txt['new_message']
  1685. );
  1686. // Set each of the errors for the template.
  1687. loadLanguage('Errors');
  1688. $context['post_error'] = array(
  1689. 'messages' => array(),
  1690. // @todo error handling: maybe fatal errors can be error_type => serious
  1691. 'error_type' => '',
  1692. );
  1693. foreach ($error_types as $error_type)
  1694. {
  1695. $context['post_error'][$error_type] = true;
  1696. if (isset($txt['error_' . $error_type]))
  1697. {
  1698. if ($error_type == 'long_message')
  1699. $txt['error_' . $error_type] = sprintf($txt['error_' . $error_type], $modSettings['max_messageLength']);
  1700. $context['post_error']['messages'][] = $txt['error_' . $error_type];
  1701. }
  1702. }
  1703. // We need to load the editor once more.
  1704. require_once($sourcedir . '/Subs-Editor.php');
  1705. // Create it...
  1706. $editorOptions = array(
  1707. 'id' => 'message',
  1708. 'value' => $context['message'],
  1709. 'width' => '90%',
  1710. 'labels' => array(
  1711. 'post_button' => $txt['send_message'],
  1712. ),
  1713. 'preview_type' => 2,
  1714. );
  1715. create_control_richedit($editorOptions);
  1716. // ... and store the ID again...
  1717. $context['post_box_name'] = $editorOptions['id'];
  1718. // Check whether we need to show the code again.
  1719. $context['require_verification'] = !$user_info['is_admin'] && !empty($modSettings['pm_posts_verification']) && $user_info['posts'] < $modSettings['pm_posts_verification'];
  1720. if ($context['require_verification'] && !isset($_REQUEST['xml']))
  1721. {
  1722. require_once($sourcedir . '/Subs-Editor.php');
  1723. $verificationOptions = array(
  1724. 'id' => 'pm',
  1725. );
  1726. $context['require_verification'] = create_control_verification($verificationOptions);
  1727. $context['visual_verification_id'] = $verificationOptions['id'];
  1728. }
  1729. $context['to_value'] = empty($named_recipients['to']) ? '' : '&quot;' . implode('&quot;, &quot;', $named_recipients['to']) . '&quot;';
  1730. $context['bcc_value'] = empty($named_recipients['bcc']) ? '' : '&quot;' . implode('&quot;, &quot;', $named_recipients['bcc']) . '&quot;';
  1731. // No check for the previous submission is needed.
  1732. checkSubmitOnce('free');
  1733. // Acquire a new form sequence number.
  1734. checkSubmitOnce('register');
  1735. }
  1736. /**
  1737. * Send it!
  1738. */
  1739. function MessagePost2()
  1740. {
  1741. global $txt, $context, $sourcedir;
  1742. global $user_info, $modSettings, $scripturl, $smcFunc;
  1743. isAllowedTo('pm_send');
  1744. require_once($sourcedir . '/Subs-Auth.php');
  1745. loadLanguage('PersonalMessage', '', false);
  1746. // Extract out the spam settings - it saves database space!
  1747. list ($modSettings['max_pm_recipients'], $modSettings['pm_posts_verification'], $modSettings['pm_posts_per_hour']) = explode(',', $modSettings['pm_spam_settings']);
  1748. // Initialize the errors we're about to make.
  1749. $post_errors = array();
  1750. // Check whether we've gone over the limit of messages we can send per hour - fatal error if fails!
  1751. if (!empty($modSettings['pm_posts_per_hour']) && !allowedTo(array('admin_forum', 'moderate_forum', 'send_mail')) && $user_info['mod_cache']['bq'] == '0=1' && $user_info['mod_cache']['gq'] == '0=1')
  1752. {
  1753. // How many have they sent this last hour?
  1754. $request = $smcFunc['db_query']('', '
  1755. SELECT COUNT(pr.id_pm) AS post_count
  1756. FROM {db_prefix}personal_messages AS pm
  1757. INNER JOIN {db_prefix}pm_recipients AS pr ON (pr.id_pm = pm.id_pm)
  1758. WHERE pm.id_member_from = {int:current_member}
  1759. AND pm.msgtime > {int:msgtime}',
  1760. array(
  1761. 'current_member' => $user_info['id'],
  1762. 'msgtime' => time() - 3600,
  1763. )
  1764. );
  1765. list ($postCount) = $smcFunc['db_fetch_row']($request);
  1766. $smcFunc['db_free_result']($request);
  1767. if (!empty($postCount) && $postCount >= $modSettings['pm_posts_per_hour'])
  1768. {
  1769. if (!isset($_REQUEST['xml']))
  1770. fatal_lang_error('pm_too_many_per_hour', true, array($modSettings['pm_posts_per_hour']));
  1771. else
  1772. $post_errors[] = 'pm_too_many_per_hour';
  1773. }
  1774. }
  1775. // If we came from WYSIWYG then turn it back into BBC regardless.
  1776. if (!empty($_POST['message_mode']) && isset($_POST['message']))
  1777. {
  1778. require_once($sourcedir . '/Subs-Editor.php');
  1779. $_POST['message'] = html_to_bbc($_POST['message']);
  1780. // We need to unhtml it now as it gets done shortly.
  1781. $_POST['message'] = un_htmlspecialchars($_POST['message']);
  1782. // We need this in case of errors etc.
  1783. $_REQUEST['message'] = $_POST['message'];
  1784. }
  1785. // If your session timed out, show an error, but do allow to re-submit.
  1786. if (!isset($_REQUEST['xml']) && checkSession('post', '', false) != '')
  1787. $post_errors[] = 'session_timeout';
  1788. $_REQUEST['subject'] = isset($_REQUEST['subject']) ? trim($_REQUEST['subject']) : '';
  1789. $_REQUEST['to'] = empty($_POST['to']) ? (empty($_GET['to']) ? '' : $_GET['to']) : $_POST['to'];
  1790. $_REQUEST['bcc'] = empty($_POST['bcc']) ? (empty($_GET['bcc']) ? '' : $_GET['bcc']) : $_POST['bcc'];
  1791. // Route the input from the 'u' parameter to the 'to'-list.
  1792. if (!empty($_POST['u']))
  1793. $_POST['recipient_to'] = explode(',', $_POST['u']);
  1794. // Construct the list of recipients.
  1795. $recipientList = array();
  1796. $namedRecipientList = array();
  1797. $namesNotFound = array();
  1798. foreach (array('to', 'bcc') as $recipientType)
  1799. {
  1800. // First, let's see if there's user ID's given.
  1801. $recipientList[$recipientType] = array();
  1802. if (!empty($_POST['recipient_' . $recipientType]) && is_array($_POST['recipient_' . $recipientType]))
  1803. {
  1804. foreach ($_POST['recipient_' . $recipientType] as $recipient)
  1805. $recipientList[$recipientType][] = (int) $recipient;
  1806. }
  1807. // Are there also literal names set?
  1808. if (!empty($_REQUEST[$recipientType]))
  1809. {
  1810. // We're going to take out the "s anyway ;).
  1811. $recipientString = strtr($_REQUEST[$recipientType], array('\\"' => '"'));
  1812. preg_match_all('~"([^"]+)"~', $recipientString, $matches);
  1813. $namedRecipientList[$recipientType] = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $recipientString))));
  1814. foreach ($namedRecipientList[$recipientType] as $index => $recipient)
  1815. {
  1816. if (strlen(trim($recipient)) > 0)
  1817. $namedRecipientList[$recipientType][$index] = $smcFunc['htmlspecialchars']($smcFunc['strtolower'](trim($recipient)));
  1818. else
  1819. unset($namedRecipientList[$recipientType][$index]);
  1820. }
  1821. if (!empty($namedRecipientList[$recipientType]))
  1822. {
  1823. $foundMembers = findMembers($namedRecipientList[$recipientType]);
  1824. // Assume all are not found, until proven otherwise.
  1825. $namesNotFound[$recipientType] = $namedRecipientList[$recipientType];
  1826. foreach ($foundMembers as $member)
  1827. {
  1828. $testNames = array(
  1829. $smcFunc['strtolower']($member['username']),
  1830. $smcFunc['strtolower']($member['name']),
  1831. $smcFunc['strtolower']($member['email']),
  1832. );
  1833. if (count(array_intersect($testNames, $namedRecipientList[$recipientType])) !== 0)
  1834. {
  1835. $recipientList[$recipientType][] = $member['id'];
  1836. // Get rid of this username, since we found it.
  1837. $namesNotFound[$recipientType] = array_diff($namesNotFound[$recipientType], $testNames);
  1838. }
  1839. }
  1840. }
  1841. }
  1842. // Selected a recipient to be deleted? Remove them now.
  1843. if (!empty($_POST['delete_recipient']))
  1844. $recipientList[$recipientType] = array_diff($recipientList[$recipientType], array((int) $_POST['delete_recipient']));
  1845. // Make sure we don't include the same name twice
  1846. $recipientList[$recipientType] = array_unique($recipientList[$recipientType]);
  1847. }
  1848. // Are we changing the recipients some how?
  1849. $is_recipient_change = !empty($_POST['delete_recipient']) || !empty($_POST['to_submit']) || !empty($_POST['bcc_submit']);
  1850. // Check if there's at least one recipient.
  1851. if (empty($recipientList['to']) && empty($recipientList['bcc']))
  1852. $post_errors[] = 'no_to';
  1853. // Make sure that we remove the members who did get it from the screen.
  1854. if (!$is_recipient_change)
  1855. {
  1856. foreach ($recipientList as $recipientType => $dummy)
  1857. {
  1858. if (!empty($namesNotFound[$recipientType]))
  1859. {
  1860. $post_errors[] = 'bad_' . $recipientType;
  1861. // Since we already have a post error, remove the previous one.
  1862. $post_errors = array_diff($post_errors, array('no_to'));
  1863. foreach ($namesNotFound[$recipientType] as $name)
  1864. $context['send_log']['failed'][] = sprintf($txt['pm_error_user_not_found'], $name);
  1865. }
  1866. }
  1867. }
  1868. // Did they make any mistakes?
  1869. if ($_REQUEST['subject'] == '')
  1870. $post_errors[] = 'no_subject';
  1871. if (!isset($_REQUEST['message']) || $_REQUEST['message'] == '')
  1872. $post_errors[] = 'no_message';
  1873. elseif (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_REQUEST['message']) > $modSettings['max_messageLength'])
  1874. $post_errors[] = 'long_message';
  1875. else
  1876. {
  1877. // Preparse the message.
  1878. $message = $_REQUEST['message'];
  1879. preparsecode($message);
  1880. // Make sure there's still some content left without the tags.
  1881. if ($smcFunc['htmltrim'](strip_tags(parse_bbc($smcFunc['htmlspecialchars']($message, ENT_QUOTES), false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($message, '[html]') === false))
  1882. $post_errors[] = 'no_message';
  1883. }
  1884. // Wrong verification code?
  1885. if (!$user_info['is_admin'] && !isset($_REQUEST['xml']) && !empty($modSettings['pm_posts_verification']) && $user_info['posts'] < $modSettings['pm_posts_verification'])
  1886. {
  1887. require_once($sourcedir . '/Subs-Editor.php');
  1888. $verificationOptions = array(
  1889. 'id' => 'pm',
  1890. );
  1891. $context['require_verification'] = create_control_verification($verificationOptions, true);
  1892. if (is_array($context['require_verification']))
  1893. {
  1894. $post_errors = array_merge($post_errors, $context['require_verification']);
  1895. }
  1896. }
  1897. // If they did, give a chance to make ammends.
  1898. if (!empty($post_errors) && !$is_recipient_change && !isset($_REQUEST['preview']) && !isset($_REQUEST['xml']))
  1899. return messagePostError($post_errors, $namedRecipientList, $recipientList);
  1900. // Want to take a second glance before you send?
  1901. if (isset($_REQUEST['preview']))
  1902. {
  1903. // Set everything up to be displayed.
  1904. $context['preview_subject'] = $smcFunc['htmlspecialchars']($_REQUEST['subject']);
  1905. $context['preview_message'] = $smcFunc['htmlspecialchars']($_REQUEST['message'], ENT_QUOTES);
  1906. preparsecode($context['preview_message'], true);
  1907. // Parse out the BBC if it is enabled.
  1908. $context['preview_message'] = parse_bbc($context['preview_message']);
  1909. // Censor, as always.
  1910. censorText($context['preview_subject']);
  1911. censorText($context['preview_message']);
  1912. // Set a descriptive title.
  1913. $context['page_title'] = $txt['preview'] . ' - ' . $context['preview_subject'];
  1914. // Pretend they messed up but don't ignore if they really did :P.
  1915. return messagePostError($post_errors, $namedRecipientList, $recipientList);
  1916. }
  1917. // Adding a recipient cause javascript ain't working?
  1918. elseif ($is_recipient_change)
  1919. {
  1920. // Maybe we couldn't find one?
  1921. foreach ($namesNotFound as $recipientType => $names)
  1922. {
  1923. $post_errors[] = 'bad_' . $recipientType;
  1924. foreach ($names as $name)
  1925. $context['send_log']['failed'][] = sprintf($txt['pm_error_user_not_found'], $name);
  1926. }
  1927. return messagePostError(array(), $namedRecipientList, $recipientList);
  1928. }
  1929. // Before we send the PM, let's make sure we don't have an abuse of numbers.
  1930. elseif (!empty($modSettings['max_pm_recipients']) && count($recipientList['to']) + count($recipientList['bcc']) > $modSettings['max_pm_recipients'] && !allowedTo(array('moderate_forum', 'send_mail', 'admin_forum')))
  1931. {
  1932. $context['send_log'] = array(
  1933. 'sent' => array(),
  1934. 'failed' => array(sprintf($txt['pm_too_many_recipients'], $modSettings['max_pm_recipients'])),
  1935. );
  1936. return messagePostError($post_errors, $namedRecipientList, $recipientList);
  1937. }
  1938. // Protect from message spamming.
  1939. spamProtection('pm');
  1940. // Prevent double submission of this form.
  1941. checkSubmitOnce('check');
  1942. // Do the actual sending of the PM.
  1943. if (!empty($recipientList['to']) || !empty($recipientList['bcc']))
  1944. $context['send_log'] = sendpm($recipientList, $_REQUEST['subject'], $_REQUEST['message'], !empty($_REQUEST['outbox']), null, !empty($_REQUEST['pm_head']) ? (int) $_REQUEST['pm_head'] : 0);
  1945. else
  1946. $context['send_log'] = array(
  1947. 'sent' => array(),
  1948. 'failed' => array()
  1949. );
  1950. // Mark the message as "replied to".
  1951. if (!empty($context['send_log']['sent']) && !empty($_REQUEST['replied_to']) && isset($_REQUEST['f']) && $_REQUEST['f'] == 'inbox')
  1952. {
  1953. $smcFunc['db_query']('', '
  1954. UPDATE {db_prefix}pm_recipients
  1955. SET is_read = is_read | 2
  1956. WHERE id_pm = {int:replied_to}
  1957. AND id_member = {int:current_member}',
  1958. array(
  1959. 'current_member' => $user_info['id'],
  1960. 'replied_to' => (int) $_REQUEST['replied_to'],
  1961. )
  1962. );
  1963. }
  1964. // If one or more of the recipient were invalid, go back to the post screen with the failed usernames.
  1965. if (!empty($context['send_log']['failed']))
  1966. return messagePostError($post_errors, $namesNotFound, array(
  1967. 'to' => array_intersect($recipientList['to'], $context['send_log']['failed']),
  1968. 'bcc' => array_intersect($recipientList['bcc'], $context['send_log']['failed'])
  1969. ));
  1970. // Message sent successfully?
  1971. if (!empty($context['send_log']) && empty($context['send_log']['failed']))
  1972. $context['current_label_redirect'] = $context['current_label_redirect'] . ';done=sent';
  1973. // Go back to the where they sent from, if possible...
  1974. redirectexit($context['current_label_redirect']);
  1975. }
  1976. /**
  1977. * This function lists all buddies for wireless protocols.
  1978. */
  1979. function WirelessAddBuddy()
  1980. {
  1981. global $scripturl, $txt, $user_info, $context, $smcFunc;
  1982. isAllowedTo('pm_send');
  1983. $context['page_title'] = $txt['wireless_pm_add_buddy'];
  1984. $current_buddies = empty($_REQUEST['u']) ? array() : explode(',', $_REQUEST['u']);
  1985. foreach ($current_buddies as $key => $buddy)
  1986. $current_buddies[$key] = (int) $buddy;
  1987. $base_url = $scripturl . '?action=pm;sa=send;u=' . (empty($current_buddies) ? '' : implode(',', $current_buddies) . ',');
  1988. $context['pm_href'] = $scripturl . '?action=pm;sa=send' . (empty($current_buddies) ? '' : ';u=' . implode(',', $current_buddies));
  1989. $context['buddies'] = array();
  1990. if (!empty($user_info['buddies']))
  1991. {
  1992. $request = $smcFunc['db_query']('', '
  1993. SELECT id_member, real_name
  1994. FROM {db_prefix}members
  1995. WHERE id_member IN ({array_int:buddy_list})
  1996. ORDER BY real_name
  1997. LIMIT ' . count($user_info['buddies']),
  1998. array(
  1999. 'buddy_list' => $user_info['buddies'],
  2000. )
  2001. );
  2002. while ($row = $smcFunc['db_fetch_assoc']($request))
  2003. $context['buddies'][] = array(
  2004. 'id' => $row['id_member'],
  2005. 'name' => $row['real_name'],
  2006. 'selected' => in_array($row['id_member'], $current_buddies),
  2007. 'add_href' => $base_url . $row['id_member'],
  2008. );
  2009. $smcFunc['db_free_result']($request);
  2010. }
  2011. }
  2012. /**
  2013. * This function performs all additional stuff...
  2014. */
  2015. function MessageActionsApply()
  2016. {
  2017. global $txt, $context, $user_info, $options, $smcFunc;
  2018. checkSession('request');
  2019. if (isset($_REQUEST['del_selected']))
  2020. $_REQUEST['pm_action'] = 'delete';
  2021. if (isset($_REQUEST['pm_action']) && $_REQUEST['pm_action'] != '' && !empty($_REQUEST['pms']) && is_array($_REQUEST['pms']))
  2022. {
  2023. foreach ($_REQUEST['pms'] as $pm)
  2024. $_REQUEST['pm_actions'][(int) $pm] = $_REQUEST['pm_action'];
  2025. }
  2026. if (empty($_REQUEST['pm_actions']))
  2027. redirectexit($context['current_label_redirect']);
  2028. // If we are in conversation, we may need to apply this to every message in the conversation.
  2029. if ($context['display_mode'] == 2 && isset($_REQUEST['conversation']))
  2030. {
  2031. $id_pms = array();
  2032. foreach ($_REQUEST['pm_actions'] as $pm => $dummy)
  2033. $id_pms[] = (int) $pm;
  2034. $request = $smcFunc['db_query']('', '
  2035. SELECT id_pm_head, id_pm
  2036. FROM {db_prefix}personal_messages
  2037. WHERE id_pm IN ({array_int:id_pms})',
  2038. array(
  2039. 'id_pms' => $id_pms,
  2040. )
  2041. );
  2042. $pm_heads = array();
  2043. while ($row = $smcFunc['db_fetch_assoc']($request))
  2044. $pm_heads[$row['id_pm_head']] = $row['id_pm'];
  2045. $smcFunc['db_free_result']($request);
  2046. $request = $smcFunc['db_query']('', '
  2047. SELECT id_pm, id_pm_head
  2048. FROM {db_prefix}personal_messages
  2049. WHERE id_pm_head IN ({array_int:pm_heads})',
  2050. array(
  2051. 'pm_heads' => array_keys($pm_heads),
  2052. )
  2053. );
  2054. // Copy the action from the single to PM to the others.
  2055. while ($row = $smcFunc['db_fetch_assoc']($request))
  2056. {
  2057. if (isset($pm_heads[$row['id_pm_head']]) && isset($_REQUEST['pm_actions'][$pm_heads[$row['id_pm_head']]]))
  2058. $_REQUEST['pm_actions'][$row['id_pm']] = $_REQUEST['pm_actions'][$pm_heads[$row['id_pm_head']]];
  2059. }
  2060. $smcFunc['db_free_result']($request);
  2061. }
  2062. $to_delete = array();
  2063. $to_label = array();
  2064. $label_type = array();
  2065. foreach ($_REQUEST['pm_actions'] as $pm => $action)
  2066. {
  2067. if ($action === 'delete')
  2068. $to_delete[] = (int) $pm;
  2069. else
  2070. {
  2071. if (substr($action, 0, 4) == 'add_')
  2072. {
  2073. $type = 'add';
  2074. $action = substr($action, 4);
  2075. }
  2076. elseif (substr($action, 0, 4) == 'rem_')
  2077. {
  2078. $type = 'rem';
  2079. $action = substr($action, 4);
  2080. }
  2081. else
  2082. $type = 'unk';
  2083. if ($action == '-1' || $action == '0' || (int) $action > 0)
  2084. {
  2085. $to_label[(int) $pm] = (int) $action;
  2086. $label_type[(int) $pm] = $type;
  2087. }
  2088. }
  2089. }
  2090. // Deleting, it looks like?
  2091. if (!empty($to_delete))
  2092. deleteMessages($to_delete, $context['display_mode'] == 2 ? null : $context['folder']);
  2093. // Are we labeling anything?
  2094. if (!empty($to_label) && $context['folder'] == 'inbox')
  2095. {
  2096. $updateErrors = 0;
  2097. // Get information about each message...
  2098. $request = $smcFunc['db_query']('', '
  2099. SELECT id_pm, labels
  2100. FROM {db_prefix}pm_recipients
  2101. WHERE id_member = {int:current_member}
  2102. AND id_pm IN ({array_int:to_label})
  2103. LIMIT ' . count($to_label),
  2104. array(
  2105. 'current_member' => $user_info['id'],
  2106. 'to_label' => array_keys($to_label),
  2107. )
  2108. );
  2109. while ($row = $smcFunc['db_fetch_assoc']($request))
  2110. {
  2111. $labels = $row['labels'] == '' ? array('-1') : explode(',', trim($row['labels']));
  2112. // Already exists? Then... unset it!
  2113. $ID_LABEL = array_search($to_label[$row['id_pm']], $labels);
  2114. if ($ID_LABEL !== false && $label_type[$row['id_pm']] !== 'add')
  2115. unset($labels[$ID_LABEL]);
  2116. elseif ($label_type[$row['id_pm']] !== 'rem')
  2117. $labels[] = $to_label[$row['id_pm']];
  2118. if (!empty($options['pm_remove_inbox_label']) && $to_label[$row['id_pm']] != '-1' && ($key = array_search('-1', $labels)) !== false)
  2119. unset($labels[$key]);
  2120. $set = implode(',', array_unique($labels));
  2121. if ($set == '')
  2122. $set = '-1';
  2123. // Check that this string isn't going to be too large for the database.
  2124. if ($set > 60)
  2125. $updateErrors++;
  2126. else
  2127. {
  2128. $smcFunc['db_query']('', '
  2129. UPDATE {db_prefix}pm_recipients
  2130. SET labels = {string:labels}
  2131. WHERE id_pm = {int:id_pm}
  2132. AND id_member = {int:current_member}',
  2133. array(
  2134. 'current_member' => $user_info['id'],
  2135. 'id_pm' => $row['id_pm'],
  2136. 'labels' => $set,
  2137. )
  2138. );
  2139. }
  2140. }
  2141. $smcFunc['db_free_result']($request);
  2142. // Any errors?
  2143. // @todo Separate the sprintf?
  2144. if (!empty($updateErrors))
  2145. fatal_lang_error('labels_too_many', true, array($updateErrors));
  2146. }
  2147. // Back to the folder.
  2148. $_SESSION['pm_selected'] = array_keys($to_label);
  2149. redirectexit($context['current_label_redirect'] . (count($to_label) == 1 ? '#msg' . $_SESSION['pm_selected'][0] : ''), count($to_label) == 1 && isBrowser('ie'));
  2150. }
  2151. /**
  2152. * Are you sure you want to PERMANENTLY (mostly) delete ALL your messages?
  2153. */
  2154. function MessageKillAllQuery()
  2155. {
  2156. global $txt, $context;
  2157. // Only have to set up the template....
  2158. $context['sub_template'] = 'ask_delete';
  2159. $context['page_title'] = $txt['delete_all'];
  2160. $context['delete_all'] = $_REQUEST['f'] == 'all';
  2161. // And set the folder name...
  2162. $txt['delete_all'] = str_replace('PMBOX', $context['folder'] != 'sent' ? $txt['inbox'] : $txt['sent_items'], $txt['delete_all']);
  2163. }
  2164. /**
  2165. * Delete ALL the messages!
  2166. */
  2167. function MessageKillAll()
  2168. {
  2169. global $context;
  2170. checkSession('get');
  2171. // If all then delete all messages the user has.
  2172. if ($_REQUEST['f'] == 'all')
  2173. deleteMessages(null, null);
  2174. // Otherwise just the selected folder.
  2175. else
  2176. deleteMessages(null, $_REQUEST['f'] != 'sent' ? 'inbox' : 'sent');
  2177. // Done... all gone.
  2178. redirectexit($context['current_label_redirect']);
  2179. }
  2180. /**
  2181. * This function allows the user to delete all messages older than so many days.
  2182. */
  2183. function MessagePrune()
  2184. {
  2185. global $txt, $context, $user_info, $scripturl, $smcFunc;
  2186. // Actually delete the messages.
  2187. if (isset($_REQUEST['age']))
  2188. {
  2189. checkSession();
  2190. // Calculate the time to delete before.
  2191. $deleteTime = max(0, time() - (86400 * (int) $_REQUEST['age']));
  2192. // Array to store the IDs in.
  2193. $toDelete = array();
  2194. // Select all the messages they have sent older than $deleteTime.
  2195. $request = $smcFunc['db_query']('', '
  2196. SELECT id_pm
  2197. FROM {db_prefix}personal_messages
  2198. WHERE deleted_by_sender = {int:not_deleted}
  2199. AND id_member_from = {int:current_member}
  2200. AND msgtime < {int:msgtime}',
  2201. array(
  2202. 'current_member' => $user_info['id'],
  2203. 'not_deleted' => 0,
  2204. 'msgtime' => $deleteTime,
  2205. )
  2206. );
  2207. while ($row = $smcFunc['db_fetch_row']($request))
  2208. $toDelete[] = $row[0];
  2209. $smcFunc['db_free_result']($request);
  2210. // Select all messages in their inbox older than $deleteTime.
  2211. $request = $smcFunc['db_query']('', '
  2212. SELECT pmr.id_pm
  2213. FROM {db_prefix}pm_recipients AS pmr
  2214. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)
  2215. WHERE pmr.deleted = {int:not_deleted}
  2216. AND pmr.id_member = {int:current_member}
  2217. AND pm.msgtime < {int:msgtime}',
  2218. array(
  2219. 'current_member' => $user_info['id'],
  2220. 'not_deleted' => 0,
  2221. 'msgtime' => $deleteTime,
  2222. )
  2223. );
  2224. while ($row = $smcFunc['db_fetch_assoc']($request))
  2225. $toDelete[] = $row['id_pm'];
  2226. $smcFunc['db_free_result']($request);
  2227. // Delete the actual messages.
  2228. deleteMessages($toDelete);
  2229. // Go back to their inbox.
  2230. redirectexit($context['current_label_redirect']);
  2231. }
  2232. // Build the link tree elements.
  2233. $context['linktree'][] = array(
  2234. 'url' => $scripturl . '?action=pm;sa=prune',
  2235. 'name' => $txt['pm_prune']
  2236. );
  2237. $context['sub_template'] = 'prune';
  2238. $context['page_title'] = $txt['pm_prune'];
  2239. }
  2240. /**
  2241. * Delete the specified personal messages.
  2242. *
  2243. * @param array $personal_messages, array of pm ids
  2244. * @param string $folder = null
  2245. * @param int $owner = null
  2246. */
  2247. function deleteMessages($personal_messages, $folder = null, $owner = null)
  2248. {
  2249. global $user_info, $smcFunc;
  2250. if ($owner === null)
  2251. $owner = array($user_info['id']);
  2252. elseif (empty($owner))
  2253. return;
  2254. elseif (!is_array($owner))
  2255. $owner = array($owner);
  2256. if ($personal_messages !== null)
  2257. {
  2258. if (empty($personal_messages) || !is_array($personal_messages))
  2259. return;
  2260. foreach ($personal_messages as $index => $delete_id)
  2261. $personal_messages[$index] = (int) $delete_id;
  2262. $where = '
  2263. AND id_pm IN ({array_int:pm_list})';
  2264. }
  2265. else
  2266. $where = '';
  2267. if ($folder == 'sent' || $folder === null)
  2268. {
  2269. $smcFunc['db_query']('', '
  2270. UPDATE {db_prefix}personal_messages
  2271. SET deleted_by_sender = {int:is_deleted}
  2272. WHERE id_member_from IN ({array_int:member_list})
  2273. AND deleted_by_sender = {int:not_deleted}' . $where,
  2274. array(
  2275. 'member_list' => $owner,
  2276. 'is_deleted' => 1,
  2277. 'not_deleted' => 0,
  2278. 'pm_list' => $personal_messages !== null ? array_unique($personal_messages) : array(),
  2279. )
  2280. );
  2281. }
  2282. if ($folder != 'sent' || $folder === null)
  2283. {
  2284. // Calculate the number of messages each member's gonna lose...
  2285. $request = $smcFunc['db_query']('', '
  2286. SELECT id_member, COUNT(*) AS num_deleted_messages, CASE WHEN is_read & 1 >= 1 THEN 1 ELSE 0 END AS is_read
  2287. FROM {db_prefix}pm_recipients
  2288. WHERE id_member IN ({array_int:member_list})
  2289. AND deleted = {int:not_deleted}' . $where . '
  2290. GROUP BY id_member, is_read',
  2291. array(
  2292. 'member_list' => $owner,
  2293. 'not_deleted' => 0,
  2294. 'pm_list' => $personal_messages !== null ? array_unique($personal_messages) : array(),
  2295. )
  2296. );
  2297. // ...And update the statistics accordingly - now including unread messages!.
  2298. while ($row = $smcFunc['db_fetch_assoc']($request))
  2299. {
  2300. if ($row['is_read'])
  2301. updateMemberData($row['id_member'], array('instant_messages' => $where == '' ? 0 : 'instant_messages - ' . $row['num_deleted_messages']));
  2302. else
  2303. updateMemberData($row['id_member'], array('instant_messages' => $where == '' ? 0 : 'instant_messages - ' . $row['num_deleted_messages'], 'unread_messages' => $where == '' ? 0 : 'unread_messages - ' . $row['num_deleted_messages']));
  2304. // If this is the current member we need to make their message count correct.
  2305. if ($user_info['id'] == $row['id_member'])
  2306. {
  2307. $user_info['messages'] -= $row['num_deleted_messages'];
  2308. if (!($row['is_read']))
  2309. $user_info['unread_messages'] -= $row['num_deleted_messages'];
  2310. }
  2311. }
  2312. $smcFunc['db_free_result']($request);
  2313. // Do the actual deletion.
  2314. $smcFunc['db_query']('', '
  2315. UPDATE {db_prefix}pm_recipients
  2316. SET deleted = {int:is_deleted}
  2317. WHERE id_member IN ({array_int:member_list})
  2318. AND deleted = {int:not_deleted}' . $where,
  2319. array(
  2320. 'member_list' => $owner,
  2321. 'is_deleted' => 1,
  2322. 'not_deleted' => 0,
  2323. 'pm_list' => $personal_messages !== null ? array_unique($personal_messages) : array(),
  2324. )
  2325. );
  2326. }
  2327. // If sender and recipients all have deleted their message, it can be removed.
  2328. $request = $smcFunc['db_query']('', '
  2329. SELECT pm.id_pm AS sender, pmr.id_pm
  2330. FROM {db_prefix}personal_messages AS pm
  2331. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm AND pmr.deleted = {int:not_deleted})
  2332. WHERE pm.deleted_by_sender = {int:is_deleted}
  2333. ' . str_replace('id_pm', 'pm.id_pm', $where) . '
  2334. GROUP BY sender, pmr.id_pm
  2335. HAVING pmr.id_pm IS null',
  2336. array(
  2337. 'not_deleted' => 0,
  2338. 'is_deleted' => 1,
  2339. 'pm_list' => $personal_messages !== null ? array_unique($personal_messages) : array(),
  2340. )
  2341. );
  2342. $remove_pms = array();
  2343. while ($row = $smcFunc['db_fetch_assoc']($request))
  2344. $remove_pms[] = $row['sender'];
  2345. $smcFunc['db_free_result']($request);
  2346. if (!empty($remove_pms))
  2347. {
  2348. $smcFunc['db_query']('', '
  2349. DELETE FROM {db_prefix}personal_messages
  2350. WHERE id_pm IN ({array_int:pm_list})',
  2351. array(
  2352. 'pm_list' => $remove_pms,
  2353. )
  2354. );
  2355. $smcFunc['db_query']('', '
  2356. DELETE FROM {db_prefix}pm_recipients
  2357. WHERE id_pm IN ({array_int:pm_list})',
  2358. array(
  2359. 'pm_list' => $remove_pms,
  2360. )
  2361. );
  2362. }
  2363. // Any cached numbers may be wrong now.
  2364. cache_put_data('labelCounts:' . $user_info['id'], null, 720);
  2365. }
  2366. /**
  2367. * Mark the specified personal messages read.
  2368. *
  2369. * @param array $personal_messages = null, array of pm ids
  2370. * @param string $label = null, if label is set, only marks messages with that label
  2371. * @param int $owner = null, if owner is set, marks messages owned by that member id
  2372. */
  2373. function markMessages($personal_messages = null, $label = null, $owner = null)
  2374. {
  2375. global $user_info, $context, $smcFunc;
  2376. if ($owner === null)
  2377. $owner = $user_info['id'];
  2378. $smcFunc['db_query']('', '
  2379. UPDATE {db_prefix}pm_recipients
  2380. SET is_read = is_read | 1
  2381. WHERE id_member = {int:id_member}
  2382. AND NOT (is_read & 1 >= 1)' . ($label === null ? '' : '
  2383. AND FIND_IN_SET({string:label}, labels) != 0') . ($personal_messages !== null ? '
  2384. AND id_pm IN ({array_int:personal_messages})' : ''),
  2385. array(
  2386. 'personal_messages' => $personal_messages,
  2387. 'id_member' => $owner,
  2388. 'label' => $label,
  2389. )
  2390. );
  2391. // If something wasn't marked as read, get the number of unread messages remaining.
  2392. if ($smcFunc['db_affected_rows']() > 0)
  2393. {
  2394. if ($owner == $user_info['id'])
  2395. {
  2396. foreach ($context['labels'] as $label)
  2397. $context['labels'][(int) $label['id']]['unread_messages'] = 0;
  2398. }
  2399. $result = $smcFunc['db_query']('', '
  2400. SELECT labels, COUNT(*) AS num
  2401. FROM {db_prefix}pm_recipients
  2402. WHERE id_member = {int:id_member}
  2403. AND NOT (is_read & 1 >= 1)
  2404. AND deleted = {int:is_not_deleted}
  2405. GROUP BY labels',
  2406. array(
  2407. 'id_member' => $owner,
  2408. 'is_not_deleted' => 0,
  2409. )
  2410. );
  2411. $total_unread = 0;
  2412. while ($row = $smcFunc['db_fetch_assoc']($result))
  2413. {
  2414. $total_unread += $row['num'];
  2415. if ($owner != $user_info['id'])
  2416. continue;
  2417. $this_labels = explode(',', $row['labels']);
  2418. foreach ($this_labels as $this_label)
  2419. $context['labels'][(int) $this_label]['unread_messages'] += $row['num'];
  2420. }
  2421. $smcFunc['db_free_result']($result);
  2422. // Need to store all this.
  2423. cache_put_data('labelCounts:' . $owner, $context['labels'], 720);
  2424. updateMemberData($owner, array('unread_messages' => $total_unread));
  2425. // If it was for the current member, reflect this in the $user_info array too.
  2426. if ($owner == $user_info['id'])
  2427. $user_info['unread_messages'] = $total_unread;
  2428. }
  2429. }
  2430. /**
  2431. * This function handles adding, deleting and editing labels on messages.
  2432. */
  2433. function ManageLabels()
  2434. {
  2435. global $txt, $context, $user_info, $scripturl, $smcFunc;
  2436. // Build the link tree elements...
  2437. $context['linktree'][] = array(
  2438. 'url' => $scripturl . '?action=pm;sa=manlabels',
  2439. 'name' => $txt['pm_manage_labels']
  2440. );
  2441. $context['page_title'] = $txt['pm_manage_labels'];
  2442. $context['sub_template'] = 'labels';
  2443. $the_labels = array();
  2444. // Add all existing labels to the array to save, slashing them as necessary...
  2445. foreach ($context['labels'] as $label)
  2446. {
  2447. if ($label['id'] != -1)
  2448. $the_labels[$label['id']] = $label['name'];
  2449. }
  2450. if (isset($_POST[$context['session_var']]))
  2451. {
  2452. checkSession('post');
  2453. // This will be for updating messages.
  2454. $message_changes = array();
  2455. $new_labels = array();
  2456. $rule_changes = array();
  2457. // Will most likely need this.
  2458. LoadRules();
  2459. // Adding a new label?
  2460. if (isset($_POST['add']))
  2461. {
  2462. $_POST['label'] = strtr($smcFunc['htmlspecialchars'](trim($_POST['label'])), array(',' => '&#044;'));
  2463. if ($smcFunc['strlen']($_POST['label']) > 30)
  2464. $_POST['label'] = $smcFunc['substr']($_POST['label'], 0, 30);
  2465. if ($_POST['label'] != '')
  2466. $the_labels[] = $_POST['label'];
  2467. }
  2468. // Deleting an existing label?
  2469. elseif (isset($_POST['delete'], $_POST['delete_label']))
  2470. {
  2471. $i = 0;
  2472. foreach ($the_labels as $id => $name)
  2473. {
  2474. if (isset($_POST['delete_label'][$id]))
  2475. {
  2476. unset($the_labels[$id]);
  2477. $message_changes[$id] = true;
  2478. }
  2479. else
  2480. $new_labels[$id] = $i++;
  2481. }
  2482. }
  2483. // The hardest one to deal with... changes.
  2484. elseif (isset($_POST['save']) && !empty($_POST['label_name']))
  2485. {
  2486. $i = 0;
  2487. foreach ($the_labels as $id => $name)
  2488. {
  2489. if ($id == -1)
  2490. continue;
  2491. elseif (isset($_POST['label_name'][$id]))
  2492. {
  2493. $_POST['label_name'][$id] = trim(strtr($smcFunc['htmlspecialchars']($_POST['label_name'][$id]), array(',' => '&#044;')));
  2494. if ($smcFunc['strlen']($_POST['label_name'][$id]) > 30)
  2495. $_POST['label_name'][$id] = $smcFunc['substr']($_POST['label_name'][$id], 0, 30);
  2496. if ($_POST['label_name'][$id] != '')
  2497. {
  2498. $the_labels[(int) $id] = $_POST['label_name'][$id];
  2499. $new_labels[$id] = $i++;
  2500. }
  2501. else
  2502. {
  2503. unset($the_labels[(int) $id]);
  2504. $message_changes[(int) $id] = true;
  2505. }
  2506. }
  2507. else
  2508. $new_labels[$id] = $i++;
  2509. }
  2510. }
  2511. // Save the label status.
  2512. updateMemberData($user_info['id'], array('message_labels' => implode(',', $the_labels)));
  2513. // Update all the messages currently with any label changes in them!
  2514. if (!empty($message_changes))
  2515. {
  2516. $searchArray = array_keys($message_changes);
  2517. if (!empty($new_labels))
  2518. {
  2519. for ($i = max($searchArray) + 1, $n = max(array_keys($new_labels)); $i <= $n; $i++)
  2520. $searchArray[] = $i;
  2521. }
  2522. // Now find the messages to change.
  2523. $request = $smcFunc['db_query']('', '
  2524. SELECT id_pm, labels
  2525. FROM {db_prefix}pm_recipients
  2526. WHERE FIND_IN_SET({raw:find_label_implode}, labels) != 0
  2527. AND id_member = {int:current_member}',
  2528. array(
  2529. 'current_member' => $user_info['id'],
  2530. 'find_label_implode' => '\'' . implode('\', labels) != 0 OR FIND_IN_SET(\'', $searchArray) . '\'',
  2531. )
  2532. );
  2533. while ($row = $smcFunc['db_fetch_assoc']($request))
  2534. {
  2535. // Do the long task of updating them...
  2536. $toChange = explode(',', $row['labels']);
  2537. foreach ($toChange as $key => $value)
  2538. if (in_array($value, $searchArray))
  2539. {
  2540. if (isset($new_labels[$value]))
  2541. $toChange[$key] = $new_labels[$value];
  2542. else
  2543. unset($toChange[$key]);
  2544. }
  2545. if (empty($toChange))
  2546. $toChange[] = '-1';
  2547. // Update the message.
  2548. $smcFunc['db_query']('', '
  2549. UPDATE {db_prefix}pm_recipients
  2550. SET labels = {string:new_labels}
  2551. WHERE id_pm = {int:id_pm}
  2552. AND id_member = {int:current_member}',
  2553. array(
  2554. 'current_member' => $user_info['id'],
  2555. 'id_pm' => $row['id_pm'],
  2556. 'new_labels' => implode(',', array_unique($toChange)),
  2557. )
  2558. );
  2559. }
  2560. $smcFunc['db_free_result']($request);
  2561. // Now do the same the rules - check through each rule.
  2562. foreach ($context['rules'] as $k => $rule)
  2563. {
  2564. // Each action...
  2565. foreach ($rule['actions'] as $k2 => $action)
  2566. {
  2567. if ($action['t'] != 'lab' || !in_array($action['v'], $searchArray))
  2568. continue;
  2569. $rule_changes[] = $rule['id'];
  2570. // If we're here we have a label which is either changed or gone...
  2571. if (isset($new_labels[$action['v']]))
  2572. $context['rules'][$k]['actions'][$k2]['v'] = $new_labels[$action['v']];
  2573. else
  2574. unset($context['rules'][$k]['actions'][$k2]);
  2575. }
  2576. }
  2577. }
  2578. // If we have rules to change do so now.
  2579. if (!empty($rule_changes))
  2580. {
  2581. $rule_changes = array_unique($rule_changes);
  2582. // Update/delete as appropriate.
  2583. foreach ($rule_changes as $k => $id)
  2584. if (!empty($context['rules'][$id]['actions']))
  2585. {
  2586. $smcFunc['db_query']('', '
  2587. UPDATE {db_prefix}pm_rules
  2588. SET actions = {string:actions}
  2589. WHERE id_rule = {int:id_rule}
  2590. AND id_member = {int:current_member}',
  2591. array(
  2592. 'current_member' => $user_info['id'],
  2593. 'id_rule' => $id,
  2594. 'actions' => serialize($context['rules'][$id]['actions']),
  2595. )
  2596. );
  2597. unset($rule_changes[$k]);
  2598. }
  2599. // Anything left here means it's lost all actions...
  2600. if (!empty($rule_changes))
  2601. $smcFunc['db_query']('', '
  2602. DELETE FROM {db_prefix}pm_rules
  2603. WHERE id_rule IN ({array_int:rule_list})
  2604. AND id_member = {int:current_member}',
  2605. array(
  2606. 'current_member' => $user_info['id'],
  2607. 'rule_list' => $rule_changes,
  2608. )
  2609. );
  2610. }
  2611. // Make sure we're not caching this!
  2612. cache_put_data('labelCounts:' . $user_info['id'], null, 720);
  2613. // To make the changes appear right away, redirect.
  2614. redirectexit('action=pm;sa=manlabels');
  2615. }
  2616. }
  2617. /**
  2618. * Allows to edit Personal Message Settings.
  2619. *
  2620. * @uses Profile.php
  2621. * @uses Profile-Modify.php
  2622. * @uses Profile template.
  2623. * @uses Profile language file.
  2624. */
  2625. function MessageSettings()
  2626. {
  2627. global $txt, $user_settings, $user_info, $context, $sourcedir, $smcFunc;
  2628. global $scripturl, $profile_vars, $cur_profile, $user_profile;
  2629. // Need this for the display.
  2630. require_once($sourcedir . '/Profile.php');
  2631. require_once($sourcedir . '/Profile-Modify.php');
  2632. // We want them to submit back to here.
  2633. $context['profile_custom_submit_url'] = $scripturl . '?action=pm;sa=settings;save';
  2634. loadMemberData($user_info['id'], false, 'profile');
  2635. $cur_profile = $user_profile[$user_info['id']];
  2636. loadLanguage('Profile');
  2637. loadTemplate('Profile');
  2638. $context['page_title'] = $txt['pm_settings'];
  2639. $context['user']['is_owner'] = true;
  2640. $context['id_member'] = $user_info['id'];
  2641. $context['require_password'] = false;
  2642. $context['menu_item_selected'] = 'settings';
  2643. $context['submit_button_text'] = $txt['pm_settings'];
  2644. $context['profile_header_text'] = $txt['personal_messages'];
  2645. // Add our position to the linktree.
  2646. $context['linktree'][] = array(
  2647. 'url' => $scripturl . '?action=pm;sa=settings',
  2648. 'name' => $txt['pm_settings']
  2649. );
  2650. // Are they saving?
  2651. if (isset($_REQUEST['save']))
  2652. {
  2653. checkSession('post');
  2654. // Mimic what profile would do.
  2655. $_POST = htmltrim__recursive($_POST);
  2656. $_POST = htmlspecialchars__recursive($_POST);
  2657. // Save the fields.
  2658. saveProfileFields();
  2659. if (!empty($profile_vars))
  2660. updateMemberData($user_info['id'], $profile_vars);
  2661. }
  2662. // Load up the fields.
  2663. pmprefs($user_info['id']);
  2664. }
  2665. /**
  2666. * Allows the user to report a personal message to an administrator.
  2667. *
  2668. * - In the first instance requires that the ID of the message to report is passed through $_GET.
  2669. * - It allows the user to report to either a particular administrator - or the whole admin team.
  2670. * - It will forward on a copy of the original message without allowing the reporter to make changes.
  2671. *
  2672. * @uses report_message sub-template.
  2673. */
  2674. function ReportMessage()
  2675. {
  2676. global $txt, $context, $scripturl, $sourcedir;
  2677. global $user_info, $language, $modSettings, $smcFunc;
  2678. // Check that this feature is even enabled!
  2679. if (empty($modSettings['enableReportPM']) || empty($_REQUEST['pmsg']))
  2680. fatal_lang_error('no_access', false);
  2681. $pmsg = (int) $_REQUEST['pmsg'];
  2682. if (!isAccessiblePM($pmsg, 'inbox'))
  2683. fatal_lang_error('no_access', false);
  2684. $context['pm_id'] = $pmsg;
  2685. $context['page_title'] = $txt['pm_report_title'];
  2686. // If we're here, just send the user to the template, with a few useful context bits.
  2687. if (!isset($_POST['report']))
  2688. {
  2689. $context['sub_template'] = 'report_message';
  2690. // @todo I don't like being able to pick who to send it to. Favoritism, etc. sucks.
  2691. // Now, get all the administrators.
  2692. $request = $smcFunc['db_query']('', '
  2693. SELECT id_member, real_name
  2694. FROM {db_prefix}members
  2695. WHERE id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0
  2696. ORDER BY real_name',
  2697. array(
  2698. 'admin_group' => 1,
  2699. )
  2700. );
  2701. $context['admins'] = array();
  2702. while ($row = $smcFunc['db_fetch_assoc']($request))
  2703. $context['admins'][$row['id_member']] = $row['real_name'];
  2704. $smcFunc['db_free_result']($request);
  2705. // How many admins in total?
  2706. $context['admin_count'] = count($context['admins']);
  2707. }
  2708. // Otherwise, let's get down to the sending stuff.
  2709. else
  2710. {
  2711. // Check the session before proceeding any further!
  2712. checkSession('post');
  2713. // First, pull out the message contents, and verify it actually went to them!
  2714. $request = $smcFunc['db_query']('', '
  2715. SELECT pm.subject, pm.body, pm.msgtime, pm.id_member_from, IFNULL(m.real_name, pm.from_name) AS sender_name
  2716. FROM {db_prefix}personal_messages AS pm
  2717. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)
  2718. LEFT JOIN {db_prefix}members AS m ON (m.id_member = pm.id_member_from)
  2719. WHERE pm.id_pm = {int:id_pm}
  2720. AND pmr.id_member = {int:current_member}
  2721. AND pmr.deleted = {int:not_deleted}
  2722. LIMIT 1',
  2723. array(
  2724. 'current_member' => $user_info['id'],
  2725. 'id_pm' => $context['pm_id'],
  2726. 'not_deleted' => 0,
  2727. )
  2728. );
  2729. // Can only be a hacker here!
  2730. if ($smcFunc['db_num_rows']($request) == 0)
  2731. fatal_lang_error('no_access', false);
  2732. list ($subject, $body, $time, $memberFromID, $memberFromName) = $smcFunc['db_fetch_row']($request);
  2733. $smcFunc['db_free_result']($request);
  2734. // Remove the line breaks...
  2735. $body = preg_replace('~<br ?/?' . '>~i', "\n", $body);
  2736. // Get any other recipients of the email.
  2737. $request = $smcFunc['db_query']('', '
  2738. SELECT mem_to.id_member AS id_member_to, mem_to.real_name AS to_name, pmr.bcc
  2739. FROM {db_prefix}pm_recipients AS pmr
  2740. LEFT JOIN {db_prefix}members AS mem_to ON (mem_to.id_member = pmr.id_member)
  2741. WHERE pmr.id_pm = {int:id_pm}
  2742. AND pmr.id_member != {int:current_member}',
  2743. array(
  2744. 'current_member' => $user_info['id'],
  2745. 'id_pm' => $context['pm_id'],
  2746. )
  2747. );
  2748. $recipients = array();
  2749. $hidden_recipients = 0;
  2750. while ($row = $smcFunc['db_fetch_assoc']($request))
  2751. {
  2752. // If it's hidden still don't reveal their names - privacy after all ;)
  2753. if ($row['bcc'])
  2754. $hidden_recipients++;
  2755. else
  2756. $recipients[] = '[url=' . $scripturl . '?action=profile;u=' . $row['id_member_to'] . ']' . $row['to_name'] . '[/url]';
  2757. }
  2758. $smcFunc['db_free_result']($request);
  2759. if ($hidden_recipients)
  2760. $recipients[] = sprintf($txt['pm_report_pm_hidden'], $hidden_recipients);
  2761. // Now let's get out and loop through the admins.
  2762. $request = $smcFunc['db_query']('', '
  2763. SELECT id_member, real_name, lngfile
  2764. FROM {db_prefix}members
  2765. WHERE (id_group = {int:admin_id} OR FIND_IN_SET({int:admin_id}, additional_groups) != 0)
  2766. ' . (empty($_POST['id_admin']) ? '' : 'AND id_member = {int:specific_admin}') . '
  2767. ORDER BY lngfile',
  2768. array(
  2769. 'admin_id' => 1,
  2770. 'specific_admin' => isset($_POST['id_admin']) ? (int) $_POST['id_admin'] : 0,
  2771. )
  2772. );
  2773. // Maybe we shouldn't advertise this?
  2774. if ($smcFunc['db_num_rows']($request) == 0)
  2775. fatal_lang_error('no_access', false);
  2776. $memberFromName = un_htmlspecialchars($memberFromName);
  2777. // Prepare the message storage array.
  2778. $messagesToSend = array();
  2779. // Loop through each admin, and add them to the right language pile...
  2780. while ($row = $smcFunc['db_fetch_assoc']($request))
  2781. {
  2782. // Need to send in the correct language!
  2783. $cur_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
  2784. if (!isset($messagesToSend[$cur_language]))
  2785. {
  2786. loadLanguage('PersonalMessage', $cur_language, false);
  2787. // Make the body.
  2788. $report_body = str_replace(array('{REPORTER}', '{SENDER}'), array(un_htmlspecialchars($user_info['name']), $memberFromName), $txt['pm_report_pm_user_sent']);
  2789. $report_body .= "\n" . '[b]' . $_POST['reason'] . '[/b]' . "\n\n";
  2790. if (!empty($recipients))
  2791. $report_body .= $txt['pm_report_pm_other_recipients'] . ' ' . implode(', ', $recipients) . "\n\n";
  2792. $report_body .= $txt['pm_report_pm_unedited_below'] . "\n" . '[quote author=' . (empty($memberFromID) ? '&quot;' . $memberFromName . '&quot;' : $memberFromName . ' link=action=profile;u=' . $memberFromID . ' date=' . $time) . ']' . "\n" . un_htmlspecialchars($body) . '[/quote]';
  2793. // Plonk it in the array ;)
  2794. $messagesToSend[$cur_language] = array(
  2795. 'subject' => ($smcFunc['strpos']($subject, $txt['pm_report_pm_subject']) === false ? $txt['pm_report_pm_subject'] : '') . un_htmlspecialchars($subject),
  2796. 'body' => $report_body,
  2797. 'recipients' => array(
  2798. 'to' => array(),
  2799. 'bcc' => array()
  2800. ),
  2801. );
  2802. }
  2803. // Add them to the list.
  2804. $messagesToSend[$cur_language]['recipients']['to'][$row['id_member']] = $row['id_member'];
  2805. }
  2806. $smcFunc['db_free_result']($request);
  2807. // Send a different email for each language.
  2808. foreach ($messagesToSend as $lang => $message)
  2809. sendpm($message['recipients'], $message['subject'], $message['body']);
  2810. // Give the user their own language back!
  2811. if (!empty($modSettings['userLanguage']))
  2812. loadLanguage('PersonalMessage', '', false);
  2813. // Leave them with a template.
  2814. $context['sub_template'] = 'report_message_complete';
  2815. }
  2816. }
  2817. /**
  2818. * List all rules, and allow adding/entering etc...
  2819. */
  2820. function ManageRules()
  2821. {
  2822. global $txt, $context, $user_info, $scripturl, $smcFunc;
  2823. // The link tree - gotta have this :o
  2824. $context['linktree'][] = array(
  2825. 'url' => $scripturl . '?action=pm;sa=manrules',
  2826. 'name' => $txt['pm_manage_rules']
  2827. );
  2828. $context['page_title'] = $txt['pm_manage_rules'];
  2829. $context['sub_template'] = 'rules';
  2830. // Load them... load them!!
  2831. LoadRules();
  2832. // Likely to need all the groups!
  2833. $request = $smcFunc['db_query']('', '
  2834. SELECT mg.id_group, mg.group_name, IFNULL(gm.id_member, 0) AS can_moderate, mg.hidden
  2835. FROM {db_prefix}membergroups AS mg
  2836. LEFT JOIN {db_prefix}group_moderators AS gm ON (gm.id_group = mg.id_group AND gm.id_member = {int:current_member})
  2837. WHERE mg.min_posts = {int:min_posts}
  2838. AND mg.id_group != {int:moderator_group}
  2839. AND mg.hidden = {int:not_hidden}
  2840. ORDER BY mg.group_name',
  2841. array(
  2842. 'current_member' => $user_info['id'],
  2843. 'min_posts' => -1,
  2844. 'moderator_group' => 3,
  2845. 'not_hidden' => 0,
  2846. )
  2847. );
  2848. $context['groups'] = array();
  2849. while ($row = $smcFunc['db_fetch_assoc']($request))
  2850. {
  2851. // Hide hidden groups!
  2852. if ($row['hidden'] && !$row['can_moderate'] && !allowedTo('manage_membergroups'))
  2853. continue;
  2854. $context['groups'][$row['id_group']] = $row['group_name'];
  2855. }
  2856. $smcFunc['db_free_result']($request);
  2857. // Applying all rules?
  2858. if (isset($_GET['apply']))
  2859. {
  2860. checkSession('get');
  2861. ApplyRules(true);
  2862. redirectexit('action=pm;sa=manrules');
  2863. }
  2864. // Editing a specific one?
  2865. if (isset($_GET['add']))
  2866. {
  2867. $context['rid'] = isset($_GET['rid']) && isset($context['rules'][$_GET['rid']])? (int) $_GET['rid'] : 0;
  2868. $context['sub_template'] = 'add_rule';
  2869. // Current rule information...
  2870. if ($context['rid'])
  2871. {
  2872. $context['rule'] = $context['rules'][$context['rid']];
  2873. $members = array();
  2874. // Need to get member names!
  2875. foreach ($context['rule']['criteria'] as $k => $criteria)
  2876. if ($criteria['t'] == 'mid' && !empty($criteria['v']))
  2877. $members[(int) $criteria['v']] = $k;
  2878. if (!empty($members))
  2879. {
  2880. $request = $smcFunc['db_query']('', '
  2881. SELECT id_member, member_name
  2882. FROM {db_prefix}members
  2883. WHERE id_member IN ({array_int:member_list})',
  2884. array(
  2885. 'member_list' => array_keys($members),
  2886. )
  2887. );
  2888. while ($row = $smcFunc['db_fetch_assoc']($request))
  2889. $context['rule']['criteria'][$members[$row['id_member']]]['v'] = $row['member_name'];
  2890. $smcFunc['db_free_result']($request);
  2891. }
  2892. }
  2893. else
  2894. $context['rule'] = array(
  2895. 'id' => '',
  2896. 'name' => '',
  2897. 'criteria' => array(),
  2898. 'actions' => array(),
  2899. 'logic' => 'and',
  2900. );
  2901. }
  2902. // Saving?
  2903. elseif (isset($_GET['save']))
  2904. {
  2905. checkSession('post');
  2906. $context['rid'] = isset($_GET['rid']) && isset($context['rules'][$_GET['rid']])? (int) $_GET['rid'] : 0;
  2907. // Name is easy!
  2908. $ruleName = $smcFunc['htmlspecialchars'](trim($_POST['rule_name']));
  2909. if (empty($ruleName))
  2910. fatal_lang_error('pm_rule_no_name', false);
  2911. // Sanity check...
  2912. if (empty($_POST['ruletype']) || empty($_POST['acttype']))
  2913. fatal_lang_error('pm_rule_no_criteria', false);
  2914. // Let's do the criteria first - it's also hardest!
  2915. $criteria = array();
  2916. foreach ($_POST['ruletype'] as $ind => $type)
  2917. {
  2918. // Check everything is here...
  2919. if ($type == 'gid' && (!isset($_POST['ruledefgroup'][$ind]) || !isset($context['groups'][$_POST['ruledefgroup'][$ind]])))
  2920. continue;
  2921. elseif ($type != 'bud' && !isset($_POST['ruledef'][$ind]))
  2922. continue;
  2923. // Members need to be found.
  2924. if ($type == 'mid')
  2925. {
  2926. $name = trim($_POST['ruledef'][$ind]);
  2927. $request = $smcFunc['db_query']('', '
  2928. SELECT id_member
  2929. FROM {db_prefix}members
  2930. WHERE real_name = {string:member_name}
  2931. OR member_name = {string:member_name}',
  2932. array(
  2933. 'member_name' => $name,
  2934. )
  2935. );
  2936. if ($smcFunc['db_num_rows']($request) == 0)
  2937. continue;
  2938. list ($memID) = $smcFunc['db_fetch_row']($request);
  2939. $smcFunc['db_free_result']($request);
  2940. $criteria[] = array('t' => 'mid', 'v' => $memID);
  2941. }
  2942. elseif ($type == 'bud')
  2943. $criteria[] = array('t' => 'bud', 'v' => 1);
  2944. elseif ($type == 'gid')
  2945. $criteria[] = array('t' => 'gid', 'v' => (int) $_POST['ruledefgroup'][$ind]);
  2946. elseif (in_array($type, array('sub', 'msg')) && trim($_POST['ruledef'][$ind]) != '')
  2947. $criteria[] = array('t' => $type, 'v' => $smcFunc['htmlspecialchars'](trim($_POST['ruledef'][$ind])));
  2948. }
  2949. // Also do the actions!
  2950. $actions = array();
  2951. $doDelete = 0;
  2952. $isOr = $_POST['rule_logic'] == 'or' ? 1 : 0;
  2953. foreach ($_POST['acttype'] as $ind => $type)
  2954. {
  2955. // Picking a valid label?
  2956. if ($type == 'lab' && (!isset($_POST['labdef'][$ind]) || !isset($context['labels'][$_POST['labdef'][$ind] - 1])))
  2957. continue;
  2958. // Record what we're doing.
  2959. if ($type == 'del')
  2960. $doDelete = 1;
  2961. elseif ($type == 'lab')
  2962. $actions[] = array('t' => 'lab', 'v' => (int) $_POST['labdef'][$ind] - 1);
  2963. }
  2964. if (empty($criteria) || (empty($actions) && !$doDelete))
  2965. fatal_lang_error('pm_rule_no_criteria', false);
  2966. // What are we storing?
  2967. $criteria = serialize($criteria);
  2968. $actions = serialize($actions);
  2969. // Create the rule?
  2970. if (empty($context['rid']))
  2971. $smcFunc['db_insert']('',
  2972. '{db_prefix}pm_rules',
  2973. array(
  2974. 'id_member' => 'int', 'rule_name' => 'string', 'criteria' => 'string', 'actions' => 'string',
  2975. 'delete_pm' => 'int', 'is_or' => 'int',
  2976. ),
  2977. array(
  2978. $user_info['id'], $ruleName, $criteria, $actions, $doDelete, $isOr,
  2979. ),
  2980. array('id_rule')
  2981. );
  2982. else
  2983. $smcFunc['db_query']('', '
  2984. UPDATE {db_prefix}pm_rules
  2985. SET rule_name = {string:rule_name}, criteria = {string:criteria}, actions = {string:actions},
  2986. delete_pm = {int:delete_pm}, is_or = {int:is_or}
  2987. WHERE id_rule = {int:id_rule}
  2988. AND id_member = {int:current_member}',
  2989. array(
  2990. 'current_member' => $user_info['id'],
  2991. 'delete_pm' => $doDelete,
  2992. 'is_or' => $isOr,
  2993. 'id_rule' => $context['rid'],
  2994. 'rule_name' => $ruleName,
  2995. 'criteria' => $criteria,
  2996. 'actions' => $actions,
  2997. )
  2998. );
  2999. redirectexit('action=pm;sa=manrules');
  3000. }
  3001. // Deleting?
  3002. elseif (isset($_POST['delselected']) && !empty($_POST['delrule']))
  3003. {
  3004. checkSession('post');
  3005. $toDelete = array();
  3006. foreach ($_POST['delrule'] as $k => $v)
  3007. $toDelete[] = (int) $k;
  3008. if (!empty($toDelete))
  3009. $smcFunc['db_query']('', '
  3010. DELETE FROM {db_prefix}pm_rules
  3011. WHERE id_rule IN ({array_int:delete_list})
  3012. AND id_member = {int:current_member}',
  3013. array(
  3014. 'current_member' => $user_info['id'],
  3015. 'delete_list' => $toDelete,
  3016. )
  3017. );
  3018. redirectexit('action=pm;sa=manrules');
  3019. }
  3020. }
  3021. /**
  3022. * This will apply rules to all unread messages. If all_messages is set will, clearly, do it to all!
  3023. *
  3024. * @param bool $all_messages = false
  3025. */
  3026. function ApplyRules($all_messages = false)
  3027. {
  3028. global $user_info, $smcFunc, $context, $options;
  3029. // Want this - duh!
  3030. loadRules();
  3031. // No rules?
  3032. if (empty($context['rules']))
  3033. return;
  3034. // Just unread ones?
  3035. $ruleQuery = $all_messages ? '' : ' AND pmr.is_new = 1';
  3036. // @todo Apply all should have timeout protection!
  3037. // Get all the messages that match this.
  3038. $request = $smcFunc['db_query']('', '
  3039. SELECT
  3040. pmr.id_pm, pm.id_member_from, pm.subject, pm.body, mem.id_group, pmr.labels
  3041. FROM {db_prefix}pm_recipients AS pmr
  3042. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)
  3043. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = pm.id_member_from)
  3044. WHERE pmr.id_member = {int:current_member}
  3045. AND pmr.deleted = {int:not_deleted}
  3046. ' . $ruleQuery,
  3047. array(
  3048. 'current_member' => $user_info['id'],
  3049. 'not_deleted' => 0,
  3050. )
  3051. );
  3052. $actions = array();
  3053. while ($row = $smcFunc['db_fetch_assoc']($request))
  3054. {
  3055. foreach ($context['rules'] as $rule)
  3056. {
  3057. $match = false;
  3058. // Loop through all the criteria hoping to make a match.
  3059. foreach ($rule['criteria'] as $criterium)
  3060. {
  3061. if (($criterium['t'] == 'mid' && $criterium['v'] == $row['id_member_from']) || ($criterium['t'] == 'gid' && $criterium['v'] == $row['id_group']) || ($criterium['t'] == 'sub' && strpos($row['subject'], $criterium['v']) !== false) || ($criterium['t'] == 'msg' && strpos($row['body'], $criterium['v']) !== false))
  3062. $match = true;
  3063. // If we're adding and one criteria don't match then we stop!
  3064. elseif ($rule['logic'] == 'and')
  3065. {
  3066. $match = false;
  3067. break;
  3068. }
  3069. }
  3070. // If we have a match the rule must be true - act!
  3071. if ($match)
  3072. {
  3073. if ($rule['delete'])
  3074. $actions['deletes'][] = $row['id_pm'];
  3075. else
  3076. {
  3077. foreach ($rule['actions'] as $ruleAction)
  3078. {
  3079. if ($ruleAction['t'] == 'lab')
  3080. {
  3081. // Get a basic pot started!
  3082. if (!isset($actions['labels'][$row['id_pm']]))
  3083. $actions['labels'][$row['id_pm']] = empty($row['labels']) ? array() : explode(',', $row['labels']);
  3084. $actions['labels'][$row['id_pm']][] = $ruleAction['v'];
  3085. }
  3086. }
  3087. }
  3088. }
  3089. }
  3090. }
  3091. $smcFunc['db_free_result']($request);
  3092. // Deletes are easy!
  3093. if (!empty($actions['deletes']))
  3094. deleteMessages($actions['deletes']);
  3095. // Relabel?
  3096. if (!empty($actions['labels']))
  3097. {
  3098. foreach ($actions['labels'] as $pm => $labels)
  3099. {
  3100. // Quickly check each label is valid!
  3101. $realLabels = array();
  3102. foreach ($context['labels'] as $label)
  3103. if (in_array($label['id'], $labels) && ($label['id'] != -1 || empty($options['pm_remove_inbox_label'])))
  3104. $realLabels[] = $label['id'];
  3105. $smcFunc['db_query']('', '
  3106. UPDATE {db_prefix}pm_recipients
  3107. SET labels = {string:new_labels}
  3108. WHERE id_pm = {int:id_pm}
  3109. AND id_member = {int:current_member}',
  3110. array(
  3111. 'current_member' => $user_info['id'],
  3112. 'id_pm' => $pm,
  3113. 'new_labels' => empty($realLabels) ? '' : implode(',', $realLabels),
  3114. )
  3115. );
  3116. }
  3117. }
  3118. }
  3119. /**
  3120. * Load up all the rules for the current user.
  3121. *
  3122. * @param bool $reload = false
  3123. */
  3124. function LoadRules($reload = false)
  3125. {
  3126. global $user_info, $context, $smcFunc;
  3127. if (isset($context['rules']) && !$reload)
  3128. return;
  3129. $request = $smcFunc['db_query']('', '
  3130. SELECT
  3131. id_rule, rule_name, criteria, actions, delete_pm, is_or
  3132. FROM {db_prefix}pm_rules
  3133. WHERE id_member = {int:current_member}',
  3134. array(
  3135. 'current_member' => $user_info['id'],
  3136. )
  3137. );
  3138. $context['rules'] = array();
  3139. // Simply fill in the data!
  3140. while ($row = $smcFunc['db_fetch_assoc']($request))
  3141. {
  3142. $context['rules'][$row['id_rule']] = array(
  3143. 'id' => $row['id_rule'],
  3144. 'name' => $row['rule_name'],
  3145. 'criteria' => unserialize($row['criteria']),
  3146. 'actions' => unserialize($row['actions']),
  3147. 'delete' => $row['delete_pm'],
  3148. 'logic' => $row['is_or'] ? 'or' : 'and',
  3149. );
  3150. if ($row['delete_pm'])
  3151. $context['rules'][$row['id_rule']]['actions'][] = array('t' => 'del', 'v' => 1);
  3152. }
  3153. $smcFunc['db_free_result']($request);
  3154. }
  3155. /**
  3156. * Check if the PM is available to the current user.
  3157. *
  3158. * @param int $pmID
  3159. * @param $validFor
  3160. * @return bool
  3161. */
  3162. function isAccessiblePM($pmID, $validFor = 'in_or_outbox')
  3163. {
  3164. global $user_info, $smcFunc;
  3165. $request = $smcFunc['db_query']('', '
  3166. SELECT
  3167. pm.id_member_from = {int:id_current_member} AND pm.deleted_by_sender = {int:not_deleted} AS valid_for_outbox,
  3168. pmr.id_pm IS NOT NULL AS valid_for_inbox
  3169. FROM {db_prefix}personal_messages AS pm
  3170. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm AND pmr.id_member = {int:id_current_member} AND pmr.deleted = {int:not_deleted})
  3171. WHERE pm.id_pm = {int:id_pm}
  3172. AND ((pm.id_member_from = {int:id_current_member} AND pm.deleted_by_sender = {int:not_deleted}) OR pmr.id_pm IS NOT NULL)',
  3173. array(
  3174. 'id_pm' => $pmID,
  3175. 'id_current_member' => $user_info['id'],
  3176. 'not_deleted' => 0,
  3177. )
  3178. );
  3179. if ($smcFunc['db_num_rows']($request) === 0)
  3180. {
  3181. $smcFunc['db_free_result']($request);
  3182. return false;
  3183. }
  3184. $validationResult = $smcFunc['db_fetch_assoc']($request);
  3185. $smcFunc['db_free_result']($request);
  3186. switch ($validFor)
  3187. {
  3188. case 'inbox':
  3189. return !empty($validationResult['valid_for_inbox']);
  3190. break;
  3191. case 'outbox':
  3192. return !empty($validationResult['valid_for_outbox']);
  3193. break;
  3194. case 'in_or_outbox':
  3195. return !empty($validationResult['valid_for_inbox']) || !empty($validationResult['valid_for_outbox']);
  3196. break;
  3197. default:
  3198. trigger_error('Undefined validation type given', E_USER_ERROR);
  3199. break;
  3200. }
  3201. }
  3202. ?>