PersonalMessage.php 125 KB

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