PersonalMessage.php 126 KB

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