PersonalMessage.php 128 KB

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