PersonalMessage.php 129 KB

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