PersonalMessage.php 139 KB

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