PersonalMessage.php 139 KB

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