Subs-Post.php 114 KB

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