Subs-Post.php 102 KB

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