PersonalMessage.php 139 KB

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