PersonalMessage.php 128 KB

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