PersonalMessage.php 128 KB

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