Subs-Post.php 104 KB

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