PersonalMessage.php 136 KB

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