Subs-Post.php 102 KB

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