PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Sources/Subs-Post.php

https://github.com/smf-portal/SMF2.1
PHP | 2968 lines | 2071 code | 365 blank | 532 comment | 436 complexity | b53b3ea73005ea52bbcf7bb7719bebfd MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * This file contains those functions pertaining to posting, and other such
  4. * operations, including sending emails, ims, blocking spam, preparsing posts,
  5. * spell checking, and the post box.
  6. *
  7. * Simple Machines Forum (SMF)
  8. *
  9. * @package SMF
  10. * @author Simple Machines http://www.simplemachines.org
  11. * @copyright 2012 Simple Machines
  12. * @license http://www.simplemachines.org/about/smf/license.php BSD
  13. *
  14. * @version 2.1 Alpha 1
  15. */
  16. if (!defined('SMF'))
  17. die('Hacking attempt...');
  18. /**
  19. * Takes a message and parses it, returning nothing.
  20. * Cleans up links (javascript, etc.) and code/quote sections.
  21. * Won't convert \n's and a few other things if previewing is true.
  22. *
  23. * @param $message
  24. * @param $previewing
  25. */
  26. function preparsecode(&$message, $previewing = false)
  27. {
  28. global $user_info, $modSettings, $smcFunc, $context;
  29. // This line makes all languages *theoretically* work even with the wrong charset ;).
  30. $message = preg_replace('~&amp;#(\d{4,5}|[2-9]\d{2,4}|1[2-9]\d);~', '&#$1;', $message);
  31. // Clean up after nobbc ;).
  32. $message = preg_replace('~\[nobbc\](.+?)\[/nobbc\]~ie', '\'[nobbc]\' . strtr(\'$1\', array(\'[\' => \'&#91;\', \']\' => \'&#93;\', \':\' => \'&#58;\', \'@\' => \'&#64;\')) . \'[/nobbc]\'', $message);
  33. // Remove \r's... they're evil!
  34. $message = strtr($message, array("\r" => ''));
  35. // You won't believe this - but too many periods upsets apache it seems!
  36. $message = preg_replace('~\.{100,}~', '...', $message);
  37. // Trim off trailing quotes - these often happen by accident.
  38. while (substr($message, -7) == '[quote]')
  39. $message = substr($message, 0, -7);
  40. while (substr($message, 0, 8) == '[/quote]')
  41. $message = substr($message, 8);
  42. // Find all code blocks, work out whether we'd be parsing them, then ensure they are all closed.
  43. $in_tag = false;
  44. $had_tag = false;
  45. $codeopen = 0;
  46. if (preg_match_all('~(\[(/)*code(?:=[^\]]+)?\])~is', $message, $matches))
  47. foreach ($matches[0] as $index => $dummy)
  48. {
  49. // Closing?
  50. if (!empty($matches[2][$index]))
  51. {
  52. // If it's closing and we're not in a tag we need to open it...
  53. if (!$in_tag)
  54. $codeopen = true;
  55. // Either way we ain't in one any more.
  56. $in_tag = false;
  57. }
  58. // Opening tag...
  59. else
  60. {
  61. $had_tag = true;
  62. // If we're in a tag don't do nought!
  63. if (!$in_tag)
  64. $in_tag = true;
  65. }
  66. }
  67. // If we have an open tag, close it.
  68. if ($in_tag)
  69. $message .= '[/code]';
  70. // Open any ones that need to be open, only if we've never had a tag.
  71. if ($codeopen && !$had_tag)
  72. $message = '[code]' . $message;
  73. // Now that we've fixed all the code tags, let's fix the img and url tags...
  74. $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
  75. // The regular expression non breaking space has many versions.
  76. $non_breaking_space = $context['utf8'] ? '\x{A0}' : '\xA0';
  77. // Only mess with stuff outside [code] tags.
  78. for ($i = 0, $n = count($parts); $i < $n; $i++)
  79. {
  80. // It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
  81. if ($i % 4 == 0)
  82. {
  83. fixTags($parts[$i]);
  84. // Replace /me.+?\n with [me=name]dsf[/me]\n.
  85. if (strpos($user_info['name'], '[') !== false || strpos($user_info['name'], ']') !== false || strpos($user_info['name'], '\'') !== false || strpos($user_info['name'], '"') !== false)
  86. $parts[$i] = preg_replace('~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '$1[me=&quot;' . $user_info['name'] . '&quot;]$2[/me]', $parts[$i]);
  87. else
  88. $parts[$i] = preg_replace('~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '$1[me=' . $user_info['name'] . ']$2[/me]', $parts[$i]);
  89. if (!$previewing && strpos($parts[$i], '[html]') !== false)
  90. {
  91. if (allowedTo('admin_forum'))
  92. $parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ise', '\'[html]\' . strtr(un_htmlspecialchars(\'$1\'), array("\n" => \'&#13;\', \' \' => \' &#32;\', \'[\' => \'&#91;\', \']\' => \'&#93;\')) . \'[/html]\'', $parts[$i]);
  93. // We should edit them out, or else if an admin edits the message they will get shown...
  94. else
  95. {
  96. while (strpos($parts[$i], '[html]') !== false)
  97. $parts[$i] = preg_replace('~\[[/]?html\]~i', '', $parts[$i]);
  98. }
  99. }
  100. // Let's look at the time tags...
  101. $parts[$i] = preg_replace('~\[time(?:=(absolute))*\](.+?)\[/time\]~ie', '\'[time]\' . (is_numeric(\'$2\') || @strtotime(\'$2\') == 0 ? \'$2\' : strtotime(\'$2\') - (\'$1\' == \'absolute\' ? 0 : (($modSettings[\'time_offset\'] + $user_info[\'time_offset\']) * 3600))) . \'[/time]\'', $parts[$i]);
  102. // Change the color specific tags to [color=the color].
  103. $parts[$i] = preg_replace('~\[(black|blue|green|red|white)\]~', '[color=$1]', $parts[$i]); // First do the opening tags.
  104. $parts[$i] = preg_replace('~\[/(black|blue|green|red|white)\]~', '[/color]', $parts[$i]); // And now do the closing tags
  105. // Make sure all tags are lowercase.
  106. $parts[$i] = preg_replace('~\[([/]?)(list|li|table|tr|td)((\s[^\]]+)*)\]~ie', '\'[$1\' . strtolower(\'$2\') . \'$3]\'', $parts[$i]);
  107. $list_open = substr_count($parts[$i], '[list]') + substr_count($parts[$i], '[list ');
  108. $list_close = substr_count($parts[$i], '[/list]');
  109. if ($list_close - $list_open > 0)
  110. $parts[$i] = str_repeat('[list]', $list_close - $list_open) . $parts[$i];
  111. if ($list_open - $list_close > 0)
  112. $parts[$i] = $parts[$i] . str_repeat('[/list]', $list_open - $list_close);
  113. $mistake_fixes = array(
  114. // Find [table]s not followed by [tr].
  115. '~\[table\](?![\s' . $non_breaking_space . ']*\[tr\])~s' . ($context['utf8'] ? 'u' : '') => '[table][tr]',
  116. // Find [tr]s not followed by [td].
  117. '~\[tr\](?![\s' . $non_breaking_space . ']*\[td\])~s' . ($context['utf8'] ? 'u' : '') => '[tr][td]',
  118. // Find [/td]s not followed by something valid.
  119. '~\[/td\](?![\s' . $non_breaking_space . ']*(?:\[td\]|\[/tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr]',
  120. // Find [/tr]s not followed by something valid.
  121. '~\[/tr\](?![\s' . $non_breaking_space . ']*(?:\[tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/tr][/table]',
  122. // Find [/td]s incorrectly followed by [/table].
  123. '~\[/td\][\s' . $non_breaking_space . ']*\[/table\]~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr][/table]',
  124. // Find [table]s, [tr]s, and [/td]s (possibly correctly) followed by [td].
  125. '~\[(table|tr|/td)\]([\s' . $non_breaking_space . ']*)\[td\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_td_]',
  126. // Now, any [td]s left should have a [tr] before them.
  127. '~\[td\]~s' => '[tr][td]',
  128. // Look for [tr]s which are correctly placed.
  129. '~\[(table|/tr)\]([\s' . $non_breaking_space . ']*)\[tr\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_tr_]',
  130. // Any remaining [tr]s should have a [table] before them.
  131. '~\[tr\]~s' => '[table][tr]',
  132. // Look for [/td]s followed by [/tr].
  133. '~\[/td\]([\s' . $non_breaking_space . ']*)\[/tr\]~s' . ($context['utf8'] ? 'u' : '') => '[/td]$1[_/tr_]',
  134. // Any remaining [/tr]s should have a [/td].
  135. '~\[/tr\]~s' => '[/td][/tr]',
  136. // Look for properly opened [li]s which aren't closed.
  137. '~\[li\]([^\[\]]+?)\[li\]~s' => '[li]$1[_/li_][_li_]',
  138. '~\[li\]([^\[\]]+?)\[/list\]~s' => '[_li_]$1[_/li_][/list]',
  139. '~\[li\]([^\[\]]+?)$~s' => '[li]$1[/li]',
  140. // Lists - find correctly closed items/lists.
  141. '~\[/li\]([\s' . $non_breaking_space . ']*)\[/list\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[/list]',
  142. // Find list items closed and then opened.
  143. '~\[/li\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[_li_]',
  144. // Now, find any [list]s or [/li]s followed by [li].
  145. '~\[(list(?: [^\]]*?)?|/li)\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_li_]',
  146. // Allow for sub lists.
  147. '~\[/li\]([\s' . $non_breaking_space . ']*)\[list\]~' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[list]',
  148. '~\[/list\]([\s' . $non_breaking_space . ']*)\[li\]~' . ($context['utf8'] ? 'u' : '') => '[/list]$1[_li_]',
  149. // Any remaining [li]s weren't inside a [list].
  150. '~\[li\]~' => '[list][li]',
  151. // Any remaining [/li]s weren't before a [/list].
  152. '~\[/li\]~' => '[/li][/list]',
  153. // Put the correct ones back how we found them.
  154. '~\[_(li|/li|td|tr|/tr)_\]~' => '[$1]',
  155. // Images with no real url.
  156. '~\[img\]https?://.{0,7}\[/img\]~' => '',
  157. );
  158. // Fix up some use of tables without [tr]s, etc. (it has to be done more than once to catch it all.)
  159. for ($j = 0; $j < 3; $j++)
  160. $parts[$i] = preg_replace(array_keys($mistake_fixes), $mistake_fixes, $parts[$i]);
  161. // Now we're going to do full scale table checking...
  162. $table_check = $parts[$i];
  163. $table_offset = 0;
  164. $table_array = array();
  165. $table_order = array(
  166. 'table' => 'td',
  167. 'tr' => 'table',
  168. 'td' => 'tr',
  169. );
  170. while (preg_match('~\[(/)*(table|tr|td)\]~', $table_check, $matches) != false)
  171. {
  172. // Keep track of where this is.
  173. $offset = strpos($table_check, $matches[0]);
  174. $remove_tag = false;
  175. // Is it opening?
  176. if ($matches[1] != '/')
  177. {
  178. // If the previous table tag isn't correct simply remove it.
  179. if ((!empty($table_array) && $table_array[0] != $table_order[$matches[2]]) || (empty($table_array) && $matches[2] != 'table'))
  180. $remove_tag = true;
  181. // Record this was the last tag.
  182. else
  183. array_unshift($table_array, $matches[2]);
  184. }
  185. // Otherwise is closed!
  186. else
  187. {
  188. // Only keep the tag if it's closing the right thing.
  189. if (empty($table_array) || ($table_array[0] != $matches[2]))
  190. $remove_tag = true;
  191. else
  192. array_shift($table_array);
  193. }
  194. // Removing?
  195. if ($remove_tag)
  196. {
  197. $parts[$i] = substr($parts[$i], 0, $table_offset + $offset) . substr($parts[$i], $table_offset + strlen($matches[0]) + $offset);
  198. // We've lost some data.
  199. $table_offset -= strlen($matches[0]);
  200. }
  201. // Remove everything up to here.
  202. $table_offset += $offset + strlen($matches[0]);
  203. $table_check = substr($table_check, $offset + strlen($matches[0]));
  204. }
  205. // Close any remaining table tags.
  206. foreach ($table_array as $tag)
  207. $parts[$i] .= '[/' . $tag . ']';
  208. // Remove empty bbc from the sections outside the code tags
  209. $parts[$i] = preg_replace('~\[[bisu]\]\s*\[/[bisu]\]~', '', $parts[$i]);
  210. $parts[$i] = preg_replace('~\[quote\]\s*\[/quote\]~', '', $parts[$i]);
  211. $parts[$i] = preg_replace('~\[color=(?:#[\da-fA-F]{3}|#[\da-fA-F]{6}|[A-Za-z]{1,20}|rgb\(\d{1,3}, ?\d{1,3}, ?\d{1,3}\))\]\s*\[/color\]~', '', $parts[$i]);
  212. }
  213. }
  214. // Put it back together!
  215. if (!$previewing)
  216. $message = strtr(implode('', $parts), array(' ' => '&nbsp; ', "\n" => '<br />', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
  217. else
  218. $message = strtr(implode('', $parts), array(' ' => '&nbsp; ', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
  219. // Now let's quickly clean up things that will slow our parser (which are common in posted code.)
  220. $message = strtr($message, array('[]' => '&#91;]', '[&#039;' => '&#91;&#039;'));
  221. }
  222. /**
  223. * This is very simple, and just removes things done by preparsecode.
  224. *
  225. * @param $message
  226. */
  227. function un_preparsecode($message)
  228. {
  229. global $smcFunc;
  230. $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
  231. // We're going to unparse only the stuff outside [code]...
  232. for ($i = 0, $n = count($parts); $i < $n; $i++)
  233. {
  234. // If $i is a multiple of four (0, 4, 8, ...) then it's not a code section...
  235. if ($i % 4 == 0)
  236. {
  237. $parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ie', '\'[html]\' . strtr(htmlspecialchars(\'$1\', ENT_QUOTES), array(\'\\&quot;\' => \'&quot;\', \'&amp;#13;\' => \'<br />\', \'&amp;#32;\' => \' \', \'&amp;#91;\' => \'[\', \'&amp;#93;\' => \']\')) . \'[/html]\'', $parts[$i]);
  238. // $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]);
  239. // Attempt to un-parse the time to something less awful.
  240. $parts[$i] = preg_replace('~\[time\](\d{0,10})\[/time\]~ie', '\'[time]\' . timeformat(\'$1\', false) . \'[/time]\'', $parts[$i]);
  241. }
  242. }
  243. // Change breaks back to \n's and &nsbp; back to spaces.
  244. return preg_replace('~<br( /)?' . '>~', "\n", str_replace('&nbsp;', ' ', implode('', $parts)));
  245. }
  246. /**
  247. * Fix any URLs posted - ie. remove 'javascript:'.
  248. * Used by preparsecode, fixes links in message and returns nothing.
  249. *
  250. * @param string $message
  251. */
  252. function fixTags(&$message)
  253. {
  254. global $modSettings;
  255. // WARNING: Editing the below can cause large security holes in your forum.
  256. // Edit only if you are sure you know what you are doing.
  257. $fixArray = array(
  258. // [img]http://...[/img] or [img width=1]http://...[/img]
  259. array(
  260. 'tag' => 'img',
  261. 'protocols' => array('http', 'https'),
  262. 'embeddedUrl' => false,
  263. 'hasEqualSign' => false,
  264. 'hasExtra' => true,
  265. ),
  266. // [url]http://...[/url]
  267. array(
  268. 'tag' => 'url',
  269. 'protocols' => array('http', 'https'),
  270. 'embeddedUrl' => true,
  271. 'hasEqualSign' => false,
  272. ),
  273. // [url=http://...]name[/url]
  274. array(
  275. 'tag' => 'url',
  276. 'protocols' => array('http', 'https'),
  277. 'embeddedUrl' => true,
  278. 'hasEqualSign' => true,
  279. ),
  280. // [iurl]http://...[/iurl]
  281. array(
  282. 'tag' => 'iurl',
  283. 'protocols' => array('http', 'https'),
  284. 'embeddedUrl' => true,
  285. 'hasEqualSign' => false,
  286. ),
  287. // [iurl=http://...]name[/iurl]
  288. array(
  289. 'tag' => 'iurl',
  290. 'protocols' => array('http', 'https'),
  291. 'embeddedUrl' => true,
  292. 'hasEqualSign' => true,
  293. ),
  294. // [ftp]ftp://...[/ftp]
  295. array(
  296. 'tag' => 'ftp',
  297. 'protocols' => array('ftp', 'ftps'),
  298. 'embeddedUrl' => true,
  299. 'hasEqualSign' => false,
  300. ),
  301. // [ftp=ftp://...]name[/ftp]
  302. array(
  303. 'tag' => 'ftp',
  304. 'protocols' => array('ftp', 'ftps'),
  305. 'embeddedUrl' => true,
  306. 'hasEqualSign' => true,
  307. ),
  308. // [flash]http://...[/flash]
  309. array(
  310. 'tag' => 'flash',
  311. 'protocols' => array('http', 'https'),
  312. 'embeddedUrl' => false,
  313. 'hasEqualSign' => false,
  314. 'hasExtra' => true,
  315. ),
  316. );
  317. // Fix each type of tag.
  318. foreach ($fixArray as $param)
  319. fixTag($message, $param['tag'], $param['protocols'], $param['embeddedUrl'], $param['hasEqualSign'], !empty($param['hasExtra']));
  320. // Now fix possible security problems with images loading links automatically...
  321. $message = preg_replace('~(\[img.*?\])(.+?)\[/img\]~eis', '\'$1\' . preg_replace(\'~action(=|%3d)(?!dlattach)~i\', \'action-\', \'$2\') . \'[/img]\'', $message);
  322. // Limit the size of images posted?
  323. if (!empty($modSettings['max_image_width']) || !empty($modSettings['max_image_height']))
  324. {
  325. // Find all the img tags - with or without width and height.
  326. preg_match_all('~\[img(\s+width=\d+)?(\s+height=\d+)?(\s+width=\d+)?\](.+?)\[/img\]~is', $message, $matches, PREG_PATTERN_ORDER);
  327. $replaces = array();
  328. foreach ($matches[0] as $match => $dummy)
  329. {
  330. // If the width was after the height, handle it.
  331. $matches[1][$match] = !empty($matches[3][$match]) ? $matches[3][$match] : $matches[1][$match];
  332. // Now figure out if they had a desired height or width...
  333. $desired_width = !empty($matches[1][$match]) ? (int) substr(trim($matches[1][$match]), 6) : 0;
  334. $desired_height = !empty($matches[2][$match]) ? (int) substr(trim($matches[2][$match]), 7) : 0;
  335. // One was omitted, or both. We'll have to find its real size...
  336. if (empty($desired_width) || empty($desired_height))
  337. {
  338. list ($width, $height) = url_image_size(un_htmlspecialchars($matches[4][$match]));
  339. // They don't have any desired width or height!
  340. if (empty($desired_width) && empty($desired_height))
  341. {
  342. $desired_width = $width;
  343. $desired_height = $height;
  344. }
  345. // Scale it to the width...
  346. elseif (empty($desired_width) && !empty($height))
  347. $desired_width = (int) (($desired_height * $width) / $height);
  348. // Scale if to the height.
  349. elseif (!empty($width))
  350. $desired_height = (int) (($desired_width * $height) / $width);
  351. }
  352. // If the width and height are fine, just continue along...
  353. if ($desired_width <= $modSettings['max_image_width'] && $desired_height <= $modSettings['max_image_height'])
  354. continue;
  355. // Too bad, it's too wide. Make it as wide as the maximum.
  356. if ($desired_width > $modSettings['max_image_width'] && !empty($modSettings['max_image_width']))
  357. {
  358. $desired_height = (int) (($modSettings['max_image_width'] * $desired_height) / $desired_width);
  359. $desired_width = $modSettings['max_image_width'];
  360. }
  361. // Now check the height, as well. Might have to scale twice, even...
  362. if ($desired_height > $modSettings['max_image_height'] && !empty($modSettings['max_image_height']))
  363. {
  364. $desired_width = (int) (($modSettings['max_image_height'] * $desired_width) / $desired_height);
  365. $desired_height = $modSettings['max_image_height'];
  366. }
  367. $replaces[$matches[0][$match]] = '[img' . (!empty($desired_width) ? ' width=' . $desired_width : '') . (!empty($desired_height) ? ' height=' . $desired_height : '') . ']' . $matches[4][$match] . '[/img]';
  368. }
  369. // If any img tags were actually changed...
  370. if (!empty($replaces))
  371. $message = strtr($message, $replaces);
  372. }
  373. }
  374. /**
  375. * Fix a specific class of tag - ie. url with =.
  376. * Used by fixTags, fixes a specific tag's links.
  377. *
  378. * @param string $message
  379. * @param string $myTag - the tag
  380. * @param string $protocols - http or ftp
  381. * @param bool $embeddedUrl = false - whether it *can* be set to something
  382. * @param bool $hasEqualSign = false, whether it *is* set to something
  383. * @param bool $hasExtra = false - whether it can have extra cruft after the begin tag.
  384. */
  385. function fixTag(&$message, $myTag, $protocols, $embeddedUrl = false, $hasEqualSign = false, $hasExtra = false)
  386. {
  387. global $boardurl, $scripturl;
  388. if (preg_match('~^([^:]+://[^/]+)~', $boardurl, $match) != 0)
  389. $domain_url = $match[1];
  390. else
  391. $domain_url = $boardurl . '/';
  392. $replaces = array();
  393. if ($hasEqualSign)
  394. preg_match_all('~\[(' . $myTag . ')=([^\]]*?)\](?:(.+?)\[/(' . $myTag . ')\])?~is', $message, $matches);
  395. else
  396. preg_match_all('~\[(' . $myTag . ($hasExtra ? '(?:[^\]]*?)' : '') . ')\](.+?)\[/(' . $myTag . ')\]~is', $message, $matches);
  397. foreach ($matches[0] as $k => $dummy)
  398. {
  399. // Remove all leading and trailing whitespace.
  400. $replace = trim($matches[2][$k]);
  401. $this_tag = $matches[1][$k];
  402. $this_close = $hasEqualSign ? (empty($matches[4][$k]) ? '' : $matches[4][$k]) : $matches[3][$k];
  403. $found = false;
  404. foreach ($protocols as $protocol)
  405. {
  406. $found = strncasecmp($replace, $protocol . '://', strlen($protocol) + 3) === 0;
  407. if ($found)
  408. break;
  409. }
  410. if (!$found && $protocols[0] == 'http')
  411. {
  412. if (substr($replace, 0, 1) == '/')
  413. $replace = $domain_url . $replace;
  414. elseif (substr($replace, 0, 1) == '?')
  415. $replace = $scripturl . $replace;
  416. elseif (substr($replace, 0, 1) == '#' && $embeddedUrl)
  417. {
  418. $replace = '#' . preg_replace('~[^A-Za-z0-9_\-#]~', '', substr($replace, 1));
  419. $this_tag = 'iurl';
  420. $this_close = 'iurl';
  421. }
  422. else
  423. $replace = $protocols[0] . '://' . $replace;
  424. }
  425. elseif (!$found && $protocols[0] == 'ftp')
  426. $replace = $protocols[0] . '://' . preg_replace('~^(?!ftps?)[^:]+://~', '', $replace);
  427. elseif (!$found)
  428. $replace = $protocols[0] . '://' . $replace;
  429. if ($hasEqualSign && $embeddedUrl)
  430. $replaces[$matches[0][$k]] = '[' . $this_tag . '=' . $replace . ']' . (empty($matches[4][$k]) ? '' : $matches[3][$k] . '[/' . $this_close . ']');
  431. elseif ($hasEqualSign)
  432. $replaces['[' . $matches[1][$k] . '=' . $matches[2][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']';
  433. elseif ($embeddedUrl)
  434. $replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']' . $matches[2][$k] . '[/' . $this_close . ']';
  435. else
  436. $replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . ']' . $replace . '[/' . $this_close . ']';
  437. }
  438. foreach ($replaces as $k => $v)
  439. {
  440. if ($k == $v)
  441. unset($replaces[$k]);
  442. }
  443. if (!empty($replaces))
  444. $message = strtr($message, $replaces);
  445. }
  446. /**
  447. * This function sends an email to the specified recipient(s).
  448. * It uses the mail_type settings and webmaster_email variable.
  449. *
  450. * @param array $to - the email(s) to send to
  451. * @param string $subject - email subject, expected to have entities, and slashes, but not be parsed
  452. * @param string $message - email body, expected to have slashes, no htmlentities
  453. * @param string $from = null - the address to use for replies
  454. * @param string $message_id = null - if specified, it will be used as local part of the Message-ID header.
  455. * @param bool $send_html = false, whether or not the message is HTML vs. plain text
  456. * @param int $priority = 3
  457. * @param bool $hotmail_fix = null
  458. * @param $is_private
  459. * @return boolean, whether ot not the email was sent properly.
  460. */
  461. function sendmail($to, $subject, $message, $from = null, $message_id = null, $send_html = false, $priority = 3, $hotmail_fix = null, $is_private = false)
  462. {
  463. global $webmaster_email, $context, $modSettings, $txt, $scripturl;
  464. global $smcFunc;
  465. // Use sendmail if it's set or if no SMTP server is set.
  466. $use_sendmail = empty($modSettings['mail_type']) || $modSettings['smtp_host'] == '';
  467. // Line breaks need to be \r\n only in windows or for SMTP.
  468. $line_break = $context['server']['is_windows'] || !$use_sendmail ? "\r\n" : "\n";
  469. // So far so good.
  470. $mail_result = true;
  471. // If the recipient list isn't an array, make it one.
  472. $to_array = is_array($to) ? $to : array($to);
  473. // Once upon a time, Hotmail could not interpret non-ASCII mails.
  474. // In honour of those days, it's still called the 'hotmail fix'.
  475. if ($hotmail_fix === null)
  476. {
  477. $hotmail_to = array();
  478. foreach ($to_array as $i => $to_address)
  479. {
  480. if (preg_match('~@(att|comcast|bellsouth)\.[a-zA-Z\.]{2,6}$~i', $to_address) === 1)
  481. {
  482. $hotmail_to[] = $to_address;
  483. $to_array = array_diff($to_array, array($to_address));
  484. }
  485. }
  486. // Call this function recursively for the hotmail addresses.
  487. if (!empty($hotmail_to))
  488. $mail_result = sendmail($hotmail_to, $subject, $message, $from, $message_id, $send_html, $priority, true, $is_private);
  489. // The remaining addresses no longer need the fix.
  490. $hotmail_fix = false;
  491. // No other addresses left? Return instantly.
  492. if (empty($to_array))
  493. return $mail_result;
  494. }
  495. // Get rid of entities.
  496. $subject = un_htmlspecialchars($subject);
  497. // Make the message use the proper line breaks.
  498. $message = str_replace(array("\r", "\n"), array('', $line_break), $message);
  499. // Make sure hotmail mails are sent as HTML so that HTML entities work.
  500. if ($hotmail_fix && !$send_html)
  501. {
  502. $send_html = true;
  503. $message = strtr($message, array($line_break => '<br />' . $line_break));
  504. $message = preg_replace('~(' . preg_quote($scripturl, '~') . '(?:[?/][\w\-_%\.,\?&;=#]+)?)~', '<a href="$1">$1</a>', $message);
  505. }
  506. list (, $from_name) = mimespecialchars(addcslashes($from !== null ? $from : $context['forum_name'], '<>()\'\\"'), true, $hotmail_fix, $line_break);
  507. list (, $subject) = mimespecialchars($subject, true, $hotmail_fix, $line_break);
  508. // Construct the mail headers...
  509. $headers = 'From: "' . $from_name . '" <' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . '>' . $line_break;
  510. $headers .= $from !== null ? 'Reply-To: <' . $from . '>' . $line_break : '';
  511. $headers .= 'Return-Path: ' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . $line_break;
  512. $headers .= 'Date: ' . gmdate('D, d M Y H:i:s') . ' -0000' . $line_break;
  513. if ($message_id !== null && empty($modSettings['mail_no_message_id']))
  514. $headers .= 'Message-ID: <' . md5($scripturl . microtime()) . '-' . $message_id . strstr(empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from'], '@') . '>' . $line_break;
  515. $headers .= 'X-Mailer: SMF' . $line_break;
  516. // Pass this to the integration before we start modifying the output -- it'll make it easier later.
  517. if (in_array(false, call_integration_hook('integrate_outgoing_email', array(&$subject, &$message, &$headers)), true))
  518. return false;
  519. // Save the original message...
  520. $orig_message = $message;
  521. // The mime boundary separates the different alternative versions.
  522. $mime_boundary = 'SMF-' . md5($message . time());
  523. // Using mime, as it allows to send a plain unencoded alternative.
  524. $headers .= 'Mime-Version: 1.0' . $line_break;
  525. $headers .= 'Content-Type: multipart/alternative; boundary="' . $mime_boundary . '"' . $line_break;
  526. $headers .= 'Content-Transfer-Encoding: 7bit' . $line_break;
  527. // Sending HTML? Let's plop in some basic stuff, then.
  528. if ($send_html)
  529. {
  530. $no_html_message = un_htmlspecialchars(strip_tags(strtr($orig_message, array('</title>' => $line_break))));
  531. // But, then, dump it and use a plain one for dinosaur clients.
  532. list(, $plain_message) = mimespecialchars($no_html_message, false, true, $line_break);
  533. $message = $plain_message . $line_break . '--' . $mime_boundary . $line_break;
  534. // This is the plain text version. Even if no one sees it, we need it for spam checkers.
  535. list($charset, $plain_charset_message, $encoding) = mimespecialchars($no_html_message, false, false, $line_break);
  536. $message .= 'Content-Type: text/plain; charset=' . $charset . $line_break;
  537. $message .= 'Content-Transfer-Encoding: ' . $encoding . $line_break . $line_break;
  538. $message .= $plain_charset_message . $line_break . '--' . $mime_boundary . $line_break;
  539. // This is the actual HTML message, prim and proper. If we wanted images, they could be inlined here (with multipart/related, etc.)
  540. list($charset, $html_message, $encoding) = mimespecialchars($orig_message, false, $hotmail_fix, $line_break);
  541. $message .= 'Content-Type: text/html; charset=' . $charset . $line_break;
  542. $message .= 'Content-Transfer-Encoding: ' . ($encoding == '' ? '7bit' : $encoding) . $line_break . $line_break;
  543. $message .= $html_message . $line_break . '--' . $mime_boundary . '--';
  544. }
  545. // Text is good too.
  546. else
  547. {
  548. // Send a plain message first, for the older web clients.
  549. list(, $plain_message) = mimespecialchars($orig_message, false, true, $line_break);
  550. $message = $plain_message . $line_break . '--' . $mime_boundary . $line_break;
  551. // Now add an encoded message using the forum's character set.
  552. list ($charset, $encoded_message, $encoding) = mimespecialchars($orig_message, false, false, $line_break);
  553. $message .= 'Content-Type: text/plain; charset=' . $charset . $line_break;
  554. $message .= 'Content-Transfer-Encoding: ' . $encoding . $line_break . $line_break;
  555. $message .= $encoded_message . $line_break . '--' . $mime_boundary . '--';
  556. }
  557. // Are we using the mail queue, if so this is where we butt in...
  558. if (!empty($modSettings['mail_queue']) && $priority != 0)
  559. return AddMailQueue(false, $to_array, $subject, $message, $headers, $send_html, $priority, $is_private);
  560. // If it's a priority mail, send it now - note though that this should NOT be used for sending many at once.
  561. elseif (!empty($modSettings['mail_queue']) && !empty($modSettings['mail_limit']))
  562. {
  563. list ($last_mail_time, $mails_this_minute) = @explode('|', $modSettings['mail_recent']);
  564. if (empty($mails_this_minute) || time() > $last_mail_time + 60)
  565. $new_queue_stat = time() . '|' . 1;
  566. else
  567. $new_queue_stat = $last_mail_time . '|' . ((int) $mails_this_minute + 1);
  568. updateSettings(array('mail_recent' => $new_queue_stat));
  569. }
  570. // SMTP or sendmail?
  571. if ($use_sendmail)
  572. {
  573. $subject = strtr($subject, array("\r" => '', "\n" => ''));
  574. if (!empty($modSettings['mail_strip_carriage']))
  575. {
  576. $message = strtr($message, array("\r" => ''));
  577. $headers = strtr($headers, array("\r" => ''));
  578. }
  579. foreach ($to_array as $to)
  580. {
  581. if (!mail(strtr($to, array("\r" => '', "\n" => '')), $subject, $message, $headers))
  582. {
  583. log_error(sprintf($txt['mail_send_unable'], $to));
  584. $mail_result = false;
  585. }
  586. // Wait, wait, I'm still sending here!
  587. @set_time_limit(300);
  588. if (function_exists('apache_reset_timeout'))
  589. @apache_reset_timeout();
  590. }
  591. }
  592. else
  593. $mail_result = $mail_result && smtp_mail($to_array, $subject, $message, $headers);
  594. // Everything go smoothly?
  595. return $mail_result;
  596. }
  597. /**
  598. * Add an email to the mail queue.
  599. *
  600. * @param bool $flush = false
  601. * @param array $to_array = array()
  602. * @param string $subject = ''
  603. * @param string $message = ''
  604. * @param string $headers = ''
  605. * @param bool $send_html = false
  606. * @param int $priority = 3
  607. * @param $is_private
  608. * @return boolean
  609. */
  610. function AddMailQueue($flush = false, $to_array = array(), $subject = '', $message = '', $headers = '', $send_html = false, $priority = 3, $is_private = false)
  611. {
  612. global $context, $modSettings, $smcFunc;
  613. static $cur_insert = array();
  614. static $cur_insert_len = 0;
  615. if ($cur_insert_len == 0)
  616. $cur_insert = array();
  617. // If we're flushing, make the final inserts - also if we're near the MySQL length limit!
  618. if (($flush || $cur_insert_len > 800000) && !empty($cur_insert))
  619. {
  620. // Only do these once.
  621. $cur_insert_len = 0;
  622. // Dump the data...
  623. $smcFunc['db_insert']('',
  624. '{db_prefix}mail_queue',
  625. array(
  626. 'time_sent' => 'int', 'recipient' => 'string-255', 'body' => 'string', 'subject' => 'string-255',
  627. 'headers' => 'string-65534', 'send_html' => 'int', 'priority' => 'int', 'private' => 'int',
  628. ),
  629. $cur_insert,
  630. array('id_mail')
  631. );
  632. $cur_insert = array();
  633. $context['flush_mail'] = false;
  634. }
  635. // If we're flushing we're done.
  636. if ($flush)
  637. {
  638. $nextSendTime = time() + 10;
  639. $smcFunc['db_query']('', '
  640. UPDATE {db_prefix}settings
  641. SET value = {string:nextSendTime}
  642. WHERE variable = {string:mail_next_send}
  643. AND value = {string:no_outstanding}',
  644. array(
  645. 'nextSendTime' => $nextSendTime,
  646. 'mail_next_send' => 'mail_next_send',
  647. 'no_outstanding' => '0',
  648. )
  649. );
  650. return true;
  651. }
  652. // Ensure we tell obExit to flush.
  653. $context['flush_mail'] = true;
  654. foreach ($to_array as $to)
  655. {
  656. // Will this insert go over MySQL's limit?
  657. $this_insert_len = strlen($to) + strlen($message) + strlen($headers) + 700;
  658. // Insert limit of 1M (just under the safety) is reached?
  659. if ($this_insert_len + $cur_insert_len > 1000000)
  660. {
  661. // Flush out what we have so far.
  662. $smcFunc['db_insert']('',
  663. '{db_prefix}mail_queue',
  664. array(
  665. 'time_sent' => 'int', 'recipient' => 'string-255', 'body' => 'string', 'subject' => 'string-255',
  666. 'headers' => 'string-65534', 'send_html' => 'int', 'priority' => 'int', 'private' => 'int',
  667. ),
  668. $cur_insert,
  669. array('id_mail')
  670. );
  671. // Clear this out.
  672. $cur_insert = array();
  673. $cur_insert_len = 0;
  674. }
  675. // Now add the current insert to the array...
  676. $cur_insert[] = array(time(), (string) $to, (string) $message, (string) $subject, (string) $headers, ($send_html ? 1 : 0), $priority, (int) $is_private);
  677. $cur_insert_len += $this_insert_len;
  678. }
  679. // If they are using SSI there is a good chance obExit will never be called. So lets be nice and flush it for them.
  680. if (SMF === 'SSI')
  681. return AddMailQueue(true);
  682. return true;
  683. }
  684. /**
  685. * Sends an personal message from the specified person to the specified people
  686. * ($from defaults to the user)
  687. *
  688. * @param array $recipients - an array containing the arrays 'to' and 'bcc', both containing id_member's.
  689. * @param string $subject - should have no slashes and no html entities
  690. * @param string $message - should have no slashes and no html entities
  691. * @param bool $store_outbox
  692. * @param array $from - an array with the id, name, and username of the member.
  693. * @param int $pm_head - the ID of the chain being replied to - if any.
  694. * @return array, an array with log entries telling how many recipients were successful and which recipients it failed to send to.
  695. */
  696. function sendpm($recipients, $subject, $message, $store_outbox = false, $from = null, $pm_head = 0)
  697. {
  698. global $scripturl, $txt, $user_info, $language;
  699. global $modSettings, $smcFunc;
  700. // Make sure the PM language file is loaded, we might need something out of it.
  701. loadLanguage('PersonalMessage');
  702. $onBehalf = $from !== null;
  703. // Initialize log array.
  704. $log = array(
  705. 'failed' => array(),
  706. 'sent' => array()
  707. );
  708. if ($from === null)
  709. $from = array(
  710. 'id' => $user_info['id'],
  711. 'name' => $user_info['name'],
  712. 'username' => $user_info['username']
  713. );
  714. // Probably not needed. /me something should be of the typer.
  715. else
  716. $user_info['name'] = $from['name'];
  717. // This is the one that will go in their inbox.
  718. $htmlmessage = $smcFunc['htmlspecialchars']($message, ENT_QUOTES);
  719. preparsecode($htmlmessage);
  720. $htmlsubject = strtr($smcFunc['htmlspecialchars']($subject), array("\r" => '', "\n" => '', "\t" => ''));
  721. if ($smcFunc['strlen']($htmlsubject) > 100)
  722. $htmlsubject = $smcFunc['substr']($htmlsubject, 0, 100);
  723. // Make sure is an array
  724. if (!is_array($recipients))
  725. $recipients = array($recipients);
  726. // Integrated PMs
  727. call_integration_hook('integrate_personal_message', array(&$recipients, &$from, &$subject, &$message));
  728. // Get a list of usernames and convert them to IDs.
  729. $usernames = array();
  730. foreach ($recipients as $rec_type => $rec)
  731. {
  732. foreach ($rec as $id => $member)
  733. {
  734. if (!is_numeric($recipients[$rec_type][$id]))
  735. {
  736. $recipients[$rec_type][$id] = $smcFunc['strtolower'](trim(preg_replace('/[<>&"\'=\\\]/', '', $recipients[$rec_type][$id])));
  737. $usernames[$recipients[$rec_type][$id]] = 0;
  738. }
  739. }
  740. }
  741. if (!empty($usernames))
  742. {
  743. $request = $smcFunc['db_query']('pm_find_username', '
  744. SELECT id_member, member_name
  745. FROM {db_prefix}members
  746. WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name') . ' IN ({array_string:usernames})',
  747. array(
  748. 'usernames' => array_keys($usernames),
  749. )
  750. );
  751. while ($row = $smcFunc['db_fetch_assoc']($request))
  752. if (isset($usernames[$smcFunc['strtolower']($row['member_name'])]))
  753. $usernames[$smcFunc['strtolower']($row['member_name'])] = $row['id_member'];
  754. $smcFunc['db_free_result']($request);
  755. // Replace the usernames with IDs. Drop usernames that couldn't be found.
  756. foreach ($recipients as $rec_type => $rec)
  757. foreach ($rec as $id => $member)
  758. {
  759. if (is_numeric($recipients[$rec_type][$id]))
  760. continue;
  761. if (!empty($usernames[$member]))
  762. $recipients[$rec_type][$id] = $usernames[$member];
  763. else
  764. {
  765. $log['failed'][$id] = sprintf($txt['pm_error_user_not_found'], $recipients[$rec_type][$id]);
  766. unset($recipients[$rec_type][$id]);
  767. }
  768. }
  769. }
  770. // Make sure there are no duplicate 'to' members.
  771. $recipients['to'] = array_unique($recipients['to']);
  772. // Only 'bcc' members that aren't already in 'to'.
  773. $recipients['bcc'] = array_diff(array_unique($recipients['bcc']), $recipients['to']);
  774. // Combine 'to' and 'bcc' recipients.
  775. $all_to = array_merge($recipients['to'], $recipients['bcc']);
  776. // Check no-one will want it deleted right away!
  777. $request = $smcFunc['db_query']('', '
  778. SELECT
  779. id_member, criteria, is_or
  780. FROM {db_prefix}pm_rules
  781. WHERE id_member IN ({array_int:to_members})
  782. AND delete_pm = {int:delete_pm}',
  783. array(
  784. 'to_members' => $all_to,
  785. 'delete_pm' => 1,
  786. )
  787. );
  788. $deletes = array();
  789. // Check whether we have to apply anything...
  790. while ($row = $smcFunc['db_fetch_assoc']($request))
  791. {
  792. $criteria = unserialize($row['criteria']);
  793. // Note we don't check the buddy status, cause deletion from buddy = madness!
  794. $delete = false;
  795. foreach ($criteria as $criterium)
  796. {
  797. $match = false;
  798. 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))
  799. $delete = true;
  800. // If we're adding and one criteria don't match then we stop!
  801. elseif (!$row['is_or'])
  802. {
  803. $delete = false;
  804. break;
  805. }
  806. }
  807. if ($delete)
  808. $deletes[$row['id_member']] = 1;
  809. }
  810. $smcFunc['db_free_result']($request);
  811. // Load the membergrounp message limits.
  812. // @todo Consider caching this?
  813. static $message_limit_cache = array();
  814. if (!allowedTo('moderate_forum') && empty($message_limit_cache))
  815. {
  816. $request = $smcFunc['db_query']('', '
  817. SELECT id_group, max_messages
  818. FROM {db_prefix}membergroups',
  819. array(
  820. )
  821. );
  822. while ($row = $smcFunc['db_fetch_assoc']($request))
  823. $message_limit_cache[$row['id_group']] = $row['max_messages'];
  824. $smcFunc['db_free_result']($request);
  825. }
  826. // Load the groups that are allowed to read PMs.
  827. // @todo move into a separate function on $permission.
  828. $allowed_groups = array();
  829. $disallowed_groups = array();
  830. $request = $smcFunc['db_query']('', '
  831. SELECT id_group, add_deny
  832. FROM {db_prefix}permissions
  833. WHERE permission = {string:read_permission}',
  834. array(
  835. 'read_permission' => 'pm_read',
  836. )
  837. );
  838. while ($row = $smcFunc['db_fetch_assoc']($request))
  839. {
  840. if (empty($row['add_deny']))
  841. $disallowed_groups[] = $row['id_group'];
  842. else
  843. $allowed_groups[] = $row['id_group'];
  844. }
  845. $smcFunc['db_free_result']($request);
  846. if (empty($modSettings['permission_enable_deny']))
  847. $disallowed_groups = array();
  848. $request = $smcFunc['db_query']('', '
  849. SELECT
  850. member_name, real_name, id_member, email_address, lngfile,
  851. pm_email_notify, instant_messages,' . (allowedTo('moderate_forum') ? ' 0' : '
  852. (pm_receive_from = {int:admins_only}' . (empty($modSettings['enable_buddylist']) ? '' : ' OR
  853. (pm_receive_from = {int:buddies_only} AND FIND_IN_SET({string:from_id}, buddy_list) = 0) OR
  854. (pm_receive_from = {int:not_on_ignore_list} AND FIND_IN_SET({string:from_id}, pm_ignore_list) != 0)') . ')') . ' AS ignored,
  855. FIND_IN_SET({string:from_id}, buddy_list) != 0 AS is_buddy, is_activated,
  856. additional_groups, id_group, id_post_group
  857. FROM {db_prefix}members
  858. WHERE id_member IN ({array_int:recipients})
  859. ORDER BY lngfile
  860. LIMIT {int:count_recipients}',
  861. array(
  862. 'not_on_ignore_list' => 1,
  863. 'buddies_only' => 2,
  864. 'admins_only' => 3,
  865. 'recipients' => $all_to,
  866. 'count_recipients' => count($all_to),
  867. 'from_id' => $from['id'],
  868. )
  869. );
  870. $notifications = array();
  871. while ($row = $smcFunc['db_fetch_assoc']($request))
  872. {
  873. // Don't do anything for members to be deleted!
  874. if (isset($deletes[$row['id_member']]))
  875. continue;
  876. // We need to know this members groups.
  877. $groups = explode(',', $row['additional_groups']);
  878. $groups[] = $row['id_group'];
  879. $groups[] = $row['id_post_group'];
  880. $message_limit = -1;
  881. // For each group see whether they've gone over their limit - assuming they're not an admin.
  882. if (!in_array(1, $groups))
  883. {
  884. foreach ($groups as $id)
  885. {
  886. if (isset($message_limit_cache[$id]) && $message_limit != 0 && $message_limit < $message_limit_cache[$id])
  887. $message_limit = $message_limit_cache[$id];
  888. }
  889. if ($message_limit > 0 && $message_limit <= $row['instant_messages'])
  890. {
  891. $log['failed'][$row['id_member']] = sprintf($txt['pm_error_data_limit_reached'], $row['real_name']);
  892. unset($all_to[array_search($row['id_member'], $all_to)]);
  893. continue;
  894. }
  895. // Do they have any of the allowed groups?
  896. if (count(array_intersect($allowed_groups, $groups)) == 0 || count(array_intersect($disallowed_groups, $groups)) != 0)
  897. {
  898. $log['failed'][$row['id_member']] = sprintf($txt['pm_error_user_cannot_read'], $row['real_name']);
  899. unset($all_to[array_search($row['id_member'], $all_to)]);
  900. continue;
  901. }
  902. }
  903. // Note that PostgreSQL can return a lowercase t/f for FIND_IN_SET
  904. if (!empty($row['ignored']) && $row['ignored'] != 'f' && $row['id_member'] != $from['id'])
  905. {
  906. $log['failed'][$row['id_member']] = sprintf($txt['pm_error_ignored_by_user'], $row['real_name']);
  907. unset($all_to[array_search($row['id_member'], $all_to)]);
  908. continue;
  909. }
  910. // If the receiving account is banned (>=10) or pending deletion (4), refuse to send the PM.
  911. if ($row['is_activated'] >= 10 || ($row['is_activated'] == 4 && !$user_info['is_admin']))
  912. {
  913. $log['failed'][$row['id_member']] = sprintf($txt['pm_error_user_cannot_read'], $row['real_name']);
  914. unset($all_to[array_search($row['id_member'], $all_to)]);
  915. continue;
  916. }
  917. // Send a notification, if enabled - taking the buddy list into account.
  918. 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)
  919. $notifications[empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']][] = $row['email_address'];
  920. $log['sent'][$row['id_member']] = sprintf(isset($txt['pm_successfully_sent']) ? $txt['pm_successfully_sent'] : '', $row['real_name']);
  921. }
  922. $smcFunc['db_free_result']($request);
  923. // Only 'send' the message if there are any recipients left.
  924. if (empty($all_to))
  925. return $log;
  926. // Insert the message itself and then grab the last insert id.
  927. $smcFunc['db_insert']('',
  928. '{db_prefix}personal_messages',
  929. array(
  930. 'id_pm_head' => 'int', 'id_member_from' => 'int', 'deleted_by_sender' => 'int',
  931. 'from_name' => 'string-255', 'msgtime' => 'int', 'subject' => 'string-255', 'body' => 'string-65534',
  932. ),
  933. array(
  934. $pm_head, $from['id'], ($store_outbox ? 0 : 1),
  935. $from['username'], time(), $htmlsubject, $htmlmessage,
  936. ),
  937. array('id_pm')
  938. );
  939. $id_pm = $smcFunc['db_insert_id']('{db_prefix}personal_messages', 'id_pm');
  940. // Add the recipients.
  941. if (!empty($id_pm))
  942. {
  943. // If this is new we need to set it part of it's own conversation.
  944. if (empty($pm_head))
  945. $smcFunc['db_query']('', '
  946. UPDATE {db_prefix}personal_messages
  947. SET id_pm_head = {int:id_pm_head}
  948. WHERE id_pm = {int:id_pm_head}',
  949. array(
  950. 'id_pm_head' => $id_pm,
  951. )
  952. );
  953. // Some people think manually deleting personal_messages is fun... it's not. We protect against it though :)
  954. $smcFunc['db_query']('', '
  955. DELETE FROM {db_prefix}pm_recipients
  956. WHERE id_pm = {int:id_pm}',
  957. array(
  958. 'id_pm' => $id_pm,
  959. )
  960. );
  961. $insertRows = array();
  962. $to_list = array();
  963. foreach ($all_to as $to)
  964. {
  965. $insertRows[] = array($id_pm, $to, in_array($to, $recipients['bcc']) ? 1 : 0, isset($deletes[$to]) ? 1 : 0, 1);
  966. if (!in_array($to, $recipients['bcc']))
  967. $to_list[] = $to;
  968. }
  969. $smcFunc['db_insert']('insert',
  970. '{db_prefix}pm_recipients',
  971. array(
  972. 'id_pm' => 'int', 'id_member' => 'int', 'bcc' => 'int', 'deleted' => 'int', 'is_new' => 'int'
  973. ),
  974. $insertRows,
  975. array('id_pm', 'id_member')
  976. );
  977. }
  978. censorText($subject);
  979. if (empty($modSettings['disallow_sendBody']))
  980. {
  981. censorText($message);
  982. $message = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc(htmlspecialchars($message), false), array('<br />' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
  983. }
  984. else
  985. $message = '';
  986. $to_names = array();
  987. if (count($to_list) > 1)
  988. {
  989. $request = $smcFunc['db_query']('', '
  990. SELECT real_name
  991. FROM {db_prefix}members
  992. WHERE id_member IN ({array_int:to_members})',
  993. array(
  994. 'to_members' => $to_list,
  995. )
  996. );
  997. while ($row = $smcFunc['db_fetch_assoc']($request))
  998. $to_names[] = un_htmlspecialchars($row['real_name']);
  999. $smcFunc['db_free_result']($request);
  1000. }
  1001. $replacements = array(
  1002. 'SUBJECT' => $subject,
  1003. 'MESSAGE' => $message,
  1004. 'SENDER' => un_htmlspecialchars($from['name']),
  1005. 'READLINK' => $scripturl . '?action=pm;pmsg=' . $id_pm . '#msg' . $id_pm,
  1006. 'REPLYLINK' => $scripturl . '?action=pm;sa=send;f=inbox;pmsg=' . $id_pm . ';quote;u=' . $from['id'],
  1007. 'TOLIST' => implode(', ', $to_names),
  1008. );
  1009. $email_template = 'new_pm' . (empty($modSettings['disallow_sendBody']) ? '_body' : '') . (!empty($to_names) ? '_tolist' : '');
  1010. foreach ($notifications as $lang => $notification_list)
  1011. {
  1012. $mail = loadEmailTemplate($email_template, $replacements, $lang);
  1013. // Off the notification email goes!
  1014. sendmail($notification_list, $mail['subject'], $mail['body'], null, 'p' . $id_pm, false, 2, null, true);
  1015. }
  1016. // Integrated After PMs
  1017. call_integration_hook('integrate_personal_message_after', array(&$id_pm, &$log, &$recipients, &$from, &$subject, &$message));
  1018. // Back to what we were on before!
  1019. loadLanguage('index+PersonalMessage');
  1020. // Add one to their unread and read message counts.
  1021. foreach ($all_to as $k => $id)
  1022. if (isset($deletes[$id]))
  1023. unset($all_to[$k]);
  1024. if (!empty($all_to))
  1025. updateMemberData($all_to, array('instant_messages' => '+', 'unread_messages' => '+', 'new_pm' => 1));
  1026. return $log;
  1027. }
  1028. /**
  1029. * Prepare text strings for sending as email body or header.
  1030. * In case there are higher ASCII characters in the given string, this
  1031. * function will attempt the transport method 'quoted-printable'.
  1032. * Otherwise the transport method '7bit' is used.
  1033. *
  1034. * @param string $string
  1035. * @param bool $with_charset = true
  1036. * @param bool $hotmail_fix = false, with hotmail_fix set all higher ASCII
  1037. * characters are converted to HTML entities to assure proper display of the mail
  1038. * @param $line_break
  1039. * @param string $custom_charset = null, if set, it uses this character set
  1040. * @return array an array containing the character set, the converted string and the transport method.
  1041. */
  1042. function mimespecialchars($string, $with_charset = true, $hotmail_fix = false, $line_break = "\r\n", $custom_charset = null)
  1043. {
  1044. global $context;
  1045. $charset = $custom_charset !== null ? $custom_charset : $context['character_set'];
  1046. // This is the fun part....
  1047. if (preg_match_all('~&#(\d{3,8});~', $string, $matches) !== 0 && !$hotmail_fix)
  1048. {
  1049. // Let's, for now, assume there are only &#021;'ish characters.
  1050. $simple = true;
  1051. foreach ($matches[1] as $entity)
  1052. if ($entity > 128)
  1053. $simple = false;
  1054. unset($matches);
  1055. if ($simple)
  1056. $string = preg_replace('~&#(\d{3,8});~e', 'chr(\'$1\')', $string);
  1057. else
  1058. {
  1059. // Try to convert the string to UTF-8.
  1060. if (!$context['utf8'] && function_exists('iconv'))
  1061. {
  1062. $newstring = @iconv($context['character_set'], 'UTF-8', $string);
  1063. if ($newstring)
  1064. $string = $newstring;
  1065. }
  1066. $string = preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $string);
  1067. // Unicode, baby.
  1068. $charset = 'UTF-8';
  1069. }
  1070. }
  1071. // Convert all special characters to HTML entities...just for Hotmail :-\
  1072. if ($hotmail_fix && ($context['utf8'] || function_exists('iconv') || $context['character_set'] === 'ISO-8859-1'))
  1073. {
  1074. if (!$context['utf8'] && function_exists('iconv'))
  1075. {
  1076. $newstring = @iconv($context['character_set'], 'UTF-8', $string);
  1077. if ($newstring)
  1078. $string = $newstring;
  1079. }
  1080. $entityConvert = create_function('$c', '
  1081. if (strlen($c) === 1 && ord($c[0]) <= 0x7F)
  1082. return $c;
  1083. elseif (strlen($c) === 2 && ord($c[0]) >= 0xC0 && ord($c[0]) <= 0xDF)
  1084. return "&#" . (((ord($c[0]) ^ 0xC0) << 6) + (ord($c[1]) ^ 0x80)) . ";";
  1085. elseif (strlen($c) === 3 && ord($c[0]) >= 0xE0 && ord($c[0]) <= 0xEF)
  1086. return "&#" . (((ord($c[0]) ^ 0xE0) << 12) + ((ord($c[1]) ^ 0x80) << 6) + (ord($c[2]) ^ 0x80)) . ";";
  1087. elseif (strlen($c) === 4 && ord($c[0]) >= 0xF0 && ord($c[0]) <= 0xF7)
  1088. return "&#" . (((ord($c[0]) ^ 0xF0) << 18) + ((ord($c[1]) ^ 0x80) << 12) + ((ord($c[2]) ^ 0x80) << 6) + (ord($c[3]) ^ 0x80)) . ";";
  1089. else
  1090. return "";');
  1091. // Convert all 'special' characters to HTML entities.
  1092. return array($charset, preg_replace('~([\x80-\x{10FFFF}])~eu', '$entityConvert(\'\1\')', $string), '7bit');
  1093. }
  1094. // We don't need to mess with the subject line if no special characters were in it..
  1095. elseif (!$hotmail_fix && preg_match('~([^\x09\x0A\x0D\x20-\x7F])~', $string) === 1)
  1096. {
  1097. // Base64 encode.
  1098. $string = base64_encode($string);
  1099. // Show the characterset and the transfer-encoding for header strings.
  1100. if ($with_charset)
  1101. $string = '=?' . $charset . '?B?' . $string . '?=';
  1102. // Break it up in lines (mail body).
  1103. else
  1104. $string = chunk_split($string, 76, $line_break);
  1105. return array($charset, $string, 'base64');
  1106. }
  1107. else
  1108. return array($charset, $string, '7bit');
  1109. }
  1110. /**
  1111. * Sends mail, like mail() but over SMTP.
  1112. * It expects no slashes or entities.
  1113. * @internal
  1114. *
  1115. * @param array $mail_to_array - array of strings (email addresses)
  1116. * @param string $subject email subject
  1117. * @param string $message email message
  1118. * @param string $headers
  1119. * @return boolean whether it sent or not.
  1120. */
  1121. function smtp_mail($mail_to_array, $subject, $message, $headers)
  1122. {
  1123. global $modSettings, $webmaster_email, $txt;
  1124. $modSettings['smtp_host'] = trim($modSettings['smtp_host']);
  1125. // Try POP3 before SMTP?
  1126. // @todo There's no interface for this yet.
  1127. if ($modSettings['mail_type'] == 2 && $modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
  1128. {
  1129. $socket = fsockopen($modSettings['smtp_host'], 110, $errno, $errstr, 2);
  1130. if (!$socket && (substr($modSettings['smtp_host'], 0, 5) == 'smtp.' || substr($modSettings['smtp_host'], 0, 11) == 'ssl://smtp.'))
  1131. $socket = fsockopen(strtr($modSettings['smtp_host'], array('smtp.' => 'pop.')), 110, $errno, $errstr, 2);
  1132. if ($socket)
  1133. {
  1134. fgets($socket, 256);
  1135. fputs($socket, 'USER ' . $modSettings['smtp_username'] . "\r\n");
  1136. fgets($socket, 256);
  1137. fputs($socket, 'PASS ' . base64_decode($modSettings['smtp_password']) . "\r\n");
  1138. fgets($socket, 256);
  1139. fputs($socket, 'QUIT' . "\r\n");
  1140. fclose($socket);
  1141. }
  1142. }
  1143. // Try to connect to the SMTP server... if it doesn't exist, only wait three seconds.
  1144. if (!$socket = fsockopen($modSettings['smtp_host'], empty($modSettings['smtp_port']) ? 25 : $modSettings['smtp_port'], $errno, $errstr, 3))
  1145. {
  1146. // Maybe we can still save this? The port might be wrong.
  1147. if (substr($modSettings['smtp_host'], 0, 4) == 'ssl:' && (empty($modSettings['smtp_port']) || $modSettings['smtp_port'] == 25))
  1148. {
  1149. if ($socket = fsockopen($modSettings['smtp_host'], 465, $errno, $errstr, 3))
  1150. log_error($txt['smtp_port_ssl']);
  1151. }
  1152. // Unable to connect! Don't show any error messa…

Large files files are truncated, but you can click here to view the full file