Subs-Post.php 114 KB

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