Subs-Post.php 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285
  1. <?php
  2. /**
  3. * This file contains those functions pertaining to posting, and other such
  4. * operations, including sending emails, ims, blocking spam, preparsing posts,
  5. * spell checking, and the post box.
  6. *
  7. * Simple Machines Forum (SMF)
  8. *
  9. * @package SMF
  10. * @author Simple Machines http://www.simplemachines.org
  11. * @copyright 2011 Simple Machines
  12. * @license http://www.simplemachines.org/about/smf/license.php BSD
  13. *
  14. * @version 2.1 Alpha 1
  15. */
  16. if (!defined('SMF'))
  17. die('Hacking attempt...');
  18. /**
  19. * Takes a message and parses it, returning nothing.
  20. * Cleans up links (javascript, etc.) and code/quote sections.
  21. * Won't convert \n's and a few other things if previewing is true.
  22. *
  23. * @param $message
  24. * @param $previewing
  25. */
  26. function preparsecode(&$message, $previewing = false)
  27. {
  28. global $user_info, $modSettings, $smcFunc, $context;
  29. // This line makes all languages *theoretically* work even with the wrong charset ;).
  30. $message = preg_replace('~&amp;#(\d{4,5}|[2-9]\d{2,4}|1[2-9]\d);~', '&#$1;', $message);
  31. // Clean up after nobbc ;).
  32. $message = preg_replace('~\[nobbc\](.+?)\[/nobbc\]~ie', '\'[nobbc]\' . strtr(\'$1\', array(\'[\' => \'&#91;\', \']\' => \'&#93;\', \':\' => \'&#58;\', \'@\' => \'&#64;\')) . \'[/nobbc]\'', $message);
  33. // Remove \r's... they're evil!
  34. $message = strtr($message, array("\r" => ''));
  35. // You won't believe this - but too many periods upsets apache it seems!
  36. $message = preg_replace('~\.{100,}~', '...', $message);
  37. // Trim off trailing quotes - these often happen by accident.
  38. while (substr($message, -7) == '[quote]')
  39. $message = substr($message, 0, -7);
  40. while (strpos($message, '[/quote]') === 0)
  41. $message = substr($message, 8);
  42. // Find all code blocks, work out whether we'd be parsing them, then ensure they are all closed.
  43. $in_tag = false;
  44. $had_tag = false;
  45. $codeopen = 0;
  46. if (preg_match_all('~(\[(/)*code(?:=[^\]]+)?\])~is', $message, $matches))
  47. foreach ($matches[0] as $index => $dummy)
  48. {
  49. // Closing?
  50. if (!empty($matches[2][$index]))
  51. {
  52. // If it's closing and we're not in a tag we need to open it...
  53. if (!$in_tag)
  54. $codeopen = true;
  55. // Either way we ain't in one any more.
  56. $in_tag = false;
  57. }
  58. // Opening tag...
  59. else
  60. {
  61. $had_tag = true;
  62. // If we're in a tag don't do nought!
  63. if (!$in_tag)
  64. $in_tag = true;
  65. }
  66. }
  67. // If we have an open tag, close it.
  68. if ($in_tag)
  69. $message .= '[/code]';
  70. // Open any ones that need to be open, only if we've never had a tag.
  71. if ($codeopen && !$had_tag)
  72. $message = '[code]' . $message;
  73. // Now that we've fixed all the code tags, let's fix the img and url tags...
  74. $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
  75. // The regular expression non breaking space has many versions.
  76. $non_breaking_space = $context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}' : "\xC2\xA0") : '\xA0';
  77. // Only mess with stuff outside [code] tags.
  78. for ($i = 0, $n = count($parts); $i < $n; $i++)
  79. {
  80. // It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
  81. if ($i % 4 == 0)
  82. {
  83. fixTags($parts[$i]);
  84. // Replace /me.+?\n with [me=name]dsf[/me]\n.
  85. if (strpos($user_info['name'], '[') !== false || strpos($user_info['name'], ']') !== false || strpos($user_info['name'], '\'') !== false || strpos($user_info['name'], '"') !== false)
  86. $parts[$i] = preg_replace('~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '$1[me=&quot;' . $user_info['name'] . '&quot;]$2[/me]', $parts[$i]);
  87. else
  88. $parts[$i] = preg_replace('~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '$1[me=' . $user_info['name'] . ']$2[/me]', $parts[$i]);
  89. if (!$previewing && strpos($parts[$i], '[html]') !== false)
  90. {
  91. if (allowedTo('admin_forum'))
  92. $parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ise', '\'[html]\' . strtr(un_htmlspecialchars(\'$1\'), array("\n" => \'&#13;\', \' \' => \' &#32;\', \'[\' => \'&#91;\', \']\' => \'&#93;\')) . \'[/html]\'', $parts[$i]);
  93. // We should edit them out, or else if an admin edits the message they will get shown...
  94. else
  95. {
  96. while (strpos($parts[$i], '[html]') !== false)
  97. $parts[$i] = preg_replace('~\[[/]?html\]~i', '', $parts[$i]);
  98. }
  99. }
  100. // Let's look at the time tags...
  101. $parts[$i] = preg_replace('~\[time(?:=(absolute))*\](.+?)\[/time\]~ie', '\'[time]\' . (is_numeric(\'$2\') || @strtotime(\'$2\') == 0 ? \'$2\' : strtotime(\'$2\') - (\'$1\' == \'absolute\' ? 0 : (($modSettings[\'time_offset\'] + $user_info[\'time_offset\']) * 3600))) . \'[/time]\'', $parts[$i]);
  102. // Change the color specific tags to [color=the color].
  103. $parts[$i] = preg_replace('~\[(black|blue|green|red|white)\]~', '[color=$1]', $parts[$i]); // First do the opening tags.
  104. $parts[$i] = preg_replace('~\[/(black|blue|green|red|white)\]~', '[/color]', $parts[$i]); // And now do the closing tags
  105. // Make sure all tags are lowercase.
  106. $parts[$i] = preg_replace('~\[([/]?)(list|li|table|tr|td)((\s[^\]]+)*)\]~ie', '\'[$1\' . strtolower(\'$2\') . \'$3]\'', $parts[$i]);
  107. $list_open = substr_count($parts[$i], '[list]') + substr_count($parts[$i], '[list ');
  108. $list_close = substr_count($parts[$i], '[/list]');
  109. if ($list_close - $list_open > 0)
  110. $parts[$i] = str_repeat('[list]', $list_close - $list_open) . $parts[$i];
  111. if ($list_open - $list_close > 0)
  112. $parts[$i] = $parts[$i] . str_repeat('[/list]', $list_open - $list_close);
  113. $mistake_fixes = array(
  114. // Find [table]s not followed by [tr].
  115. '~\[table\](?![\s' . $non_breaking_space . ']*\[tr\])~s' . ($context['utf8'] ? 'u' : '') => '[table][tr]',
  116. // Find [tr]s not followed by [td].
  117. '~\[tr\](?![\s' . $non_breaking_space . ']*\[td\])~s' . ($context['utf8'] ? 'u' : '') => '[tr][td]',
  118. // Find [/td]s not followed by something valid.
  119. '~\[/td\](?![\s' . $non_breaking_space . ']*(?:\[td\]|\[/tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr]',
  120. // Find [/tr]s not followed by something valid.
  121. '~\[/tr\](?![\s' . $non_breaking_space . ']*(?:\[tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/tr][/table]',
  122. // Find [/td]s incorrectly followed by [/table].
  123. '~\[/td\][\s' . $non_breaking_space . ']*\[/table\]~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr][/table]',
  124. // Find [table]s, [tr]s, and [/td]s (possibly correctly) followed by [td].
  125. '~\[(table|tr|/td)\]([\s' . $non_breaking_space . ']*)\[td\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_td_]',
  126. // Now, any [td]s left should have a [tr] before them.
  127. '~\[td\]~s' => '[tr][td]',
  128. // Look for [tr]s which are correctly placed.
  129. '~\[(table|/tr)\]([\s' . $non_breaking_space . ']*)\[tr\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_tr_]',
  130. // Any remaining [tr]s should have a [table] before them.
  131. '~\[tr\]~s' => '[table][tr]',
  132. // Look for [/td]s followed by [/tr].
  133. '~\[/td\]([\s' . $non_breaking_space . ']*)\[/tr\]~s' . ($context['utf8'] ? 'u' : '') => '[/td]$1[_/tr_]',
  134. // Any remaining [/tr]s should have a [/td].
  135. '~\[/tr\]~s' => '[/td][/tr]',
  136. // Look for properly opened [li]s which aren't closed.
  137. '~\[li\]([^\[\]]+?)\[li\]~s' => '[li]$1[_/li_][_li_]',
  138. '~\[li\]([^\[\]]+?)\[/list\]~s' => '[_li_]$1[_/li_][/list]',
  139. '~\[li\]([^\[\]]+?)$~s' => '[li]$1[/li]',
  140. // Lists - find correctly closed items/lists.
  141. '~\[/li\]([\s' . $non_breaking_space . ']*)\[/list\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[/list]',
  142. // Find list items closed and then opened.
  143. '~\[/li\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[_li_]',
  144. // Now, find any [list]s or [/li]s followed by [li].
  145. '~\[(list(?: [^\]]*?)?|/li)\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_li_]',
  146. // Allow for sub lists.
  147. '~\[/li\]([\s' . $non_breaking_space . ']*)\[list\]~' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[list]',
  148. '~\[/list\]([\s' . $non_breaking_space . ']*)\[li\]~' . ($context['utf8'] ? 'u' : '') => '[/list]$1[_li_]',
  149. // Any remaining [li]s weren't inside a [list].
  150. '~\[li\]~' => '[list][li]',
  151. // Any remaining [/li]s weren't before a [/list].
  152. '~\[/li\]~' => '[/li][/list]',
  153. // Put the correct ones back how we found them.
  154. '~\[_(li|/li|td|tr|/tr)_\]~' => '[$1]',
  155. // Images with no real url.
  156. '~\[img\]https?://.{0,7}\[/img\]~' => '',
  157. );
  158. // Fix up some use of tables without [tr]s, etc. (it has to be done more than once to catch it all.)
  159. for ($j = 0; $j < 3; $j++)
  160. $parts[$i] = preg_replace(array_keys($mistake_fixes), $mistake_fixes, $parts[$i]);
  161. // Now we're going to do full scale table checking...
  162. $table_check = $parts[$i];
  163. $table_offset = 0;
  164. $table_array = array();
  165. $table_order = array(
  166. 'table' => 'td',
  167. 'tr' => 'table',
  168. 'td' => 'tr',
  169. );
  170. while (preg_match('~\[(/)*(table|tr|td)\]~', $table_check, $matches) != false)
  171. {
  172. // Keep track of where this is.
  173. $offset = strpos($table_check, $matches[0]);
  174. $remove_tag = false;
  175. // Is it opening?
  176. if ($matches[1] != '/')
  177. {
  178. // If the previous table tag isn't correct simply remove it.
  179. if ((!empty($table_array) && $table_array[0] != $table_order[$matches[2]]) || (empty($table_array) && $matches[2] != 'table'))
  180. $remove_tag = true;
  181. // Record this was the last tag.
  182. else
  183. array_unshift($table_array, $matches[2]);
  184. }
  185. // Otherwise is closed!
  186. else
  187. {
  188. // Only keep the tag if it's closing the right thing.
  189. if (empty($table_array) || ($table_array[0] != $matches[2]))
  190. $remove_tag = true;
  191. else
  192. array_shift($table_array);
  193. }
  194. // Removing?
  195. if ($remove_tag)
  196. {
  197. $parts[$i] = substr($parts[$i], 0, $table_offset + $offset) . substr($parts[$i], $table_offset + strlen($matches[0]) + $offset);
  198. // We've lost some data.
  199. $table_offset -= strlen($matches[0]);
  200. }
  201. // Remove everything up to here.
  202. $table_offset += $offset + strlen($matches[0]);
  203. $table_check = substr($table_check, $offset + strlen($matches[0]));
  204. }
  205. // Close any remaining table tags.
  206. foreach ($table_array as $tag)
  207. $parts[$i] .= '[/' . $tag . ']';
  208. }
  209. }
  210. // Put it back together!
  211. if (!$previewing)
  212. $message = strtr(implode('', $parts), array(' ' => '&nbsp; ', "\n" => '<br />', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
  213. else
  214. $message = strtr(implode('', $parts), array(' ' => '&nbsp; ', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
  215. // Now let's quickly clean up things that will slow our parser (which are common in posted code.)
  216. $message = strtr($message, array('[]' => '&#91;]', '[&#039;' => '&#91;&#039;'));
  217. // Remove empty bbc.
  218. $message = preg_replace('~\[([^\]]+)\]\[/\1\]~i', '', $message);
  219. }
  220. /**
  221. * This is very simple, and just removes things done by preparsecode.
  222. *
  223. * @param $message
  224. */
  225. function un_preparsecode($message)
  226. {
  227. global $smcFunc;
  228. $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
  229. // We're going to unparse only the stuff outside [code]...
  230. for ($i = 0, $n = count($parts); $i < $n; $i++)
  231. {
  232. // If $i is a multiple of four (0, 4, 8, ...) then it's not a code section...
  233. if ($i % 4 == 0)
  234. {
  235. $parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ie', '\'[html]\' . strtr(htmlspecialchars(\'$1\', ENT_QUOTES), array(\'\\&quot;\' => \'&quot;\', \'&amp;#13;\' => \'<br />\', \'&amp;#32;\' => \' \', \'&amp;#91;\' => \'[\', \'&amp;#93;\' => \']\')) . \'[/html]\'', $parts[$i]);
  236. // $parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ie', '\'[html]\' . strtr(htmlspecialchars(\'$1\', ENT_QUOTES), array(\'\\&quot;\' => \'&quot;\', \'&amp;#13;\' => \'<br />\', \'&amp;#32;\' => \' \', \'&amp;#38;\' => \'&#38;\', \'&amp;#91;\' => \'[\', \'&amp;#93;\' => \']\')) . \'[/html]\'', $parts[$i]);
  237. // Attempt to un-parse the time to something less awful.
  238. $parts[$i] = preg_replace('~\[time\](\d{0,10})\[/time\]~ie', '\'[time]\' . timeformat(\'$1\', false) . \'[/time]\'', $parts[$i]);
  239. }
  240. }
  241. // Change breaks back to \n's and &nsbp; back to spaces.
  242. return preg_replace('~<br( /)?' . '>~', "\n", str_replace('&nbsp;', ' ', implode('', $parts)));
  243. }
  244. /**
  245. * Fix any URLs posted - ie. remove 'javascript:'.
  246. * Used by preparsecode, fixes links in message and returns nothing.
  247. *
  248. * @param string $message
  249. */
  250. function fixTags(&$message)
  251. {
  252. global $modSettings;
  253. // WARNING: Editing the below can cause large security holes in your forum.
  254. // Edit only if you are sure you know what you are doing.
  255. $fixArray = array(
  256. // [img]http://...[/img] or [img width=1]http://...[/img]
  257. array(
  258. 'tag' => 'img',
  259. 'protocols' => array('http', 'https'),
  260. 'embeddedUrl' => false,
  261. 'hasEqualSign' => false,
  262. 'hasExtra' => true,
  263. ),
  264. // [url]http://...[/url]
  265. array(
  266. 'tag' => 'url',
  267. 'protocols' => array('http', 'https'),
  268. 'embeddedUrl' => true,
  269. 'hasEqualSign' => false,
  270. ),
  271. // [url=http://...]name[/url]
  272. array(
  273. 'tag' => 'url',
  274. 'protocols' => array('http', 'https'),
  275. 'embeddedUrl' => true,
  276. 'hasEqualSign' => true,
  277. ),
  278. // [iurl]http://...[/iurl]
  279. array(
  280. 'tag' => 'iurl',
  281. 'protocols' => array('http', 'https'),
  282. 'embeddedUrl' => true,
  283. 'hasEqualSign' => false,
  284. ),
  285. // [iurl=http://...]name[/iurl]
  286. array(
  287. 'tag' => 'iurl',
  288. 'protocols' => array('http', 'https'),
  289. 'embeddedUrl' => true,
  290. 'hasEqualSign' => true,
  291. ),
  292. // [ftp]ftp://...[/ftp]
  293. array(
  294. 'tag' => 'ftp',
  295. 'protocols' => array('ftp', 'ftps'),
  296. 'embeddedUrl' => true,
  297. 'hasEqualSign' => false,
  298. ),
  299. // [ftp=ftp://...]name[/ftp]
  300. array(
  301. 'tag' => 'ftp',
  302. 'protocols' => array('ftp', 'ftps'),
  303. 'embeddedUrl' => true,
  304. 'hasEqualSign' => true,
  305. ),
  306. // [flash]http://...[/flash]
  307. array(
  308. 'tag' => 'flash',
  309. 'protocols' => array('http', 'https'),
  310. 'embeddedUrl' => false,
  311. 'hasEqualSign' => false,
  312. 'hasExtra' => true,
  313. ),
  314. );
  315. // Fix each type of tag.
  316. foreach ($fixArray as $param)
  317. fixTag($message, $param['tag'], $param['protocols'], $param['embeddedUrl'], $param['hasEqualSign'], !empty($param['hasExtra']));
  318. // Now fix possible security problems with images loading links automatically...
  319. $message = preg_replace('~(\[img.*?\])(.+?)\[/img\]~eis', '\'$1\' . preg_replace(\'~action(=|%3d)(?!dlattach)~i\', \'action-\', \'$2\') . \'[/img]\'', $message);
  320. // Limit the size of images posted?
  321. if (!empty($modSettings['max_image_width']) || !empty($modSettings['max_image_height']))
  322. {
  323. // Find all the img tags - with or without width and height.
  324. preg_match_all('~\[img(\s+width=\d+)?(\s+height=\d+)?(\s+width=\d+)?\](.+?)\[/img\]~is', $message, $matches, PREG_PATTERN_ORDER);
  325. $replaces = array();
  326. foreach ($matches[0] as $match => $dummy)
  327. {
  328. // If the width was after the height, handle it.
  329. $matches[1][$match] = !empty($matches[3][$match]) ? $matches[3][$match] : $matches[1][$match];
  330. // Now figure out if they had a desired height or width...
  331. $desired_width = !empty($matches[1][$match]) ? (int) substr(trim($matches[1][$match]), 6) : 0;
  332. $desired_height = !empty($matches[2][$match]) ? (int) substr(trim($matches[2][$match]), 7) : 0;
  333. // One was omitted, or both. We'll have to find its real size...
  334. if (empty($desired_width) || empty($desired_height))
  335. {
  336. list ($width, $height) = url_image_size(un_htmlspecialchars($matches[4][$match]));
  337. // They don't have any desired width or height!
  338. if (empty($desired_width) && empty($desired_height))
  339. {
  340. $desired_width = $width;
  341. $desired_height = $height;
  342. }
  343. // Scale it to the width...
  344. elseif (empty($desired_width) && !empty($height))
  345. $desired_width = (int) (($desired_height * $width) / $height);
  346. // Scale if to the height.
  347. elseif (!empty($width))
  348. $desired_height = (int) (($desired_width * $height) / $width);
  349. }
  350. // If the width and height are fine, just continue along...
  351. if ($desired_width <= $modSettings['max_image_width'] && $desired_height <= $modSettings['max_image_height'])
  352. continue;
  353. // Too bad, it's too wide. Make it as wide as the maximum.
  354. if ($desired_width > $modSettings['max_image_width'] && !empty($modSettings['max_image_width']))
  355. {
  356. $desired_height = (int) (($modSettings['max_image_width'] * $desired_height) / $desired_width);
  357. $desired_width = $modSettings['max_image_width'];
  358. }
  359. // Now check the height, as well. Might have to scale twice, even...
  360. if ($desired_height > $modSettings['max_image_height'] && !empty($modSettings['max_image_height']))
  361. {
  362. $desired_width = (int) (($modSettings['max_image_height'] * $desired_width) / $desired_height);
  363. $desired_height = $modSettings['max_image_height'];
  364. }
  365. $replaces[$matches[0][$match]] = '[img' . (!empty($desired_width) ? ' width=' . $desired_width : '') . (!empty($desired_height) ? ' height=' . $desired_height : '') . ']' . $matches[4][$match] . '[/img]';
  366. }
  367. // If any img tags were actually changed...
  368. if (!empty($replaces))
  369. $message = strtr($message, $replaces);
  370. }
  371. }
  372. /**
  373. * Fix a specific class of tag - ie. url with =.
  374. * Used by fixTags, fixes a specific tag's links.
  375. *
  376. * @param string $message
  377. * @param string $myTag - the tag
  378. * @param string $protocols - http or ftp
  379. * @param bool $embeddedUrl = false - whether it *can* be set to something
  380. * @param bool $hasEqualSign = false, whether it *is* set to something
  381. * @param bool $hasExtra = false - whether it can have extra cruft after the begin tag.
  382. */
  383. function fixTag(&$message, $myTag, $protocols, $embeddedUrl = false, $hasEqualSign = false, $hasExtra = false)
  384. {
  385. global $boardurl, $scripturl;
  386. if (preg_match('~^([^:]+://[^/]+)~', $boardurl, $match) != 0)
  387. $domain_url = $match[1];
  388. else
  389. $domain_url = $boardurl . '/';
  390. $replaces = array();
  391. if ($hasEqualSign)
  392. preg_match_all('~\[(' . $myTag . ')=([^\]]*?)\](?:(.+?)\[/(' . $myTag . ')\])?~is', $message, $matches);
  393. else
  394. preg_match_all('~\[(' . $myTag . ($hasExtra ? '(?:[^\]]*?)' : '') . ')\](.+?)\[/(' . $myTag . ')\]~is', $message, $matches);
  395. foreach ($matches[0] as $k => $dummy)
  396. {
  397. // Remove all leading and trailing whitespace.
  398. $replace = trim($matches[2][$k]);
  399. $this_tag = $matches[1][$k];
  400. $this_close = $hasEqualSign ? (empty($matches[4][$k]) ? '' : $matches[4][$k]) : $matches[3][$k];
  401. $found = false;
  402. foreach ($protocols as $protocol)
  403. {
  404. $found = strncasecmp($replace, $protocol . '://', strlen($protocol) + 3) === 0;
  405. if ($found)
  406. break;
  407. }
  408. if (!$found && $protocols[0] == 'http')
  409. {
  410. if (strpos($replace, '/') === 0)
  411. $replace = $domain_url . $replace;
  412. elseif (strpos($replace, '?') === 0)
  413. $replace = $scripturl . $replace;
  414. elseif (strpos($replace, '#') === 0 && $embeddedUrl)
  415. {
  416. $replace = '#' . preg_replace('~[^A-Za-z0-9_\-#]~', '', substr($replace, 1));
  417. $this_tag = 'iurl';
  418. $this_close = 'iurl';
  419. }
  420. else
  421. $replace = $protocols[0] . '://' . $replace;
  422. }
  423. elseif (!$found && $protocols[0] == 'ftp')
  424. $replace = $protocols[0] . '://' . preg_replace('~^(?!ftps?)[^:]+://~', '', $replace);
  425. elseif (!$found)
  426. $replace = $protocols[0] . '://' . $replace;
  427. if ($hasEqualSign && $embeddedUrl)
  428. $replaces[$matches[0][$k]] = '[' . $this_tag . '=' . $replace . ']' . (empty($matches[4][$k]) ? '' : $matches[3][$k] . '[/' . $this_close . ']');
  429. elseif ($hasEqualSign)
  430. $replaces['[' . $matches[1][$k] . '=' . $matches[2][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']';
  431. elseif ($embeddedUrl)
  432. $replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']' . $matches[2][$k] . '[/' . $this_close . ']';
  433. else
  434. $replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . ']' . $replace . '[/' . $this_close . ']';
  435. }
  436. foreach ($replaces as $k => $v)
  437. {
  438. if ($k == $v)
  439. unset($replaces[$k]);
  440. }
  441. if (!empty($replaces))
  442. $message = strtr($message, $replaces);
  443. }
  444. /**
  445. * This function sends an email to the specified recipient(s).
  446. * It uses the mail_type settings and webmaster_email variable.
  447. *
  448. * @param array $to - the email(s) to send to
  449. * @param string $subject - email subject, expected to have entities, and slashes, but not be parsed
  450. * @param string $message - email body, expected to have slashes, no htmlentities
  451. * @param string $from = null - the address to use for replies
  452. * @param string $message_id = null - if specified, it will be used as local part of the Message-ID header.
  453. * @param bool $send_html = false, whether or not the message is HTML vs. plain text
  454. * @param int $priority = 3
  455. * @param bool $hotmail_fix = null
  456. * @param $is_private
  457. * @return bool, whether ot not the email was sent properly.
  458. */
  459. function sendmail($to, $subject, $message, $from = null, $message_id = null, $send_html = false, $priority = 3, $hotmail_fix = null, $is_private = false)
  460. {
  461. global $webmaster_email, $context, $modSettings, $txt, $scripturl;
  462. global $smcFunc;
  463. // Use sendmail if it's set or if no SMTP server is set.
  464. $use_sendmail = empty($modSettings['mail_type']) || $modSettings['smtp_host'] == '';
  465. // Line breaks need to be \r\n only in windows or for SMTP.
  466. $line_break = $context['server']['is_windows'] || !$use_sendmail ? "\r\n" : "\n";
  467. // So far so good.
  468. $mail_result = true;
  469. // If the recipient list isn't an array, make it one.
  470. $to_array = is_array($to) ? $to : array($to);
  471. // Once upon a time, Hotmail could not interpret non-ASCII mails.
  472. // In honour of those days, it's still called the 'hotmail fix'.
  473. if ($hotmail_fix === null)
  474. {
  475. $hotmail_to = array();
  476. foreach ($to_array as $i => $to_address)
  477. {
  478. if (preg_match('~@(att|comcast|bellsouth)\.[a-zA-Z\.]{2,6}$~i', $to_address) === 1)
  479. {
  480. $hotmail_to[] = $to_address;
  481. $to_array = array_diff($to_array, array($to_address));
  482. }
  483. }
  484. // Call this function recursively for the hotmail addresses.
  485. if (!empty($hotmail_to))
  486. $mail_result = sendmail($hotmail_to, $subject, $message, $from, $message_id, $send_html, $priority, true, $is_private);
  487. // The remaining addresses no longer need the fix.
  488. $hotmail_fix = false;
  489. // No other addresses left? Return instantly.
  490. if (empty($to_array))
  491. return $mail_result;
  492. }
  493. // Get rid of entities.
  494. $subject = un_htmlspecialchars($subject);
  495. // Make the message use the proper line breaks.
  496. $message = str_replace(array("\r", "\n"), array('', $line_break), $message);
  497. // Make sure hotmail mails are sent as HTML so that HTML entities work.
  498. if ($hotmail_fix && !$send_html)
  499. {
  500. $send_html = true;
  501. $message = strtr($message, array($line_break => '<br />' . $line_break));
  502. $message = preg_replace('~(' . preg_quote($scripturl, '~') . '(?:[?/][\w\-_%\.,\?&;=#]+)?)~', '<a href="$1">$1</a>', $message);
  503. }
  504. list (, $from_name) = mimespecialchars(addcslashes($from !== null ? $from : $context['forum_name'], '<>()\'\\"'), true, $hotmail_fix, $line_break);
  505. list (, $subject) = mimespecialchars($subject, true, $hotmail_fix, $line_break);
  506. // Construct the mail headers...
  507. $headers = 'From: "' . $from_name . '" <' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . '>' . $line_break;
  508. $headers .= $from !== null ? 'Reply-To: <' . $from . '>' . $line_break : '';
  509. $headers .= 'Return-Path: ' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . $line_break;
  510. $headers .= 'Date: ' . gmdate('D, d M Y H:i:s') . ' -0000' . $line_break;
  511. if ($message_id !== null && empty($modSettings['mail_no_message_id']))
  512. $headers .= 'Message-ID: <' . md5($scripturl . microtime()) . '-' . $message_id . strstr(empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from'], '@') . '>' . $line_break;
  513. $headers .= 'X-Mailer: SMF' . $line_break;
  514. // Pass this to the integration before we start modifying the output -- it'll make it easier later.
  515. if (in_array(false, call_integration_hook('integrate_outgoing_email', array(&$subject, &$message, &$headers)), true))
  516. return false;
  517. // Save the original message...
  518. $orig_message = $message;
  519. // The mime boundary separates the different alternative versions.
  520. $mime_boundary = 'SMF-' . md5($message . time());
  521. // Using mime, as it allows to send a plain unencoded alternative.
  522. $headers .= 'Mime-Version: 1.0' . $line_break;
  523. $headers .= 'Content-Type: multipart/alternative; boundary="' . $mime_boundary . '"' . $line_break;
  524. $headers .= 'Content-Transfer-Encoding: 7bit' . $line_break;
  525. // Sending HTML? Let's plop in some basic stuff, then.
  526. if ($send_html)
  527. {
  528. $no_html_message = un_htmlspecialchars(strip_tags(strtr($orig_message, array('</title>' => $line_break))));
  529. // But, then, dump it and use a plain one for dinosaur clients.
  530. list(, $plain_message) = mimespecialchars($no_html_message, false, true, $line_break);
  531. $message = $plain_message . $line_break . '--' . $mime_boundary . $line_break;
  532. // This is the plain text version. Even if no one sees it, we need it for spam checkers.
  533. list($charset, $plain_charset_message, $encoding) = mimespecialchars($no_html_message, false, false, $line_break);
  534. $message .= 'Content-Type: text/plain; charset=' . $charset . $line_break;
  535. $message .= 'Content-Transfer-Encoding: ' . $encoding . $line_break . $line_break;
  536. $message .= $plain_charset_message . $line_break . '--' . $mime_boundary . $line_break;
  537. // This is the actual HTML message, prim and proper. If we wanted images, they could be inlined here (with multipart/related, etc.)
  538. list($charset, $html_message, $encoding) = mimespecialchars($orig_message, false, $hotmail_fix, $line_break);
  539. $message .= 'Content-Type: text/html; charset=' . $charset . $line_break;
  540. $message .= 'Content-Transfer-Encoding: ' . ($encoding == '' ? '7bit' : $encoding) . $line_break . $line_break;
  541. $message .= $html_message . $line_break . '--' . $mime_boundary . '--';
  542. }
  543. // Text is good too.
  544. else
  545. {
  546. // Send a plain message first, for the older web clients.
  547. list(, $plain_message) = mimespecialchars($orig_message, false, true, $line_break);
  548. $message = $plain_message . $line_break . '--' . $mime_boundary . $line_break;
  549. // Now add an encoded message using the forum's character set.
  550. list ($charset, $encoded_message, $encoding) = mimespecialchars($orig_message, false, false, $line_break);
  551. $message .= 'Content-Type: text/plain; charset=' . $charset . $line_break;
  552. $message .= 'Content-Transfer-Encoding: ' . $encoding . $line_break . $line_break;
  553. $message .= $encoded_message . $line_break . '--' . $mime_boundary . '--';
  554. }
  555. // Are we using the mail queue, if so this is where we butt in...
  556. if (!empty($modSettings['mail_queue']) && $priority != 0)
  557. return AddMailQueue(false, $to_array, $subject, $message, $headers, $send_html, $priority, $is_private);
  558. // If it's a priority mail, send it now - note though that this should NOT be used for sending many at once.
  559. elseif (!empty($modSettings['mail_queue']) && !empty($modSettings['mail_limit']))
  560. {
  561. list ($last_mail_time, $mails_this_minute) = @explode('|', $modSettings['mail_recent']);
  562. if (empty($mails_this_minute) || time() > $last_mail_time + 60)
  563. $new_queue_stat = time() . '|' . 1;
  564. else
  565. $new_queue_stat = $last_mail_time . '|' . ((int) $mails_this_minute + 1);
  566. updateSettings(array('mail_recent' => $new_queue_stat));
  567. }
  568. // SMTP or sendmail?
  569. if ($use_sendmail)
  570. {
  571. $subject = strtr($subject, array("\r" => '', "\n" => ''));
  572. if (!empty($modSettings['mail_strip_carriage']))
  573. {
  574. $message = strtr($message, array("\r" => ''));
  575. $headers = strtr($headers, array("\r" => ''));
  576. }
  577. foreach ($to_array as $to)
  578. {
  579. if (!mail(strtr($to, array("\r" => '', "\n" => '')), $subject, $message, $headers))
  580. {
  581. log_error(sprintf($txt['mail_send_unable'], $to));
  582. $mail_result = false;
  583. }
  584. // Wait, wait, I'm still sending here!
  585. @set_time_limit(300);
  586. if (function_exists('apache_reset_timeout'))
  587. @apache_reset_timeout();
  588. }
  589. }
  590. else
  591. $mail_result = $mail_result && smtp_mail($to_array, $subject, $message, $headers);
  592. // Everything go smoothly?
  593. return $mail_result;
  594. }
  595. /**
  596. * Add an email to the mail queue.
  597. *
  598. * @param bool $flush = false
  599. * @param array $to_array = array()
  600. * @param string $subject = ''
  601. * @param string $message = ''
  602. * @param string $headers = ''
  603. * @param bool $send_html = false
  604. * @param int $priority = 3
  605. * @param $is_private
  606. */
  607. function AddMailQueue($flush = false, $to_array = array(), $subject = '', $message = '', $headers = '', $send_html = false, $priority = 3, $is_private = false)
  608. {
  609. global $context, $modSettings, $smcFunc;
  610. static $cur_insert = array();
  611. static $cur_insert_len = 0;
  612. if ($cur_insert_len == 0)
  613. $cur_insert = array();
  614. // If we're flushing, make the final inserts - also if we're near the MySQL length limit!
  615. if (($flush || $cur_insert_len > 800000) && !empty($cur_insert))
  616. {
  617. // Only do these once.
  618. $cur_insert_len = 0;
  619. // Dump the data...
  620. $smcFunc['db_insert']('',
  621. '{db_prefix}mail_queue',
  622. array(
  623. 'time_sent' => 'int', 'recipient' => 'string-255', 'body' => 'string-65534', 'subject' => 'string-255',
  624. 'headers' => 'string-65534', 'send_html' => 'int', 'priority' => 'int', 'private' => 'int',
  625. ),
  626. $cur_insert,
  627. array('id_mail')
  628. );
  629. $cur_insert = array();
  630. $context['flush_mail'] = false;
  631. }
  632. // If we're flushing we're done.
  633. if ($flush)
  634. {
  635. $nextSendTime = time() + 10;
  636. $smcFunc['db_query']('', '
  637. UPDATE {db_prefix}settings
  638. SET value = {string:nextSendTime}
  639. WHERE variable = {string:mail_next_send}
  640. AND value = {string:no_outstanding}',
  641. array(
  642. 'nextSendTime' => $nextSendTime,
  643. 'mail_next_send' => 'mail_next_send',
  644. 'no_outstanding' => '0',
  645. )
  646. );
  647. return true;
  648. }
  649. // Ensure we tell obExit to flush.
  650. $context['flush_mail'] = true;
  651. foreach ($to_array as $to)
  652. {
  653. // Will this insert go over MySQL's limit?
  654. $this_insert_len = strlen($to) + strlen($message) + strlen($headers) + 700;
  655. // Insert limit of 1M (just under the safety) is reached?
  656. if ($this_insert_len + $cur_insert_len > 1000000)
  657. {
  658. // Flush out what we have so far.
  659. $smcFunc['db_insert']('',
  660. '{db_prefix}mail_queue',
  661. array(
  662. 'time_sent' => 'int', 'recipient' => 'string-255', 'body' => 'string-65534', 'subject' => 'string-255',
  663. 'headers' => 'string-65534', 'send_html' => 'int', 'priority' => 'int', 'private' => 'int',
  664. ),
  665. $cur_insert,
  666. array('id_mail')
  667. );
  668. // Clear this out.
  669. $cur_insert = array();
  670. $cur_insert_len = 0;
  671. }
  672. // Now add the current insert to the array...
  673. $cur_insert[] = array(time(), (string) $to, (string) $message, (string) $subject, (string) $headers, ($send_html ? 1 : 0), $priority, (int) $is_private);
  674. $cur_insert_len += $this_insert_len;
  675. }
  676. // If they are using SSI there is a good chance obExit will never be called. So lets be nice and flush it for them.
  677. if (SMF === 'SSI')
  678. return AddMailQueue(true);
  679. return true;
  680. }
  681. /**
  682. * Sends an personal message from the specified person to the specified people
  683. * ($from defaults to the user)
  684. *
  685. * @param array $recipients - an array containing the arrays 'to' and 'bcc',
  686. * both containing id_member's.
  687. * @param string $subject - should have no slashes and no html entities
  688. * @param string $message - should have no slashes and no html entities
  689. * @param bool $store_outbox
  690. * @param array $from - an array with the id, name, and username of the member.
  691. * @param int $pm_head - the ID of the chain being replied to - if any.
  692. * @return array, an array with log entries telling how many recipients were
  693. * successful and which recipients it failed to send to.
  694. */
  695. function sendpm($recipients, $subject, $message, $store_outbox = false, $from = null, $pm_head = 0)
  696. {
  697. global $scripturl, $txt, $user_info, $language;
  698. global $modSettings, $smcFunc;
  699. // Make sure the PM language file is loaded, we might need something out of it.
  700. loadLanguage('PersonalMessage');
  701. $onBehalf = $from !== null;
  702. // Initialize log array.
  703. $log = array(
  704. 'failed' => array(),
  705. 'sent' => array()
  706. );
  707. if ($from === null)
  708. $from = array(
  709. 'id' => $user_info['id'],
  710. 'name' => $user_info['name'],
  711. 'username' => $user_info['username']
  712. );
  713. // Probably not needed. /me something should be of the typer.
  714. else
  715. $user_info['name'] = $from['name'];
  716. // This is the one that will go in their inbox.
  717. $htmlmessage = $smcFunc['htmlspecialchars']($message, ENT_QUOTES);
  718. $htmlsubject = $smcFunc['htmlspecialchars']($subject);
  719. preparsecode($htmlmessage);
  720. // Integrated PMs
  721. call_integration_hook('integrate_personal_message', array($recipients, $from['username'], $subject, $message));
  722. // Get a list of usernames and convert them to IDs.
  723. $usernames = array();
  724. foreach ($recipients as $rec_type => $rec)
  725. {
  726. foreach ($rec as $id => $member)
  727. {
  728. if (!is_numeric($recipients[$rec_type][$id]))
  729. {
  730. $recipients[$rec_type][$id] = $smcFunc['strtolower'](trim(preg_replace('/[<>&"\'=\\\]/', '', $recipients[$rec_type][$id])));
  731. $usernames[$recipients[$rec_type][$id]] = 0;
  732. }
  733. }
  734. }
  735. if (!empty($usernames))
  736. {
  737. $request = $smcFunc['db_query']('pm_find_username', '
  738. SELECT id_member, member_name
  739. FROM {db_prefix}members
  740. WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name') . ' IN ({array_string:usernames})',
  741. array(
  742. 'usernames' => array_keys($usernames),
  743. )
  744. );
  745. while ($row = $smcFunc['db_fetch_assoc']($request))
  746. if (isset($usernames[$smcFunc['strtolower']($row['member_name'])]))
  747. $usernames[$smcFunc['strtolower']($row['member_name'])] = $row['id_member'];
  748. $smcFunc['db_free_result']($request);
  749. // Replace the usernames with IDs. Drop usernames that couldn't be found.
  750. foreach ($recipients as $rec_type => $rec)
  751. foreach ($rec as $id => $member)
  752. {
  753. if (is_numeric($recipients[$rec_type][$id]))
  754. continue;
  755. if (!empty($usernames[$member]))
  756. $recipients[$rec_type][$id] = $usernames[$member];
  757. else
  758. {
  759. $log['failed'][$id] = sprintf($txt['pm_error_user_not_found'], $recipients[$rec_type][$id]);
  760. unset($recipients[$rec_type][$id]);
  761. }
  762. }
  763. }
  764. // Make sure there are no duplicate 'to' members.
  765. $recipients['to'] = array_unique($recipients['to']);
  766. // Only 'bcc' members that aren't already in 'to'.
  767. $recipients['bcc'] = array_diff(array_unique($recipients['bcc']), $recipients['to']);
  768. // Combine 'to' and 'bcc' recipients.
  769. $all_to = array_merge($recipients['to'], $recipients['bcc']);
  770. // Check no-one will want it deleted right away!
  771. $request = $smcFunc['db_query']('', '
  772. SELECT
  773. id_member, criteria, is_or
  774. FROM {db_prefix}pm_rules
  775. WHERE id_member IN ({array_int:to_members})
  776. AND delete_pm = {int:delete_pm}',
  777. array(
  778. 'to_members' => $all_to,
  779. 'delete_pm' => 1,
  780. )
  781. );
  782. $deletes = array();
  783. // Check whether we have to apply anything...
  784. while ($row = $smcFunc['db_fetch_assoc']($request))
  785. {
  786. $criteria = unserialize($row['criteria']);
  787. // Note we don't check the buddy status, cause deletion from buddy = madness!
  788. $delete = false;
  789. foreach ($criteria as $criterium)
  790. {
  791. $match = false;
  792. if (($criterium['t'] == 'mid' && $criterium['v'] == $from['id']) || ($criterium['t'] == 'gid' && in_array($criterium['v'], $user_info['groups'])) || ($criterium['t'] == 'sub' && strpos($subject, $criterium['v']) !== false) || ($criterium['t'] == 'msg' && strpos($message, $criterium['v']) !== false))
  793. $delete = true;
  794. // If we're adding and one criteria don't match then we stop!
  795. elseif (!$row['is_or'])
  796. {
  797. $delete = false;
  798. break;
  799. }
  800. }
  801. if ($delete)
  802. $deletes[$row['id_member']] = 1;
  803. }
  804. $smcFunc['db_free_result']($request);
  805. // Load the membergrounp message limits.
  806. //!!! Consider caching this?
  807. static $message_limit_cache = array();
  808. if (!allowedTo('moderate_forum') && empty($message_limit_cache))
  809. {
  810. $request = $smcFunc['db_query']('', '
  811. SELECT id_group, max_messages
  812. FROM {db_prefix}membergroups',
  813. array(
  814. )
  815. );
  816. while ($row = $smcFunc['db_fetch_assoc']($request))
  817. $message_limit_cache[$row['id_group']] = $row['max_messages'];
  818. $smcFunc['db_free_result']($request);
  819. }
  820. // Load the groups that are allowed to read PMs.
  821. $allowed_groups = array();
  822. $disallowed_groups = array();
  823. $request = $smcFunc['db_query']('', '
  824. SELECT id_group, add_deny
  825. FROM {db_prefix}permissions
  826. WHERE permission = {string:read_permission}',
  827. array(
  828. 'read_permission' => 'pm_read',
  829. )
  830. );
  831. while ($row = $smcFunc['db_fetch_assoc']($request))
  832. {
  833. if (empty($row['add_deny']))
  834. $disallowed_groups[] = $row['id_group'];
  835. else
  836. $allowed_groups[] = $row['id_group'];
  837. }
  838. $smcFunc['db_free_result']($request);
  839. if (empty($modSettings['permission_enable_deny']))
  840. $disallowed_groups = array();
  841. $request = $smcFunc['db_query']('', '
  842. SELECT
  843. member_name, real_name, id_member, email_address, lngfile,
  844. pm_email_notify, instant_messages,' . (allowedTo('moderate_forum') ? ' 0' : '
  845. (pm_receive_from = {int:admins_only}' . (empty($modSettings['enable_buddylist']) ? '' : ' OR
  846. (pm_receive_from = {int:buddies_only} AND FIND_IN_SET({string:from_id}, buddy_list) = 0) OR
  847. (pm_receive_from = {int:not_on_ignore_list} AND FIND_IN_SET({string:from_id}, pm_ignore_list) != 0)') . ')') . ' AS ignored,
  848. FIND_IN_SET({string:from_id}, buddy_list) != 0 AS is_buddy, is_activated,
  849. additional_groups, id_group, id_post_group
  850. FROM {db_prefix}members
  851. WHERE id_member IN ({array_int:recipients})
  852. ORDER BY lngfile
  853. LIMIT {int:count_recipients}',
  854. array(
  855. 'not_on_ignore_list' => 1,
  856. 'buddies_only' => 2,
  857. 'admins_only' => 3,
  858. 'recipients' => $all_to,
  859. 'count_recipients' => count($all_to),
  860. 'from_id' => $from['id'],
  861. )
  862. );
  863. $notifications = array();
  864. while ($row = $smcFunc['db_fetch_assoc']($request))
  865. {
  866. // Don't do anything for members to be deleted!
  867. if (isset($deletes[$row['id_member']]))
  868. continue;
  869. // We need to know this members groups.
  870. $groups = explode(',', $row['additional_groups']);
  871. $groups[] = $row['id_group'];
  872. $groups[] = $row['id_post_group'];
  873. $message_limit = -1;
  874. // For each group see whether they've gone over their limit - assuming they're not an admin.
  875. if (!in_array(1, $groups))
  876. {
  877. foreach ($groups as $id)
  878. {
  879. if (isset($message_limit_cache[$id]) && $message_limit != 0 && $message_limit < $message_limit_cache[$id])
  880. $message_limit = $message_limit_cache[$id];
  881. }
  882. if ($message_limit > 0 && $message_limit <= $row['instant_messages'])
  883. {
  884. $log['failed'][$row['id_member']] = sprintf($txt['pm_error_data_limit_reached'], $row['real_name']);
  885. unset($all_to[array_search($row['id_member'], $all_to)]);
  886. continue;
  887. }
  888. // Do they have any of the allowed groups?
  889. if (count(array_intersect($allowed_groups, $groups)) == 0 || count(array_intersect($disallowed_groups, $groups)) != 0)
  890. {
  891. $log['failed'][$row['id_member']] = sprintf($txt['pm_error_user_cannot_read'], $row['real_name']);
  892. unset($all_to[array_search($row['id_member'], $all_to)]);
  893. continue;
  894. }
  895. }
  896. // Note that PostgreSQL can return a lowercase t/f for FIND_IN_SET
  897. if (!empty($row['ignored']) && $row['ignored'] != 'f' && $row['id_member'] != $from['id'])
  898. {
  899. $log['failed'][$row['id_member']] = sprintf($txt['pm_error_ignored_by_user'], $row['real_name']);
  900. unset($all_to[array_search($row['id_member'], $all_to)]);
  901. continue;
  902. }
  903. // If the receiving account is banned (>=10) or pending deletion (4), refuse to send the PM.
  904. if ($row['is_activated'] >= 10 || ($row['is_activated'] == 4 && !$user_info['is_admin']))
  905. {
  906. $log['failed'][$row['id_member']] = sprintf($txt['pm_error_user_cannot_read'], $row['real_name']);
  907. unset($all_to[array_search($row['id_member'], $all_to)]);
  908. continue;
  909. }
  910. // Send a notification, if enabled - taking the buddy list into account.
  911. if (!empty($row['email_address']) && ($row['pm_email_notify'] == 1 || ($row['pm_email_notify'] > 1 && (!empty($modSettings['enable_buddylist']) && $row['is_buddy']))) && $row['is_activated'] == 1)
  912. $notifications[empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']][] = $row['email_address'];
  913. $log['sent'][$row['id_member']] = sprintf(isset($txt['pm_successfully_sent']) ? $txt['pm_successfully_sent'] : '', $row['real_name']);
  914. }
  915. $smcFunc['db_free_result']($request);
  916. // Only 'send' the message if there are any recipients left.
  917. if (empty($all_to))
  918. return $log;
  919. // Insert the message itself and then grab the last insert id.
  920. $smcFunc['db_insert']('',
  921. '{db_prefix}personal_messages',
  922. array(
  923. 'id_pm_head' => 'int', 'id_member_from' => 'int', 'deleted_by_sender' => 'int',
  924. 'from_name' => 'string-255', 'msgtime' => 'int', 'subject' => 'string-255', 'body' => 'string-65534',
  925. ),
  926. array(
  927. $pm_head, $from['id'], ($store_outbox ? 0 : 1),
  928. $from['username'], time(), $htmlsubject, $htmlmessage,
  929. ),
  930. array('id_pm')
  931. );
  932. $id_pm = $smcFunc['db_insert_id']('{db_prefix}personal_messages', 'id_pm');
  933. // Add the recipients.
  934. if (!empty($id_pm))
  935. {
  936. // If this is new we need to set it part of it's own conversation.
  937. if (empty($pm_head))
  938. $smcFunc['db_query']('', '
  939. UPDATE {db_prefix}personal_messages
  940. SET id_pm_head = {int:id_pm_head}
  941. WHERE id_pm = {int:id_pm_head}',
  942. array(
  943. 'id_pm_head' => $id_pm,
  944. )
  945. );
  946. // Some people think manually deleting personal_messages is fun... it's not. We protect against it though :)
  947. $smcFunc['db_query']('', '
  948. DELETE FROM {db_prefix}pm_recipients
  949. WHERE id_pm = {int:id_pm}',
  950. array(
  951. 'id_pm' => $id_pm,
  952. )
  953. );
  954. $insertRows = array();
  955. foreach ($all_to as $to)
  956. {
  957. $insertRows[] = array($id_pm, $to, in_array($to, $recipients['bcc']) ? 1 : 0, isset($deletes[$to]) ? 1 : 0, 1);
  958. }
  959. $smcFunc['db_insert']('insert',
  960. '{db_prefix}pm_recipients',
  961. array(
  962. 'id_pm' => 'int', 'id_member' => 'int', 'bcc' => 'int', 'deleted' => 'int', 'is_new' => 'int'
  963. ),
  964. $insertRows,
  965. array('id_pm', 'id_member')
  966. );
  967. }
  968. censorText($message);
  969. censorText($subject);
  970. $message = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc(htmlspecialchars($message), false), array('<br />' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
  971. foreach ($notifications as $lang => $notification_list)
  972. {
  973. // Make sure to use the right language.
  974. loadLanguage('index+PersonalMessage', $lang, false);
  975. // Replace the right things in the message strings.
  976. $mailsubject = str_replace(array('SUBJECT', 'SENDER'), array($subject, un_htmlspecialchars($from['name'])), $txt['new_pm_subject']);
  977. $mailmessage = str_replace(array('SUBJECT', 'MESSAGE', 'SENDER'), array($subject, $message, un_htmlspecialchars($from['name'])), $txt['pm_email']);
  978. $mailmessage .= "\n\n" . $txt['instant_reply'] . ' ' . $scripturl . '?action=pm;sa=send;f=inbox;pmsg=' . $id_pm . ';quote;u=' . $from['id'];
  979. // Off the notification email goes!
  980. sendmail($notification_list, $mailsubject, $mailmessage, null, 'p' . $id_pm, false, 2, null, true);
  981. }
  982. // Back to what we were on before!
  983. loadLanguage('index+PersonalMessage');
  984. // Add one to their unread and read message counts.
  985. foreach ($all_to as $k => $id)
  986. if (isset($deletes[$id]))
  987. unset($all_to[$k]);
  988. if (!empty($all_to))
  989. updateMemberData($all_to, array('instant_messages' => '+', 'unread_messages' => '+', 'new_pm' => 1));
  990. return $log;
  991. }
  992. /**
  993. * Prepare text strings for sending as email body or header.
  994. * In case there are higher ASCII characters in the given string, this
  995. * function will attempt the transport method 'quoted-printable'.
  996. * Otherwise the transport method '7bit' is used.
  997. *
  998. * @param string $string
  999. * @param bool $with_charset = true
  1000. * @param bool $hotmail_fix = false, with hotmail_fix set all higher ASCII
  1001. * characters are converted to HTML entities to assure proper display of the mail
  1002. * @param $line_break
  1003. * @param string $custom_charset = null, if set, it uses this character set
  1004. * @return an array containing the character set, the converted string and the transport method.
  1005. */
  1006. function mimespecialchars($string, $with_charset = true, $hotmail_fix = false, $line_break = "\r\n", $custom_charset = null)
  1007. {
  1008. global $context;
  1009. $charset = $custom_charset !== null ? $custom_charset : $context['character_set'];
  1010. // This is the fun part....
  1011. if (preg_match_all('~&#(\d{3,8});~', $string, $matches) !== 0 && !$hotmail_fix)
  1012. {
  1013. // Let's, for now, assume there are only &#021;'ish characters.
  1014. $simple = true;
  1015. foreach ($matches[1] as $entity)
  1016. if ($entity > 128)
  1017. $simple = false;
  1018. unset($matches);
  1019. if ($simple)
  1020. $string = preg_replace('~&#(\d{3,8});~e', 'chr(\'$1\')', $string);
  1021. else
  1022. {
  1023. // Try to convert the string to UTF-8.
  1024. if (!$context['utf8'] && function_exists('iconv'))
  1025. {
  1026. $newstring = @iconv($context['character_set'], 'UTF-8', $string);
  1027. if ($newstring)
  1028. $string = $newstring;
  1029. }
  1030. $fixchar = create_function('$n', '
  1031. if ($n < 128)
  1032. return chr($n);
  1033. elseif ($n < 2048)
  1034. return chr(192 | $n >> 6) . chr(128 | $n & 63);
  1035. elseif ($n < 65536)
  1036. return chr(224 | $n >> 12) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);
  1037. else
  1038. return chr(240 | $n >> 18) . chr(128 | $n >> 12 & 63) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);');
  1039. $string = preg_replace('~&#(\d{3,8});~e', '$fixchar(\'$1\')', $string);
  1040. // Unicode, baby.
  1041. $charset = 'UTF-8';
  1042. }
  1043. }
  1044. // Convert all special characters to HTML entities...just for Hotmail :-\
  1045. if ($hotmail_fix && ($context['utf8'] || function_exists('iconv') || $context['character_set'] === 'ISO-8859-1'))
  1046. {
  1047. if (!$context['utf8'] && function_exists('iconv'))
  1048. {
  1049. $newstring = @iconv($context['character_set'], 'UTF-8', $string);
  1050. if ($newstring)
  1051. $string = $newstring;
  1052. }
  1053. $entityConvert = create_function('$c', '
  1054. if (strlen($c) === 1 && ord($c[0]) <= 0x7F)
  1055. return $c;
  1056. elseif (strlen($c) === 2 && ord($c[0]) >= 0xC0 && ord($c[0]) <= 0xDF)
  1057. return "&#" . (((ord($c[0]) ^ 0xC0) << 6) + (ord($c[1]) ^ 0x80)) . ";";
  1058. elseif (strlen($c) === 3 && ord($c[0]) >= 0xE0 && ord($c[0]) <= 0xEF)
  1059. return "&#" . (((ord($c[0]) ^ 0xE0) << 12) + ((ord($c[1]) ^ 0x80) << 6) + (ord($c[2]) ^ 0x80)) . ";";
  1060. elseif (strlen($c) === 4 && ord($c[0]) >= 0xF0 && ord($c[0]) <= 0xF7)
  1061. return "&#" . (((ord($c[0]) ^ 0xF0) << 18) + ((ord($c[1]) ^ 0x80) << 12) + ((ord($c[2]) ^ 0x80) << 6) + (ord($c[3]) ^ 0x80)) . ";";
  1062. else
  1063. return "";');
  1064. // Convert all 'special' characters to HTML entities.
  1065. return array($charset, preg_replace('~([\x80-' . ($context['server']['complex_preg_chars'] ? '\x{10FFFF}' : "\xF7\xBF\xBF\xBF") . '])~eu', '$entityConvert(\'\1\')', $string), '7bit');
  1066. }
  1067. // We don't need to mess with the subject line if no special characters were in it..
  1068. elseif (!$hotmail_fix && preg_match('~([^\x09\x0A\x0D\x20-\x7F])~', $string) === 1)
  1069. {
  1070. // Base64 encode.
  1071. $string = base64_encode($string);
  1072. // Show the characterset and the transfer-encoding for header strings.
  1073. if ($with_charset)
  1074. $string = '=?' . $charset . '?B?' . $string . '?=';
  1075. // Break it up in lines (mail body).
  1076. else
  1077. $string = chunk_split($string, 76, $line_break);
  1078. return array($charset, $string, 'base64');
  1079. }
  1080. else
  1081. return array($charset, $string, '7bit');
  1082. }
  1083. // Send an email via SMTP.
  1084. /**
  1085. * Sends mail, like mail() but over SMTP.
  1086. * It expects no slashes or entities.
  1087. * @internal
  1088. *
  1089. * @param array $mail_to_array - array of strings (email addresses)
  1090. * @param string $subject, email subject
  1091. * @param string $message, email message
  1092. * @param string $headers
  1093. * @return bool, whether it sent or not.
  1094. */
  1095. function smtp_mail($mail_to_array, $subject, $message, $headers)
  1096. {
  1097. global $modSettings, $webmaster_email, $txt;
  1098. $modSettings['smtp_host'] = trim($modSettings['smtp_host']);
  1099. // Try POP3 before SMTP?
  1100. // !!! There's no interface for this yet.
  1101. if ($modSettings['mail_type'] == 2 && $modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
  1102. {
  1103. $socket = fsockopen($modSettings['smtp_host'], 110, $errno, $errstr, 2);
  1104. if (!$socket && (substr($modSettings['smtp_host'], 0, 5) == 'smtp.' || substr($modSettings['smtp_host'], 0, 11) == 'ssl://smtp.'))
  1105. $socket = fsockopen(strtr($modSettings['smtp_host'], array('smtp.' => 'pop.')), 110, $errno, $errstr, 2);
  1106. if ($socket)
  1107. {
  1108. fgets($socket, 256);
  1109. fputs($socket, 'USER ' . $modSettings['smtp_username'] . "\r\n");
  1110. fgets($socket, 256);
  1111. fputs($socket, 'PASS ' . base64_decode($modSettings['smtp_password']) . "\r\n");
  1112. fgets($socket, 256);
  1113. fputs($socket, 'QUIT' . "\r\n");
  1114. fclose($socket);
  1115. }
  1116. }
  1117. // Try to connect to the SMTP server... if it doesn't exist, only wait three seconds.
  1118. if (!$socket = fsockopen($modSettings['smtp_host'], empty($modSettings['smtp_port']) ? 25 : $modSettings['smtp_port'], $errno, $errstr, 3))
  1119. {
  1120. // Maybe we can still save this? The port might be wrong.
  1121. if (substr($modSettings['smtp_host'], 0, 4) == 'ssl:' && (empty($modSettings['smtp_port']) || $modSettings['smtp_port'] == 25))
  1122. {
  1123. if ($socket = fsockopen($modSettings['smtp_host'], 465, $errno, $errstr, 3))
  1124. log_error($txt['smtp_port_ssl']);
  1125. }
  1126. // Unable to connect! Don't show any error message, but just log one and try to continue anyway.
  1127. if (!$socket)
  1128. {
  1129. log_error($txt['smtp_no_connect'] . ': ' . $errno . ' : ' . $errstr);
  1130. return false;
  1131. }
  1132. }
  1133. // Wait for a response of 220, without "-" continuer.
  1134. if (!server_parse(null, $socket, '220'))
  1135. return false;
  1136. if ($modSettings['mail_type'] == 1 && $modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
  1137. {
  1138. // !!! These should send the CURRENT server's name, not the mail server's!
  1139. // EHLO could be understood to mean encrypted hello...
  1140. if (server_parse('EHLO ' . $modSettings['smtp_host'], $socket, null) == '250')
  1141. {
  1142. if (!server_parse('AUTH LOGIN', $socket, '334'))
  1143. return false;
  1144. // Send the username and password, encoded.
  1145. if (!server_parse(base64_encode($modSettings['smtp_username']), $socket, '334'))
  1146. return false;
  1147. // The password is already encoded ;)
  1148. if (!server_parse($modSettings['smtp_password'], $socket, '235'))
  1149. return false;
  1150. }
  1151. elseif (!server_parse('HELO ' . $modSettings['smtp_host'], $socket, '250'))
  1152. return false;
  1153. }
  1154. else
  1155. {
  1156. // Just say "helo".
  1157. if (!server_parse('HELO ' . $modSettings['smtp_host'], $socket, '250'))
  1158. return false;
  1159. }
  1160. // Fix the message for any lines beginning with a period! (the first is ignored, you see.)
  1161. $message = strtr($message, array("\r\n" . '.' => "\r\n" . '..'));
  1162. // !! Theoretically, we should be able to just loop the RCPT TO.
  1163. $mail_to_array = array_values($mail_to_array);
  1164. foreach ($mail_to_array as $i => $mail_to)
  1165. {
  1166. // Reset the connection to send another email.
  1167. if ($i != 0)
  1168. {
  1169. if (!server_parse('RSET', $socket, '250'))
  1170. return false;
  1171. }
  1172. // From, to, and then start the data...
  1173. if (!server_parse('MAIL FROM: <' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . '>', $socket, '250'))
  1174. return false;
  1175. if (!server_parse('RCPT TO: <' . $mail_to . '>', $socket, '250'))
  1176. return false;
  1177. if (!server_parse('DATA', $socket, '354'))
  1178. return false;
  1179. fputs($socket, 'Subject: ' . $subject . "\r\n");
  1180. if (strlen($mail_to) > 0)
  1181. fputs($socket, 'To: <' . $mail_to . '>' . "\r\n");
  1182. fputs($socket, $headers . "\r\n\r\n");
  1183. fputs($socket, $message . "\r\n");
  1184. // Send a ., or in other words "end of data".
  1185. if (!server_parse('.', $socket, '250'))
  1186. return false;
  1187. // Almost done, almost done... don't stop me just yet!
  1188. @set_time_limit(300);
  1189. if (function_exists('apache_reset_timeout'))
  1190. @apache_reset_timeout();
  1191. }
  1192. fputs($socket, 'QUIT' . "\r\n");
  1193. fclose($socket);
  1194. return true;
  1195. }
  1196. /**
  1197. * Parse a message to the SMTP server.
  1198. * Sends the specified message to the server, and checks for the
  1199. * expected response.
  1200. * @internal
  1201. *
  1202. * @param string $message - the message to send
  1203. * @param resource $socket - socket to send on
  1204. * @param string $response - the expected response code
  1205. * @return whether it responded as such.
  1206. */
  1207. function server_parse($message, $socket, $response)
  1208. {
  1209. global $txt;
  1210. if ($message !== null)
  1211. fputs($socket, $message . "\r\n");
  1212. // No response yet.
  1213. $server_response = '';
  1214. while (substr($server_response, 3, 1) != ' ')
  1215. if (!($server_response = fgets($socket, 256)))
  1216. {
  1217. // !!! Change this message to reflect that it may mean bad user/password/server issues/etc.
  1218. log_error($txt['smtp_bad_response']);
  1219. return false;
  1220. }
  1221. if ($response === null)
  1222. return substr($server_response, 0, 3);
  1223. if (substr($server_response, 0, 3) != $response)
  1224. {
  1225. log_error($txt['smtp_error'] . $server_response);
  1226. return false;
  1227. }
  1228. return true;
  1229. }
  1230. /**
  1231. * Spell checks the post for typos ;).
  1232. * It uses the pspell library, which MUST be installed.
  1233. * It has problems with internationalization.
  1234. * It is accessed via ?action=spellcheck.
  1235. */
  1236. function SpellCheck()
  1237. {
  1238. global $txt, $context, $smcFunc;
  1239. // A list of "words" we know about but pspell doesn't.
  1240. $known_words = array('smf', 'php', 'mysql', 'www', 'gif', 'jpeg', 'png', 'http', 'smfisawesome', 'grandia', 'terranigma', 'rpgs');
  1241. loadLanguage('Post');
  1242. loadTemplate('Post');
  1243. // Okay, this looks funny, but it actually fixes a weird bug.
  1244. ob_start();
  1245. $old = error_reporting(0);
  1246. // See, first, some windows machines don't load pspell properly on the first try. Dumb, but this is a workaround.
  1247. pspell_new('en');
  1248. // Next, the dictionary in question may not exist. So, we try it... but...
  1249. $pspell_link = pspell_new($txt['lang_dictionary'], $txt['lang_spelling'], '', strtr($context['character_set'], array('iso-' => 'iso', 'ISO-' => 'iso')), PSPELL_FAST | PSPELL_RUN_TOGETHER);
  1250. // Most people don't have anything but English installed... So we use English as a last resort.
  1251. if (!$pspell_link)
  1252. $pspell_link = pspell_new('en', '', '', '', PSPELL_FAST | PSPELL_RUN_TOGETHER);
  1253. error_reporting($old);
  1254. ob_end_clean();
  1255. if (!isset($_POST['spellstring']) || !$pspell_link)
  1256. die;
  1257. // Construct a bit of Javascript code.
  1258. $context['spell_js'] = '
  1259. var txt = {"done": "' . $txt['spellcheck_done'] . '"};
  1260. var mispstr = window.opener.document.forms[spell_formname][spell_fieldname].value;
  1261. var misps = Array(';
  1262. // Get all the words (Javascript already separated them).
  1263. $alphas = explode("\n", strtr($_POST['spellstring'], array("\r" => '')));
  1264. $found_words = false;
  1265. for ($i = 0, $n = count($alphas); $i < $n; $i++)
  1266. {
  1267. // Words are sent like 'word|offset_begin|offset_end'.
  1268. $check_word = explode('|', $alphas[$i]);
  1269. // If the word is a known word, or spelled right...
  1270. if (in_array($smcFunc['strtolower']($check_word[0]), $known_words) || pspell_check($pspell_link, $check_word[0]) || !isset($check_word[2]))
  1271. continue;
  1272. // Find the word, and move up the "last occurance" to here.
  1273. $found_words = true;
  1274. // Add on the javascript for this misspelling.
  1275. $context['spell_js'] .= '
  1276. new misp("' . strtr($check_word[0], array('\\' => '\\\\', '"' => '\\"', '<' => '', '&gt;' => '')) . '", ' . (int) $check_word[1] . ', ' . (int) $check_word[2] . ', [';
  1277. // If there are suggestions, add them in...
  1278. $suggestions = pspell_suggest($pspell_link, $check_word[0]);
  1279. if (!empty($suggestions))
  1280. {
  1281. // But first check they aren't going to be censored - no naughty words!
  1282. foreach ($suggestions as $k => $word)
  1283. if ($suggestions[$k] != censorText($word))
  1284. unset($suggestions[$k]);
  1285. if (!empty($suggestions))
  1286. $context['spell_js'] .= '"' . implode('", "', $suggestions) . '"';
  1287. }
  1288. $context['spell_js'] .= ']),';
  1289. }
  1290. // If words were found, take off the last comma.
  1291. if ($found_words)
  1292. $context['spell_js'] = substr($context['spell_js'], 0, -1);
  1293. $context['spell_js'] .= '
  1294. );';
  1295. // And instruct the template system to just show the spellcheck sub template.
  1296. $context['template_layers'] = array();
  1297. $context['sub_template'] = 'spellcheck';
  1298. }
  1299. /**
  1300. * Sends a notification to members who have elected to receive emails
  1301. * when things happen to a topic, such as replies are posted.
  1302. * The function automatically finds the subject and its board, and
  1303. * checks permissions for each member who is "signed up" for notifications.
  1304. * It will not send 'reply' notifications more than once in a row.
  1305. *
  1306. * @param array $topics - represents the topics the action is happening to.
  1307. * @param string $type - can be any of reply, sticky, lock, unlock, remove,
  1308. * move, merge, and split. An appropriate message will be sent for each.
  1309. * @param array $exclude = array() - members in the exclude array will not be
  1310. * processed for the topic with the same key.
  1311. * @param array $members_only = array() - are the only ones that will be sent the notification if they have it on.
  1312. * @uses Post language file
  1313. */
  1314. function sendNotifications($topics, $type, $exclude = array(), $members_only = array())
  1315. {
  1316. global $txt, $scripturl, $language, $user_info;
  1317. global $modSettings, $sourcedir, $context, $smcFunc;
  1318. // Can't do it if there's no topics.
  1319. if (empty($topics))
  1320. return;
  1321. // It must be an array - it must!
  1322. if (!is_array($topics))
  1323. $topics = array($topics);
  1324. // Get the subject and body...
  1325. $result = $smcFunc['db_query']('', '
  1326. SELECT mf.subject, ml.body, ml.id_member, t.id_last_msg, t.id_topic,
  1327. IFNULL(mem.real_name, ml.poster_name) AS poster_name
  1328. FROM {db_prefix}topics AS t
  1329. INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
  1330. INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
  1331. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ml.id_member)
  1332. WHERE t.id_topic IN ({array_int:topic_list})
  1333. LIMIT 1',
  1334. array(
  1335. 'topic_list' => $topics,
  1336. )
  1337. );
  1338. $topicData = array();
  1339. while ($row = $smcFunc['db_fetch_assoc']($result))
  1340. {
  1341. // Clean it up.
  1342. censorText($row['subject']);
  1343. censorText($row['body']);
  1344. $row['subject'] = un_htmlspecialchars($row['subject']);
  1345. $row['body'] = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc($row['body'], false, $row['id_last_msg']), array('<br />' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
  1346. $topicData[$row['id_topic']] = array(
  1347. 'subject' => $row['subject'],
  1348. 'body' => $row['body'],
  1349. 'last_id' => $row['id_last_msg'],
  1350. 'topic' => $row['id_topic'],
  1351. 'name' => $user_info['name'],
  1352. 'exclude' => '',
  1353. );
  1354. }
  1355. $smcFunc['db_free_result']($result);
  1356. // Work out any exclusions...
  1357. foreach ($topics as $key => $id)
  1358. if (isset($topicData[$id]) && !empty($exclude[$key]))
  1359. $topicData[$id]['exclude'] = (int) $exclude[$key];
  1360. // Nada?
  1361. if (empty($topicData))
  1362. trigger_error('sendNotifications(): topics not found', E_USER_NOTICE);
  1363. $topics = array_keys($topicData);
  1364. // Just in case they've gone walkies.
  1365. if (empty($topics))
  1366. return;
  1367. // Insert all of these items into the digest log for those who want notifications later.
  1368. $digest_insert = array();
  1369. foreach ($topicData as $id => $data)
  1370. $digest_insert[] = array($data['topic'], $data['last_id'], $type, (int) $data['exclude']);
  1371. $smcFunc['db_insert']('',
  1372. '{db_prefix}log_digest',
  1373. array(
  1374. 'id_topic' => 'int', 'id_msg' => 'int', 'note_type' => 'string', 'exclude' => 'int',
  1375. ),
  1376. $digest_insert,
  1377. array()
  1378. );
  1379. // Find the members with notification on for this topic.
  1380. $members = $smcFunc['db_query']('', '
  1381. SELECT
  1382. mem.id_member, mem.email_address, mem.notify_regularity, mem.notify_types, mem.notify_send_body, mem.lngfile,
  1383. ln.sent, mem.id_group, mem.additional_groups, b.member_groups, mem.id_post_group, t.id_member_started,
  1384. ln.id_topic
  1385. FROM {db_prefix}log_notify AS ln
  1386. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ln.id_member)
  1387. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)
  1388. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  1389. WHERE ln.id_topic IN ({array_int:topic_list})
  1390. AND mem.notify_types < {int:notify_types}
  1391. AND mem.notify_regularity < {int:notify_regularity}
  1392. AND mem.is_activated = {int:is_activated}
  1393. AND ln.id_member != {int:current_member}' .
  1394. (empty($members_only) ? '' : ' AND ln.id_member IN ({array_int:members_only})') . '
  1395. ORDER BY mem.lngfile',
  1396. array(
  1397. 'current_member' => $user_info['id'],
  1398. 'topic_list' => $topics,
  1399. 'notify_types' => $type == 'reply' ? '4' : '3',
  1400. 'notify_regularity' => 2,
  1401. 'is_activated' => 1,
  1402. 'members_only' => is_array($members_only) ? $members_only : array($members_only),
  1403. )
  1404. );
  1405. $sent = 0;
  1406. $current_language = '';
  1407. while ($row = $smcFunc['db_fetch_assoc']($members))
  1408. {
  1409. // Don't do the excluded...
  1410. if ($topicData[$row['id_topic']]['exclude'] == $row['id_member'])
  1411. continue;
  1412. // Easier to check this here... if they aren't the topic poster do they really want to know?
  1413. if ($type != 'reply' && $row['notify_types'] == 2 && $row['id_member'] != $row['id_member_started'])
  1414. continue;
  1415. if ($row['id_group'] != 1)
  1416. {
  1417. $allowed = explode(',', $row['member_groups']);
  1418. $row['additional_groups'] = explode(',', $row['additional_groups']);
  1419. $row['additional_groups'][] = $row['id_group'];
  1420. $row['additional_groups'][] = $row['id_post_group'];
  1421. if (count(array_intersect($allowed, $row['additional_groups'])) == 0)
  1422. continue;
  1423. }
  1424. $needed_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
  1425. if (empty($current_language) || $current_language != $needed_language)
  1426. $current_language = loadLanguage('Post', $needed_language, false);
  1427. $message_type = 'notification_' . $type;
  1428. $replacements = array(
  1429. 'TOPICSUBJECT' => $topicData[$row['id_topic']]['subject'],
  1430. 'POSTERNAME' => un_htmlspecialchars($topicData[$row['id_topic']]['name']),
  1431. 'TOPICLINK' => $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new',
  1432. 'UNSUBSCRIBELINK' => $scripturl . '?action=notify;topic=' . $row['id_topic'] . '.0',
  1433. );
  1434. if ($type == 'remove')
  1435. unset($replacements['TOPICLINK'], $replacements['UNSUBSCRIBELINK']);
  1436. // Do they want the body of the message sent too?
  1437. if (!empty($row['notify_send_body']) && $type == 'reply' && empty($modSettings['disallow_sendBody']))
  1438. {
  1439. $message_type .= '_body';
  1440. $replacements['MESSAGE'] = $topicData[$row['id_topic']]['body'];
  1441. }
  1442. if (!empty($row['notify_regularity']) && $type == 'reply')
  1443. $message_type .= '_once';
  1444. // Send only if once is off or it's on and it hasn't been sent.
  1445. if ($type != 'reply' || empty($row['notify_regularity']) || empty($row['sent']))
  1446. {
  1447. $emaildata = loadEmailTemplate($message_type, $replacements, $needed_language);
  1448. sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, 'm' . $topicData[$row['id_topic']]['last_id']);
  1449. $sent++;
  1450. }
  1451. }
  1452. $smcFunc['db_free_result']($members);
  1453. if (isset($current_language) && $current_language != $user_info['language'])
  1454. loadLanguage('Post');
  1455. // Sent!
  1456. if ($type == 'reply' && !empty($sent))
  1457. $smcFunc['db_query']('', '
  1458. UPDATE {db_prefix}log_notify
  1459. SET sent = {int:is_sent}
  1460. WHERE id_topic IN ({array_int:topic_list})
  1461. AND id_member != {int:current_member}',
  1462. array(
  1463. 'current_member' => $user_info['id'],
  1464. 'topic_list' => $topics,
  1465. 'is_sent' => 1,
  1466. )
  1467. );
  1468. // For approvals we need to unsend the exclusions (This *is* the quickest way!)
  1469. if (!empty($sent) && !empty($exclude))
  1470. {
  1471. foreach ($topicData as $id => $data)
  1472. if ($data['exclude'])
  1473. $smcFunc['db_query']('', '
  1474. UPDATE {db_prefix}log_notify
  1475. SET sent = {int:not_sent}
  1476. WHERE id_topic = {int:id_topic}
  1477. AND id_member = {int:id_member}',
  1478. array(
  1479. 'not_sent' => 0,
  1480. 'id_topic' => $id,
  1481. 'id_member' => $data['exclude'],
  1482. )
  1483. );
  1484. }
  1485. }
  1486. /**
  1487. * Create a post, either as new topic (id_topic = 0) or in an existing one.
  1488. * The input parameters of this function assume:
  1489. * - Strings have been escaped.
  1490. * - Integers have been cast to integer.
  1491. * - Mandatory parameters are set.
  1492. *
  1493. * @param array $msgOptions
  1494. * @param array $topicOptions
  1495. * @param array $posterOptions
  1496. */
  1497. function createPost(&$msgOptions, &$topicOptions, &$posterOptions)
  1498. {
  1499. global $user_info, $txt, $modSettings, $smcFunc, $context;
  1500. // Set optional parameters to the default value.
  1501. $msgOptions['icon'] = empty($msgOptions['icon']) ? 'xx' : $msgOptions['icon'];
  1502. $msgOptions['smileys_enabled'] = !empty($msgOptions['smileys_enabled']);
  1503. $msgOptions['attachments'] = empty($msgOptions['attachments']) ? array() : $msgOptions['attachments'];
  1504. $msgOptions['approved'] = isset($msgOptions['approved']) ? (int) $msgOptions['approved'] : 1;
  1505. $topicOptions['id'] = empty($topicOptions['id']) ? 0 : (int) $topicOptions['id'];
  1506. $topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null;
  1507. $topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null;
  1508. $topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null;
  1509. $posterOptions['id'] = empty($posterOptions['id']) ? 0 : (int) $posterOptions['id'];
  1510. $posterOptions['ip'] = empty($posterOptions['ip']) ? $user_info['ip'] : $posterOptions['ip'];
  1511. // We need to know if the topic is approved. If we're told that's great - if not find out.
  1512. if (!$modSettings['postmod_active'])
  1513. $topicOptions['is_approved'] = true;
  1514. elseif (!empty($topicOptions['id']) && !isset($topicOptions['is_approved']))
  1515. {
  1516. $request = $smcFunc['db_query']('', '
  1517. SELECT approved
  1518. FROM {db_prefix}topics
  1519. WHERE id_topic = {int:id_topic}
  1520. LIMIT 1',
  1521. array(
  1522. 'id_topic' => $topicOptions['id'],
  1523. )
  1524. );
  1525. list ($topicOptions['is_approved']) = $smcFunc['db_fetch_row']($request);
  1526. $smcFunc['db_free_result']($request);
  1527. }
  1528. // If nothing was filled in as name/e-mail address, try the member table.
  1529. if (!isset($posterOptions['name']) || $posterOptions['name'] == '' || (empty($posterOptions['email']) && !empty($posterOptions['id'])))
  1530. {
  1531. if (empty($posterOptions['id']))
  1532. {
  1533. $posterOptions['id'] = 0;
  1534. $posterOptions['name'] = $txt['guest_title'];
  1535. $posterOptions['email'] = '';
  1536. }
  1537. elseif ($posterOptions['id'] != $user_info['id'])
  1538. {
  1539. $request = $smcFunc['db_query']('', '
  1540. SELECT member_name, email_address
  1541. FROM {db_prefix}members
  1542. WHERE id_member = {int:id_member}
  1543. LIMIT 1',
  1544. array(
  1545. 'id_member' => $posterOptions['id'],
  1546. )
  1547. );
  1548. // Couldn't find the current poster?
  1549. if ($smcFunc['db_num_rows']($request) == 0)
  1550. {
  1551. trigger_error('createPost(): Invalid member id ' . $posterOptions['id'], E_USER_NOTICE);
  1552. $posterOptions['id'] = 0;
  1553. $posterOptions['name'] = $txt['guest_title'];
  1554. $posterOptions['email'] = '';
  1555. }
  1556. else
  1557. list ($posterOptions['name'], $posterOptions['email']) = $smcFunc['db_fetch_row']($request);
  1558. $smcFunc['db_free_result']($request);
  1559. }
  1560. else
  1561. {
  1562. $posterOptions['name'] = $user_info['name'];
  1563. $posterOptions['email'] = $user_info['email'];
  1564. }
  1565. }
  1566. // It's do or die time: forget any user aborts!
  1567. $previous_ignore_user_abort = ignore_user_abort(true);
  1568. $new_topic = empty($topicOptions['id']);
  1569. // Insert the post.
  1570. $smcFunc['db_insert']('',
  1571. '{db_prefix}messages',
  1572. array(
  1573. 'id_board' => 'int', 'id_topic' => 'int', 'id_member' => 'int', 'subject' => 'string-255', 'body' => (!empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] > 65534 ? 'string-' . $modSettings['max_messageLength'] : 'string-65534'),
  1574. 'poster_name' => 'string-255', 'poster_email' => 'string-255', 'poster_time' => 'int', 'poster_ip' => 'string-255',
  1575. 'smileys_enabled' => 'int', 'modified_name' => 'string', 'icon' => 'string-16', 'approved' => 'int',
  1576. ),
  1577. array(
  1578. $topicOptions['board'], $topicOptions['id'], $posterOptions['id'], $msgOptions['subject'], $msgOptions['body'],
  1579. $posterOptions['name'], $posterOptions['email'], time(), $posterOptions['ip'],
  1580. $msgOptions['smileys_enabled'] ? 1 : 0, '', $msgOptions['icon'], $msgOptions['approved'],
  1581. ),
  1582. array('id_msg')
  1583. );
  1584. $msgOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}messages', 'id_msg');
  1585. // Something went wrong creating the message...
  1586. if (empty($msgOptions['id']))
  1587. return false;
  1588. // Fix the attachments.
  1589. if (!empty($msgOptions['attachments']))
  1590. $smcFunc['db_query']('', '
  1591. UPDATE {db_prefix}attachments
  1592. SET id_msg = {int:id_msg}
  1593. WHERE id_attach IN ({array_int:attachment_list})',
  1594. array(
  1595. 'attachment_list' => $msgOptions['attachments'],
  1596. 'id_msg' => $msgOptions['id'],
  1597. )
  1598. );
  1599. // Insert a new topic (if the topicID was left empty.)
  1600. if ($new_topic)
  1601. {
  1602. $smcFunc['db_insert']('',
  1603. '{db_prefix}topics',
  1604. array(
  1605. 'id_board' => 'int', 'id_member_started' => 'int', 'id_member_updated' => 'int', 'id_first_msg' => 'int',
  1606. 'id_last_msg' => 'int', 'locked' => 'int', 'is_sticky' => 'int', 'num_views' => 'int',
  1607. 'id_poll' => 'int', 'unapproved_posts' => 'int', 'approved' => 'int',
  1608. ),
  1609. array(
  1610. $topicOptions['board'], $posterOptions['id'], $posterOptions['id'], $msgOptions['id'],
  1611. $msgOptions['id'], $topicOptions['lock_mode'] === null ? 0 : $topicOptions['lock_mode'], $topicOptions['sticky_mode'] === null ? 0 : $topicOptions['sticky_mode'], 0,
  1612. $topicOptions['poll'] === null ? 0 : $topicOptions['poll'], $msgOptions['approved'] ? 0 : 1, $msgOptions['approved'],
  1613. ),
  1614. array('id_topic')
  1615. );
  1616. $topicOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}topics', 'id_topic');
  1617. // The topic couldn't be created for some reason.
  1618. if (empty($topicOptions['id']))
  1619. {
  1620. // We should delete the post that did work, though...
  1621. $smcFunc['db_query']('', '
  1622. DELETE FROM {db_prefix}messages
  1623. WHERE id_msg = {int:id_msg}',
  1624. array(
  1625. 'id_msg' => $msgOptions['id'],
  1626. )
  1627. );
  1628. return false;
  1629. }
  1630. // Fix the message with the topic.
  1631. $smcFunc['db_query']('', '
  1632. UPDATE {db_prefix}messages
  1633. SET id_topic = {int:id_topic}
  1634. WHERE id_msg = {int:id_msg}',
  1635. array(
  1636. 'id_topic' => $topicOptions['id'],
  1637. 'id_msg' => $msgOptions['id'],
  1638. )
  1639. );
  1640. // There's been a new topic AND a new post today.
  1641. trackStats(array('topics' => '+', 'posts' => '+'));
  1642. updateStats('topic', true);
  1643. updateStats('subject', $topicOptions['id'], $msgOptions['subject']);
  1644. // What if we want to export new topics out to a CMS?
  1645. call_integration_hook('integrate_create_topic', array($msgOptions, $topicOptions, $posterOptions));
  1646. }
  1647. // The topic already exists, it only needs a little updating.
  1648. else
  1649. {
  1650. $countChange = $msgOptions['approved'] ? 'num_replies = num_replies + 1' : 'unapproved_posts = unapproved_posts + 1';
  1651. // Update the number of replies and the lock/sticky status.
  1652. $smcFunc['db_query']('', '
  1653. UPDATE {db_prefix}topics
  1654. SET
  1655. ' . ($msgOptions['approved'] ? 'id_member_updated = {int:poster_id}, id_last_msg = {int:id_msg},' : '') . '
  1656. ' . $countChange . ($topicOptions['lock_mode'] === null ? '' : ',
  1657. locked = {int:locked}') . ($topicOptions['sticky_mode'] === null ? '' : ',
  1658. is_sticky = {int:is_sticky}') . '
  1659. WHERE id_topic = {int:id_topic}',
  1660. array(
  1661. 'poster_id' => $posterOptions['id'],
  1662. 'id_msg' => $msgOptions['id'],
  1663. 'locked' => $topicOptions['lock_mode'],
  1664. 'is_sticky' => $topicOptions['sticky_mode'],
  1665. 'id_topic' => $topicOptions['id'],
  1666. )
  1667. );
  1668. // One new post has been added today.
  1669. trackStats(array('posts' => '+'));
  1670. }
  1671. // Creating is modifying...in a way.
  1672. // @todo Why not set id_msg_modified on the insert?
  1673. $smcFunc['db_query']('', '
  1674. UPDATE {db_prefix}messages
  1675. SET id_msg_modified = {int:id_msg}
  1676. WHERE id_msg = {int:id_msg}',
  1677. array(
  1678. 'id_msg' => $msgOptions['id'],
  1679. )
  1680. );
  1681. // Increase the number of posts and topics on the board.
  1682. if ($msgOptions['approved'])
  1683. $smcFunc['db_query']('', '
  1684. UPDATE {db_prefix}boards
  1685. SET num_posts = num_posts + 1' . ($new_topic ? ', num_topics = num_topics + 1' : '') . '
  1686. WHERE id_board = {int:id_board}',
  1687. array(
  1688. 'id_board' => $topicOptions['board'],
  1689. )
  1690. );
  1691. else
  1692. {
  1693. $smcFunc['db_query']('', '
  1694. UPDATE {db_prefix}boards
  1695. SET unapproved_posts = unapproved_posts + 1' . ($new_topic ? ', unapproved_topics = unapproved_topics + 1' : '') . '
  1696. WHERE id_board = {int:id_board}',
  1697. array(
  1698. 'id_board' => $topicOptions['board'],
  1699. )
  1700. );
  1701. // Add to the approval queue too.
  1702. $smcFunc['db_insert']('',
  1703. '{db_prefix}approval_queue',
  1704. array(
  1705. 'id_msg' => 'int',
  1706. ),
  1707. array(
  1708. $msgOptions['id'],
  1709. ),
  1710. array()
  1711. );
  1712. }
  1713. // Mark inserted topic as read (only for the user calling this function).
  1714. if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest'])
  1715. {
  1716. // Since it's likely they *read* it before replying, let's try an UPDATE first.
  1717. if (!$new_topic)
  1718. {
  1719. $smcFunc['db_query']('', '
  1720. UPDATE {db_prefix}log_topics
  1721. SET id_msg = {int:id_msg}
  1722. WHERE id_member = {int:current_member}
  1723. AND id_topic = {int:id_topic}',
  1724. array(
  1725. 'current_member' => $posterOptions['id'],
  1726. 'id_msg' => $msgOptions['id'],
  1727. 'id_topic' => $topicOptions['id'],
  1728. )
  1729. );
  1730. $flag = $smcFunc['db_affected_rows']() != 0;
  1731. }
  1732. if (empty($flag))
  1733. {
  1734. $smcFunc['db_insert']('ignore',
  1735. '{db_prefix}log_topics',
  1736. array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'),
  1737. array($topicOptions['id'], $posterOptions['id'], $msgOptions['id']),
  1738. array('id_topic', 'id_member')
  1739. );
  1740. }
  1741. }
  1742. // If there's a custom search index, it needs updating...
  1743. if (!empty($modSettings['search_custom_index_config']))
  1744. {
  1745. $customIndexSettings = unserialize($modSettings['search_custom_index_config']);
  1746. $inserts = array();
  1747. foreach (text2words($msgOptions['body'], $customIndexSettings['bytes_per_word'], true) as $word)
  1748. $inserts[] = array($word, $msgOptions['id']);
  1749. if (!empty($inserts))
  1750. $smcFunc['db_insert']('ignore',
  1751. '{db_prefix}log_search_words',
  1752. array('id_word' => 'int', 'id_msg' => 'int'),
  1753. $inserts,
  1754. array('id_word', 'id_msg')
  1755. );
  1756. }
  1757. // Increase the post counter for the user that created the post.
  1758. if (!empty($posterOptions['update_post_count']) && !empty($posterOptions['id']) && $msgOptions['approved'])
  1759. {
  1760. // Are you the one that happened to create this post?
  1761. if ($user_info['id'] == $posterOptions['id'])
  1762. $user_info['posts']++;
  1763. updateMemberData($posterOptions['id'], array('posts' => '+'));
  1764. }
  1765. // They've posted, so they can make the view count go up one if they really want. (this is to keep views >= replies...)
  1766. $_SESSION['last_read_topic'] = 0;
  1767. // Better safe than sorry.
  1768. if (isset($_SESSION['topicseen_cache'][$topicOptions['board']]))
  1769. $_SESSION['topicseen_cache'][$topicOptions['board']]--;
  1770. // Update all the stats so everyone knows about this new topic and message.
  1771. updateStats('message', true, $msgOptions['id']);
  1772. // Update the last message on the board assuming it's approved AND the topic is.
  1773. if ($msgOptions['approved'])
  1774. updateLastMessages($topicOptions['board'], $new_topic || !empty($topicOptions['is_approved']) ? $msgOptions['id'] : 0);
  1775. // Alright, done now... we can abort now, I guess... at least this much is done.
  1776. ignore_user_abort($previous_ignore_user_abort);
  1777. // Success.
  1778. return true;
  1779. }
  1780. /**
  1781. * Create an attachment, with the given array of parameters.
  1782. *
  1783. * @param array $attachmentOptions
  1784. */
  1785. function createAttachment(&$attachmentOptions)
  1786. {
  1787. global $modSettings, $sourcedir, $smcFunc, $context;
  1788. require_once($sourcedir . '/Subs-Graphics.php');
  1789. // We need to know where this thing is going.
  1790. if (!empty($modSettings['currentAttachmentUploadDir']))
  1791. {
  1792. if (!is_array($modSettings['attachmentUploadDir']))
  1793. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1794. // Just use the current path for temp files.
  1795. $attach_dir = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
  1796. $id_folder = $modSettings['currentAttachmentUploadDir'];
  1797. }
  1798. else
  1799. {
  1800. $attach_dir = $modSettings['attachmentUploadDir'];
  1801. $id_folder = 1;
  1802. }
  1803. $attachmentOptions['errors'] = array();
  1804. if (!isset($attachmentOptions['post']))
  1805. $attachmentOptions['post'] = 0;
  1806. if (!isset($attachmentOptions['approved']))
  1807. $attachmentOptions['approved'] = 1;
  1808. $already_uploaded = preg_match('~^post_tmp_' . $attachmentOptions['poster'] . '_\d+$~', $attachmentOptions['tmp_name']) != 0;
  1809. $file_restricted = @ini_get('open_basedir') != '' && !$already_uploaded;
  1810. if ($already_uploaded)
  1811. $attachmentOptions['tmp_name'] = $attach_dir . '/' . $attachmentOptions['tmp_name'];
  1812. // Make sure the file actually exists... sometimes it doesn't.
  1813. if ((!$file_restricted && !file_exists($attachmentOptions['tmp_name'])) || (!$already_uploaded && !is_uploaded_file($attachmentOptions['tmp_name'])))
  1814. {
  1815. $attachmentOptions['errors'] = array('could_not_upload');
  1816. return false;
  1817. }
  1818. // These are the only valid image types for SMF.
  1819. $validImageTypes = array(
  1820. 1 => 'gif',
  1821. 2 => 'jpeg',
  1822. 3 => 'png',
  1823. 5 => 'psd',
  1824. 6 => 'bmp',
  1825. 7 => 'tiff',
  1826. 8 => 'tiff',
  1827. 9 => 'jpeg',
  1828. 14 => 'iff'
  1829. );
  1830. if (!$file_restricted || $already_uploaded)
  1831. {
  1832. $size = @getimagesize($attachmentOptions['tmp_name']);
  1833. list ($attachmentOptions['width'], $attachmentOptions['height']) = $size;
  1834. // If it's an image get the mime type right.
  1835. if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width'])
  1836. {
  1837. // Got a proper mime type?
  1838. if (!empty($size['mime']))
  1839. $attachmentOptions['mime_type'] = $size['mime'];
  1840. // Otherwise a valid one?
  1841. elseif (isset($validImageTypes[$size[2]]))
  1842. $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
  1843. }
  1844. }
  1845. // Get the hash if no hash has been given yet.
  1846. if (empty($attachmentOptions['file_hash']))
  1847. $attachmentOptions['file_hash'] = getAttachmentFilename($attachmentOptions['name'], false, null, true);
  1848. // Is the file too big?
  1849. if (!empty($modSettings['attachmentSizeLimit']) && $attachmentOptions['size'] > $modSettings['attachmentSizeLimit'] * 1024)
  1850. $attachmentOptions['errors'][] = 'too_large';
  1851. if (!empty($modSettings['attachmentCheckExtensions']))
  1852. {
  1853. $allowed = explode(',', strtolower($modSettings['attachmentExtensions']));
  1854. foreach ($allowed as $k => $dummy)
  1855. $allowed[$k] = trim($dummy);
  1856. if (!in_array(strtolower(substr(strrchr($attachmentOptions['name'], '.'), 1)), $allowed))
  1857. $attachmentOptions['errors'][] = 'bad_extension';
  1858. }
  1859. if (!empty($modSettings['attachmentDirSizeLimit']))
  1860. {
  1861. // Make sure the directory isn't full.
  1862. $dirSize = 0;
  1863. $dir = @opendir($attach_dir) or fatal_lang_error('cant_access_upload_path', 'critical');
  1864. while ($file = readdir($dir))
  1865. {
  1866. if ($file == '.' || $file == '..')
  1867. continue;
  1868. if (preg_match('~^post_tmp_\d+_\d+$~', $file) != 0)
  1869. {
  1870. // Temp file is more than 5 hours old!
  1871. if (filemtime($attach_dir . '/' . $file) < time() - 18000)
  1872. @unlink($attach_dir . '/' . $file);
  1873. continue;
  1874. }
  1875. $dirSize += filesize($attach_dir . '/' . $file);
  1876. }
  1877. closedir($dir);
  1878. // Too big! Maybe you could zip it or something...
  1879. if ($attachmentOptions['size'] + $dirSize > $modSettings['attachmentDirSizeLimit'] * 1024)
  1880. $attachmentOptions['errors'][] = 'directory_full';
  1881. // Soon to be too big - warn the admins...
  1882. elseif (!isset($modSettings['attachment_full_notified']) && $modSettings['attachmentDirSizeLimit'] > 4000 && $attachmentOptions['size'] + $dirSize > ($modSettings['attachmentDirSizeLimit'] - 2000) * 1024)
  1883. {
  1884. require_once($sourcedir . '/Subs-Admin.php');
  1885. emailAdmins('admin_attachments_full');
  1886. updateSettings(array('attachment_full_notified' => 1));
  1887. }
  1888. }
  1889. // Check if the file already exists.... (for those who do not encrypt their filenames...)
  1890. if (empty($modSettings['attachmentEncryptFilenames']))
  1891. {
  1892. // Make sure they aren't trying to upload a nasty file.
  1893. $disabledFiles = array('con', 'com1', 'com2', 'com3', 'com4', 'prn', 'aux', 'lpt1', '.htaccess', 'index.php');
  1894. if (in_array(strtolower(basename($attachmentOptions['name'])), $disabledFiles))
  1895. $attachmentOptions['errors'][] = 'bad_filename';
  1896. // Check if there's another file with that name...
  1897. $request = $smcFunc['db_query']('', '
  1898. SELECT id_attach
  1899. FROM {db_prefix}attachments
  1900. WHERE filename = {string:filename}
  1901. LIMIT 1',
  1902. array(
  1903. 'filename' => strtolower($attachmentOptions['name']),
  1904. )
  1905. );
  1906. if ($smcFunc['db_num_rows']($request) > 0)
  1907. $attachmentOptions['errors'][] = 'taken_filename';
  1908. $smcFunc['db_free_result']($request);
  1909. }
  1910. if (!empty($attachmentOptions['errors']))
  1911. return false;
  1912. if (!is_writable($attach_dir))
  1913. fatal_lang_error('attachments_no_write', 'critical');
  1914. // Assuming no-one set the extension let's take a look at it.
  1915. if (empty($attachmentOptions['fileext']))
  1916. {
  1917. $attachmentOptions['fileext'] = strtolower(strrpos($attachmentOptions['name'], '.') !== false ? substr($attachmentOptions['name'], strrpos($attachmentOptions['name'], '.') + 1) : '');
  1918. if (strlen($attachmentOptions['fileext']) > 8 || '.' . $attachmentOptions['fileext'] == $attachmentOptions['name'])
  1919. $attachmentOptions['fileext'] = '';
  1920. }
  1921. $smcFunc['db_insert']('',
  1922. '{db_prefix}attachments',
  1923. array(
  1924. 'id_folder' => 'int', 'id_msg' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8',
  1925. 'size' => 'int', 'width' => 'int', 'height' => 'int',
  1926. 'mime_type' => 'string-20', 'approved' => 'int',
  1927. ),
  1928. array(
  1929. $id_folder, (int) $attachmentOptions['post'], $attachmentOptions['name'], $attachmentOptions['file_hash'], $attachmentOptions['fileext'],
  1930. (int) $attachmentOptions['size'], (empty($attachmentOptions['width']) ? 0 : (int) $attachmentOptions['width']), (empty($attachmentOptions['height']) ? '0' : (int) $attachmentOptions['height']),
  1931. (!empty($attachmentOptions['mime_type']) ? $attachmentOptions['mime_type'] : ''), (int) $attachmentOptions['approved'],
  1932. ),
  1933. array('id_attach')
  1934. );
  1935. $attachmentOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
  1936. if (empty($attachmentOptions['id']))
  1937. return false;
  1938. // If it's not approved add to the approval queue.
  1939. if (!$attachmentOptions['approved'])
  1940. $smcFunc['db_insert']('',
  1941. '{db_prefix}approval_queue',
  1942. array(
  1943. 'id_attach' => 'int', 'id_msg' => 'int',
  1944. ),
  1945. array(
  1946. $attachmentOptions['id'], (int) $attachmentOptions['post'],
  1947. ),
  1948. array()
  1949. );
  1950. $attachmentOptions['destination'] = getAttachmentFilename(basename($attachmentOptions['name']), $attachmentOptions['id'], $id_folder, false, $attachmentOptions['file_hash']);
  1951. if ($already_uploaded)
  1952. rename($attachmentOptions['tmp_name'], $attachmentOptions['destination']);
  1953. elseif (!move_uploaded_file($attachmentOptions['tmp_name'], $attachmentOptions['destination']))
  1954. fatal_lang_error('attach_timeout', 'critical');
  1955. // Attempt to chmod it.
  1956. @chmod($attachmentOptions['destination'], 0644);
  1957. $size = @getimagesize($attachmentOptions['destination']);
  1958. list ($attachmentOptions['width'], $attachmentOptions['height']) = empty($size) ? array(null, null, null) : $size;
  1959. // We couldn't access the file before...
  1960. if ($file_restricted)
  1961. {
  1962. // Have a go at getting the right mime type.
  1963. if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width'])
  1964. {
  1965. if (!empty($size['mime']))
  1966. $attachmentOptions['mime_type'] = $size['mime'];
  1967. elseif (isset($validImageTypes[$size[2]]))
  1968. $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
  1969. }
  1970. if (!empty($attachmentOptions['width']) && !empty($attachmentOptions['height']))
  1971. $smcFunc['db_query']('', '
  1972. UPDATE {db_prefix}attachments
  1973. SET
  1974. width = {int:width},
  1975. height = {int:height},
  1976. mime_type = {string:mime_type}
  1977. WHERE id_attach = {int:id_attach}',
  1978. array(
  1979. 'width' => (int) $attachmentOptions['width'],
  1980. 'height' => (int) $attachmentOptions['height'],
  1981. 'id_attach' => $attachmentOptions['id'],
  1982. 'mime_type' => empty($attachmentOptions['mime_type']) ? '' : $attachmentOptions['mime_type'],
  1983. )
  1984. );
  1985. }
  1986. // Security checks for images
  1987. // Do we have an image? If yes, we need to check it out!
  1988. if (isset($validImageTypes[$size[2]]))
  1989. {
  1990. if (!checkImageContents($attachmentOptions['destination'], !empty($modSettings['attachment_image_paranoid'])))
  1991. {
  1992. // It's bad. Last chance, maybe we can re-encode it?
  1993. if (empty($modSettings['attachment_image_reencode']) || (!reencodeImage($attachmentOptions['destination'], $size[2])))
  1994. {
  1995. // Nothing to do: not allowed or not successful re-encoding it.
  1996. require_once($sourcedir . '/ManageAttachments.php');
  1997. removeAttachments(array(
  1998. 'id_attach' => $attachmentOptions['id']
  1999. ));
  2000. $attachmentOptions['id'] = null;
  2001. $attachmentOptions['errors'][] = 'bad_attachment';
  2002. return false;
  2003. }
  2004. // Success! However, successes usually come for a price:
  2005. // we might get a new format for our image...
  2006. $old_format = $size[2];
  2007. $size = @getimagesize($attachmentOptions['destination']);
  2008. if (!(empty($size)) && ($size[2] != $old_format))
  2009. {
  2010. // Let's update the image information
  2011. // !!! This is becoming a mess: we keep coming back and update the database,
  2012. // instead of getting it right the first time.
  2013. if (isset($validImageTypes[$size[2]]))
  2014. {
  2015. $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
  2016. $smcFunc['db_query']('', '
  2017. UPDATE {db_prefix}attachments
  2018. SET
  2019. mime_type = {string:mime_type}
  2020. WHERE id_attach = {int:id_attach}',
  2021. array(
  2022. 'id_attach' => $attachmentOptions['id'],
  2023. 'mime_type' => $attachmentOptions['mime_type'],
  2024. )
  2025. );
  2026. }
  2027. }
  2028. }
  2029. }
  2030. if (!empty($attachmentOptions['skip_thumbnail']) || (empty($attachmentOptions['width']) && empty($attachmentOptions['height'])))
  2031. return true;
  2032. // Like thumbnails, do we?
  2033. if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > $modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > $modSettings['attachmentThumbHeight']))
  2034. {
  2035. if (createThumbnail($attachmentOptions['destination'], $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight']))
  2036. {
  2037. // Figure out how big we actually made it.
  2038. $size = @getimagesize($attachmentOptions['destination'] . '_thumb');
  2039. list ($thumb_width, $thumb_height) = $size;
  2040. if (!empty($size['mime']))
  2041. $thumb_mime = $size['mime'];
  2042. elseif (isset($validImageTypes[$size[2]]))
  2043. $thumb_mime = 'image/' . $validImageTypes[$size[2]];
  2044. // Lord only knows how this happened...
  2045. else
  2046. $thumb_mime = '';
  2047. $thumb_filename = $attachmentOptions['name'] . '_thumb';
  2048. $thumb_size = filesize($attachmentOptions['destination'] . '_thumb');
  2049. $thumb_file_hash = getAttachmentFilename($thumb_filename, false, null, true);
  2050. // To the database we go!
  2051. $smcFunc['db_insert']('',
  2052. '{db_prefix}attachments',
  2053. array(
  2054. 'id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8',
  2055. 'size' => 'int', 'width' => 'int', 'height' => 'int', 'mime_type' => 'string-20', 'approved' => 'int',
  2056. ),
  2057. array(
  2058. $id_folder, (int) $attachmentOptions['post'], 3, $thumb_filename, $thumb_file_hash, $attachmentOptions['fileext'],
  2059. $thumb_size, $thumb_width, $thumb_height, $thumb_mime, (int) $attachmentOptions['approved'],
  2060. ),
  2061. array('id_attach')
  2062. );
  2063. $attachmentOptions['thumb'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
  2064. if (!empty($attachmentOptions['thumb']))
  2065. {
  2066. $smcFunc['db_query']('', '
  2067. UPDATE {db_prefix}attachments
  2068. SET id_thumb = {int:id_thumb}
  2069. WHERE id_attach = {int:id_attach}',
  2070. array(
  2071. 'id_thumb' => $attachmentOptions['thumb'],
  2072. 'id_attach' => $attachmentOptions['id'],
  2073. )
  2074. );
  2075. rename($attachmentOptions['destination'] . '_thumb', getAttachmentFilename($thumb_filename, $attachmentOptions['thumb'], $id_folder, false, $thumb_file_hash));
  2076. }
  2077. }
  2078. }
  2079. return true;
  2080. }
  2081. /**
  2082. * Modifying a post...
  2083. *
  2084. * @param array &$msgOptions
  2085. * @param array &$topicOptions
  2086. * @param array &$posterOptions
  2087. */
  2088. function modifyPost(&$msgOptions, &$topicOptions, &$posterOptions)
  2089. {
  2090. global $user_info, $modSettings, $smcFunc, $context;
  2091. $topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null;
  2092. $topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null;
  2093. $topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null;
  2094. // This is longer than it has to be, but makes it so we only set/change what we have to.
  2095. $messages_columns = array();
  2096. if (isset($posterOptions['name']))
  2097. $messages_columns['poster_name'] = $posterOptions['name'];
  2098. if (isset($posterOptions['email']))
  2099. $messages_columns['poster_email'] = $posterOptions['email'];
  2100. if (isset($msgOptions['icon']))
  2101. $messages_columns['icon'] = $msgOptions['icon'];
  2102. if (isset($msgOptions['subject']))
  2103. $messages_columns['subject'] = $msgOptions['subject'];
  2104. if (isset($msgOptions['body']))
  2105. {
  2106. $messages_columns['body'] = $msgOptions['body'];
  2107. if (!empty($modSettings['search_custom_index_config']))
  2108. {
  2109. $request = $smcFunc['db_query']('', '
  2110. SELECT body
  2111. FROM {db_prefix}messages
  2112. WHERE id_msg = {int:id_msg}',
  2113. array(
  2114. 'id_msg' => $msgOptions['id'],
  2115. )
  2116. );
  2117. list ($old_body) = $smcFunc['db_fetch_row']($request);
  2118. $smcFunc['db_free_result']($request);
  2119. }
  2120. }
  2121. if (!empty($msgOptions['modify_time']))
  2122. {
  2123. $messages_columns['modified_time'] = $msgOptions['modify_time'];
  2124. $messages_columns['modified_name'] = $msgOptions['modify_name'];
  2125. $messages_columns['id_msg_modified'] = $modSettings['maxMsgID'];
  2126. }
  2127. if (isset($msgOptions['smileys_enabled']))
  2128. $messages_columns['smileys_enabled'] = empty($msgOptions['smileys_enabled']) ? 0 : 1;
  2129. // Which columns need to be ints?
  2130. $messageInts = array('modified_time', 'id_msg_modified', 'smileys_enabled');
  2131. $update_parameters = array(
  2132. 'id_msg' => $msgOptions['id'],
  2133. );
  2134. foreach ($messages_columns as $var => $val)
  2135. {
  2136. $messages_columns[$var] = $var . ' = {' . (in_array($var, $messageInts) ? 'int' : 'string') . ':var_' . $var . '}';
  2137. $update_parameters['var_' . $var] = $val;
  2138. }
  2139. // Nothing to do?
  2140. if (empty($messages_columns))
  2141. return true;
  2142. // Change the post.
  2143. $smcFunc['db_query']('', '
  2144. UPDATE {db_prefix}messages
  2145. SET ' . implode(', ', $messages_columns) . '
  2146. WHERE id_msg = {int:id_msg}',
  2147. $update_parameters
  2148. );
  2149. // Lock and or sticky the post.
  2150. if ($topicOptions['sticky_mode'] !== null || $topicOptions['lock_mode'] !== null || $topicOptions['poll'] !== null)
  2151. {
  2152. $smcFunc['db_query']('', '
  2153. UPDATE {db_prefix}topics
  2154. SET
  2155. is_sticky = {raw:is_sticky},
  2156. locked = {raw:locked},
  2157. id_poll = {raw:id_poll}
  2158. WHERE id_topic = {int:id_topic}',
  2159. array(
  2160. 'is_sticky' => $topicOptions['sticky_mode'] === null ? 'is_sticky' : (int) $topicOptions['sticky_mode'],
  2161. 'locked' => $topicOptions['lock_mode'] === null ? 'locked' : (int) $topicOptions['lock_mode'],
  2162. 'id_poll' => $topicOptions['poll'] === null ? 'id_poll' : (int) $topicOptions['poll'],
  2163. 'id_topic' => $topicOptions['id'],
  2164. )
  2165. );
  2166. }
  2167. // Mark the edited post as read.
  2168. if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest'])
  2169. {
  2170. // Since it's likely they *read* it before editing, let's try an UPDATE first.
  2171. $smcFunc['db_query']('', '
  2172. UPDATE {db_prefix}log_topics
  2173. SET id_msg = {int:id_msg}
  2174. WHERE id_member = {int:current_member}
  2175. AND id_topic = {int:id_topic}',
  2176. array(
  2177. 'current_member' => $user_info['id'],
  2178. 'id_msg' => $modSettings['maxMsgID'],
  2179. 'id_topic' => $topicOptions['id'],
  2180. )
  2181. );
  2182. $flag = $smcFunc['db_affected_rows']() != 0;
  2183. if (empty($flag))
  2184. {
  2185. $smcFunc['db_insert']('ignore',
  2186. '{db_prefix}log_topics',
  2187. array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'),
  2188. array($topicOptions['id'], $user_info['id'], $modSettings['maxMsgID']),
  2189. array('id_topic', 'id_member')
  2190. );
  2191. }
  2192. }
  2193. // If there's a custom search index, it needs to be modified...
  2194. if (isset($msgOptions['body']) && !empty($modSettings['search_custom_index_config']))
  2195. {
  2196. $customIndexSettings = unserialize($modSettings['search_custom_index_config']);
  2197. $stopwords = empty($modSettings['search_stopwords']) ? array() : explode(',', $modSettings['search_stopwords']);
  2198. $old_index = text2words($old_body, $customIndexSettings['bytes_per_word'], true);
  2199. $new_index = text2words($msgOptions['body'], $customIndexSettings['bytes_per_word'], true);
  2200. // Calculate the words to be added and removed from the index.
  2201. $removed_words = array_diff(array_diff($old_index, $new_index), $stopwords);
  2202. $inserted_words = array_diff(array_diff($new_index, $old_index), $stopwords);
  2203. // Delete the removed words AND the added ones to avoid key constraints.
  2204. if (!empty($removed_words))
  2205. {
  2206. $removed_words = array_merge($removed_words, $inserted_words);
  2207. $smcFunc['db_query']('', '
  2208. DELETE FROM {db_prefix}log_search_words
  2209. WHERE id_msg = {int:id_msg}
  2210. AND id_word IN ({array_int:removed_words})',
  2211. array(
  2212. 'removed_words' => $removed_words,
  2213. 'id_msg' => $msgOptions['id'],
  2214. )
  2215. );
  2216. }
  2217. // Add the new words to be indexed.
  2218. if (!empty($inserted_words))
  2219. {
  2220. $inserts = array();
  2221. foreach ($inserted_words as $word)
  2222. $inserts[] = array($word, $msgOptions['id']);
  2223. $smcFunc['db_insert']('insert',
  2224. '{db_prefix}log_search_words',
  2225. array('id_word' => 'string', 'id_msg' => 'int'),
  2226. $inserts,
  2227. array('id_word', 'id_msg')
  2228. );
  2229. }
  2230. }
  2231. if (isset($msgOptions['subject']))
  2232. {
  2233. // Only update the subject if this was the first message in the topic.
  2234. $request = $smcFunc['db_query']('', '
  2235. SELECT id_topic
  2236. FROM {db_prefix}topics
  2237. WHERE id_first_msg = {int:id_first_msg}
  2238. LIMIT 1',
  2239. array(
  2240. 'id_first_msg' => $msgOptions['id'],
  2241. )
  2242. );
  2243. if ($smcFunc['db_num_rows']($request) == 1)
  2244. updateStats('subject', $topicOptions['id'], $msgOptions['subject']);
  2245. $smcFunc['db_free_result']($request);
  2246. }
  2247. // Finally, if we are setting the approved state we need to do much more work :(
  2248. if ($modSettings['postmod_active'] && isset($msgOptions['approved']))
  2249. approvePosts($msgOptions['id'], $msgOptions['approved']);
  2250. return true;
  2251. }
  2252. /**
  2253. * Approve (or not) some posts... without permission checks...
  2254. *
  2255. * @param array $msgs - array of message ids
  2256. * @param bool $approve = true
  2257. */
  2258. function approvePosts($msgs, $approve = true)
  2259. {
  2260. global $sourcedir, $smcFunc;
  2261. if (!is_array($msgs))
  2262. $msgs = array($msgs);
  2263. if (empty($msgs))
  2264. return false;
  2265. // May as well start at the beginning, working out *what* we need to change.
  2266. $request = $smcFunc['db_query']('', '
  2267. SELECT m.id_msg, m.approved, m.id_topic, m.id_board, t.id_first_msg, t.id_last_msg,
  2268. m.body, m.subject, IFNULL(mem.real_name, m.poster_name) AS poster_name, m.id_member,
  2269. t.approved AS topic_approved, b.count_posts
  2270. FROM {db_prefix}messages AS m
  2271. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
  2272. INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
  2273. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
  2274. WHERE m.id_msg IN ({array_int:message_list})
  2275. AND m.approved = {int:approved_state}',
  2276. array(
  2277. 'message_list' => $msgs,
  2278. 'approved_state' => $approve ? 0 : 1,
  2279. )
  2280. );
  2281. $msgs = array();
  2282. $topics = array();
  2283. $topic_changes = array();
  2284. $board_changes = array();
  2285. $notification_topics = array();
  2286. $notification_posts = array();
  2287. $member_post_changes = array();
  2288. while ($row = $smcFunc['db_fetch_assoc']($request))
  2289. {
  2290. // Easy...
  2291. $msgs[] = $row['id_msg'];
  2292. $topics[] = $row['id_topic'];
  2293. // Ensure our change array exists already.
  2294. if (!isset($topic_changes[$row['id_topic']]))
  2295. $topic_changes[$row['id_topic']] = array(
  2296. 'id_last_msg' => $row['id_last_msg'],
  2297. 'approved' => $row['topic_approved'],
  2298. 'replies' => 0,
  2299. 'unapproved_posts' => 0,
  2300. );
  2301. if (!isset($board_changes[$row['id_board']]))
  2302. $board_changes[$row['id_board']] = array(
  2303. 'posts' => 0,
  2304. 'topics' => 0,
  2305. 'unapproved_posts' => 0,
  2306. 'unapproved_topics' => 0,
  2307. );
  2308. // If it's the first message then the topic state changes!
  2309. if ($row['id_msg'] == $row['id_first_msg'])
  2310. {
  2311. $topic_changes[$row['id_topic']]['approved'] = $approve ? 1 : 0;
  2312. $board_changes[$row['id_board']]['unapproved_topics'] += $approve ? -1 : 1;
  2313. $board_changes[$row['id_board']]['topics'] += $approve ? 1 : -1;
  2314. // Note we need to ensure we announce this topic!
  2315. $notification_topics[] = array(
  2316. 'body' => $row['body'],
  2317. 'subject' => $row['subject'],
  2318. 'name' => $row['poster_name'],
  2319. 'board' => $row['id_board'],
  2320. 'topic' => $row['id_topic'],
  2321. 'msg' => $row['id_first_msg'],
  2322. 'poster' => $row['id_member'],
  2323. );
  2324. }
  2325. else
  2326. {
  2327. $topic_changes[$row['id_topic']]['replies'] += $approve ? 1 : -1;
  2328. // This will be a post... but don't notify unless it's not followed by approved ones.
  2329. if ($row['id_msg'] > $row['id_last_msg'])
  2330. $notification_posts[$row['id_topic']][] = array(
  2331. 'id' => $row['id_msg'],
  2332. 'body' => $row['body'],
  2333. 'subject' => $row['subject'],
  2334. 'name' => $row['poster_name'],
  2335. 'topic' => $row['id_topic'],
  2336. );
  2337. }
  2338. // If this is being approved and id_msg is higher than the current id_last_msg then it changes.
  2339. if ($approve && $row['id_msg'] > $topic_changes[$row['id_topic']]['id_last_msg'])
  2340. $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_msg'];
  2341. // If this is being unapproved, and it's equal to the id_last_msg we need to find a new one!
  2342. elseif (!$approve)
  2343. // Default to the first message and then we'll override in a bit ;)
  2344. $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_first_msg'];
  2345. $topic_changes[$row['id_topic']]['unapproved_posts'] += $approve ? -1 : 1;
  2346. $board_changes[$row['id_board']]['unapproved_posts'] += $approve ? -1 : 1;
  2347. $board_changes[$row['id_board']]['posts'] += $approve ? 1 : -1;
  2348. // Post count for the user?
  2349. if ($row['id_member'] && empty($row['count_posts']))
  2350. $member_post_changes[$row['id_member']] = isset($member_post_changes[$row['id_member']]) ? $member_post_changes[$row['id_member']] + 1 : 1;
  2351. }
  2352. $smcFunc['db_free_result']($request);
  2353. if (empty($msgs))
  2354. return;
  2355. // Now we have the differences make the changes, first the easy one.
  2356. $smcFunc['db_query']('', '
  2357. UPDATE {db_prefix}messages
  2358. SET approved = {int:approved_state}
  2359. WHERE id_msg IN ({array_int:message_list})',
  2360. array(
  2361. 'message_list' => $msgs,
  2362. 'approved_state' => $approve ? 1 : 0,
  2363. )
  2364. );
  2365. // If we were unapproving find the last msg in the topics...
  2366. if (!$approve)
  2367. {
  2368. $request = $smcFunc['db_query']('', '
  2369. SELECT id_topic, MAX(id_msg) AS id_last_msg
  2370. FROM {db_prefix}messages
  2371. WHERE id_topic IN ({array_int:topic_list})
  2372. AND approved = {int:approved}
  2373. GROUP BY id_topic',
  2374. array(
  2375. 'topic_list' => $topics,
  2376. 'approved' => 1,
  2377. )
  2378. );
  2379. while ($row = $smcFunc['db_fetch_assoc']($request))
  2380. $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_last_msg'];
  2381. $smcFunc['db_free_result']($request);
  2382. }
  2383. // ... next the topics...
  2384. foreach ($topic_changes as $id => $changes)
  2385. $smcFunc['db_query']('', '
  2386. UPDATE {db_prefix}topics
  2387. SET approved = {int:approved}, unapproved_posts = unapproved_posts + {int:unapproved_posts},
  2388. num_replies = num_replies + {int:num_replies}, id_last_msg = {int:id_last_msg}
  2389. WHERE id_topic = {int:id_topic}',
  2390. array(
  2391. 'approved' => $changes['approved'],
  2392. 'unapproved_posts' => $changes['unapproved_posts'],
  2393. 'num_replies' => $changes['replies'],
  2394. 'id_last_msg' => $changes['id_last_msg'],
  2395. 'id_topic' => $id,
  2396. )
  2397. );
  2398. // ... finally the boards...
  2399. foreach ($board_changes as $id => $changes)
  2400. $smcFunc['db_query']('', '
  2401. UPDATE {db_prefix}boards
  2402. SET num_posts = num_posts + {int:num_posts}, unapproved_posts = unapproved_posts + {int:unapproved_posts},
  2403. num_topics = num_topics + {int:num_topics}, unapproved_topics = unapproved_topics + {int:unapproved_topics}
  2404. WHERE id_board = {int:id_board}',
  2405. array(
  2406. 'num_posts' => $changes['posts'],
  2407. 'unapproved_posts' => $changes['unapproved_posts'],
  2408. 'num_topics' => $changes['topics'],
  2409. 'unapproved_topics' => $changes['unapproved_topics'],
  2410. 'id_board' => $id,
  2411. )
  2412. );
  2413. // Finally, least importantly, notifications!
  2414. if ($approve)
  2415. {
  2416. if (!empty($notification_topics))
  2417. {
  2418. require_once($sourcedir . '/Post.php');
  2419. notifyMembersBoard($notification_topics);
  2420. }
  2421. if (!empty($notification_posts))
  2422. sendApprovalNotifications($notification_posts);
  2423. $smcFunc['db_query']('', '
  2424. DELETE FROM {db_prefix}approval_queue
  2425. WHERE id_msg IN ({array_int:message_list})
  2426. AND id_attach = {int:id_attach}',
  2427. array(
  2428. 'message_list' => $msgs,
  2429. 'id_attach' => 0,
  2430. )
  2431. );
  2432. }
  2433. // If unapproving add to the approval queue!
  2434. else
  2435. {
  2436. $msgInserts = array();
  2437. foreach ($msgs as $msg)
  2438. $msgInserts[] = array($msg);
  2439. $smcFunc['db_insert']('ignore',
  2440. '{db_prefix}approval_queue',
  2441. array('id_msg' => 'int'),
  2442. $msgInserts,
  2443. array('id_msg')
  2444. );
  2445. }
  2446. // Update the last messages on the boards...
  2447. updateLastMessages(array_keys($board_changes));
  2448. // Post count for the members?
  2449. if (!empty($member_post_changes))
  2450. foreach ($member_post_changes as $id_member => $count_change)
  2451. updateMemberData($id_member, array('posts' => 'posts ' . ($approve ? '+' : '-') . ' ' . $count_change));
  2452. return true;
  2453. }
  2454. /**
  2455. * Approve topics?
  2456. * @todo shouldn't this be in topic
  2457. *
  2458. * @param array $topics, array of topics ids
  2459. * @param bool $approve = true
  2460. */
  2461. function approveTopics($topics, $approve = true)
  2462. {
  2463. global $smcFunc;
  2464. if (!is_array($topics))
  2465. $topics = array($topics);
  2466. if (empty($topics))
  2467. return false;
  2468. $approve_type = $approve ? 0 : 1;
  2469. // Just get the messages to be approved and pass through...
  2470. $request = $smcFunc['db_query']('', '
  2471. SELECT id_msg
  2472. FROM {db_prefix}messages
  2473. WHERE id_topic IN ({array_int:topic_list})
  2474. AND approved = {int:approve_type}',
  2475. array(
  2476. 'topic_list' => $topics,
  2477. 'approve_type' => $approve_type,
  2478. )
  2479. );
  2480. $msgs = array();
  2481. while ($row = $smcFunc['db_fetch_assoc']($request))
  2482. $msgs[] = $row['id_msg'];
  2483. $smcFunc['db_free_result']($request);
  2484. return approvePosts($msgs, $approve);
  2485. }
  2486. /**
  2487. * A special function for handling the hell which is sending approval notifications.
  2488. *
  2489. * @param $topicData
  2490. */
  2491. function sendApprovalNotifications(&$topicData)
  2492. {
  2493. global $txt, $scripturl, $language, $user_info;
  2494. global $modSettings, $sourcedir, $context, $smcFunc;
  2495. // Clean up the data...
  2496. if (!is_array($topicData) || empty($topicData))
  2497. return;
  2498. $topics = array();
  2499. $digest_insert = array();
  2500. foreach ($topicData as $topic => $msgs)
  2501. foreach ($msgs as $msgKey => $msg)
  2502. {
  2503. censorText($topicData[$topic][$msgKey]['subject']);
  2504. censorText($topicData[$topic][$msgKey]['body']);
  2505. $topicData[$topic][$msgKey]['subject'] = un_htmlspecialchars($topicData[$topic][$msgKey]['subject']);
  2506. $topicData[$topic][$msgKey]['body'] = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc($topicData[$topic][$msgKey]['body'], false), array('<br />' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
  2507. $topics[] = $msg['id'];
  2508. $digest_insert[] = array($msg['topic'], $msg['id'], 'reply', $user_info['id']);
  2509. }
  2510. // These need to go into the digest too...
  2511. $smcFunc['db_insert']('',
  2512. '{db_prefix}log_digest',
  2513. array(
  2514. 'id_topic' => 'int', 'id_msg' => 'int', 'note_type' => 'string', 'exclude' => 'int',
  2515. ),
  2516. $digest_insert,
  2517. array()
  2518. );
  2519. // Find everyone who needs to know about this.
  2520. $members = $smcFunc['db_query']('', '
  2521. SELECT
  2522. mem.id_member, mem.email_address, mem.notify_regularity, mem.notify_types, mem.notify_send_body, mem.lngfile,
  2523. ln.sent, mem.id_group, mem.additional_groups, b.member_groups, mem.id_post_group, t.id_member_started,
  2524. ln.id_topic
  2525. FROM {db_prefix}log_notify AS ln
  2526. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ln.id_member)
  2527. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)
  2528. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  2529. WHERE ln.id_topic IN ({array_int:topic_list})
  2530. AND mem.is_activated = {int:is_activated}
  2531. AND mem.notify_types < {int:notify_types}
  2532. AND mem.notify_regularity < {int:notify_regularity}
  2533. GROUP BY mem.id_member, ln.id_topic, mem.email_address, mem.notify_regularity, mem.notify_types, mem.notify_send_body, mem.lngfile, ln.sent, mem.id_group, mem.additional_groups, b.member_groups, mem.id_post_group, t.id_member_started
  2534. ORDER BY mem.lngfile',
  2535. array(
  2536. 'topic_list' => $topics,
  2537. 'is_activated' => 1,
  2538. 'notify_types' => 4,
  2539. 'notify_regularity' => 2,
  2540. )
  2541. );
  2542. $sent = 0;
  2543. while ($row = $smcFunc['db_fetch_assoc']($members))
  2544. {
  2545. if ($row['id_group'] != 1)
  2546. {
  2547. $allowed = explode(',', $row['member_groups']);
  2548. $row['additional_groups'] = explode(',', $row['additional_groups']);
  2549. $row['additional_groups'][] = $row['id_group'];
  2550. $row['additional_groups'][] = $row['id_post_group'];
  2551. if (count(array_intersect($allowed, $row['additional_groups'])) == 0)
  2552. continue;
  2553. }
  2554. $needed_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
  2555. if (empty($current_language) || $current_language != $needed_language)
  2556. $current_language = loadLanguage('Post', $needed_language, false);
  2557. $sent_this_time = false;
  2558. // Now loop through all the messages to send.
  2559. foreach ($topicData[$row['id_topic']] as $msg)
  2560. {
  2561. $replacements = array(
  2562. 'TOPICSUBJECT' => $topicData[$row['id_topic']]['subject'],
  2563. 'POSTERNAME' => un_htmlspecialchars($topicData[$row['id_topic']]['name']),
  2564. 'TOPICLINK' => $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new',
  2565. 'UNSUBSCRIBELINK' => $scripturl . '?action=notify;topic=' . $row['id_topic'] . '.0',
  2566. );
  2567. $message_type = 'notification_reply';
  2568. // Do they want the body of the message sent too?
  2569. if (!empty($row['notify_send_body']) && empty($modSettings['disallow_sendBody']))
  2570. {
  2571. $message_type .= '_body';
  2572. $replacements['BODY'] = $topicData[$row['id_topic']]['body'];
  2573. }
  2574. if (!empty($row['notify_regularity']))
  2575. $message_type .= '_once';
  2576. // Send only if once is off or it's on and it hasn't been sent.
  2577. if (empty($row['notify_regularity']) || (empty($row['sent']) && !$sent_this_time))
  2578. {
  2579. $emaildata = loadEmailTemplate($message_type, $replacements, $needed_language);
  2580. sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, 'm' . $topicData[$row['id_topic']]['last_id']);
  2581. $sent++;
  2582. }
  2583. $sent_this_time = true;
  2584. }
  2585. }
  2586. $smcFunc['db_free_result']($members);
  2587. if (isset($current_language) && $current_language != $user_info['language'])
  2588. loadLanguage('Post');
  2589. // Sent!
  2590. if (!empty($sent))
  2591. $smcFunc['db_query']('', '
  2592. UPDATE {db_prefix}log_notify
  2593. SET sent = {int:is_sent}
  2594. WHERE id_topic IN ({array_int:topic_list})
  2595. AND id_member != {int:current_member}',
  2596. array(
  2597. 'current_member' => $user_info['id'],
  2598. 'topic_list' => $topics,
  2599. 'is_sent' => 1,
  2600. )
  2601. );
  2602. }
  2603. /**
  2604. * Takes an array of board IDs and updates their last messages.
  2605. * If the board has a parent, that parent board is also automatically
  2606. * updated.
  2607. * The columns updated are id_last_msg and last_updated.
  2608. * Note that id_last_msg should always be updated using this function,
  2609. * and is not automatically updated upon other changes.
  2610. *
  2611. * @param array $setboards
  2612. * @param int $id_msg = 0
  2613. */
  2614. function updateLastMessages($setboards, $id_msg = 0)
  2615. {
  2616. global $board_info, $board, $modSettings, $smcFunc;
  2617. // Please - let's be sane.
  2618. if (empty($setboards))
  2619. return false;
  2620. if (!is_array($setboards))
  2621. $setboards = array($setboards);
  2622. // If we don't know the id_msg we need to find it.
  2623. if (!$id_msg)
  2624. {
  2625. // Find the latest message on this board (highest id_msg.)
  2626. $request = $smcFunc['db_query']('', '
  2627. SELECT id_board, MAX(id_last_msg) AS id_msg
  2628. FROM {db_prefix}topics
  2629. WHERE id_board IN ({array_int:board_list})
  2630. AND approved = {int:approved}
  2631. GROUP BY id_board',
  2632. array(
  2633. 'board_list' => $setboards,
  2634. 'approved' => 1,
  2635. )
  2636. );
  2637. $lastMsg = array();
  2638. while ($row = $smcFunc['db_fetch_assoc']($request))
  2639. $lastMsg[$row['id_board']] = $row['id_msg'];
  2640. $smcFunc['db_free_result']($request);
  2641. }
  2642. else
  2643. {
  2644. // Just to note - there should only be one board passed if we are doing this.
  2645. foreach ($setboards as $id_board)
  2646. $lastMsg[$id_board] = $id_msg;
  2647. }
  2648. $parent_boards = array();
  2649. // Keep track of last modified dates.
  2650. $lastModified = $lastMsg;
  2651. // Get all the child boards for the parents, if they have some...
  2652. foreach ($setboards as $id_board)
  2653. {
  2654. if (!isset($lastMsg[$id_board]))
  2655. {
  2656. $lastMsg[$id_board] = 0;
  2657. $lastModified[$id_board] = 0;
  2658. }
  2659. if (!empty($board) && $id_board == $board)
  2660. $parents = $board_info['parent_boards'];
  2661. else
  2662. $parents = getBoardParents($id_board);
  2663. // Ignore any parents on the top child level.
  2664. // @todo Why?
  2665. foreach ($parents as $id => $parent)
  2666. {
  2667. if ($parent['level'] != 0)
  2668. {
  2669. // If we're already doing this one as a board, is this a higher last modified?
  2670. if (isset($lastModified[$id]) && $lastModified[$id_board] > $lastModified[$id])
  2671. $lastModified[$id] = $lastModified[$id_board];
  2672. elseif (!isset($lastModified[$id]) && (!isset($parent_boards[$id]) || $parent_boards[$id] < $lastModified[$id_board]))
  2673. $parent_boards[$id] = $lastModified[$id_board];
  2674. }
  2675. }
  2676. }
  2677. // Note to help understand what is happening here. For parents we update the timestamp of the last message for determining
  2678. // whether there are child boards which have not been read. For the boards themselves we update both this and id_last_msg.
  2679. $board_updates = array();
  2680. $parent_updates = array();
  2681. // Finally, to save on queries make the changes...
  2682. foreach ($parent_boards as $id => $msg)
  2683. {
  2684. if (!isset($parent_updates[$msg]))
  2685. $parent_updates[$msg] = array($id);
  2686. else
  2687. $parent_updates[$msg][] = $id;
  2688. }
  2689. foreach ($lastMsg as $id => $msg)
  2690. {
  2691. if (!isset($board_updates[$msg . '-' . $lastModified[$id]]))
  2692. $board_updates[$msg . '-' . $lastModified[$id]] = array(
  2693. 'id' => $msg,
  2694. 'updated' => $lastModified[$id],
  2695. 'boards' => array($id)
  2696. );
  2697. else
  2698. $board_updates[$msg . '-' . $lastModified[$id]]['boards'][] = $id;
  2699. }
  2700. // Now commit the changes!
  2701. foreach ($parent_updates as $id_msg => $boards)
  2702. {
  2703. $smcFunc['db_query']('', '
  2704. UPDATE {db_prefix}boards
  2705. SET id_msg_updated = {int:id_msg_updated}
  2706. WHERE id_board IN ({array_int:board_list})
  2707. AND id_msg_updated < {int:id_msg_updated}',
  2708. array(
  2709. 'board_list' => $boards,
  2710. 'id_msg_updated' => $id_msg,
  2711. )
  2712. );
  2713. }
  2714. foreach ($board_updates as $board_data)
  2715. {
  2716. $smcFunc['db_query']('', '
  2717. UPDATE {db_prefix}boards
  2718. SET id_last_msg = {int:id_last_msg}, id_msg_updated = {int:id_msg_updated}
  2719. WHERE id_board IN ({array_int:board_list})',
  2720. array(
  2721. 'board_list' => $board_data['boards'],
  2722. 'id_last_msg' => $board_data['id'],
  2723. 'id_msg_updated' => $board_data['updated'],
  2724. )
  2725. );
  2726. }
  2727. }
  2728. /**
  2729. * This simple function gets a list of all administrators and sends them an email
  2730. * to let them know a new member has joined.
  2731. * Called by registerMember() function in Subs-Members.php.
  2732. * Email is sent to all groups that have the moderate_forum permission.
  2733. * The language set by each member is being used (if available).
  2734. *
  2735. * @param string $type, types supported are 'approval', 'activation', and 'standard'.
  2736. * @param int $memberID
  2737. * @param string $member_name = null
  2738. * @uses the Login language file.
  2739. */
  2740. function adminNotify($type, $memberID, $member_name = null)
  2741. {
  2742. global $txt, $modSettings, $language, $scripturl, $user_info, $context, $smcFunc;
  2743. // If the setting isn't enabled then just exit.
  2744. if (empty($modSettings['notify_new_registration']))
  2745. return;
  2746. if ($member_name == null)
  2747. {
  2748. // Get the new user's name....
  2749. $request = $smcFunc['db_query']('', '
  2750. SELECT real_name
  2751. FROM {db_prefix}members
  2752. WHERE id_member = {int:id_member}
  2753. LIMIT 1',
  2754. array(
  2755. 'id_member' => $memberID,
  2756. )
  2757. );
  2758. list ($member_name) = $smcFunc['db_fetch_row']($request);
  2759. $smcFunc['db_free_result']($request);
  2760. }
  2761. $toNotify = array();
  2762. $groups = array();
  2763. // All membergroups who can approve members.
  2764. $request = $smcFunc['db_query']('', '
  2765. SELECT id_group
  2766. FROM {db_prefix}permissions
  2767. WHERE permission = {string:moderate_forum}
  2768. AND add_deny = {int:add_deny}
  2769. AND id_group != {int:id_group}',
  2770. array(
  2771. 'add_deny' => 1,
  2772. 'id_group' => 0,
  2773. 'moderate_forum' => 'moderate_forum',
  2774. )
  2775. );
  2776. while ($row = $smcFunc['db_fetch_assoc']($request))
  2777. $groups[] = $row['id_group'];
  2778. $smcFunc['db_free_result']($request);
  2779. // Add administrators too...
  2780. $groups[] = 1;
  2781. $groups = array_unique($groups);
  2782. // Get a list of all members who have ability to approve accounts - these are the people who we inform.
  2783. $request = $smcFunc['db_query']('', '
  2784. SELECT id_member, lngfile, email_address
  2785. FROM {db_prefix}members
  2786. WHERE (id_group IN ({array_int:group_list}) OR FIND_IN_SET({raw:group_array_implode}, additional_groups) != 0)
  2787. AND notify_types != {int:notify_types}
  2788. ORDER BY lngfile',
  2789. array(
  2790. 'group_list' => $groups,
  2791. 'notify_types' => 4,
  2792. 'group_array_implode' => implode(', additional_groups) != 0 OR FIND_IN_SET(', $groups),
  2793. )
  2794. );
  2795. while ($row = $smcFunc['db_fetch_assoc']($request))
  2796. {
  2797. $replacements = array(
  2798. 'USERNAME' => $member_name,
  2799. 'PROFILELINK' => $scripturl . '?action=profile;u=' . $memberID
  2800. );
  2801. $emailtype = 'admin_notify';
  2802. // If they need to be approved add more info...
  2803. if ($type == 'approval')
  2804. {
  2805. $replacements['APPROVALLINK'] = $scripturl . '?action=admin;area=viewmembers;sa=browse;type=approve';
  2806. $emailtype .= '_approval';
  2807. }
  2808. $emaildata = loadEmailTemplate($emailtype, $replacements, empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']);
  2809. // And do the actual sending...
  2810. sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
  2811. }
  2812. $smcFunc['db_free_result']($request);
  2813. if (isset($current_language) && $current_language != $user_info['language'])
  2814. loadLanguage('Login');
  2815. }
  2816. /**
  2817. * Load a template from EmailTemplates language file.
  2818. *
  2819. * @param string $template
  2820. * @param array $replacements = array()
  2821. * @param string $lang = ''
  2822. * @param bool $loadLang = true
  2823. */
  2824. function loadEmailTemplate($template, $replacements = array(), $lang = '', $loadLang = true)
  2825. {
  2826. global $txt, $mbname, $scripturl, $settings, $user_info;
  2827. // First things first, load up the email templates language file, if we need to.
  2828. if ($loadLang)
  2829. loadLanguage('EmailTemplates', $lang);
  2830. if (!isset($txt['emails'][$template]))
  2831. fatal_lang_error('email_no_template', 'template', array($template));
  2832. $ret = array(
  2833. 'subject' => $txt['emails'][$template]['subject'],
  2834. 'body' => $txt['emails'][$template]['body'],
  2835. );
  2836. // Add in the default replacements.
  2837. $replacements += array(
  2838. 'FORUMNAME' => $mbname,
  2839. 'SCRIPTURL' => $scripturl,
  2840. 'THEMEURL' => $settings['theme_url'],
  2841. 'IMAGESURL' => $settings['images_url'],
  2842. 'DEFAULT_THEMEURL' => $settings['default_theme_url'],
  2843. 'REGARDS' => $txt['regards_team'],
  2844. );
  2845. // Split the replacements up into two arrays, for use with str_replace
  2846. $find = array();
  2847. $replace = array();
  2848. foreach ($replacements as $f => $r)
  2849. {
  2850. $find[] = '{' . $f . '}';
  2851. $replace[] = $r;
  2852. }
  2853. // Do the variable replacements.
  2854. $ret['subject'] = str_replace($find, $replace, $ret['subject']);
  2855. $ret['body'] = str_replace($find, $replace, $ret['body']);
  2856. // Now deal with the {USER.variable} items.
  2857. $ret['subject'] = preg_replace_callback('~{USER.([^}]+)}~', 'user_info_callback', $ret['subject']);
  2858. $ret['body'] = preg_replace_callback('~{USER.([^}]+)}~', 'user_info_callback', $ret['body']);
  2859. // Finally return the email to the caller so they can send it out.
  2860. return $ret;
  2861. }
  2862. function user_info_callback($matches)
  2863. {
  2864. global $user_info;
  2865. if (empty($matches[1]))
  2866. return '';
  2867. $use_ref = true;
  2868. $ref = &$user_info;
  2869. foreach (explode('.', $matches[1]) as $index)
  2870. {
  2871. if ($use_ref && isset($ref[$index]))
  2872. $ref = &$ref[$index];
  2873. else
  2874. {
  2875. $use_ref = false;
  2876. break;
  2877. }
  2878. }
  2879. return $use_ref ? $ref : $matches[0];
  2880. }
  2881. ?>