Subs-Post.php 113 KB

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