Passed
Push — release-2.1 ( 7401ba...5d05c6 )
by Mathias
08:16 queued 14s
created

clearApprovalAlerts()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 49
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 24
c 0
b 0
f 0
nc 7
nop 2
dl 0
loc 49
rs 8.6026
1
<?php
2
3
/**
4
 * This file contains those functions pertaining to posting, and other such
5
 * operations, including sending emails, ims, blocking spam, preparsing posts,
6
 * spell checking, and the post box.
7
 *
8
 * Simple Machines Forum (SMF)
9
 *
10
 * @package SMF
11
 * @author Simple Machines https://www.simplemachines.org
12
 * @copyright 2022 Simple Machines and individual contributors
13
 * @license https://www.simplemachines.org/about/smf/license.php BSD
14
 *
15
 * @version 2.1.3
16
 */
17
18
if (!defined('SMF'))
19
	die('No direct access...');
20
21
/**
22
 * Takes a message and parses it, returning nothing.
23
 * Cleans up links (javascript, etc.) and code/quote sections.
24
 * Won't convert \n's and a few other things if previewing is true.
25
 *
26
 * @param string $message The message
27
 * @param bool $previewing Whether we're previewing
28
 */
29
function preparsecode(&$message, $previewing = false)
30
{
31
	global $user_info, $modSettings, $context, $sourcedir, $smcFunc;
32
33
	static $tags_regex, $disallowed_tags_regex;
34
35
	// Convert control characters (except \t, \r, and \n) to harmless Unicode symbols
36
	$control_replacements = array(
37
		"\x00" => '&#x2400;', "\x01" => '&#x2401;', "\x02" => '&#x2402;', "\x03" => '&#x2403;',
38
		"\x04" => '&#x2404;', "\x05" => '&#x2405;', "\x06" => '&#x2406;', "\x07" => '&#x2407;',
39
		"\x08" => '&#x2408;', "\x0b" => '&#x240b;', "\x0c" => '&#x240c;', "\x0e" => '&#x240e;',
40
		"\x0f" => '&#x240f;', "\x10" => '&#x2410;', "\x11" => '&#x2411;', "\x12" => '&#x2412;',
41
		"\x13" => '&#x2413;', "\x14" => '&#x2414;', "\x15" => '&#x2415;', "\x16" => '&#x2416;',
42
		"\x17" => '&#x2417;', "\x18" => '&#x2418;', "\x19" => '&#x2419;', "\x1a" => '&#x241a;',
43
		"\x1b" => '&#x241b;', "\x1c" => '&#x241c;', "\x1d" => '&#x241d;', "\x1e" => '&#x241e;',
44
		"\x1f" => '&#x241f;',
45
	);
46
	$message = strtr($message, $control_replacements);
47
48
	// This line makes all languages *theoretically* work even with the wrong charset ;).
49
	if (empty($context['utf8']))
50
		$message = preg_replace('~&amp;#(\d{4,5}|[2-9]\d{2,4}|1[2-9]\d);~', '&#$1;', $message);
51
52
	// Normalize Unicode characters for storage efficiency, better searching, etc.
53
	else
54
		$message = $smcFunc['normalize']($message);
55
56
	// Clean out any other funky stuff.
57
	$message = sanitize_chars($message, 0);
58
59
	// Clean up after nobbc ;).
60
	$message = preg_replace_callback(
61
		'~\[nobbc\](.+?)\[/nobbc\]~is',
62
		function($a)
63
		{
64
			return '[nobbc]' . strtr($a[1], array('[' => '&#91;', ']' => '&#93;', ':' => '&#58;', '@' => '&#64;')) . '[/nobbc]';
65
		},
66
		$message
67
	);
68
69
	// Remove \r's... they're evil!
70
	$message = strtr($message, array("\r" => ''));
71
72
	// You won't believe this - but too many periods upsets apache it seems!
73
	$message = preg_replace('~\.{100,}~', '...', $message);
74
75
	// Trim off trailing quotes - these often happen by accident.
76
	while (substr($message, -7) == '[quote]')
77
		$message = substr($message, 0, -7);
78
	while (substr($message, 0, 8) == '[/quote]')
79
		$message = substr($message, 8);
80
81
	if (strpos($message, '[cowsay') !== false && !allowedTo('bbc_cowsay'))
82
		$message = preg_replace('~\[(/?)cowsay[^\]]*\]~iu', '[$1pre]', $message);
83
84
	// Find all code blocks, work out whether we'd be parsing them, then ensure they are all closed.
85
	$in_tag = false;
86
	$had_tag = false;
87
	$codeopen = 0;
88
	if (preg_match_all('~(\[(/)*code(?:=[^\]]+)?\])~is', $message, $matches))
89
		foreach ($matches[0] as $index => $dummy)
90
		{
91
			// Closing?
92
			if (!empty($matches[2][$index]))
93
			{
94
				// If it's closing and we're not in a tag we need to open it...
95
				if (!$in_tag)
96
					$codeopen = true;
97
				// Either way we ain't in one any more.
98
				$in_tag = false;
99
			}
100
			// Opening tag...
101
			else
102
			{
103
				$had_tag = true;
104
				// If we're in a tag don't do nought!
105
				if (!$in_tag)
106
					$in_tag = true;
107
			}
108
		}
109
110
	// If we have an open tag, close it.
111
	if ($in_tag)
112
		$message .= '[/code]';
113
	// Open any ones that need to be open, only if we've never had a tag.
114
	if ($codeopen && !$had_tag)
115
		$message = '[code]' . $message;
116
117
	// Replace code BBC with placeholders. We'll restore them at the end.
118
	$parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
119
	for ($i = 0, $n = count($parts); $i < $n; $i++)
120
	{
121
		// It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
122
		if ($i % 4 == 2)
123
		{
124
			$code_tag = $parts[$i - 1] . $parts[$i] . $parts[$i + 1];
125
			$substitute = $parts[$i - 1] . $i . $parts[$i + 1];
126
			$code_tags[$substitute] = $code_tag;
127
			$parts[$i] = $i;
128
		}
129
	}
130
131
	$message = implode('', $parts);
132
133
	// The regular expression non breaking space has many versions.
134
	$non_breaking_space = $context['utf8'] ? '\x{A0}' : '\xA0';
135
136
	// Now that we've fixed all the code tags, let's fix the img and url tags...
137
	fixTags($message);
138
139
	// Replace /me.+?\n with [me=name]dsf[/me]\n.
140
	if (strpos($user_info['name'], '[') !== false || strpos($user_info['name'], ']') !== false || strpos($user_info['name'], '\'') !== false || strpos($user_info['name'], '"') !== false)
141
		$message = preg_replace('~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '$1[me=&quot;' . $user_info['name'] . '&quot;]$2[/me]', $message);
142
	else
143
		$message = preg_replace('~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '$1[me=' . $user_info['name'] . ']$2[/me]', $message);
144
145
	if (!$previewing && strpos($message, '[html]') !== false)
146
	{
147
		if (allowedTo('bbc_html'))
148
			$message = preg_replace_callback(
149
				'~\[html\](.+?)\[/html\]~is',
150
				function($m)
151
				{
152
					return '[html]' . strtr(un_htmlspecialchars($m[1]), array("\n" => '&#13;', '  ' => ' &#32;', '[' => '&#91;', ']' => '&#93;')) . '[/html]';
153
				},
154
				$message
155
			);
156
157
		// We should edit them out, or else if an admin edits the message they will get shown...
158
		else
159
		{
160
			while (strpos($message, '[html]') !== false)
161
				$message = preg_replace('~\[[/]?html\]~i', '', $message);
162
		}
163
	}
164
165
	// Let's look at the time tags...
166
	$message = preg_replace_callback(
167
		'~\[time(?:=(absolute))*\](.+?)\[/time\]~i',
168
		function($m) use ($modSettings, $user_info)
169
		{
170
			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]";
171
		},
172
		$message
173
	);
174
175
	// Change the color specific tags to [color=the color].
176
	$message = preg_replace('~\[(black|blue|green|red|white)\]~', '[color=$1]', $message); // First do the opening tags.
177
	$message = preg_replace('~\[/(black|blue|green|red|white)\]~', '[/color]', $message); // And now do the closing tags
178
179
	// Neutralize any BBC tags this member isn't permitted to use.
180
	if (empty($disallowed_tags_regex))
181
	{
182
		// Legacy BBC are only retained for historical reasons. They're not for use in new posts.
183
		$disallowed_bbc = $context['legacy_bbc'];
184
185
		// Some BBC require permissions.
186
		foreach ($context['restricted_bbc'] as $bbc)
187
		{
188
			// Skip html, since we handled it separately above.
189
			if ($bbc === 'html')
190
				continue;
191
			if (!allowedTo('bbc_' . $bbc))
192
				$disallowed_bbc[] = $bbc;
193
		}
194
195
		$disallowed_tags_regex = build_regex(array_unique($disallowed_bbc), '~');
196
	}
197
	if (!empty($disallowed_tags_regex))
198
		$message = preg_replace('~\[(?=/?' . $disallowed_tags_regex . '\b)~i', '&#91;', $message);
199
200
	// Make sure all tags are lowercase.
201
	$message = preg_replace_callback(
202
		'~\[(/?)(list|li|table|tr|td)\b([^\]]*)\]~i',
203
		function($m)
204
		{
205
			return "[$m[1]" . strtolower("$m[2]") . "$m[3]]";
206
		},
207
		$message
208
	);
209
210
	$list_open = substr_count($message, '[list]') + substr_count($message, '[list ');
211
	$list_close = substr_count($message, '[/list]');
212
	if ($list_close - $list_open > 0)
213
		$message = str_repeat('[list]', $list_close - $list_open) . $message;
214
	if ($list_open - $list_close > 0)
215
		$message = $message . str_repeat('[/list]', $list_open - $list_close);
216
217
	$mistake_fixes = array(
218
		// Find [table]s not followed by [tr].
219
		'~\[table\](?![\s' . $non_breaking_space . ']*\[tr\])~s' . ($context['utf8'] ? 'u' : '') => '[table][tr]',
220
		// Find [tr]s not followed by [td].
221
		'~\[tr\](?![\s' . $non_breaking_space . ']*\[td\])~s' . ($context['utf8'] ? 'u' : '') => '[tr][td]',
222
		// Find [/td]s not followed by something valid.
223
		'~\[/td\](?![\s' . $non_breaking_space . ']*(?:\[td\]|\[/tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr]',
224
		// Find [/tr]s not followed by something valid.
225
		'~\[/tr\](?![\s' . $non_breaking_space . ']*(?:\[tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/tr][/table]',
226
		// Find [/td]s incorrectly followed by [/table].
227
		'~\[/td\][\s' . $non_breaking_space . ']*\[/table\]~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr][/table]',
228
		// Find [table]s, [tr]s, and [/td]s (possibly correctly) followed by [td].
229
		'~\[(table|tr|/td)\]([\s' . $non_breaking_space . ']*)\[td\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_td_]',
230
		// Now, any [td]s left should have a [tr] before them.
231
		'~\[td\]~s' => '[tr][td]',
232
		// Look for [tr]s which are correctly placed.
233
		'~\[(table|/tr)\]([\s' . $non_breaking_space . ']*)\[tr\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_tr_]',
234
		// Any remaining [tr]s should have a [table] before them.
235
		'~\[tr\]~s' => '[table][tr]',
236
		// Look for [/td]s followed by [/tr].
237
		'~\[/td\]([\s' . $non_breaking_space . ']*)\[/tr\]~s' . ($context['utf8'] ? 'u' : '') => '[/td]$1[_/tr_]',
238
		// Any remaining [/tr]s should have a [/td].
239
		'~\[/tr\]~s' => '[/td][/tr]',
240
		// Look for properly opened [li]s which aren't closed.
241
		'~\[li\]([^\[\]]+?)\[li\]~s' => '[li]$1[_/li_][_li_]',
242
		'~\[li\]([^\[\]]+?)\[/list\]~s' => '[_li_]$1[_/li_][/list]',
243
		'~\[li\]([^\[\]]+?)$~s' => '[li]$1[/li]',
244
		// Lists - find correctly closed items/lists.
245
		'~\[/li\]([\s' . $non_breaking_space . ']*)\[/list\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[/list]',
246
		// Find list items closed and then opened.
247
		'~\[/li\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[_li_]',
248
		// Now, find any [list]s or [/li]s followed by [li].
249
		'~\[(list(?: [^\]]*?)?|/li)\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_li_]',
250
		// Allow for sub lists.
251
		'~\[/li\]([\s' . $non_breaking_space . ']*)\[list\]~' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[list]',
252
		'~\[/list\]([\s' . $non_breaking_space . ']*)\[li\]~' . ($context['utf8'] ? 'u' : '') => '[/list]$1[_li_]',
253
		// Any remaining [li]s weren't inside a [list].
254
		'~\[li\]~' => '[list][li]',
255
		// Any remaining [/li]s weren't before a [/list].
256
		'~\[/li\]~' => '[/li][/list]',
257
		// Put the correct ones back how we found them.
258
		'~\[_(li|/li|td|tr|/tr)_\]~' => '[$1]',
259
		// Images with no real url.
260
		'~\[img\]https?://.{0,7}\[/img\]~' => '',
261
	);
262
263
	// Fix up some use of tables without [tr]s, etc. (it has to be done more than once to catch it all.)
264
	for ($j = 0; $j < 3; $j++)
265
		$message = preg_replace(array_keys($mistake_fixes), $mistake_fixes, $message);
266
267
	// Remove empty bbc from the sections outside the code tags
268
	if (empty($tags_regex))
269
	{
270
		require_once($sourcedir . '/Subs.php');
271
272
		$allowed_empty = array('anchor', 'td',);
273
274
		$tags = array();
275
		foreach (($codes = parse_bbc(false)) as $code)
0 ignored issues
show
Unused Code introduced by
The assignment to $codes is dead and can be removed.
Loading history...
Bug introduced by
The expression $codes = parse_bbc(false) of type string is not traversable.
Loading history...
276
			if (!in_array($code['tag'], $allowed_empty))
277
				$tags[] = $code['tag'];
278
279
		$tags_regex = build_regex($tags, '~');
280
	}
281
	while (preg_match('~\[(' . $tags_regex . ')\b[^\]]*\]\s*\[/\1\]\s?~i', $message))
282
		$message = preg_replace('~\[(' . $tags_regex . ')[^\]]*\]\s*\[/\1\]\s?~i', '', $message);
283
284
	// Restore code blocks
285
	if (!empty($code_tags))
286
		$message = str_replace(array_keys($code_tags), array_values($code_tags), $message);
287
288
	// Restore white space entities
289
	if (!$previewing)
290
		$message = strtr($message, array('  ' => '&nbsp; ', "\n" => '<br>', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
291
	else
292
		$message = strtr($message, array('  ' => '&nbsp; ', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
293
294
	// Now let's quickly clean up things that will slow our parser (which are common in posted code.)
295
	$message = strtr($message, array('[]' => '&#91;]', '[&#039;' => '&#91;&#039;'));
296
297
	// Any hooks want to work here?
298
	call_integration_hook('integrate_preparsecode', array(&$message, $previewing));
299
}
300
301
/**
302
 * This is very simple, and just removes things done by preparsecode.
303
 *
304
 * @param string $message The message
305
 */
306
function un_preparsecode($message)
307
{
308
	global $smcFunc;
309
310
	// Any hooks want to work here?
311
	call_integration_hook('integrate_unpreparsecode', array(&$message));
312
313
	$parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
314
315
	// We're going to unparse only the stuff outside [code]...
316
	for ($i = 0, $n = count($parts); $i < $n; $i++)
317
	{
318
		// If $i is a multiple of four (0, 4, 8, ...) then it's not a code section...
319
		if ($i % 4 == 2)
320
		{
321
			$code_tag = $parts[$i - 1] . $parts[$i] . $parts[$i + 1];
322
			$substitute = $parts[$i - 1] . $i . $parts[$i + 1];
323
			$code_tags[$substitute] = $code_tag;
324
			$parts[$i] = $i;
325
		}
326
	}
327
328
	$message = implode('', $parts);
329
330
	$message = preg_replace_callback(
331
		'~\[html\](.+?)\[/html\]~i',
332
		function($m) use ($smcFunc)
333
		{
334
			return "[html]" . strtr($smcFunc['htmlspecialchars']("$m[1]", ENT_QUOTES), array("\\&quot;" => "&quot;", "&amp;#13;" => "<br>", "&amp;#32;" => " ", "&amp;#91;" => "[", "&amp;#93;" => "]")) . "[/html]";
335
		},
336
		$message
337
	);
338
339
	if (strpos($message, '[cowsay') !== false && !allowedTo('bbc_cowsay'))
340
		$message = preg_replace('~\[(/?)cowsay[^\]]*\]~iu', '[$1pre]', $message);
341
342
	// Attempt to un-parse the time to something less awful.
343
	$message = preg_replace_callback(
344
		'~\[time\](\d{0,10})\[/time\]~i',
345
		function($m)
346
		{
347
			return "[time]" . timeformat("$m[1]", false) . "[/time]";
0 ignored issues
show
Bug introduced by
$m['1'] of type string is incompatible with the type integer expected by parameter $log_time of timeformat(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

347
			return "[time]" . timeformat(/** @scrutinizer ignore-type */ "$m[1]", false) . "[/time]";
Loading history...
348
		},
349
		$message
350
	);
351
352
	if (!empty($code_tags))
353
		$message = strtr($message, $code_tags);
354
355
	// Change breaks back to \n's and &nsbp; back to spaces.
356
	return preg_replace('~<br\s*/?' . '>~', "\n", str_replace('&nbsp;', ' ', $message));
357
}
358
359
/**
360
 * Fix any URLs posted - ie. remove 'javascript:'.
361
 * Used by preparsecode, fixes links in message and returns nothing.
362
 *
363
 * @param string $message The message
364
 */
365
function fixTags(&$message)
366
{
367
	global $modSettings;
368
369
	// WARNING: Editing the below can cause large security holes in your forum.
370
	// Edit only if you are sure you know what you are doing.
371
372
	$fixArray = array(
373
		// [img]http://...[/img] or [img width=1]http://...[/img]
374
		array(
375
			'tag' => 'img',
376
			'protocols' => array('http', 'https'),
377
			'embeddedUrl' => false,
378
			'hasEqualSign' => false,
379
			'hasExtra' => true,
380
		),
381
		// [url]http://...[/url]
382
		array(
383
			'tag' => 'url',
384
			'protocols' => array('http', 'https'),
385
			'embeddedUrl' => false,
386
			'hasEqualSign' => false,
387
		),
388
		// [url=http://...]name[/url]
389
		array(
390
			'tag' => 'url',
391
			'protocols' => array('http', 'https'),
392
			'embeddedUrl' => true,
393
			'hasEqualSign' => true,
394
		),
395
		// [iurl]http://...[/iurl]
396
		array(
397
			'tag' => 'iurl',
398
			'protocols' => array('http', 'https'),
399
			'embeddedUrl' => false,
400
			'hasEqualSign' => false,
401
		),
402
		// [iurl=http://...]name[/iurl]
403
		array(
404
			'tag' => 'iurl',
405
			'protocols' => array('http', 'https'),
406
			'embeddedUrl' => true,
407
			'hasEqualSign' => true,
408
		),
409
		// The rest of these are deprecated.
410
		// [ftp]ftp://...[/ftp]
411
		array(
412
			'tag' => 'ftp',
413
			'protocols' => array('ftp', 'ftps', 'sftp'),
414
			'embeddedUrl' => false,
415
			'hasEqualSign' => false,
416
		),
417
		// [ftp=ftp://...]name[/ftp]
418
		array(
419
			'tag' => 'ftp',
420
			'protocols' => array('ftp', 'ftps', 'sftp'),
421
			'embeddedUrl' => true,
422
			'hasEqualSign' => true,
423
		),
424
		// [flash]http://...[/flash]
425
		array(
426
			'tag' => 'flash',
427
			'protocols' => array('http', 'https'),
428
			'embeddedUrl' => false,
429
			'hasEqualSign' => false,
430
			'hasExtra' => true,
431
		),
432
	);
433
434
	// Fix each type of tag.
435
	foreach ($fixArray as $param)
436
		fixTag($message, $param['tag'], $param['protocols'], $param['embeddedUrl'], $param['hasEqualSign'], !empty($param['hasExtra']));
437
438
	// Now fix possible security problems with images loading links automatically...
439
	$message = preg_replace_callback(
440
		'~(\[img.*?\])(.+?)\[/img\]~is',
441
		function($m)
442
		{
443
			return "$m[1]" . preg_replace("~action(=|%3d)(?!dlattach)~i", "action-", "$m[2]") . "[/img]";
444
		},
445
		$message
446
	);
447
448
}
449
450
/**
451
 * Fix a specific class of tag - ie. url with =.
452
 * Used by fixTags, fixes a specific tag's links.
453
 *
454
 * @param string $message The message
455
 * @param string $myTag The tag
456
 * @param string $protocols The protocols
457
 * @param bool $embeddedUrl Whether it *can* be set to something
458
 * @param bool $hasEqualSign Whether it *is* set to something
459
 * @param bool $hasExtra Whether it can have extra cruft after the begin tag.
460
 */
461
function fixTag(&$message, $myTag, $protocols, $embeddedUrl = false, $hasEqualSign = false, $hasExtra = false)
462
{
463
	global $boardurl, $scripturl;
464
465
	$forbidden_protocols = array(
466
		// Poses security risks.
467
		'javascript',
468
		// Allows file data to be embedded, bypassing our attachment system.
469
		'data',
470
	);
471
472
	if (preg_match('~^([^:]+://[^/]+)~', $boardurl, $match) != 0)
473
		$domain_url = $match[1];
474
	else
475
		$domain_url = $boardurl . '/';
476
477
	$replaces = array();
478
479
	if ($hasEqualSign && $embeddedUrl)
480
	{
481
		$quoted = preg_match('~\[(' . $myTag . ')=&quot;~', $message);
482
		preg_match_all('~\[(' . $myTag . ')=' . ($quoted ? '&quot;(.*?)&quot;' : '([^\]]*?)') . '\](?:(.+?)\[/(' . $myTag . ')\])?~is', $message, $matches);
483
	}
484
	elseif ($hasEqualSign)
485
		preg_match_all('~\[(' . $myTag . ')=([^\]]*?)\](?:(.+?)\[/(' . $myTag . ')\])?~is', $message, $matches);
486
	else
487
		preg_match_all('~\[(' . $myTag . ($hasExtra ? '(?:[^\]]*?)' : '') . ')\](.+?)\[/(' . $myTag . ')\]~is', $message, $matches);
488
489
	foreach ($matches[0] as $k => $dummy)
490
	{
491
		// Remove all leading and trailing whitespace.
492
		$replace = trim($matches[2][$k]);
493
		$this_tag = $matches[1][$k];
494
		$this_close = $hasEqualSign ? (empty($matches[4][$k]) ? '' : $matches[4][$k]) : $matches[3][$k];
495
496
		$found = false;
497
		foreach ($protocols as $protocol)
0 ignored issues
show
Bug introduced by
The expression $protocols of type string is not traversable.
Loading history...
498
		{
499
			$found = strncasecmp($replace, $protocol . '://', strlen($protocol) + 3) === 0;
500
			if ($found)
501
				break;
502
		}
503
504
		$current_protocol = strtolower(parse_iri($replace, PHP_URL_SCHEME) ?? "");
505
506
		if (in_array($current_protocol, $forbidden_protocols))
507
		{
508
			$replace = 'about:invalid';
509
		}
510
		elseif (!$found && $protocols[0] == 'http')
511
		{
512
			// A path
513
			if (substr($replace, 0, 1) == '/' && substr($replace, 0, 2) != '//')
514
				$replace = $domain_url . $replace;
515
			// A query
516
			elseif (substr($replace, 0, 1) == '?')
517
				$replace = $scripturl . $replace;
518
			// A fragment
519
			elseif (substr($replace, 0, 1) == '#' && $embeddedUrl)
520
			{
521
				$replace = '#' . preg_replace('~[^A-Za-z0-9_\-#]~', '', substr($replace, 1));
522
				$this_tag = 'iurl';
523
				$this_close = 'iurl';
524
			}
525
			elseif (substr($replace, 0, 2) != '//' && empty($current_protocol))
526
				$replace = $protocols[0] . '://' . $replace;
527
		}
528
		elseif (!$found && $protocols[0] == 'ftp')
529
			$replace = $protocols[0] . '://' . preg_replace('~^(?!ftps?)[^:]+://~', '', $replace);
530
		elseif (!$found && empty($current_protocol))
531
			$replace = $protocols[0] . '://' . $replace;
532
533
		if ($hasEqualSign && $embeddedUrl)
534
			$replaces[$matches[0][$k]] = '[' . $this_tag . '=&quot;' . $replace . '&quot;]' . (empty($matches[4][$k]) ? '' : $matches[3][$k] . '[/' . $this_close . ']');
535
		elseif ($hasEqualSign)
536
			$replaces['[' . $matches[1][$k] . '=' . $matches[2][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']';
537
		elseif ($embeddedUrl)
538
			$replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']' . $matches[2][$k] . '[/' . $this_close . ']';
539
		else
540
			$replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . ']' . $replace . '[/' . $this_close . ']';
541
	}
542
543
	foreach ($replaces as $k => $v)
544
	{
545
		if ($k == $v)
546
			unset($replaces[$k]);
547
	}
548
549
	if (!empty($replaces))
550
		$message = strtr($message, $replaces);
551
}
552
553
/**
554
 * This function sends an email to the specified recipient(s).
555
 * It uses the mail_type settings and webmaster_email variable.
556
 *
557
 * @param array $to The email(s) to send to
558
 * @param string $subject Email subject, expected to have entities, and slashes, but not be parsed
559
 * @param string $message Email body, expected to have slashes, no htmlentities
560
 * @param string $from The address to use for replies
561
 * @param string $message_id If specified, it will be used as local part of the Message-ID header.
562
 * @param bool $send_html Whether or not the message is HTML vs. plain text
563
 * @param int $priority The priority of the message
564
 * @param bool $hotmail_fix Whether to apply the "hotmail fix"
565
 * @param bool $is_private Whether this is private
566
 * @return boolean Whether ot not the email was sent properly.
567
 */
568
function sendmail($to, $subject, $message, $from = null, $message_id = null, $send_html = false, $priority = 3, $hotmail_fix = null, $is_private = false)
569
{
570
	global $webmaster_email, $context, $modSettings, $txt, $scripturl;
571
572
	// Use sendmail if it's set or if no SMTP server is set.
573
	$use_sendmail = empty($modSettings['mail_type']) || $modSettings['smtp_host'] == '';
574
575
	// Line breaks need to be \r\n only in windows or for SMTP.
576
	// Starting with php 8x, line breaks need to be \r\n even for linux.
577
	$line_break = ($context['server']['is_windows'] || !$use_sendmail || version_compare(PHP_VERSION, '8.0.0', '>=')) ? "\r\n" : "\n";
578
579
	// So far so good.
580
	$mail_result = true;
581
582
	// If the recipient list isn't an array, make it one.
583
	$to_array = is_array($to) ? $to : array($to);
0 ignored issues
show
introduced by
The condition is_array($to) is always true.
Loading history...
584
585
	// Make sure we actually have email addresses to send this to
586
	foreach ($to_array as $k => $v)
587
	{
588
		// This should never happen, but better safe than sorry
589
		if (trim($v) == '')
590
		{
591
			unset($to_array[$k]);
592
		}
593
	}
594
595
	// Nothing left? Nothing else to do
596
	if (empty($to_array))
597
		return true;
598
599
	// Once upon a time, Hotmail could not interpret non-ASCII mails.
600
	// In honour of those days, it's still called the 'hotmail fix'.
601
	if ($hotmail_fix === null)
602
	{
603
		$hotmail_to = array();
604
		foreach ($to_array as $i => $to_address)
605
		{
606
			if (preg_match('~@(att|comcast|bellsouth)\.[a-zA-Z\.]{2,6}$~i', $to_address) === 1)
607
			{
608
				$hotmail_to[] = $to_address;
609
				$to_array = array_diff($to_array, array($to_address));
610
			}
611
		}
612
613
		// Call this function recursively for the hotmail addresses.
614
		if (!empty($hotmail_to))
615
			$mail_result = sendmail($hotmail_to, $subject, $message, $from, $message_id, $send_html, $priority, true, $is_private);
616
617
		// The remaining addresses no longer need the fix.
618
		$hotmail_fix = false;
619
620
		// No other addresses left? Return instantly.
621
		if (empty($to_array))
622
			return $mail_result;
623
	}
624
625
	// Get rid of entities.
626
	$subject = un_htmlspecialchars($subject);
627
	// Make the message use the proper line breaks.
628
	$message = str_replace(array("\r", "\n"), array('', $line_break), $message);
629
630
	// Make sure hotmail mails are sent as HTML so that HTML entities work.
631
	if ($hotmail_fix && !$send_html)
632
	{
633
		$send_html = true;
634
		$message = strtr($message, array($line_break => '<br>' . $line_break));
635
		$message = preg_replace('~(' . preg_quote($scripturl, '~') . '(?:[?/][\w\-_%\.,\?&;=#]+)?)~', '<a href="$1">$1</a>', $message);
636
	}
637
638
	list (, $from_name) = mimespecialchars(addcslashes($from !== null ? $from : $context['forum_name'], '<>()\'\\"'), true, $hotmail_fix, $line_break);
639
	list (, $subject) = mimespecialchars($subject, true, $hotmail_fix, $line_break);
640
641
	// Construct the mail headers...
642
	$headers = 'From: "' . $from_name . '" <' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . '>' . $line_break;
643
	$headers .= $from !== null ? 'Reply-To: <' . $from . '>' . $line_break : '';
644
	$headers .= 'Return-Path: ' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . $line_break;
645
	$headers .= 'Date: ' . gmdate('D, d M Y H:i:s') . ' -0000' . $line_break;
646
647
	if ($message_id !== null && empty($modSettings['mail_no_message_id']))
648
		$headers .= 'Message-ID: <' . md5($scripturl . microtime()) . '-' . $message_id . strstr(empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from'], '@') . '>' . $line_break;
649
	$headers .= 'X-Mailer: SMF' . $line_break;
650
651
	// Pass this to the integration before we start modifying the output -- it'll make it easier later.
652
	if (in_array(false, call_integration_hook('integrate_outgoing_email', array(&$subject, &$message, &$headers, &$to_array)), true))
653
		return false;
654
655
	// Save the original message...
656
	$orig_message = $message;
657
658
	// The mime boundary separates the different alternative versions.
659
	$mime_boundary = 'SMF-' . md5($message . time());
660
661
	// Using mime, as it allows to send a plain unencoded alternative.
662
	$headers .= 'Mime-Version: 1.0' . $line_break;
663
	$headers .= 'content-type: multipart/alternative; boundary="' . $mime_boundary . '"' . $line_break;
664
	$headers .= 'content-transfer-encoding: 7bit' . $line_break;
665
666
	// Sending HTML?  Let's plop in some basic stuff, then.
667
	if ($send_html)
668
	{
669
		$no_html_message = un_htmlspecialchars(strip_tags(strtr($orig_message, array('</title>' => $line_break))));
670
671
		// But, then, dump it and use a plain one for dinosaur clients.
672
		list(, $plain_message) = mimespecialchars($no_html_message, false, true, $line_break);
673
		$message = $plain_message . $line_break . '--' . $mime_boundary . $line_break;
674
675
		// This is the plain text version.  Even if no one sees it, we need it for spam checkers.
676
		list($charset, $plain_charset_message, $encoding) = mimespecialchars($no_html_message, false, false, $line_break);
677
		$message .= 'content-type: text/plain; charset=' . $charset . $line_break;
678
		$message .= 'content-transfer-encoding: ' . $encoding . $line_break . $line_break;
679
		$message .= $plain_charset_message . $line_break . '--' . $mime_boundary . $line_break;
680
681
		// This is the actual HTML message, prim and proper.  If we wanted images, they could be inlined here (with multipart/related, etc.)
682
		list($charset, $html_message, $encoding) = mimespecialchars($orig_message, false, $hotmail_fix, $line_break);
683
		$message .= 'content-type: text/html; charset=' . $charset . $line_break;
684
		$message .= 'content-transfer-encoding: ' . ($encoding == '' ? '7bit' : $encoding) . $line_break . $line_break;
685
		$message .= $html_message . $line_break . '--' . $mime_boundary . '--';
686
	}
687
	// Text is good too.
688
	else
689
	{
690
		// Send a plain message first, for the older web clients.
691
		list(, $plain_message) = mimespecialchars($orig_message, false, true, $line_break);
692
		$message = $plain_message . $line_break . '--' . $mime_boundary . $line_break;
693
694
		// Now add an encoded message using the forum's character set.
695
		list ($charset, $encoded_message, $encoding) = mimespecialchars($orig_message, false, false, $line_break);
696
		$message .= 'content-type: text/plain; charset=' . $charset . $line_break;
697
		$message .= 'content-transfer-encoding: ' . $encoding . $line_break . $line_break;
698
		$message .= $encoded_message . $line_break . '--' . $mime_boundary . '--';
699
	}
700
701
	// Are we using the mail queue, if so this is where we butt in...
702
	if ($priority != 0)
703
		return AddMailQueue(false, $to_array, $subject, $message, $headers, $send_html, $priority, $is_private);
704
705
	// If it's a priority mail, send it now - note though that this should NOT be used for sending many at once.
706
	elseif (!empty($modSettings['mail_limit']))
707
	{
708
		list ($last_mail_time, $mails_this_minute) = @explode('|', $modSettings['mail_recent']);
709
		if (empty($mails_this_minute) || time() > $last_mail_time + 60)
710
			$new_queue_stat = time() . '|' . 1;
711
		else
712
			$new_queue_stat = $last_mail_time . '|' . ((int) $mails_this_minute + 1);
713
714
		updateSettings(array('mail_recent' => $new_queue_stat));
715
	}
716
717
	// SMTP or sendmail?
718
	if ($use_sendmail)
719
	{
720
		$subject = strtr($subject, array("\r" => '', "\n" => ''));
721
		if (!empty($modSettings['mail_strip_carriage']))
722
		{
723
			$message = strtr($message, array("\r" => ''));
724
			$headers = strtr($headers, array("\r" => ''));
725
		}
726
727
		foreach ($to_array as $to)
0 ignored issues
show
introduced by
$to is overwriting one of the parameters of this function.
Loading history...
728
		{
729
			set_error_handler(
730
				function($errno, $errstr, $errfile, $errline)
731
				{
732
					// error was suppressed with the @-operator
733
					if (0 === error_reporting())
734
						return false;
735
736
					throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
737
				}
738
			);
739
			try
740
			{
741
				if (!mail(strtr($to, array("\r" => '', "\n" => '')), $subject, $message, $headers))
742
				{
743
					log_error(sprintf($txt['mail_send_unable'], $to));
744
					$mail_result = false;
745
				}
746
			}
747
			catch (ErrorException $e)
748
			{
749
				log_error($e->getMessage(), 'general', $e->getFile(), $e->getLine());
750
				log_error(sprintf($txt['mail_send_unable'], $to));
751
				$mail_result = false;
752
			}
753
			restore_error_handler();
754
755
			// Wait, wait, I'm still sending here!
756
			@set_time_limit(300);
757
			if (function_exists('apache_reset_timeout'))
758
				@apache_reset_timeout();
759
		}
760
	}
761
	else
762
		$mail_result = $mail_result && smtp_mail($to_array, $subject, $message, $headers);
763
764
	// Everything go smoothly?
765
	return $mail_result;
766
}
767
768
/**
769
 * Add an email to the mail queue.
770
 *
771
 * @param bool $flush Whether to flush the queue
772
 * @param array $to_array An array of recipients
773
 * @param string $subject The subject of the message
774
 * @param string $message The message
775
 * @param string $headers The headers
776
 * @param bool $send_html Whether to send in HTML format
777
 * @param int $priority The priority
778
 * @param bool $is_private Whether this is private
779
 * @return boolean Whether the message was added
780
 */
781
function AddMailQueue($flush = false, $to_array = array(), $subject = '', $message = '', $headers = '', $send_html = false, $priority = 3, $is_private = false)
782
{
783
	global $context, $smcFunc;
784
785
	static $cur_insert = array();
786
	static $cur_insert_len = 0;
787
788
	if ($cur_insert_len == 0)
789
		$cur_insert = array();
790
791
	// If we're flushing, make the final inserts - also if we're near the MySQL length limit!
792
	if (($flush || $cur_insert_len > 800000) && !empty($cur_insert))
793
	{
794
		// Only do these once.
795
		$cur_insert_len = 0;
796
797
		// Dump the data...
798
		$smcFunc['db_insert']('',
799
			'{db_prefix}mail_queue',
800
			array(
801
				'time_sent' => 'int', 'recipient' => 'string-255', 'body' => 'string', 'subject' => 'string-255',
802
				'headers' => 'string-65534', 'send_html' => 'int', 'priority' => 'int', 'private' => 'int',
803
			),
804
			$cur_insert,
805
			array('id_mail')
806
		);
807
808
		$cur_insert = array();
809
		$context['flush_mail'] = false;
810
	}
811
812
	// If we're flushing we're done.
813
	if ($flush)
814
	{
815
		$nextSendTime = time() + 10;
816
817
		$smcFunc['db_query']('', '
818
			UPDATE {db_prefix}settings
819
			SET value = {string:nextSendTime}
820
			WHERE variable = {literal:mail_next_send}
821
				AND value = {string:no_outstanding}',
822
			array(
823
				'nextSendTime' => $nextSendTime,
824
				'no_outstanding' => '0',
825
			)
826
		);
827
828
		return true;
829
	}
830
831
	// Ensure we tell obExit to flush.
832
	$context['flush_mail'] = true;
833
834
	foreach ($to_array as $to)
835
	{
836
		// Will this insert go over MySQL's limit?
837
		$this_insert_len = strlen($to) + strlen($message) + strlen($headers) + 700;
838
839
		// Insert limit of 1M (just under the safety) is reached?
840
		if ($this_insert_len + $cur_insert_len > 1000000)
841
		{
842
			// Flush out what we have so far.
843
			$smcFunc['db_insert']('',
844
				'{db_prefix}mail_queue',
845
				array(
846
					'time_sent' => 'int', 'recipient' => 'string-255', 'body' => 'string', 'subject' => 'string-255',
847
					'headers' => 'string-65534', 'send_html' => 'int', 'priority' => 'int', 'private' => 'int',
848
				),
849
				$cur_insert,
850
				array('id_mail')
851
			);
852
853
			// Clear this out.
854
			$cur_insert = array();
855
			$cur_insert_len = 0;
856
		}
857
858
		// Now add the current insert to the array...
859
		$cur_insert[] = array(time(), (string) $to, (string) $message, (string) $subject, (string) $headers, ($send_html ? 1 : 0), $priority, (int) $is_private);
860
		$cur_insert_len += $this_insert_len;
861
	}
862
863
	// If they are using SSI there is a good chance obExit will never be called.  So lets be nice and flush it for them.
864
	if (SMF === 'SSI' || SMF === 'BACKGROUND')
0 ignored issues
show
introduced by
The condition SMF === 'SSI' is always true.
Loading history...
865
		return AddMailQueue(true);
866
867
	return true;
868
}
869
870
/**
871
 * Sends an personal message from the specified person to the specified people
872
 * ($from defaults to the user)
873
 *
874
 * @param array $recipients An array containing the arrays 'to' and 'bcc', both containing id_member's.
875
 * @param string $subject Should have no slashes and no html entities
876
 * @param string $message Should have no slashes and no html entities
877
 * @param bool $store_outbox Whether to store it in the sender's outbox
878
 * @param array $from An array with the id, name, and username of the member.
879
 * @param int $pm_head The ID of the chain being replied to - if any.
880
 * @return array An array with log entries telling how many recipients were successful and which recipients it failed to send to.
881
 */
882
function sendpm($recipients, $subject, $message, $store_outbox = false, $from = null, $pm_head = 0)
883
{
884
	global $scripturl, $txt, $user_info, $language, $sourcedir;
885
	global $modSettings, $smcFunc;
886
887
	// Make sure the PM language file is loaded, we might need something out of it.
888
	loadLanguage('PersonalMessage');
889
890
	// Initialize log array.
891
	$log = array(
892
		'failed' => array(),
893
		'sent' => array()
894
	);
895
896
	if ($from === null)
897
		$from = array(
898
			'id' => $user_info['id'],
899
			'name' => $user_info['name'],
900
			'username' => $user_info['username']
901
		);
902
903
	// This is the one that will go in their inbox.
904
	$htmlmessage = $smcFunc['htmlspecialchars']($message, ENT_QUOTES);
905
	preparsecode($htmlmessage);
906
	$htmlsubject = strtr($smcFunc['htmlspecialchars']($subject), array("\r" => '', "\n" => '', "\t" => ''));
907
	if ($smcFunc['strlen']($htmlsubject) > 100)
908
		$htmlsubject = $smcFunc['substr']($htmlsubject, 0, 100);
909
910
	// Make sure is an array
911
	if (!is_array($recipients))
0 ignored issues
show
introduced by
The condition is_array($recipients) is always true.
Loading history...
912
		$recipients = array($recipients);
913
914
	// Integrated PMs
915
	call_integration_hook('integrate_personal_message', array(&$recipients, &$from, &$subject, &$message));
916
917
	// Get a list of usernames and convert them to IDs.
918
	$usernames = array();
919
	foreach ($recipients as $rec_type => $rec)
920
	{
921
		foreach ($rec as $id => $member)
922
		{
923
			if (!is_numeric($recipients[$rec_type][$id]))
924
			{
925
				$recipients[$rec_type][$id] = $smcFunc['strtolower'](trim(preg_replace('~[<>&"\'=\\\]~', '', $recipients[$rec_type][$id])));
926
				$usernames[$recipients[$rec_type][$id]] = 0;
927
			}
928
		}
929
	}
930
	if (!empty($usernames))
931
	{
932
		$request = $smcFunc['db_query']('pm_find_username', '
933
			SELECT id_member, member_name
934
			FROM {db_prefix}members
935
			WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name') . ' IN ({array_string:usernames})',
936
			array(
937
				'usernames' => array_keys($usernames),
938
			)
939
		);
940
		while ($row = $smcFunc['db_fetch_assoc']($request))
941
			if (isset($usernames[$smcFunc['strtolower']($row['member_name'])]))
942
				$usernames[$smcFunc['strtolower']($row['member_name'])] = $row['id_member'];
943
		$smcFunc['db_free_result']($request);
944
945
		// Replace the usernames with IDs. Drop usernames that couldn't be found.
946
		foreach ($recipients as $rec_type => $rec)
947
			foreach ($rec as $id => $member)
948
			{
949
				if (is_numeric($recipients[$rec_type][$id]))
950
					continue;
951
952
				if (!empty($usernames[$member]))
953
					$recipients[$rec_type][$id] = $usernames[$member];
954
				else
955
				{
956
					$log['failed'][$id] = sprintf($txt['pm_error_user_not_found'], $recipients[$rec_type][$id]);
957
					unset($recipients[$rec_type][$id]);
958
				}
959
			}
960
	}
961
962
	// Make sure there are no duplicate 'to' members.
963
	$recipients['to'] = array_unique($recipients['to']);
964
965
	// Only 'bcc' members that aren't already in 'to'.
966
	$recipients['bcc'] = array_diff(array_unique($recipients['bcc']), $recipients['to']);
967
968
	// Combine 'to' and 'bcc' recipients.
969
	$all_to = array_merge($recipients['to'], $recipients['bcc']);
970
971
	// Check no-one will want it deleted right away!
972
	$request = $smcFunc['db_query']('', '
973
		SELECT
974
			id_member, criteria, is_or
975
		FROM {db_prefix}pm_rules
976
		WHERE id_member IN ({array_int:to_members})
977
			AND delete_pm = {int:delete_pm}',
978
		array(
979
			'to_members' => $all_to,
980
			'delete_pm' => 1,
981
		)
982
	);
983
	$deletes = array();
984
	// Check whether we have to apply anything...
985
	while ($row = $smcFunc['db_fetch_assoc']($request))
986
	{
987
		$criteria = $smcFunc['json_decode']($row['criteria'], true);
988
		// Note we don't check the buddy status, cause deletion from buddy = madness!
989
		$delete = false;
990
		foreach ($criteria as $criterium)
991
		{
992
			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))
993
				$delete = true;
994
			// If we're adding and one criteria don't match then we stop!
995
			elseif (!$row['is_or'])
996
			{
997
				$delete = false;
998
				break;
999
			}
1000
		}
1001
		if ($delete)
1002
			$deletes[$row['id_member']] = 1;
1003
	}
1004
	$smcFunc['db_free_result']($request);
1005
1006
	// Load the membergrounp message limits.
1007
	// @todo Consider caching this?
1008
	static $message_limit_cache = array();
1009
	if (!allowedTo('moderate_forum') && empty($message_limit_cache))
1010
	{
1011
		$request = $smcFunc['db_query']('', '
1012
			SELECT id_group, max_messages
1013
			FROM {db_prefix}membergroups',
1014
			array(
1015
			)
1016
		);
1017
		while ($row = $smcFunc['db_fetch_assoc']($request))
1018
			$message_limit_cache[$row['id_group']] = $row['max_messages'];
1019
		$smcFunc['db_free_result']($request);
1020
	}
1021
1022
	// Load the groups that are allowed to read PMs.
1023
	require_once($sourcedir . '/Subs-Members.php');
1024
	$pmReadGroups = groupsAllowedTo('pm_read');
1025
1026
	if (empty($modSettings['permission_enable_deny']))
1027
		$pmReadGroups['denied'] = array();
1028
1029
	// Load their alert preferences
1030
	require_once($sourcedir . '/Subs-Notify.php');
1031
	$notifyPrefs = getNotifyPrefs($all_to, array('pm_new', 'pm_reply', 'pm_notify'), true);
1032
1033
	$request = $smcFunc['db_query']('', '
1034
		SELECT
1035
			member_name, real_name, id_member, email_address, lngfile,
1036
			instant_messages,' . (allowedTo('moderate_forum') ? ' 0' : '
1037
			(pm_receive_from = {int:admins_only}' . (empty($modSettings['enable_buddylist']) ? '' : ' OR
1038
			(pm_receive_from = {int:buddies_only} AND FIND_IN_SET({string:from_id}, buddy_list) = 0) OR
1039
			(pm_receive_from = {int:not_on_ignore_list} AND FIND_IN_SET({string:from_id}, pm_ignore_list) != 0)') . ')') . ' AS ignored,
1040
			FIND_IN_SET({string:from_id}, buddy_list) != 0 AS is_buddy, is_activated,
1041
			additional_groups, id_group, id_post_group
1042
		FROM {db_prefix}members
1043
		WHERE id_member IN ({array_int:recipients})
1044
		ORDER BY lngfile
1045
		LIMIT {int:count_recipients}',
1046
		array(
1047
			'not_on_ignore_list' => 1,
1048
			'buddies_only' => 2,
1049
			'admins_only' => 3,
1050
			'recipients' => $all_to,
1051
			'count_recipients' => count($all_to),
1052
			'from_id' => $from['id'],
1053
		)
1054
	);
1055
	$notifications = array();
1056
	while ($row = $smcFunc['db_fetch_assoc']($request))
1057
	{
1058
		// Don't do anything for members to be deleted!
1059
		if (isset($deletes[$row['id_member']]))
1060
			continue;
1061
1062
		// Load the preferences for this member (if any)
1063
		$prefs = !empty($notifyPrefs[$row['id_member']]) ? $notifyPrefs[$row['id_member']] : array();
1064
		$prefs = array_merge(array(
1065
			'pm_new' => 0,
1066
			'pm_reply' => 0,
1067
			'pm_notify' => 0,
1068
		), $prefs);
1069
1070
		// We need to know this members groups.
1071
		$groups = explode(',', $row['additional_groups']);
1072
		$groups[] = $row['id_group'];
1073
		$groups[] = $row['id_post_group'];
1074
1075
		$message_limit = -1;
1076
		// For each group see whether they've gone over their limit - assuming they're not an admin.
1077
		if (!in_array(1, $groups))
1078
		{
1079
			foreach ($groups as $id)
1080
			{
1081
				if (isset($message_limit_cache[$id]) && $message_limit != 0 && $message_limit < $message_limit_cache[$id])
1082
					$message_limit = $message_limit_cache[$id];
1083
			}
1084
1085
			if ($message_limit > 0 && $message_limit <= $row['instant_messages'])
1086
			{
1087
				$log['failed'][$row['id_member']] = sprintf($txt['pm_error_data_limit_reached'], $row['real_name']);
1088
				unset($all_to[array_search($row['id_member'], $all_to)]);
1089
				continue;
1090
			}
1091
1092
			// Do they have any of the allowed groups?
1093
			if (count(array_intersect($pmReadGroups['allowed'], $groups)) == 0 || count(array_intersect($pmReadGroups['denied'], $groups)) != 0)
1094
			{
1095
				$log['failed'][$row['id_member']] = sprintf($txt['pm_error_user_cannot_read'], $row['real_name']);
1096
				unset($all_to[array_search($row['id_member'], $all_to)]);
1097
				continue;
1098
			}
1099
		}
1100
1101
		// Note that PostgreSQL can return a lowercase t/f for FIND_IN_SET
1102
		if (!empty($row['ignored']) && $row['ignored'] != 'f' && $row['id_member'] != $from['id'])
1103
		{
1104
			$log['failed'][$row['id_member']] = sprintf($txt['pm_error_ignored_by_user'], $row['real_name']);
1105
			unset($all_to[array_search($row['id_member'], $all_to)]);
1106
			continue;
1107
		}
1108
1109
		// If the receiving account is banned (>=10) or pending deletion (4), refuse to send the PM.
1110
		if ($row['is_activated'] >= 10 || ($row['is_activated'] == 4 && !$user_info['is_admin']))
1111
		{
1112
			$log['failed'][$row['id_member']] = sprintf($txt['pm_error_user_cannot_read'], $row['real_name']);
1113
			unset($all_to[array_search($row['id_member'], $all_to)]);
1114
			continue;
1115
		}
1116
1117
		// Send a notification, if enabled - taking the buddy list into account.
1118
		if (!empty($row['email_address'])
1119
			&& ((empty($pm_head) && $prefs['pm_new'] & 0x02) || (!empty($pm_head) && $prefs['pm_reply'] & 0x02))
1120
			&& ($prefs['pm_notify'] <= 1 || ($prefs['pm_notify'] > 1 && (!empty($modSettings['enable_buddylist']) && $row['is_buddy']))) && $row['is_activated'] == 1)
1121
		{
1122
			$notifications[empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']][] = $row['email_address'];
1123
		}
1124
1125
		$log['sent'][$row['id_member']] = sprintf(isset($txt['pm_successfully_sent']) ? $txt['pm_successfully_sent'] : '', $row['real_name']);
1126
	}
1127
	$smcFunc['db_free_result']($request);
1128
1129
	// Only 'send' the message if there are any recipients left.
1130
	if (empty($all_to))
1131
		return $log;
1132
1133
	// Insert the message itself and then grab the last insert id.
1134
	$id_pm = $smcFunc['db_insert']('',
1135
		'{db_prefix}personal_messages',
1136
		array(
1137
			'id_pm_head' => 'int', 'id_member_from' => 'int', 'deleted_by_sender' => 'int',
1138
			'from_name' => 'string-255', 'msgtime' => 'int', 'subject' => 'string-255', 'body' => 'string-65534',
1139
		),
1140
		array(
1141
			$pm_head, $from['id'], ($store_outbox ? 0 : 1),
1142
			$from['username'], time(), $htmlsubject, $htmlmessage,
1143
		),
1144
		array('id_pm'),
1145
		1
1146
	);
1147
1148
	// Add the recipients.
1149
	if (!empty($id_pm))
1150
	{
1151
		// If this is new we need to set it part of its own conversation.
1152
		if (empty($pm_head))
1153
			$smcFunc['db_query']('', '
1154
				UPDATE {db_prefix}personal_messages
1155
				SET id_pm_head = {int:id_pm_head}
1156
				WHERE id_pm = {int:id_pm_head}',
1157
				array(
1158
					'id_pm_head' => $id_pm,
1159
				)
1160
			);
1161
1162
		// Some people think manually deleting personal_messages is fun... it's not. We protect against it though :)
1163
		$smcFunc['db_query']('', '
1164
			DELETE FROM {db_prefix}pm_recipients
1165
			WHERE id_pm = {int:id_pm}',
1166
			array(
1167
				'id_pm' => $id_pm,
1168
			)
1169
		);
1170
1171
		$insertRows = array();
1172
		$to_list = array();
1173
		foreach ($all_to as $to)
1174
		{
1175
			$insertRows[] = array($id_pm, $to, in_array($to, $recipients['bcc']) ? 1 : 0, isset($deletes[$to]) ? 1 : 0, 1);
1176
			if (!in_array($to, $recipients['bcc']))
1177
				$to_list[] = $to;
1178
		}
1179
1180
		$smcFunc['db_insert']('insert',
1181
			'{db_prefix}pm_recipients',
1182
			array(
1183
				'id_pm' => 'int', 'id_member' => 'int', 'bcc' => 'int', 'deleted' => 'int', 'is_new' => 'int'
1184
			),
1185
			$insertRows,
1186
			array('id_pm', 'id_member')
1187
		);
1188
	}
1189
1190
	$to_names = array();
1191
	if (count($to_list) > 1)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $to_list does not seem to be defined for all execution paths leading up to this point.
Loading history...
1192
	{
1193
		$request = $smcFunc['db_query']('', '
1194
			SELECT real_name
1195
			FROM {db_prefix}members
1196
			WHERE id_member IN ({array_int:to_members})
1197
				AND id_member != {int:from}',
1198
			array(
1199
				'to_members' => $to_list,
1200
				'from' => $from['id'],
1201
			)
1202
		);
1203
		while ($row = $smcFunc['db_fetch_assoc']($request))
1204
			$to_names[] = un_htmlspecialchars($row['real_name']);
1205
		$smcFunc['db_free_result']($request);
1206
	}
1207
	$replacements = array(
1208
		'SUBJECT' => $subject,
1209
		'MESSAGE' => $message,
1210
		'SENDER' => un_htmlspecialchars($from['name']),
1211
		'READLINK' => $scripturl . '?action=pm;pmsg=' . $id_pm . '#msg' . $id_pm,
1212
		'REPLYLINK' => $scripturl . '?action=pm;sa=send;f=inbox;pmsg=' . $id_pm . ';quote;u=' . $from['id'],
1213
		'TOLIST' => implode(', ', $to_names),
1214
	);
1215
	$email_template = 'new_pm' . (empty($modSettings['disallow_sendBody']) ? '_body' : '') . (!empty($to_names) ? '_tolist' : '');
1216
1217
	$notification_texts = array();
1218
1219
	foreach ($notifications as $lang => $notification_list)
1220
	{
1221
		// Censor and parse BBC in the receiver's language. Only do each language once.
1222
		if (empty($notification_texts[$lang]))
1223
		{
1224
			if ($lang != $user_info['language'])
1225
				loadLanguage('index+Modifications', $lang, false);
1226
1227
			$notification_texts[$lang]['subject'] = $subject;
1228
			censorText($notification_texts[$lang]['subject']);
1229
1230
			if (empty($modSettings['disallow_sendBody']))
1231
			{
1232
				$notification_texts[$lang]['body'] = $message;
1233
1234
				censorText($notification_texts[$lang]['body']);
1235
1236
				$notification_texts[$lang]['body'] = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc($smcFunc['htmlspecialchars']($notification_texts[$lang]['body']), false), array('<br>' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
1237
			}
1238
			else
1239
				$notification_texts[$lang]['body'] = '';
1240
1241
1242
			if ($lang != $user_info['language'])
1243
				loadLanguage('index+Modifications', $user_info['language'], false);
1244
		}
1245
1246
		$replacements['SUBJECT'] = $notification_texts[$lang]['subject'];
1247
		$replacements['MESSAGE'] = $notification_texts[$lang]['body'];
1248
1249
		$emaildata = loadEmailTemplate($email_template, $replacements, $lang);
1250
1251
		// Off the notification email goes!
1252
		sendmail($notification_list, $emaildata['subject'], $emaildata['body'], null, 'p' . $id_pm, $emaildata['is_html'], 2, null, true);
1253
	}
1254
1255
	// Integrated After PMs
1256
	call_integration_hook('integrate_personal_message_after', array(&$id_pm, &$log, &$recipients, &$from, &$subject, &$message));
1257
1258
	// Back to what we were on before!
1259
	loadLanguage('index+PersonalMessage');
1260
1261
	// Add one to their unread and read message counts.
1262
	foreach ($all_to as $k => $id)
1263
		if (isset($deletes[$id]))
1264
			unset($all_to[$k]);
1265
	if (!empty($all_to))
1266
		updateMemberData($all_to, array('instant_messages' => '+', 'unread_messages' => '+', 'new_pm' => 1));
1267
1268
	return $log;
1269
}
1270
1271
/**
1272
 * Prepare text strings for sending as email body or header.
1273
 * In case there are higher ASCII characters in the given string, this
1274
 * function will attempt the transport method 'quoted-printable'.
1275
 * Otherwise the transport method '7bit' is used.
1276
 *
1277
 * @param string $string The string
1278
 * @param bool $with_charset Whether we're specifying a charset ($custom_charset must be set here)
1279
 * @param bool $hotmail_fix Whether to apply the hotmail fix  (all higher ASCII characters are converted to HTML entities to assure proper display of the mail)
1280
 * @param string $line_break The linebreak
1281
 * @param string $custom_charset If set, it uses this character set
1282
 * @return array An array containing the character set, the converted string and the transport method.
1283
 */
1284
function mimespecialchars($string, $with_charset = true, $hotmail_fix = false, $line_break = "\r\n", $custom_charset = null)
1285
{
1286
	global $context;
1287
1288
	$charset = $custom_charset !== null ? $custom_charset : $context['character_set'];
1289
1290
	// This is the fun part....
1291
	if (preg_match_all('~&#(\d{3,8});~', $string, $matches) !== 0 && !$hotmail_fix)
1292
	{
1293
		// Let's, for now, assume there are only &#021;'ish characters.
1294
		$simple = true;
1295
1296
		foreach ($matches[1] as $entity)
1297
			if ($entity > 128)
1298
				$simple = false;
1299
		unset($matches);
1300
1301
		if ($simple)
1302
			$string = preg_replace_callback(
1303
				'~&#(\d{3,8});~',
1304
				function($m)
1305
				{
1306
					return chr("$m[1]");
0 ignored issues
show
Bug introduced by
$m['1'] of type string is incompatible with the type integer expected by parameter $codepoint of chr(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1306
					return chr(/** @scrutinizer ignore-type */ "$m[1]");
Loading history...
1307
				},
1308
				$string
1309
			);
1310
		else
1311
		{
1312
			// Try to convert the string to UTF-8.
1313
			if (!$context['utf8'] && function_exists('iconv'))
1314
			{
1315
				$newstring = @iconv($context['character_set'], 'UTF-8', $string);
1316
				if ($newstring)
1317
					$string = $newstring;
1318
			}
1319
1320
			$string = preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $string);
1321
1322
			// Unicode, baby.
1323
			$charset = 'UTF-8';
1324
		}
1325
	}
1326
1327
	// Convert all special characters to HTML entities...just for Hotmail :-\
1328
	if ($hotmail_fix && ($context['utf8'] || function_exists('iconv') || $context['character_set'] === 'ISO-8859-1'))
1329
	{
1330
		if (!$context['utf8'] && function_exists('iconv'))
1331
		{
1332
			$newstring = @iconv($context['character_set'], 'UTF-8', $string);
1333
			if ($newstring)
1334
				$string = $newstring;
1335
		}
1336
1337
		$entityConvert = function($m)
1338
		{
1339
			$c = $m[1];
1340
			if (strlen($c) === 1 && ord($c[0]) <= 0x7F)
1341
				return $c;
1342
			elseif (strlen($c) === 2 && ord($c[0]) >= 0xC0 && ord($c[0]) <= 0xDF)
1343
				return "&#" . (((ord($c[0]) ^ 0xC0) << 6) + (ord($c[1]) ^ 0x80)) . ";";
1344
			elseif (strlen($c) === 3 && ord($c[0]) >= 0xE0 && ord($c[0]) <= 0xEF)
1345
				return "&#" . (((ord($c[0]) ^ 0xE0) << 12) + ((ord($c[1]) ^ 0x80) << 6) + (ord($c[2]) ^ 0x80)) . ";";
1346
			elseif (strlen($c) === 4 && ord($c[0]) >= 0xF0 && ord($c[0]) <= 0xF7)
1347
				return "&#" . (((ord($c[0]) ^ 0xF0) << 18) + ((ord($c[1]) ^ 0x80) << 12) + ((ord($c[2]) ^ 0x80) << 6) + (ord($c[3]) ^ 0x80)) . ";";
1348
			else
1349
				return "";
1350
		};
1351
1352
		// Convert all 'special' characters to HTML entities.
1353
		return array($charset, preg_replace_callback('~([\x80-\x{10FFFF}])~u', $entityConvert, $string), '7bit');
1354
	}
1355
1356
	// We don't need to mess with the subject line if no special characters were in it..
1357
	elseif (!$hotmail_fix && preg_match('~([^\x09\x0A\x0D\x20-\x7F])~', $string) === 1)
1358
	{
1359
		// Base64 encode.
1360
		$string = base64_encode($string);
1361
1362
		// Show the characterset and the transfer-encoding for header strings.
1363
		if ($with_charset)
1364
			$string = '=?' . $charset . '?B?' . $string . '?=';
1365
1366
		// Break it up in lines (mail body).
1367
		else
1368
			$string = chunk_split($string, 76, $line_break);
1369
1370
		return array($charset, $string, 'base64');
1371
	}
1372
1373
	else
1374
		return array($charset, $string, '7bit');
1375
}
1376
1377
/**
1378
 * Sends mail, like mail() but over SMTP.
1379
 * It expects no slashes or entities.
1380
 *
1381
 * @internal
1382
 *
1383
 * @param array $mail_to_array Array of strings (email addresses)
1384
 * @param string $subject Email subject
1385
 * @param string $message Email message
1386
 * @param string $headers Email headers
1387
 * @return boolean Whether it sent or not.
1388
 */
1389
function smtp_mail($mail_to_array, $subject, $message, $headers)
1390
{
1391
	global $modSettings, $webmaster_email, $txt, $boardurl, $sourcedir;
1392
1393
	static $helo;
1394
1395
	$modSettings['smtp_host'] = trim($modSettings['smtp_host']);
1396
1397
	// Try POP3 before SMTP?
1398
	// @todo There's no interface for this yet.
1399
	if ($modSettings['mail_type'] == 3 && $modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
1400
	{
1401
		$socket = fsockopen($modSettings['smtp_host'], 110, $errno, $errstr, 2);
1402
		if (!$socket && (substr($modSettings['smtp_host'], 0, 5) == 'smtp.' || substr($modSettings['smtp_host'], 0, 11) == 'ssl://smtp.'))
0 ignored issues
show
introduced by
$socket is of type resource, thus it always evaluated to false.
Loading history...
1403
			$socket = fsockopen(strtr($modSettings['smtp_host'], array('smtp.' => 'pop.')), 110, $errno, $errstr, 2);
1404
1405
		if ($socket)
0 ignored issues
show
introduced by
$socket is of type resource, thus it always evaluated to false.
Loading history...
1406
		{
1407
			fgets($socket, 256);
1408
			fputs($socket, 'USER ' . $modSettings['smtp_username'] . "\r\n");
1409
			fgets($socket, 256);
1410
			fputs($socket, 'PASS ' . base64_decode($modSettings['smtp_password']) . "\r\n");
1411
			fgets($socket, 256);
1412
			fputs($socket, 'QUIT' . "\r\n");
1413
1414
			fclose($socket);
1415
		}
1416
	}
1417
1418
	// Try to connect to the SMTP server... if it doesn't exist, only wait three seconds.
1419
	if (!$socket = fsockopen($modSettings['smtp_host'], empty($modSettings['smtp_port']) ? 25 : $modSettings['smtp_port'], $errno, $errstr, 3))
1420
	{
1421
		// Maybe we can still save this?  The port might be wrong.
1422
		if (substr($modSettings['smtp_host'], 0, 4) == 'ssl:' && (empty($modSettings['smtp_port']) || $modSettings['smtp_port'] == 25))
1423
		{
1424
			// ssl:hostname can cause fsocketopen to fail with a lookup failure, ensure it exists for this test.
1425
			if (substr($modSettings['smtp_host'], 0, 6) != 'ssl://')
1426
				$modSettings['smtp_host'] = str_replace('ssl:', 'ss://', $modSettings['smtp_host']);
1427
1428
			if ($socket = fsockopen($modSettings['smtp_host'], 465, $errno, $errstr, 3))
1429
				log_error($txt['smtp_port_ssl']);
1430
		}
1431
1432
		// Unable to connect!  Don't show any error message, but just log one and try to continue anyway.
1433
		if (!$socket)
0 ignored issues
show
introduced by
$socket is of type resource, thus it always evaluated to false.
Loading history...
1434
		{
1435
			log_error($txt['smtp_no_connect'] . ': ' . $errno . ' : ' . $errstr);
1436
			return false;
1437
		}
1438
	}
1439
1440
	// Wait for a response of 220, without "-" continuer.
1441
	if (!server_parse(null, $socket, '220'))
1442
		return false;
1443
1444
	// Try to determine the server's fully qualified domain name
1445
	// Can't rely on $_SERVER['SERVER_NAME'] because it can be spoofed on Apache
1446
	if (empty($helo))
1447
	{
1448
		// See if we can get the domain name from the host itself
1449
		if (function_exists('gethostname'))
1450
			$helo = gethostname();
1451
		elseif (function_exists('php_uname'))
1452
			$helo = php_uname('n');
1453
1454
		// If the hostname isn't a fully qualified domain name, we can use the host name from $boardurl instead
1455
		if (empty($helo) || strpos($helo, '.') === false || substr_compare($helo, '.local', -6) === 0 || (!empty($modSettings['tld_regex']) && !preg_match('/\.' . $modSettings['tld_regex'] . '$/u', $helo)))
1456
			$helo = parse_iri($boardurl, PHP_URL_HOST);
1457
1458
		// This is one of those situations where 'www.' is undesirable
1459
		if (strpos($helo, 'www.') === 0)
1460
			$helo = substr($helo, 4);
1461
1462
		if (!function_exists('idn_to_ascii'))
1463
			require_once($sourcedir . '/Subs-Compat.php');
1464
1465
		$helo = idn_to_ascii($helo, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
1466
	}
1467
1468
	// SMTP = 1, SMTP - STARTTLS = 2
1469
	if (in_array($modSettings['mail_type'], array(1, 2)) && $modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
1470
	{
1471
		// EHLO could be understood to mean encrypted hello...
1472
		if (server_parse('EHLO ' . $helo, $socket, null, $response) == '250')
1473
		{
1474
			// Are we using STARTTLS and does the server support STARTTLS?
1475
			if ($modSettings['mail_type'] == 2 && preg_match("~250( |-)STARTTLS~mi", $response))
1476
			{
1477
				// Send STARTTLS to enable encryption
1478
				if (!server_parse('STARTTLS', $socket, '220'))
1479
					return false;
1480
				// Enable the encryption
1481
				// php 5.6+ fix
1482
				$crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
1483
1484
				if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT'))
1485
				{
1486
					$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
1487
					$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
1488
				}
1489
1490
				if (!@stream_socket_enable_crypto($socket, true, $crypto_method))
1491
					return false;
1492
				// Send the EHLO command again
1493
				if (!server_parse('EHLO ' . $helo, $socket, null) == '250')
1494
					return false;
1495
			}
1496
1497
			if (!server_parse('AUTH LOGIN', $socket, '334'))
1498
				return false;
1499
			// Send the username and password, encoded.
1500
			if (!server_parse(base64_encode($modSettings['smtp_username']), $socket, '334'))
1501
				return false;
1502
			// The password is already encoded ;)
1503
			if (!server_parse($modSettings['smtp_password'], $socket, '235'))
1504
				return false;
1505
		}
1506
		elseif (!server_parse('HELO ' . $helo, $socket, '250'))
1507
			return false;
1508
	}
1509
	else
1510
	{
1511
		// Just say "helo".
1512
		if (!server_parse('HELO ' . $helo, $socket, '250'))
1513
			return false;
1514
	}
1515
1516
	// Fix the message for any lines beginning with a period! (the first is ignored, you see.)
1517
	$message = strtr($message, array("\r\n" . '.' => "\r\n" . '..'));
1518
1519
	// !! Theoretically, we should be able to just loop the RCPT TO.
1520
	$mail_to_array = array_values($mail_to_array);
1521
	foreach ($mail_to_array as $i => $mail_to)
1522
	{
1523
		// Reset the connection to send another email.
1524
		if ($i != 0)
1525
		{
1526
			if (!server_parse('RSET', $socket, '250'))
1527
				return false;
1528
		}
1529
1530
		// From, to, and then start the data...
1531
		if (!server_parse('MAIL FROM: <' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . '>', $socket, '250'))
1532
			return false;
1533
		if (!server_parse('RCPT TO: <' . $mail_to . '>', $socket, '250'))
1534
			return false;
1535
		if (!server_parse('DATA', $socket, '354'))
1536
			return false;
1537
		fputs($socket, 'Subject: ' . $subject . "\r\n");
1538
		if (strlen($mail_to) > 0)
1539
			fputs($socket, 'To: <' . $mail_to . '>' . "\r\n");
1540
		fputs($socket, $headers . "\r\n\r\n");
1541
		fputs($socket, $message . "\r\n");
1542
1543
		// Send a ., or in other words "end of data".
1544
		if (!server_parse('.', $socket, '250'))
1545
			return false;
1546
1547
		// Almost done, almost done... don't stop me just yet!
1548
		@set_time_limit(300);
1549
		if (function_exists('apache_reset_timeout'))
1550
			@apache_reset_timeout();
1551
	}
1552
	fputs($socket, 'QUIT' . "\r\n");
1553
	fclose($socket);
1554
1555
	return true;
1556
}
1557
1558
/**
1559
 * Parse a message to the SMTP server.
1560
 * Sends the specified message to the server, and checks for the
1561
 * expected response.
1562
 *
1563
 * @internal
1564
 *
1565
 * @param string $message The message to send
1566
 * @param resource $socket Socket to send on
1567
 * @param string $code The expected response code
1568
 * @param string $response The response from the SMTP server
1569
 * @return bool Whether it responded as such.
1570
 */
1571
function server_parse($message, $socket, $code, &$response = null)
1572
{
1573
	global $txt;
1574
1575
	if ($message !== null)
0 ignored issues
show
introduced by
The condition $message !== null is always true.
Loading history...
1576
		fputs($socket, $message . "\r\n");
1577
1578
	// No response yet.
1579
	$server_response = '';
1580
1581
	while (substr($server_response, 3, 1) != ' ')
1582
	{
1583
		if (!($server_response = fgets($socket, 256)))
1584
		{
1585
			// @todo Change this message to reflect that it may mean bad user/password/server issues/etc.
1586
			log_error($txt['smtp_bad_response']);
1587
			return false;
1588
		}
1589
		$response .= $server_response;
1590
	}
1591
1592
	if ($code === null)
0 ignored issues
show
introduced by
The condition $code === null is always false.
Loading history...
1593
		return substr($server_response, 0, 3);
1594
1595
	$response_code = (int) substr($server_response, 0, 3);
1596
	if ($response_code != $code)
1597
	{
1598
		// Ignoreable errors that we can't fix should not be logged.
1599
		/*
1600
		 * 550 - cPanel rejected sending due to DNS issues
1601
		 * 450 - DNS Routing issues
1602
		 * 451 - cPanel "Temporary local problem - please try later"
1603
		 */
1604
		if ($response_code < 500 && !in_array($response_code, array(450, 451)))
1605
			log_error($txt['smtp_error'] . $server_response);
1606
1607
		return false;
1608
	}
1609
1610
	return true;
1611
}
1612
1613
/**
1614
 * Spell checks the post for typos ;).
1615
 * It uses the pspell or enchant library, one of which MUST be installed.
1616
 * It has problems with internationalization.
1617
 * It is accessed via ?action=spellcheck.
1618
 */
1619
function SpellCheck()
1620
{
1621
	global $txt, $context, $smcFunc;
1622
1623
	// A list of "words" we know about but pspell doesn't.
1624
	$known_words = array('smf', 'php', 'mysql', 'www', 'gif', 'jpeg', 'png', 'http', 'smfisawesome', 'grandia', 'terranigma', 'rpgs');
1625
1626
	loadLanguage('Post');
1627
	loadTemplate('Post');
1628
1629
	// Create a pspell or enchant dictionary resource
1630
	$dict = spell_init();
1631
1632
	if (!isset($_POST['spellstring']) || !$dict)
1633
		die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1634
1635
	// Construct a bit of Javascript code.
1636
	$context['spell_js'] = '
1637
		var txt = {"done": "' . $txt['spellcheck_done'] . '"};
1638
		var mispstr = window.opener.spellCheckGetText(spell_fieldname);
1639
		var misps = Array(';
1640
1641
	// Get all the words (Javascript already separated them).
1642
	$alphas = explode("\n", strtr($_POST['spellstring'], array("\r" => '')));
1643
1644
	$found_words = false;
1645
	for ($i = 0, $n = count($alphas); $i < $n; $i++)
1646
	{
1647
		// Words are sent like 'word|offset_begin|offset_end'.
1648
		$check_word = explode('|', $alphas[$i]);
1649
1650
		// If the word is a known word, or spelled right...
1651
		if (in_array($smcFunc['strtolower']($check_word[0]), $known_words) || spell_check($dict, $check_word[0]) || !isset($check_word[2]))
1652
			continue;
1653
1654
		// Find the word, and move up the "last occurrence" to here.
1655
		$found_words = true;
1656
1657
		// Add on the javascript for this misspelling.
1658
		$context['spell_js'] .= '
1659
			new misp("' . strtr($check_word[0], array('\\' => '\\\\', '"' => '\\"', '<' => '', '&gt;' => '')) . '", ' . (int) $check_word[1] . ', ' . (int) $check_word[2] . ', [';
1660
1661
		// If there are suggestions, add them in...
1662
		$suggestions = spell_suggest($dict, $check_word[0]);
1663
		if (!empty($suggestions))
1664
		{
1665
			// But first check they aren't going to be censored - no naughty words!
1666
			foreach ($suggestions as $k => $word)
1667
				if ($suggestions[$k] != censorText($word))
1668
					unset($suggestions[$k]);
1669
1670
			if (!empty($suggestions))
1671
				$context['spell_js'] .= '"' . implode('", "', $suggestions) . '"';
1672
		}
1673
1674
		$context['spell_js'] .= ']),';
1675
	}
1676
1677
	// If words were found, take off the last comma.
1678
	if ($found_words)
1679
		$context['spell_js'] = substr($context['spell_js'], 0, -1);
1680
1681
	$context['spell_js'] .= '
1682
		);';
1683
1684
	// And instruct the template system to just show the spellcheck sub template.
1685
	$context['template_layers'] = array();
1686
	$context['sub_template'] = 'spellcheck';
1687
1688
	// Free resources for enchant...
1689
	if (isset($context['enchant_broker']))
1690
	{
1691
		enchant_broker_free_dict($dict);
1692
		enchant_broker_free($context['enchant_broker']);
1693
	}
1694
}
1695
1696
/**
1697
 * Sends a notification to members who have elected to receive emails
1698
 * when things happen to a topic, such as replies are posted.
1699
 * The function automatically finds the subject and its board, and
1700
 * checks permissions for each member who is "signed up" for notifications.
1701
 * It will not send 'reply' notifications more than once in a row.
1702
 * Uses Post language file
1703
 *
1704
 * @param array $topics Represents the topics the action is happening to.
1705
 * @param string $type Can be any of reply, sticky, lock, unlock, remove, move, merge, and split.  An appropriate message will be sent for each.
1706
 * @param array $exclude Members in the exclude array will not be processed for the topic with the same key.
1707
 * @param array $members_only Are the only ones that will be sent the notification if they have it on.
1708
 */
1709
function sendNotifications($topics, $type, $exclude = array(), $members_only = array())
1710
{
1711
	global $user_info, $smcFunc;
1712
1713
	// Can't do it if there's no topics.
1714
	if (empty($topics))
1715
		return;
1716
	// It must be an array - it must!
1717
	if (!is_array($topics))
0 ignored issues
show
introduced by
The condition is_array($topics) is always true.
Loading history...
1718
		$topics = array($topics);
1719
1720
	// Get the subject and body...
1721
	$result = $smcFunc['db_query']('', '
1722
		SELECT mf.subject, ml.body, ml.id_member, t.id_last_msg, t.id_topic, t.id_board,
1723
			COALESCE(mem.real_name, ml.poster_name) AS poster_name, mf.id_msg
1724
		FROM {db_prefix}topics AS t
1725
			INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
1726
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
1727
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ml.id_member)
1728
		WHERE t.id_topic IN ({array_int:topic_list})
1729
		LIMIT 1',
1730
		array(
1731
			'topic_list' => $topics,
1732
		)
1733
	);
1734
	$task_rows = array();
1735
	while ($row = $smcFunc['db_fetch_assoc']($result))
1736
	{
1737
		$task_rows[] = array(
1738
			'$sourcedir/tasks/CreatePost-Notify.php', 'CreatePost_Notify_Background', $smcFunc['json_encode'](array(
1739
				'msgOptions' => array(
1740
					'id' => $row['id_msg'],
1741
					'subject' => $row['subject'],
1742
					'body' => $row['body'],
1743
				),
1744
				'topicOptions' => array(
1745
					'id' => $row['id_topic'],
1746
					'board' => $row['id_board'],
1747
				),
1748
				// Kinda cheeky, but for any action the originator is usually the current user
1749
				'posterOptions' => array(
1750
					'id' => $user_info['id'],
1751
					'name' => $user_info['name'],
1752
				),
1753
				'type' => $type,
1754
				'members_only' => $members_only,
1755
			)), 0
1756
		);
1757
	}
1758
	$smcFunc['db_free_result']($result);
1759
1760
	if (!empty($task_rows))
1761
		$smcFunc['db_insert']('',
1762
			'{db_prefix}background_tasks',
1763
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
1764
			$task_rows,
1765
			array('id_task')
1766
		);
1767
}
1768
1769
/**
1770
 * Create a post, either as new topic (id_topic = 0) or in an existing one.
1771
 * The input parameters of this function assume:
1772
 * - Strings have been escaped.
1773
 * - Integers have been cast to integer.
1774
 * - Mandatory parameters are set.
1775
 *
1776
 * @param array $msgOptions An array of information/options for the post
1777
 * @param array $topicOptions An array of information/options for the topic
1778
 * @param array $posterOptions An array of information/options for the poster
1779
 * @return bool Whether the operation was a success
1780
 */
1781
function createPost(&$msgOptions, &$topicOptions, &$posterOptions)
1782
{
1783
	global $user_info, $txt, $modSettings, $smcFunc, $sourcedir;
1784
1785
	require_once($sourcedir . '/Mentions.php');
1786
1787
	// Set optional parameters to the default value.
1788
	$msgOptions['icon'] = empty($msgOptions['icon']) ? 'xx' : $msgOptions['icon'];
1789
	$msgOptions['smileys_enabled'] = !empty($msgOptions['smileys_enabled']);
1790
	$msgOptions['attachments'] = empty($msgOptions['attachments']) ? array() : $msgOptions['attachments'];
1791
	$msgOptions['approved'] = isset($msgOptions['approved']) ? (int) $msgOptions['approved'] : 1;
1792
	$msgOptions['poster_time'] = isset($msgOptions['poster_time']) ? (int) $msgOptions['poster_time'] : time();
1793
	$topicOptions['id'] = empty($topicOptions['id']) ? 0 : (int) $topicOptions['id'];
1794
	$topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null;
1795
	$topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null;
1796
	$topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null;
1797
	$topicOptions['redirect_expires'] = isset($topicOptions['redirect_expires']) ? $topicOptions['redirect_expires'] : null;
1798
	$topicOptions['redirect_topic'] = isset($topicOptions['redirect_topic']) ? $topicOptions['redirect_topic'] : null;
1799
	$posterOptions['id'] = empty($posterOptions['id']) ? 0 : (int) $posterOptions['id'];
1800
	$posterOptions['ip'] = empty($posterOptions['ip']) ? $user_info['ip'] : $posterOptions['ip'];
1801
1802
	// Not exactly a post option but it allows hooks and/or other sources to skip sending notifications if they don't want to
1803
	$msgOptions['send_notifications'] = isset($msgOptions['send_notifications']) ? (bool) $msgOptions['send_notifications'] : true;
1804
1805
	// We need to know if the topic is approved. If we're told that's great - if not find out.
1806
	if (!$modSettings['postmod_active'])
1807
		$topicOptions['is_approved'] = true;
1808
	elseif (!empty($topicOptions['id']) && !isset($topicOptions['is_approved']))
1809
	{
1810
		$request = $smcFunc['db_query']('', '
1811
			SELECT approved
1812
			FROM {db_prefix}topics
1813
			WHERE id_topic = {int:id_topic}
1814
			LIMIT 1',
1815
			array(
1816
				'id_topic' => $topicOptions['id'],
1817
			)
1818
		);
1819
		list ($topicOptions['is_approved']) = $smcFunc['db_fetch_row']($request);
1820
		$smcFunc['db_free_result']($request);
1821
	}
1822
1823
	// If nothing was filled in as name/e-mail address, try the member table.
1824
	if (!isset($posterOptions['name']) || $posterOptions['name'] == '' || (empty($posterOptions['email']) && !empty($posterOptions['id'])))
1825
	{
1826
		if (empty($posterOptions['id']))
1827
		{
1828
			$posterOptions['id'] = 0;
1829
			$posterOptions['name'] = $txt['guest_title'];
1830
			$posterOptions['email'] = '';
1831
		}
1832
		elseif ($posterOptions['id'] != $user_info['id'])
1833
		{
1834
			$request = $smcFunc['db_query']('', '
1835
				SELECT member_name, email_address
1836
				FROM {db_prefix}members
1837
				WHERE id_member = {int:id_member}
1838
				LIMIT 1',
1839
				array(
1840
					'id_member' => $posterOptions['id'],
1841
				)
1842
			);
1843
			// Couldn't find the current poster?
1844
			if ($smcFunc['db_num_rows']($request) == 0)
1845
			{
1846
				loadLanguage('Errors');
1847
				trigger_error(sprintf($txt['create_post_invalid_member_id'], $posterOptions['id']), E_USER_NOTICE);
1848
				$posterOptions['id'] = 0;
1849
				$posterOptions['name'] = $txt['guest_title'];
1850
				$posterOptions['email'] = '';
1851
			}
1852
			else
1853
				list ($posterOptions['name'], $posterOptions['email']) = $smcFunc['db_fetch_row']($request);
1854
			$smcFunc['db_free_result']($request);
1855
		}
1856
		else
1857
		{
1858
			$posterOptions['name'] = $user_info['name'];
1859
			$posterOptions['email'] = $user_info['email'];
1860
		}
1861
	}
1862
1863
	// Get any members who were quoted in this post.
1864
	$msgOptions['quoted_members'] = Mentions::getQuotedMembers($msgOptions['body'], $posterOptions['id']);
1865
1866
	if (!empty($modSettings['enable_mentions']))
1867
	{
1868
		// Get any members who were possibly mentioned
1869
		$msgOptions['mentioned_members'] = Mentions::getMentionedMembers($msgOptions['body']);
1870
		if (!empty($msgOptions['mentioned_members']))
1871
		{
1872
			// Replace @name with [member=id]name[/member]
1873
			$msgOptions['body'] = Mentions::getBody($msgOptions['body'], $msgOptions['mentioned_members']);
1874
1875
			// Remove any members who weren't actually mentioned, to prevent bogus notifications
1876
			$msgOptions['mentioned_members'] = Mentions::verifyMentionedMembers($msgOptions['body'], $msgOptions['mentioned_members']);
1877
		}
1878
	}
1879
1880
	// It's do or die time: forget any user aborts!
1881
	$previous_ignore_user_abort = ignore_user_abort(true);
1882
1883
	$new_topic = empty($topicOptions['id']);
1884
1885
	$message_columns = array(
1886
		'id_board' => 'int', 'id_topic' => 'int', 'id_member' => 'int', 'subject' => 'string-255', 'body' => (!empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] > 65534 ? 'string-' . $modSettings['max_messageLength'] : (empty($modSettings['max_messageLength']) ? 'string' : 'string-65534')),
1887
		'poster_name' => 'string-255', 'poster_email' => 'string-255', 'poster_time' => 'int', 'poster_ip' => 'inet',
1888
		'smileys_enabled' => 'int', 'modified_name' => 'string', 'icon' => 'string-16', 'approved' => 'int',
1889
	);
1890
1891
	$message_parameters = array(
1892
		$topicOptions['board'], $topicOptions['id'], $posterOptions['id'], $msgOptions['subject'], $msgOptions['body'],
1893
		$posterOptions['name'], $posterOptions['email'], $msgOptions['poster_time'], $posterOptions['ip'],
1894
		$msgOptions['smileys_enabled'] ? 1 : 0, '', $msgOptions['icon'], $msgOptions['approved'],
1895
	);
1896
1897
	// What if we want to do anything with posts?
1898
	call_integration_hook('integrate_create_post', array(&$msgOptions, &$topicOptions, &$posterOptions, &$message_columns, &$message_parameters));
1899
1900
	// Insert the post.
1901
	$msgOptions['id'] = $smcFunc['db_insert']('',
1902
		'{db_prefix}messages',
1903
		$message_columns,
1904
		$message_parameters,
1905
		array('id_msg'),
1906
		1
1907
	);
1908
1909
	// Something went wrong creating the message...
1910
	if (empty($msgOptions['id']))
1911
		return false;
1912
1913
	// Fix the attachments.
1914
	if (!empty($msgOptions['attachments']))
1915
		$smcFunc['db_query']('', '
1916
			UPDATE {db_prefix}attachments
1917
			SET id_msg = {int:id_msg}
1918
			WHERE id_attach IN ({array_int:attachment_list})',
1919
			array(
1920
				'attachment_list' => $msgOptions['attachments'],
1921
				'id_msg' => $msgOptions['id'],
1922
			)
1923
		);
1924
1925
	// What if we want to export new posts out to a CMS?
1926
	call_integration_hook('integrate_after_create_post', array($msgOptions, $topicOptions, $posterOptions, $message_columns, $message_parameters));
1927
1928
	// Insert a new topic (if the topicID was left empty.)
1929
	if ($new_topic)
1930
	{
1931
		$topic_columns = array(
1932
			'id_board' => 'int', 'id_member_started' => 'int', 'id_member_updated' => 'int', 'id_first_msg' => 'int',
1933
			'id_last_msg' => 'int', 'locked' => 'int', 'is_sticky' => 'int', 'num_views' => 'int',
1934
			'id_poll' => 'int', 'unapproved_posts' => 'int', 'approved' => 'int',
1935
			'redirect_expires' => 'int', 'id_redirect_topic' => 'int',
1936
		);
1937
		$topic_parameters = array(
1938
			$topicOptions['board'], $posterOptions['id'], $posterOptions['id'], $msgOptions['id'],
1939
			$msgOptions['id'], $topicOptions['lock_mode'] === null ? 0 : $topicOptions['lock_mode'], $topicOptions['sticky_mode'] === null ? 0 : $topicOptions['sticky_mode'], 0,
1940
			$topicOptions['poll'] === null ? 0 : $topicOptions['poll'], $msgOptions['approved'] ? 0 : 1, $msgOptions['approved'],
1941
			$topicOptions['redirect_expires'] === null ? 0 : $topicOptions['redirect_expires'], $topicOptions['redirect_topic'] === null ? 0 : $topicOptions['redirect_topic'],
1942
		);
1943
1944
		call_integration_hook('integrate_before_create_topic', array(&$msgOptions, &$topicOptions, &$posterOptions, &$topic_columns, &$topic_parameters));
1945
1946
		$topicOptions['id'] = $smcFunc['db_insert']('',
1947
			'{db_prefix}topics',
1948
			$topic_columns,
1949
			$topic_parameters,
1950
			array('id_topic'),
1951
			1
1952
		);
1953
1954
		// The topic couldn't be created for some reason.
1955
		if (empty($topicOptions['id']))
1956
		{
1957
			// We should delete the post that did work, though...
1958
			$smcFunc['db_query']('', '
1959
				DELETE FROM {db_prefix}messages
1960
				WHERE id_msg = {int:id_msg}',
1961
				array(
1962
					'id_msg' => $msgOptions['id'],
1963
				)
1964
			);
1965
1966
			return false;
1967
		}
1968
1969
		// Fix the message with the topic.
1970
		$smcFunc['db_query']('', '
1971
			UPDATE {db_prefix}messages
1972
			SET id_topic = {int:id_topic}
1973
			WHERE id_msg = {int:id_msg}',
1974
			array(
1975
				'id_topic' => $topicOptions['id'],
1976
				'id_msg' => $msgOptions['id'],
1977
			)
1978
		);
1979
1980
		// There's been a new topic AND a new post today.
1981
		trackStats(array('topics' => '+', 'posts' => '+'));
1982
1983
		updateStats('topic', true);
1984
		updateStats('subject', $topicOptions['id'], $msgOptions['subject']);
1985
1986
		// What if we want to export new topics out to a CMS?
1987
		call_integration_hook('integrate_create_topic', array(&$msgOptions, &$topicOptions, &$posterOptions));
1988
	}
1989
	// The topic already exists, it only needs a little updating.
1990
	else
1991
	{
1992
		$update_parameters = array(
1993
			'poster_id' => $posterOptions['id'],
1994
			'id_msg' => $msgOptions['id'],
1995
			'locked' => $topicOptions['lock_mode'],
1996
			'is_sticky' => $topicOptions['sticky_mode'],
1997
			'id_topic' => $topicOptions['id'],
1998
			'counter_increment' => 1,
1999
		);
2000
		if ($msgOptions['approved'])
2001
			$topics_columns = array(
2002
				'id_member_updated = {int:poster_id}',
2003
				'id_last_msg = {int:id_msg}',
2004
				'num_replies = num_replies + {int:counter_increment}',
2005
			);
2006
		else
2007
			$topics_columns = array(
2008
				'unapproved_posts = unapproved_posts + {int:counter_increment}',
2009
			);
2010
		if ($topicOptions['lock_mode'] !== null)
2011
			$topics_columns[] = 'locked = {int:locked}';
2012
		if ($topicOptions['sticky_mode'] !== null)
2013
			$topics_columns[] = 'is_sticky = {int:is_sticky}';
2014
2015
		call_integration_hook('integrate_modify_topic', array(&$topics_columns, &$update_parameters, &$msgOptions, &$topicOptions, &$posterOptions));
2016
2017
		// Update the number of replies and the lock/sticky status.
2018
		$smcFunc['db_query']('', '
2019
			UPDATE {db_prefix}topics
2020
			SET
2021
				' . implode(', ', $topics_columns) . '
2022
			WHERE id_topic = {int:id_topic}',
2023
			$update_parameters
2024
		);
2025
2026
		// One new post has been added today.
2027
		trackStats(array('posts' => '+'));
2028
	}
2029
2030
	// Creating is modifying...in a way.
2031
	// @todo Why not set id_msg_modified on the insert?
2032
	$smcFunc['db_query']('', '
2033
		UPDATE {db_prefix}messages
2034
		SET id_msg_modified = {int:id_msg}
2035
		WHERE id_msg = {int:id_msg}',
2036
		array(
2037
			'id_msg' => $msgOptions['id'],
2038
		)
2039
	);
2040
2041
	// Increase the number of posts and topics on the board.
2042
	if ($msgOptions['approved'])
2043
		$smcFunc['db_query']('', '
2044
			UPDATE {db_prefix}boards
2045
			SET num_posts = num_posts + 1' . ($new_topic ? ', num_topics = num_topics + 1' : '') . '
2046
			WHERE id_board = {int:id_board}',
2047
			array(
2048
				'id_board' => $topicOptions['board'],
2049
			)
2050
		);
2051
	else
2052
	{
2053
		$smcFunc['db_query']('', '
2054
			UPDATE {db_prefix}boards
2055
			SET unapproved_posts = unapproved_posts + 1' . ($new_topic ? ', unapproved_topics = unapproved_topics + 1' : '') . '
2056
			WHERE id_board = {int:id_board}',
2057
			array(
2058
				'id_board' => $topicOptions['board'],
2059
			)
2060
		);
2061
2062
		// Add to the approval queue too.
2063
		$smcFunc['db_insert']('',
2064
			'{db_prefix}approval_queue',
2065
			array(
2066
				'id_msg' => 'int',
2067
			),
2068
			array(
2069
				$msgOptions['id'],
2070
			),
2071
			array()
2072
		);
2073
2074
		$smcFunc['db_insert']('',
2075
			'{db_prefix}background_tasks',
2076
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
2077
			array(
2078
				'$sourcedir/tasks/ApprovePost-Notify.php', 'ApprovePost_Notify_Background', $smcFunc['json_encode'](array(
2079
					'msgOptions' => $msgOptions,
2080
					'topicOptions' => $topicOptions,
2081
					'posterOptions' => $posterOptions,
2082
					'type' => $new_topic ? 'topic' : 'post',
2083
				)), 0
2084
			),
2085
			array('id_task')
2086
		);
2087
	}
2088
2089
	// Mark inserted topic as read (only for the user calling this function).
2090
	if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest'])
2091
	{
2092
		// Since it's likely they *read* it before replying, let's try an UPDATE first.
2093
		if (!$new_topic)
2094
		{
2095
			$smcFunc['db_query']('', '
2096
				UPDATE {db_prefix}log_topics
2097
				SET id_msg = {int:id_msg}
2098
				WHERE id_member = {int:current_member}
2099
					AND id_topic = {int:id_topic}',
2100
				array(
2101
					'current_member' => $posterOptions['id'],
2102
					'id_msg' => $msgOptions['id'],
2103
					'id_topic' => $topicOptions['id'],
2104
				)
2105
			);
2106
2107
			$flag = $smcFunc['db_affected_rows']() != 0;
2108
		}
2109
2110
		if (empty($flag))
2111
		{
2112
			$smcFunc['db_insert']('ignore',
2113
				'{db_prefix}log_topics',
2114
				array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'),
2115
				array($topicOptions['id'], $posterOptions['id'], $msgOptions['id']),
2116
				array('id_topic', 'id_member')
2117
			);
2118
		}
2119
	}
2120
2121
	if ($msgOptions['approved'] && empty($topicOptions['is_approved']) && $posterOptions['id'] != $user_info['id'])
2122
		$smcFunc['db_insert']('',
2123
			'{db_prefix}background_tasks',
2124
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
2125
			array(
2126
				'$sourcedir/tasks/ApproveReply-Notify.php', 'ApproveReply_Notify_Background', $smcFunc['json_encode'](array(
2127
					'msgOptions' => $msgOptions,
2128
					'topicOptions' => $topicOptions,
2129
					'posterOptions' => $posterOptions,
2130
				)), 0
2131
			),
2132
			array('id_task')
2133
		);
2134
2135
	// If there's a custom search index, it may need updating...
2136
	require_once($sourcedir . '/Search.php');
2137
	$searchAPI = findSearchAPI();
2138
	if (is_callable(array($searchAPI, 'postCreated')))
2139
		$searchAPI->postCreated($msgOptions, $topicOptions, $posterOptions);
2140
2141
	// Increase the post counter for the user that created the post.
2142
	if (!empty($posterOptions['update_post_count']) && !empty($posterOptions['id']) && $msgOptions['approved'])
2143
	{
2144
		// Are you the one that happened to create this post?
2145
		if ($user_info['id'] == $posterOptions['id'])
2146
			$user_info['posts']++;
2147
		updateMemberData($posterOptions['id'], array('posts' => '+'));
2148
	}
2149
2150
	// They've posted, so they can make the view count go up one if they really want. (this is to keep views >= replies...)
2151
	$_SESSION['last_read_topic'] = 0;
2152
2153
	// Better safe than sorry.
2154
	if (isset($_SESSION['topicseen_cache'][$topicOptions['board']]))
2155
		$_SESSION['topicseen_cache'][$topicOptions['board']]--;
2156
2157
	// Keep track of quotes and mentions.
2158
	if (!empty($msgOptions['quoted_members']))
2159
		Mentions::insertMentions('quote', $msgOptions['id'], $msgOptions['quoted_members'], $posterOptions['id']);
2160
	if (!empty($msgOptions['mentioned_members']))
2161
		Mentions::insertMentions('msg', $msgOptions['id'], $msgOptions['mentioned_members'], $posterOptions['id']);
2162
2163
	// Update all the stats so everyone knows about this new topic and message.
2164
	updateStats('message', true, $msgOptions['id']);
2165
2166
	// Update the last message on the board assuming it's approved AND the topic is.
2167
	if ($msgOptions['approved'])
2168
		updateLastMessages($topicOptions['board'], $new_topic || !empty($topicOptions['is_approved']) ? $msgOptions['id'] : 0);
2169
2170
	// Queue createPost background notification
2171
	if ($msgOptions['send_notifications'] && $msgOptions['approved'])
2172
		$smcFunc['db_insert']('',
2173
			'{db_prefix}background_tasks',
2174
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
2175
			array('$sourcedir/tasks/CreatePost-Notify.php', 'CreatePost_Notify_Background', $smcFunc['json_encode'](array(
2176
				'msgOptions' => $msgOptions,
2177
				'topicOptions' => $topicOptions,
2178
				'posterOptions' => $posterOptions,
2179
				'type' => $new_topic ? 'topic' : 'reply',
2180
			)), 0),
2181
			array('id_task')
2182
		);
2183
2184
	// Alright, done now... we can abort now, I guess... at least this much is done.
2185
	ignore_user_abort($previous_ignore_user_abort);
0 ignored issues
show
Bug introduced by
$previous_ignore_user_abort of type integer is incompatible with the type boolean|null expected by parameter $enable of ignore_user_abort(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2185
	ignore_user_abort(/** @scrutinizer ignore-type */ $previous_ignore_user_abort);
Loading history...
2186
2187
	// Success.
2188
	return true;
2189
}
2190
2191
/**
2192
 * Modifying a post...
2193
 *
2194
 * @param array &$msgOptions An array of information/options for the post
2195
 * @param array &$topicOptions An array of information/options for the topic
2196
 * @param array &$posterOptions An array of information/options for the poster
2197
 * @return bool Whether the post was modified successfully
2198
 */
2199
function modifyPost(&$msgOptions, &$topicOptions, &$posterOptions)
2200
{
2201
	global $user_info, $modSettings, $smcFunc, $sourcedir;
2202
2203
	$topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null;
2204
	$topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null;
2205
	$topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null;
2206
2207
	// This is longer than it has to be, but makes it so we only set/change what we have to.
2208
	$messages_columns = array();
2209
	if (isset($posterOptions['name']))
2210
		$messages_columns['poster_name'] = $posterOptions['name'];
2211
	if (isset($posterOptions['email']))
2212
		$messages_columns['poster_email'] = $posterOptions['email'];
2213
	if (isset($msgOptions['icon']))
2214
		$messages_columns['icon'] = $msgOptions['icon'];
2215
	if (isset($msgOptions['subject']))
2216
		$messages_columns['subject'] = $msgOptions['subject'];
2217
	if (isset($msgOptions['body']))
2218
	{
2219
		$messages_columns['body'] = $msgOptions['body'];
2220
2221
		// using a custom search index, then lets get the old message so we can update our index as needed
2222
		if (!empty($modSettings['search_custom_index_config']))
2223
		{
2224
			$request = $smcFunc['db_query']('', '
2225
				SELECT body
2226
				FROM {db_prefix}messages
2227
				WHERE id_msg = {int:id_msg}',
2228
				array(
2229
					'id_msg' => $msgOptions['id'],
2230
				)
2231
			);
2232
			list ($msgOptions['old_body']) = $smcFunc['db_fetch_row']($request);
2233
			$smcFunc['db_free_result']($request);
2234
		}
2235
	}
2236
	if (!empty($msgOptions['modify_time']))
2237
	{
2238
		$messages_columns['modified_time'] = $msgOptions['modify_time'];
2239
		$messages_columns['modified_name'] = $msgOptions['modify_name'];
2240
		$messages_columns['modified_reason'] = $msgOptions['modify_reason'];
2241
		$messages_columns['id_msg_modified'] = $modSettings['maxMsgID'];
2242
	}
2243
	if (isset($msgOptions['smileys_enabled']))
2244
		$messages_columns['smileys_enabled'] = empty($msgOptions['smileys_enabled']) ? 0 : 1;
2245
2246
	// Which columns need to be ints?
2247
	$messageInts = array('modified_time', 'id_msg_modified', 'smileys_enabled');
2248
	$update_parameters = array(
2249
		'id_msg' => $msgOptions['id'],
2250
	);
2251
2252
	// Update search api
2253
	require_once($sourcedir . '/Search.php');
2254
	$searchAPI = findSearchAPI();
2255
	if ($searchAPI->supportsMethod('postRemoved'))
2256
		$searchAPI->postRemoved($msgOptions['id']);
2257
2258
	// Anyone quoted or mentioned?
2259
	require_once($sourcedir . '/Mentions.php');
2260
2261
	$quoted_members = Mentions::getQuotedMembers($msgOptions['body'], $posterOptions['id']);
2262
	$quoted_modifications = Mentions::modifyMentions('quote', $msgOptions['id'], $quoted_members, $posterOptions['id']);
2263
2264
	if (!empty($quoted_modifications['added']))
2265
	{
2266
		$msgOptions['quoted_members'] = array_intersect_key($quoted_members, array_flip(array_keys($quoted_modifications['added'])));
2267
2268
		// You don't need a notification about quoting yourself.
2269
		unset($msgOptions['quoted_members'][$user_info['id']]);
2270
	}
2271
2272
	if (!empty($modSettings['enable_mentions']) && isset($msgOptions['body']))
2273
	{
2274
		$mentions = Mentions::getMentionedMembers($msgOptions['body']);
2275
		$messages_columns['body'] = $msgOptions['body'] = Mentions::getBody($msgOptions['body'], $mentions);
2276
		$mentions = Mentions::verifyMentionedMembers($msgOptions['body'], $mentions);
2277
2278
		// Update our records in the database.
2279
		$mention_modifications = Mentions::modifyMentions('msg', $msgOptions['id'], $mentions, $posterOptions['id']);
2280
2281
		if (!empty($mention_modifications['added']))
2282
		{
2283
			// Queue this for notification.
2284
			$msgOptions['mentioned_members'] = array_intersect_key($mentions, array_flip(array_keys($mention_modifications['added'])));
2285
2286
			// Mentioning yourself is silly, and we aren't going to notify you about it.
2287
			unset($msgOptions['mentioned_members'][$user_info['id']]);
2288
		}
2289
	}
2290
2291
	// This allows mods to skip sending notifications if they don't want to.
2292
	$msgOptions['send_notifications'] = isset($msgOptions['send_notifications']) ? (bool) $msgOptions['send_notifications'] : true;
2293
2294
	// Maybe a mod wants to make some changes?
2295
	call_integration_hook('integrate_modify_post', array(&$messages_columns, &$update_parameters, &$msgOptions, &$topicOptions, &$posterOptions, &$messageInts));
2296
2297
	foreach ($messages_columns as $var => $val)
2298
	{
2299
		$messages_columns[$var] = $var . ' = {' . (in_array($var, $messageInts) ? 'int' : 'string') . ':var_' . $var . '}';
2300
		$update_parameters['var_' . $var] = $val;
2301
	}
2302
2303
	// Nothing to do?
2304
	if (empty($messages_columns))
2305
		return true;
2306
2307
	// Change the post.
2308
	$smcFunc['db_query']('', '
2309
		UPDATE {db_prefix}messages
2310
		SET ' . implode(', ', $messages_columns) . '
2311
		WHERE id_msg = {int:id_msg}',
2312
		$update_parameters
2313
	);
2314
2315
	// Lock and or sticky the post.
2316
	if ($topicOptions['sticky_mode'] !== null || $topicOptions['lock_mode'] !== null || $topicOptions['poll'] !== null)
2317
	{
2318
		$smcFunc['db_query']('', '
2319
			UPDATE {db_prefix}topics
2320
			SET
2321
				is_sticky = {raw:is_sticky},
2322
				locked = {raw:locked},
2323
				id_poll = {raw:id_poll}
2324
			WHERE id_topic = {int:id_topic}',
2325
			array(
2326
				'is_sticky' => $topicOptions['sticky_mode'] === null ? 'is_sticky' : (int) $topicOptions['sticky_mode'],
2327
				'locked' => $topicOptions['lock_mode'] === null ? 'locked' : (int) $topicOptions['lock_mode'],
2328
				'id_poll' => $topicOptions['poll'] === null ? 'id_poll' : (int) $topicOptions['poll'],
2329
				'id_topic' => $topicOptions['id'],
2330
			)
2331
		);
2332
	}
2333
2334
	// Mark the edited post as read.
2335
	if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest'])
2336
	{
2337
		// Since it's likely they *read* it before editing, let's try an UPDATE first.
2338
		$smcFunc['db_query']('', '
2339
			UPDATE {db_prefix}log_topics
2340
			SET id_msg = {int:id_msg}
2341
			WHERE id_member = {int:current_member}
2342
				AND id_topic = {int:id_topic}',
2343
			array(
2344
				'current_member' => $user_info['id'],
2345
				'id_msg' => $modSettings['maxMsgID'],
2346
				'id_topic' => $topicOptions['id'],
2347
			)
2348
		);
2349
2350
		$flag = $smcFunc['db_affected_rows']() != 0;
2351
2352
		if (empty($flag))
2353
		{
2354
			$smcFunc['db_insert']('ignore',
2355
				'{db_prefix}log_topics',
2356
				array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'),
2357
				array($topicOptions['id'], $user_info['id'], $modSettings['maxMsgID']),
2358
				array('id_topic', 'id_member')
2359
			);
2360
		}
2361
	}
2362
2363
	// If there's a custom search index, it needs to be modified...
2364
	require_once($sourcedir . '/Search.php');
2365
	$searchAPI = findSearchAPI();
2366
	if (is_callable(array($searchAPI, 'postModified')))
2367
		$searchAPI->postModified($msgOptions, $topicOptions, $posterOptions);
2368
2369
	// Send notifications about any new quotes or mentions.
2370
	if ($msgOptions['send_notifications'] && !empty($msgOptions['approved']) && (!empty($msgOptions['quoted_members']) || !empty($msgOptions['mentioned_members']) || !empty($mention_modifications['removed']) || !empty($quoted_modifications['removed'])))
2371
	{
2372
		$smcFunc['db_insert']('',
2373
			'{db_prefix}background_tasks',
2374
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
2375
			array('$sourcedir/tasks/CreatePost-Notify.php', 'CreatePost_Notify_Background', $smcFunc['json_encode'](array(
2376
				'msgOptions' => $msgOptions,
2377
				'topicOptions' => $topicOptions,
2378
				'posterOptions' => $posterOptions,
2379
				'type' => 'edit',
2380
			)), 0),
2381
			array('id_task')
2382
		);
2383
	}
2384
2385
	if (isset($msgOptions['subject']))
2386
	{
2387
		// Only update the subject if this was the first message in the topic.
2388
		$request = $smcFunc['db_query']('', '
2389
			SELECT id_topic
2390
			FROM {db_prefix}topics
2391
			WHERE id_first_msg = {int:id_first_msg}
2392
			LIMIT 1',
2393
			array(
2394
				'id_first_msg' => $msgOptions['id'],
2395
			)
2396
		);
2397
		if ($smcFunc['db_num_rows']($request) == 1)
2398
			updateStats('subject', $topicOptions['id'], $msgOptions['subject']);
2399
		$smcFunc['db_free_result']($request);
2400
	}
2401
2402
	// Finally, if we are setting the approved state we need to do much more work :(
2403
	if ($modSettings['postmod_active'] && isset($msgOptions['approved']))
2404
		approvePosts($msgOptions['id'], $msgOptions['approved']);
2405
2406
	return true;
2407
}
2408
2409
/**
2410
 * Approve (or not) some posts... without permission checks...
2411
 *
2412
 * @param array $msgs Array of message ids
2413
 * @param bool $approve Whether to approve the posts (if false, posts are unapproved)
2414
 * @param bool $notify Whether to notify users
2415
 * @return bool Whether the operation was successful
2416
 */
2417
function approvePosts($msgs, $approve = true, $notify = true)
2418
{
2419
	global $smcFunc;
2420
2421
	if (!is_array($msgs))
0 ignored issues
show
introduced by
The condition is_array($msgs) is always true.
Loading history...
2422
		$msgs = array($msgs);
2423
2424
	if (empty($msgs))
2425
		return false;
2426
2427
	// May as well start at the beginning, working out *what* we need to change.
2428
	$request = $smcFunc['db_query']('', '
2429
		SELECT m.id_msg, m.approved, m.id_topic, m.id_board, t.id_first_msg, t.id_last_msg,
2430
			m.body, m.subject, COALESCE(mem.real_name, m.poster_name) AS poster_name, m.id_member,
2431
			t.approved AS topic_approved, b.count_posts
2432
		FROM {db_prefix}messages AS m
2433
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
2434
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
2435
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
2436
		WHERE m.id_msg IN ({array_int:message_list})
2437
			AND m.approved = {int:approved_state}',
2438
		array(
2439
			'message_list' => $msgs,
2440
			'approved_state' => $approve ? 0 : 1,
2441
		)
2442
	);
2443
	$msgs = array();
2444
	$topics = array();
2445
	$topic_changes = array();
2446
	$board_changes = array();
2447
	$notification_topics = array();
2448
	$notification_posts = array();
2449
	$member_post_changes = array();
2450
	while ($row = $smcFunc['db_fetch_assoc']($request))
2451
	{
2452
		// Easy...
2453
		$msgs[] = $row['id_msg'];
2454
		$topics[] = $row['id_topic'];
2455
2456
		// Ensure our change array exists already.
2457
		if (!isset($topic_changes[$row['id_topic']]))
2458
			$topic_changes[$row['id_topic']] = array(
2459
				'id_last_msg' => $row['id_last_msg'],
2460
				'approved' => $row['topic_approved'],
2461
				'replies' => 0,
2462
				'unapproved_posts' => 0,
2463
			);
2464
		if (!isset($board_changes[$row['id_board']]))
2465
			$board_changes[$row['id_board']] = array(
2466
				'posts' => 0,
2467
				'topics' => 0,
2468
				'unapproved_posts' => 0,
2469
				'unapproved_topics' => 0,
2470
			);
2471
2472
		// If it's the first message then the topic state changes!
2473
		if ($row['id_msg'] == $row['id_first_msg'])
2474
		{
2475
			$topic_changes[$row['id_topic']]['approved'] = $approve ? 1 : 0;
2476
2477
			$board_changes[$row['id_board']]['unapproved_topics'] += $approve ? -1 : 1;
2478
			$board_changes[$row['id_board']]['topics'] += $approve ? 1 : -1;
2479
2480
			// Note we need to ensure we announce this topic!
2481
			$notification_topics[] = array(
2482
				'body' => $row['body'],
2483
				'subject' => $row['subject'],
2484
				'name' => $row['poster_name'],
2485
				'board' => $row['id_board'],
2486
				'topic' => $row['id_topic'],
2487
				'msg' => $row['id_first_msg'],
2488
				'poster' => $row['id_member'],
2489
				'new_topic' => true,
2490
			);
2491
		}
2492
		else
2493
		{
2494
			$topic_changes[$row['id_topic']]['replies'] += $approve ? 1 : -1;
2495
2496
			// This will be a post... but don't notify unless it's not followed by approved ones.
2497
			if ($row['id_msg'] > $row['id_last_msg'])
2498
				$notification_posts[$row['id_topic']] = array(
2499
					'id' => $row['id_msg'],
2500
					'body' => $row['body'],
2501
					'subject' => $row['subject'],
2502
					'name' => $row['poster_name'],
2503
					'topic' => $row['id_topic'],
2504
					'board' => $row['id_board'],
2505
					'poster' => $row['id_member'],
2506
					'new_topic' => false,
2507
					'msg' => $row['id_msg'],
2508
				);
2509
		}
2510
2511
		// If this is being approved and id_msg is higher than the current id_last_msg then it changes.
2512
		if ($approve && $row['id_msg'] > $topic_changes[$row['id_topic']]['id_last_msg'])
2513
			$topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_msg'];
2514
		// If this is being unapproved, and it's equal to the id_last_msg we need to find a new one!
2515
		elseif (!$approve)
2516
			// Default to the first message and then we'll override in a bit ;)
2517
			$topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_first_msg'];
2518
2519
		$topic_changes[$row['id_topic']]['unapproved_posts'] += $approve ? -1 : 1;
2520
		$board_changes[$row['id_board']]['unapproved_posts'] += $approve ? -1 : 1;
2521
		$board_changes[$row['id_board']]['posts'] += $approve ? 1 : -1;
2522
2523
		// Post count for the user?
2524
		if ($row['id_member'] && empty($row['count_posts']))
2525
			$member_post_changes[$row['id_member']] = isset($member_post_changes[$row['id_member']]) ? $member_post_changes[$row['id_member']] + 1 : 1;
2526
	}
2527
	$smcFunc['db_free_result']($request);
2528
2529
	if (empty($msgs))
2530
		return;
2531
2532
	// Now we have the differences make the changes, first the easy one.
2533
	$smcFunc['db_query']('', '
2534
		UPDATE {db_prefix}messages
2535
		SET approved = {int:approved_state}
2536
		WHERE id_msg IN ({array_int:message_list})',
2537
		array(
2538
			'message_list' => $msgs,
2539
			'approved_state' => $approve ? 1 : 0,
2540
		)
2541
	);
2542
2543
	// If we were unapproving find the last msg in the topics...
2544
	if (!$approve)
2545
	{
2546
		$request = $smcFunc['db_query']('', '
2547
			SELECT id_topic, MAX(id_msg) AS id_last_msg
2548
			FROM {db_prefix}messages
2549
			WHERE id_topic IN ({array_int:topic_list})
2550
				AND approved = {int:approved}
2551
			GROUP BY id_topic',
2552
			array(
2553
				'topic_list' => $topics,
2554
				'approved' => 1,
2555
			)
2556
		);
2557
		while ($row = $smcFunc['db_fetch_assoc']($request))
2558
			$topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_last_msg'];
2559
		$smcFunc['db_free_result']($request);
2560
	}
2561
2562
	// ... next the topics...
2563
	foreach ($topic_changes as $id => $changes)
2564
		$smcFunc['db_query']('', '
2565
			UPDATE {db_prefix}topics
2566
			SET approved = {int:approved}, unapproved_posts = unapproved_posts + {int:unapproved_posts},
2567
				num_replies = num_replies + {int:num_replies}, id_last_msg = {int:id_last_msg}
2568
			WHERE id_topic = {int:id_topic}',
2569
			array(
2570
				'approved' => $changes['approved'],
2571
				'unapproved_posts' => $changes['unapproved_posts'],
2572
				'num_replies' => $changes['replies'],
2573
				'id_last_msg' => $changes['id_last_msg'],
2574
				'id_topic' => $id,
2575
			)
2576
		);
2577
2578
	// ... finally the boards...
2579
	foreach ($board_changes as $id => $changes)
2580
		$smcFunc['db_query']('', '
2581
			UPDATE {db_prefix}boards
2582
			SET num_posts = num_posts + {int:num_posts}, unapproved_posts = unapproved_posts + {int:unapproved_posts},
2583
				num_topics = num_topics + {int:num_topics}, unapproved_topics = unapproved_topics + {int:unapproved_topics}
2584
			WHERE id_board = {int:id_board}',
2585
			array(
2586
				'num_posts' => $changes['posts'],
2587
				'unapproved_posts' => $changes['unapproved_posts'],
2588
				'num_topics' => $changes['topics'],
2589
				'unapproved_topics' => $changes['unapproved_topics'],
2590
				'id_board' => $id,
2591
			)
2592
		);
2593
2594
	// Finally, least importantly, notifications!
2595
	if ($approve)
2596
	{
2597
		$task_rows = array();
2598
		foreach (array_merge($notification_topics, $notification_posts) as $topic)
2599
			$task_rows[] = array(
2600
				'$sourcedir/tasks/CreatePost-Notify.php', 'CreatePost_Notify_Background', $smcFunc['json_encode'](array(
2601
					'msgOptions' => array(
2602
						'id' => $topic['msg'],
2603
						'body' => $topic['body'],
2604
						'subject' => $topic['subject'],
2605
					),
2606
					'topicOptions' => array(
2607
						'id' => $topic['topic'],
2608
						'board' => $topic['board'],
2609
					),
2610
					'posterOptions' => array(
2611
						'id' => $topic['poster'],
2612
						'name' => $topic['name'],
2613
					),
2614
					'type' => $topic['new_topic'] ? 'topic' : 'reply',
2615
				)), 0
2616
			);
2617
2618
		if ($notify)
2619
			$smcFunc['db_insert']('',
2620
				'{db_prefix}background_tasks',
2621
				array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
2622
				$task_rows,
2623
				array('id_task')
2624
			);
2625
2626
		$smcFunc['db_query']('', '
2627
			DELETE FROM {db_prefix}approval_queue
2628
			WHERE id_msg IN ({array_int:message_list})
2629
				AND id_attach = {int:id_attach}',
2630
			array(
2631
				'message_list' => $msgs,
2632
				'id_attach' => 0,
2633
			)
2634
		);
2635
2636
		// Clean up moderator alerts
2637
		if (!empty($notification_topics))
2638
			clearApprovalAlerts(array_column($notification_topics, 'topic'), 'unapproved_topic');
2639
		if (!empty($notification_posts))
2640
			clearApprovalAlerts(array_column($notification_posts, 'id'), 'unapproved_post');
2641
	}
2642
	// If unapproving add to the approval queue!
2643
	else
2644
	{
2645
		$msgInserts = array();
2646
		foreach ($msgs as $msg)
2647
			$msgInserts[] = array($msg);
2648
2649
		$smcFunc['db_insert']('ignore',
2650
			'{db_prefix}approval_queue',
2651
			array('id_msg' => 'int'),
2652
			$msgInserts,
2653
			array('id_msg')
2654
		);
2655
	}
2656
2657
	// Update the last messages on the boards...
2658
	updateLastMessages(array_keys($board_changes));
2659
2660
	// Post count for the members?
2661
	if (!empty($member_post_changes))
2662
		foreach ($member_post_changes as $id_member => $count_change)
2663
			updateMemberData($id_member, array('posts' => 'posts ' . ($approve ? '+' : '-') . ' ' . $count_change));
2664
2665
	// In case an external CMS needs to know about this approval/unapproval.
2666
	call_integration_hook('integrate_after_approve_posts', array($approve, $msgs, $topic_changes, $member_post_changes));
2667
2668
	return true;
2669
}
2670
2671
/**
2672
 * Approve topics?
2673
 *
2674
 * @todo shouldn't this be in topic
2675
 *
2676
 * @param array $topics Array of topic ids
2677
 * @param bool $approve Whether to approve the topics. If false, unapproves them instead
2678
 * @return bool Whether the operation was successful
2679
 */
2680
function approveTopics($topics, $approve = true)
2681
{
2682
	global $smcFunc;
2683
2684
	if (!is_array($topics))
0 ignored issues
show
introduced by
The condition is_array($topics) is always true.
Loading history...
2685
		$topics = array($topics);
2686
2687
	if (empty($topics))
2688
		return false;
2689
2690
	$approve_type = $approve ? 0 : 1;
2691
2692
	// Just get the messages to be approved and pass through...
2693
	$request = $smcFunc['db_query']('', '
2694
		SELECT id_first_msg
2695
		FROM {db_prefix}topics
2696
		WHERE id_topic IN ({array_int:topic_list})
2697
			AND approved = {int:approve_type}',
2698
		array(
2699
			'topic_list' => $topics,
2700
			'approve_type' => $approve_type,
2701
		)
2702
	);
2703
	$msgs = array();
2704
	while ($row = $smcFunc['db_fetch_assoc']($request))
2705
		$msgs[] = $row['id_first_msg'];
2706
	$smcFunc['db_free_result']($request);
2707
2708
	return approvePosts($msgs, $approve);
2709
}
2710
2711
/**
2712
 * Upon approval, clear unread alerts.
2713
 *
2714
 * @param int[] $content_ids either id_msgs or id_topics
2715
 * @param string $content_action will be either 'unapproved_post' or 'unapproved_topic'
2716
 * @return void
2717
 */
2718
function clearApprovalAlerts($content_ids, $content_action)
2719
{
2720
	global $smcFunc;
2721
2722
	// Some data hygiene...
2723
	if (!is_array($content_ids))
0 ignored issues
show
introduced by
The condition is_array($content_ids) is always true.
Loading history...
2724
		return;
2725
	$content_ids = array_filter(array_map('intval', $content_ids));
2726
	if (empty($content_ids))
2727
		return;
2728
2729
	if (!in_array($content_action, array('unapproved_post', 'unapproved_topic')))
2730
		return;
2731
2732
	// Check to see if there are unread alerts to delete...
2733
	// Might be multiple alerts, for multiple moderators...
2734
	$alerts = array();
2735
	$moderators = array();
2736
	$result = $smcFunc['db_query']('', '
2737
		SELECT id_alert, id_member FROM {db_prefix}user_alerts
2738
		WHERE content_id IN ({array_int:content_ids})
2739
			AND content_type = {string:content_type}
2740
			AND content_action = {string:content_action}
2741
			AND is_read = {int:unread}',
2742
		array(
2743
			'content_ids' => $content_ids,
2744
			'content_type' => $content_action === 'unapproved_topic' ? 'topic' : 'msg',
2745
			'content_action' => $content_action,
2746
			'unread' => 0,
2747
		)
2748
	);
2749
	// Found any?
2750
	while ($row = $smcFunc['db_fetch_assoc']($result))
2751
	{
2752
		$alerts[] = $row['id_alert'];
2753
		$moderators[] = $row['id_member'];
2754
	}
2755
	if (!empty($alerts))
2756
	{
2757
		// Delete 'em
2758
		$smcFunc['db_query']('', '
2759
			DELETE FROM {db_prefix}user_alerts
2760
			WHERE id_alert IN ({array_int:alerts})',
2761
			array(
2762
				'alerts' => $alerts,
2763
			)
2764
		);
2765
		// Decrement counter for each moderator who received an alert
2766
		updateMemberData($moderators, array('alerts' => '-'));
2767
	}
2768
}
2769
2770
/**
2771
 * Takes an array of board IDs and updates their last messages.
2772
 * If the board has a parent, that parent board is also automatically
2773
 * updated.
2774
 * The columns updated are id_last_msg and last_updated.
2775
 * Note that id_last_msg should always be updated using this function,
2776
 * and is not automatically updated upon other changes.
2777
 *
2778
 * @param array $setboards An array of board IDs
2779
 * @param int $id_msg The ID of the message
2780
 * @return void|false Returns false if $setboards is empty for some reason
2781
 */
2782
function updateLastMessages($setboards, $id_msg = 0)
2783
{
2784
	global $board_info, $board, $smcFunc;
2785
2786
	// Please - let's be sane.
2787
	if (empty($setboards))
2788
		return false;
2789
2790
	if (!is_array($setboards))
0 ignored issues
show
introduced by
The condition is_array($setboards) is always true.
Loading history...
2791
		$setboards = array($setboards);
2792
2793
	// If we don't know the id_msg we need to find it.
2794
	if (!$id_msg)
2795
	{
2796
		// Find the latest message on this board (highest id_msg.)
2797
		$request = $smcFunc['db_query']('', '
2798
			SELECT id_board, MAX(id_last_msg) AS id_msg
2799
			FROM {db_prefix}topics
2800
			WHERE id_board IN ({array_int:board_list})
2801
				AND approved = {int:approved}
2802
			GROUP BY id_board',
2803
			array(
2804
				'board_list' => $setboards,
2805
				'approved' => 1,
2806
			)
2807
		);
2808
		$lastMsg = array();
2809
		while ($row = $smcFunc['db_fetch_assoc']($request))
2810
			$lastMsg[$row['id_board']] = $row['id_msg'];
2811
		$smcFunc['db_free_result']($request);
2812
	}
2813
	else
2814
	{
2815
		// Just to note - there should only be one board passed if we are doing this.
2816
		foreach ($setboards as $id_board)
2817
			$lastMsg[$id_board] = $id_msg;
2818
	}
2819
2820
	$parent_boards = array();
2821
	// Keep track of last modified dates.
2822
	$lastModified = $lastMsg;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $lastMsg does not seem to be defined for all execution paths leading up to this point.
Loading history...
2823
	// Get all the child boards for the parents, if they have some...
2824
	foreach ($setboards as $id_board)
2825
	{
2826
		if (!isset($lastMsg[$id_board]))
2827
		{
2828
			$lastMsg[$id_board] = 0;
2829
			$lastModified[$id_board] = 0;
2830
		}
2831
2832
		if (!empty($board) && $id_board == $board)
2833
			$parents = $board_info['parent_boards'];
2834
		else
2835
			$parents = getBoardParents($id_board);
2836
2837
		// Ignore any parents on the top child level.
2838
		// @todo Why?
2839
		foreach ($parents as $id => $parent)
2840
		{
2841
			if ($parent['level'] != 0)
2842
			{
2843
				// If we're already doing this one as a board, is this a higher last modified?
2844
				if (isset($lastModified[$id]) && $lastModified[$id_board] > $lastModified[$id])
2845
					$lastModified[$id] = $lastModified[$id_board];
2846
				elseif (!isset($lastModified[$id]) && (!isset($parent_boards[$id]) || $parent_boards[$id] < $lastModified[$id_board]))
2847
					$parent_boards[$id] = $lastModified[$id_board];
2848
			}
2849
		}
2850
	}
2851
2852
	// Note to help understand what is happening here. For parents we update the timestamp of the last message for determining
2853
	// whether there are child boards which have not been read. For the boards themselves we update both this and id_last_msg.
2854
2855
	$board_updates = array();
2856
	$parent_updates = array();
2857
	// Finally, to save on queries make the changes...
2858
	foreach ($parent_boards as $id => $msg)
2859
	{
2860
		if (!isset($parent_updates[$msg]))
2861
			$parent_updates[$msg] = array($id);
2862
		else
2863
			$parent_updates[$msg][] = $id;
2864
	}
2865
2866
	foreach ($lastMsg as $id => $msg)
2867
	{
2868
		if (!isset($board_updates[$msg . '-' . $lastModified[$id]]))
2869
			$board_updates[$msg . '-' . $lastModified[$id]] = array(
2870
				'id' => $msg,
2871
				'updated' => $lastModified[$id],
2872
				'boards' => array($id)
2873
			);
2874
2875
		else
2876
			$board_updates[$msg . '-' . $lastModified[$id]]['boards'][] = $id;
2877
	}
2878
2879
	// Now commit the changes!
2880
	foreach ($parent_updates as $id_msg => $boards)
2881
	{
2882
		$smcFunc['db_query']('', '
2883
			UPDATE {db_prefix}boards
2884
			SET id_msg_updated = {int:id_msg_updated}
2885
			WHERE id_board IN ({array_int:board_list})
2886
				AND id_msg_updated < {int:id_msg_updated}',
2887
			array(
2888
				'board_list' => $boards,
2889
				'id_msg_updated' => $id_msg,
2890
			)
2891
		);
2892
	}
2893
	foreach ($board_updates as $board_data)
2894
	{
2895
		$smcFunc['db_query']('', '
2896
			UPDATE {db_prefix}boards
2897
			SET id_last_msg = {int:id_last_msg}, id_msg_updated = {int:id_msg_updated}
2898
			WHERE id_board IN ({array_int:board_list})',
2899
			array(
2900
				'board_list' => $board_data['boards'],
2901
				'id_last_msg' => $board_data['id'],
2902
				'id_msg_updated' => $board_data['updated'],
2903
			)
2904
		);
2905
	}
2906
}
2907
2908
/**
2909
 * This simple function gets a list of all administrators and sends them an email
2910
 *  to let them know a new member has joined.
2911
 * Called by registerMember() function in Subs-Members.php.
2912
 * Email is sent to all groups that have the moderate_forum permission.
2913
 * The language set by each member is being used (if available).
2914
 * Uses the Login language file
2915
 *
2916
 * @param string $type The type. Types supported are 'approval', 'activation', and 'standard'.
2917
 * @param int $memberID The ID of the member
2918
 * @param string $member_name The name of the member (if null, it is pulled from the database)
2919
 */
2920
function adminNotify($type, $memberID, $member_name = null)
2921
{
2922
	global $smcFunc;
2923
2924
	if ($member_name == null)
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $member_name of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
2925
	{
2926
		// Get the new user's name....
2927
		$request = $smcFunc['db_query']('', '
2928
			SELECT real_name
2929
			FROM {db_prefix}members
2930
			WHERE id_member = {int:id_member}
2931
			LIMIT 1',
2932
			array(
2933
				'id_member' => $memberID,
2934
			)
2935
		);
2936
		list ($member_name) = $smcFunc['db_fetch_row']($request);
2937
		$smcFunc['db_free_result']($request);
2938
	}
2939
2940
	// This is really just a wrapper for making a new background task to deal with all the fun.
2941
	$smcFunc['db_insert']('insert',
2942
		'{db_prefix}background_tasks',
2943
		array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
2944
		array('$sourcedir/tasks/Register-Notify.php', 'Register_Notify_Background', $smcFunc['json_encode'](array(
2945
			'new_member_id' => $memberID,
2946
			'new_member_name' => $member_name,
2947
			'notify_type' => $type,
2948
			'time' => time(),
2949
		)), 0),
2950
		array('id_task')
2951
	);
2952
}
2953
2954
/**
2955
 * Load a template from EmailTemplates language file.
2956
 *
2957
 * @param string $template The name of the template to load
2958
 * @param array $replacements An array of replacements for the variables in the template
2959
 * @param string $lang The language to use, if different than the user's current language
2960
 * @param bool $loadLang Whether to load the language file first
2961
 * @return array An array containing the subject and body of the email template, with replacements made
2962
 */
2963
function loadEmailTemplate($template, $replacements = array(), $lang = '', $loadLang = true)
2964
{
2965
	global $txt, $mbname, $scripturl, $settings, $context;
2966
2967
	// First things first, load up the email templates language file, if we need to.
2968
	if ($loadLang)
2969
		loadLanguage('EmailTemplates', $lang);
2970
2971
	if (!isset($txt[$template . '_subject']) || !isset($txt[$template . '_body']))
2972
		fatal_lang_error('email_no_template', 'template', array($template));
2973
2974
	$ret = array(
2975
		'subject' => $txt[$template . '_subject'],
2976
		'body' => $txt[$template . '_body'],
2977
		'is_html' => !empty($txt[$template . '_html']),
2978
	);
2979
2980
	// Add in the default replacements.
2981
	$replacements += array(
2982
		'FORUMNAME' => $mbname,
2983
		'SCRIPTURL' => $scripturl,
2984
		'THEMEURL' => $settings['theme_url'],
2985
		'IMAGESURL' => $settings['images_url'],
2986
		'DEFAULT_THEMEURL' => $settings['default_theme_url'],
2987
		'REGARDS' => sprintf($txt['regards_team'], $context['forum_name']),
2988
	);
2989
2990
	// Split the replacements up into two arrays, for use with str_replace
2991
	$find = array();
2992
	$replace = array();
2993
2994
	foreach ($replacements as $f => $r)
2995
	{
2996
		$find[] = '{' . $f . '}';
2997
		$replace[] = $r;
2998
	}
2999
3000
	// Do the variable replacements.
3001
	$ret['subject'] = str_replace($find, $replace, $ret['subject']);
3002
	$ret['body'] = str_replace($find, $replace, $ret['body']);
3003
3004
	// Now deal with the {USER.variable} items.
3005
	$ret['subject'] = preg_replace_callback('~{USER.([^}]+)}~', 'user_info_callback', $ret['subject']);
3006
	$ret['body'] = preg_replace_callback('~{USER.([^}]+)}~', 'user_info_callback', $ret['body']);
3007
3008
	// Finally return the email to the caller so they can send it out.
3009
	return $ret;
3010
}
3011
3012
/**
3013
 * Callback function for loademaitemplate on subject and body
3014
 * Uses capture group 1 in array
3015
 *
3016
 * @param array $matches An array of matches
3017
 * @return string The match
3018
 */
3019
function user_info_callback($matches)
3020
{
3021
	global $user_info;
3022
	if (empty($matches[1]))
3023
		return '';
3024
3025
	$use_ref = true;
3026
	$ref = &$user_info;
3027
3028
	foreach (explode('.', $matches[1]) as $index)
3029
	{
3030
		if ($use_ref && isset($ref[$index]))
3031
			$ref = &$ref[$index];
3032
		else
3033
		{
3034
			$use_ref = false;
3035
			break;
3036
		}
3037
	}
3038
3039
	return $use_ref ? $ref : $matches[0];
3040
}
3041
3042
/**
3043
 * spell_init()
3044
 *
3045
 * Sets up a dictionary resource handle. Tries enchant first then falls through to pspell.
3046
 *
3047
 * @return resource|bool An enchant or pspell dictionary resource handle or false if the dictionary couldn't be loaded
3048
 */
3049
function spell_init()
3050
{
3051
	global $context, $txt;
3052
3053
	// Check for UTF-8 and strip ".utf8" off the lang_locale string for enchant
3054
	$context['spell_utf8'] = ($txt['lang_character_set'] == 'UTF-8');
3055
	$lang_locale = str_replace('.utf8', '', $txt['lang_locale']);
3056
3057
	// Try enchant first since PSpell is (supposedly) deprecated as of PHP 5.3
3058
	// enchant only does UTF-8, so we need iconv if you aren't using UTF-8
3059
	if (function_exists('enchant_broker_init') && ($context['spell_utf8'] || function_exists('iconv')))
3060
	{
3061
		// We'll need this to free resources later...
3062
		$context['enchant_broker'] = enchant_broker_init();
3063
3064
		// Try locale first, then general...
3065
		if (!empty($lang_locale) && enchant_broker_dict_exists($context['enchant_broker'], $lang_locale))
3066
		{
3067
			$enchant_link = enchant_broker_request_dict($context['enchant_broker'], $lang_locale);
3068
		}
3069
		elseif (enchant_broker_dict_exists($context['enchant_broker'], $txt['lang_dictionary']))
3070
		{
3071
			$enchant_link = enchant_broker_request_dict($context['enchant_broker'], $txt['lang_dictionary']);
3072
		}
3073
3074
		// Success
3075
		if (!empty($enchant_link))
3076
		{
3077
			$context['provider'] = 'enchant';
3078
			return $enchant_link;
3079
		}
3080
		else
3081
		{
3082
			// Free up any resources used...
3083
			@enchant_broker_free($context['enchant_broker']);
3084
		}
3085
	}
3086
3087
	// Fall through to pspell if enchant didn't work
3088
	if (function_exists('pspell_new'))
3089
	{
3090
		// Okay, this looks funny, but it actually fixes a weird bug.
3091
		ob_start();
3092
		$old = error_reporting(0);
3093
3094
		// See, first, some windows machines don't load pspell properly on the first try.  Dumb, but this is a workaround.
3095
		pspell_new('en');
3096
3097
		// Next, the dictionary in question may not exist. So, we try it... but...
3098
		$pspell_link = pspell_new($txt['lang_dictionary'], '', '', strtr($context['character_set'], array('iso-' => 'iso', 'ISO-' => 'iso')), PSPELL_FAST | PSPELL_RUN_TOGETHER);
3099
3100
		// Most people don't have anything but English installed... So we use English as a last resort.
3101
		if (!$pspell_link)
3102
			$pspell_link = pspell_new('en', '', '', '', PSPELL_FAST | PSPELL_RUN_TOGETHER);
3103
3104
		error_reporting($old);
3105
		ob_end_clean();
3106
3107
		// If we have pspell, exit now...
3108
		if ($pspell_link)
3109
		{
3110
			$context['provider'] = 'pspell';
3111
			return $pspell_link;
3112
		}
3113
	}
3114
3115
	// If we get this far, we're doomed
3116
	return false;
3117
}
3118
3119
/**
3120
 * spell_check()
3121
 *
3122
 * Determines whether or not the specified word is spelled correctly
3123
 *
3124
 * @param resource $dict An enchant or pspell dictionary resource set up by {@link spell_init()}
3125
 * @param string $word A word to check the spelling of
3126
 * @return bool Whether or not the specified word is spelled properly
3127
 */
3128
function spell_check($dict, $word)
3129
{
3130
	global $context, $txt;
3131
3132
	// Enchant or pspell?
3133
	if ($context['provider'] == 'enchant')
3134
	{
3135
		// This is a bit tricky here...
3136
		if (!$context['spell_utf8'])
3137
		{
3138
			// Convert the word to UTF-8 with iconv
3139
			$word = iconv($txt['lang_character_set'], 'UTF-8', $word);
3140
		}
3141
		return enchant_dict_check($dict, $word);
3142
	}
3143
	elseif ($context['provider'] == 'pspell')
3144
	{
3145
		return pspell_check($dict, $word);
0 ignored issues
show
Bug introduced by
$dict of type resource is incompatible with the type integer expected by parameter $dictionary_link of pspell_check(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3145
		return pspell_check(/** @scrutinizer ignore-type */ $dict, $word);
Loading history...
3146
	}
3147
}
3148
3149
/**
3150
 * spell_suggest()
3151
 *
3152
 * Returns an array of suggested replacements for the specified word
3153
 *
3154
 * @param resource $dict An enchant or pspell dictionary resource
3155
 * @param string $word A misspelled word
3156
 * @return array An array of suggested replacements for the misspelled word
3157
 */
3158
function spell_suggest($dict, $word)
3159
{
3160
	global $context, $txt;
3161
3162
	if ($context['provider'] == 'enchant')
3163
	{
3164
		// If we're not using UTF-8, we need iconv to handle some stuff...
3165
		if (!$context['spell_utf8'])
3166
		{
3167
			// Convert the word to UTF-8 before getting suggestions
3168
			$word = iconv($txt['lang_character_set'], 'UTF-8', $word);
3169
			$suggestions = enchant_dict_suggest($dict, $word);
3170
3171
			// Go through the suggestions and convert them back to the proper character set
3172
			foreach ($suggestions as $index => $suggestion)
3173
			{
3174
				// //TRANSLIT makes it use similar-looking characters for incompatible ones...
3175
				$suggestions[$index] = iconv('UTF-8', $txt['lang_character_set'] . '//TRANSLIT', $suggestion);
3176
			}
3177
3178
			return $suggestions;
3179
		}
3180
		else
3181
		{
3182
			return enchant_dict_suggest($dict, $word);
3183
		}
3184
	}
3185
	elseif ($context['provider'] == 'pspell')
3186
	{
3187
		return pspell_suggest($dict, $word);
0 ignored issues
show
Bug introduced by
$dict of type resource is incompatible with the type integer expected by parameter $dictionary_link of pspell_suggest(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3187
		return pspell_suggest(/** @scrutinizer ignore-type */ $dict, $word);
Loading history...
3188
	}
3189
}
3190
3191
?>