PersonalMessage.php 124 KB

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