2
0

PersonalMessage.php 139 KB

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