2
0

PersonalMessage.php 141 KB

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