PersonalMessage.php 128 KB

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