PageRenderTime 77ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/php/Sources/Subs-Post.php

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