Subs-Post.php 113 KB

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