Passed
Pull Request — release-2.1 (#5778)
by Fran
03:34
created
Severity
1
<?php
2
3
/**
4
 * This is a slightly strange file. It is not designed to ever be run directly from within SMF's
5
 * conventional running, but called externally to facilitate background tasks. It can be called
6
 * either directly or via cron, and in either case will completely ignore anything supplied
7
 * via command line, or $_GET, $_POST, $_COOKIE etc. because those things should never affect the
8
 * running of this script.
9
 *
10
 * Because of the way this runs, etc. we do need some of SMF but not everything to try to keep this
11
 * running a little bit faster.
12
 *
13
 * Simple Machines Forum (SMF)
14
 *
15
 * @package SMF
16
 * @author Simple Machines http://www.simplemachines.org
17
 * @copyright 2019 Simple Machines and individual contributors
18
 * @license http://www.simplemachines.org/about/smf/license.php BSD
19
 *
20
 * @version 2.1 RC2
21
 */
22
23
define('SMF', 'BACKGROUND');
24
define('SMF_VERSION', '2.1 RC2');
25
define('SMF_FULL_VERSION', 'SMF ' . SMF_VERSION);
26
define('SMF_SOFTWARE_YEAR', '2019');
27
define('FROM_CLI', empty($_SERVER['REQUEST_METHOD']));
28
define('JQUERY_VERSION', '3.4.1');
29
30
// This one setting is worth bearing in mind. If you are running this from proper cron, make sure you
31
// don't run this file any more frequently than indicated here. It might turn ugly if you do.
32
// But on proper cron you can always increase this value provided you don't go beyond max_limit.
33
define('MAX_CRON_TIME', 10);
34
// If a task fails for whatever reason it will still be marked as claimed. This is the threshold
35
// by which if a task has not completed in this time, the task should become available again.
36
define('MAX_CLAIM_THRESHOLD', 300);
37
38
// We're going to want a few globals... these are all set later.
39
global $time_start, $maintenance, $msubject, $mmessage, $mbname, $language;
40
global $boardurl, $boarddir, $sourcedir, $webmaster_email;
41
global $db_server, $db_name, $db_user, $db_prefix, $db_persist, $db_error_send, $db_last_error;
42
global $db_connection, $modSettings, $context, $sc, $user_info, $txt;
43
global $smcFunc, $ssi_db_user, $scripturl, $db_passwd, $cachedir;
44
45
define('TIME_START', microtime(true));
46
47
// Just being safe...
48
foreach (array('db_character_set', 'cachedir') as $variable)
49
	if (isset($GLOBALS[$variable]))
50
		unset($GLOBALS[$variable]);
51
52
// Get the forum's settings for database and file paths.
53
require_once(dirname(__FILE__) . '/Settings.php');
54
55
// Make absolutely sure the cache directory is defined.
56
if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache'))
57
	$cachedir = $boarddir . '/cache';
58
59
// Don't do john didley if the forum's been shut down completely.
60
if ($maintenance == 2)
61
	die($mmessage);
62
63
// Fix for using the current directory as a path.
64
if (substr($sourcedir, 0, 1) == '.' && substr($sourcedir, 1, 1) != '.')
65
	$sourcedir = dirname(__FILE__) . substr($sourcedir, 1);
66
67
// Have we already turned this off? If so, exist gracefully.
68
if (file_exists($cachedir . '/cron.lock'))
69
	obExit_cron();
70
71
// Before we go any further, if this is not a CLI request, we need to do some checking.
72
if (!FROM_CLI)
73
{
74
	// When using sub-domains with SSI and ssi_themes set, browsers will receive a "Access-Control-Allow-Origin" error.
75
	// * is not ideal but the best method to preventing this from occurring.
76
	header('Access-Control-Allow-Origin: *');
77
78
	// We will clean up $_GET shortly. But we want to this ASAP.
79
	$ts = isset($_GET['ts']) ? (int) $_GET['ts'] : 0;
80
	if ($ts <= 0 || $ts % 15 != 0 || time() - $ts < 0 || time() - $ts > 20)
81
		obExit_cron();
82
}
83
84
// Load the most important includes. In general, a background should be loading its own dependencies.
85
require_once($sourcedir . '/Errors.php');
86
require_once($sourcedir . '/Load.php');
87
require_once($sourcedir . '/Security.php');
88
require_once($sourcedir . '/Subs.php');
89
90
// Create a variable to store some SMF specific functions in.
91
$smcFunc = array();
92
93
// This is our general bootstrap, a la SSI.php but with a few differences.
94
unset ($db_show_debug);
95
loadDatabase();
96
reloadSettings();
97
98
// Just in case there's a problem...
99
set_error_handler('smf_error_handler_cron');
100
$sc = '';
101
$_SERVER['QUERY_STRING'] = '';
102
$_SERVER['REQUEST_URL'] = FROM_CLI ? 'CLI cron.php' : $boardurl . '/cron.php';
103
104
// Now 'clean the request' (or more accurately, ignore everything we're not going to use)
105
cleanRequest_cron();
106
107
// At this point we could reseed the RNG but I don't think we need to risk it being seeded *even more*.
108
// Meanwhile, time we got on with the real business here.
109
while ($task_details = fetch_task())
110
{
111
	$result = perform_task($task_details);
112
	if ($result)
113
	{
114
		$smcFunc['db_query']('', '
115
			DELETE FROM {db_prefix}background_tasks
116
			WHERE id_task = {int:task}',
117
			array(
118
				'task' => $task_details['id_task'],
119
			)
120
		);
121
	}
122
}
123
obExit_cron();
124
exit;
125
126
/**
127
 * The heart of this cron handler...
128
 *
129
 * @return bool|array False if there's nothing to do or an array of info about the task
130
 */
131
function fetch_task()
132
{
133
	global $smcFunc;
134
135
	// Check we haven't run over our time limit.
136
	if (microtime(true) - TIME_START > MAX_CRON_TIME)
137
		return false;
138
139
	// Try to find a task. Specifically, try to find one that hasn't been claimed previously, or failing that,
140
	// a task that was claimed but failed for whatever reason and failed long enough ago. We should not care
141
	// what task it is, merely that it is one in the queue, the order is irrelevant.
142
	$request = $smcFunc['db_query']('', '
143
		SELECT id_task, task_file, task_class, task_data, claimed_time
144
		FROM {db_prefix}background_tasks
145
		WHERE claimed_time < {int:claim_limit}
146
		LIMIT 1',
147
		array(
148
			'claim_limit' => time() - MAX_CLAIM_THRESHOLD,
149
		)
150
	);
151
	if ($row = $smcFunc['db_fetch_assoc']($request))
152
	{
153
		// We found one. Let's try and claim it immediately.
154
		$smcFunc['db_free_result']($request);
155
		$smcFunc['db_query']('', '
156
			UPDATE {db_prefix}background_tasks
157
			SET claimed_time = {int:new_claimed}
158
			WHERE id_task = {int:task}
159
				AND claimed_time = {int:old_claimed}',
160
			array(
161
				'new_claimed' => time(),
162
				'task' => $row['id_task'],
163
				'old_claimed' => $row['claimed_time'],
164
			)
165
		);
166
		// Could we claim it? If so, return it back.
167
		if ($smcFunc['db_affected_rows']() != 0)
168
		{
169
			// Update the time and go back.
170
			$row['claimed_time'] = time();
171
			return $row;
172
		}
173
		else
174
		{
175
			// Uh oh, we just missed it. Try to claim another one, and let it fall through if there aren't any.
176
			return fetch_task();
177
		}
178
	}
179
	else
180
	{
181
		// No dice. Clean up and go home.
182
		$smcFunc['db_free_result']($request);
183
		return false;
184
	}
185
}
186
187
/**
188
 * This actually handles the task
189
 *
190
 * @param array $task_details An array of info about the task
191
 * @return bool|void True if the task is invalid; otherwise calls the function to execute the task
192
 */
193
function perform_task($task_details)
194
{
195
	global $smcFunc, $sourcedir, $boarddir;
196
197
	// This indicates the file to load.
198
	if (!empty($task_details['task_file']))
199
	{
200
		$include = strtr(trim($task_details['task_file']), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir));
201
		if (file_exists($include))
202
			require_once($include);
203
	}
204
205
	if (empty($task_details['task_class']))
206
	{
207
		// This would be nice to translate but the language files aren't loaded for any specific language.
208
		log_error('Invalid background task specified (no class, ' . (empty($task_details['task_file']) ? ' no file' : ' to load ' . $task_details['task_file']) . ')');
209
		return true; // So we clear it from the queue.
210
	}
211
212
	// All background tasks need to be classes.
213
	elseif (class_exists($task_details['task_class']) && is_subclass_of($task_details['task_class'], 'SMF_BackgroundTask'))
214
	{
215
		$details = empty($task_details['task_data']) ? array() : $smcFunc['json_decode']($task_details['task_data'], true);
216
		$bgtask = new $task_details['task_class']($details);
217
		return $bgtask->execute();
218
	}
219
	else
220
	{
221
		log_error('Invalid background task specified: (class: ' . $task_details['task_class'] . ', ' . (empty($task_details['task_file']) ? ' no file' : ' to load ' . $task_details['task_file']) . ')');
222
		return true; // So we clear it from the queue.
223
	}
224
}
225
226
// These are all our helper functions that resemble their big brother counterparts. These are not so important.
227
/**
228
 * Cleans up the request variables
229
 *
230
 * @return void
231
 */
232
function cleanRequest_cron()
233
{
234
	global $scripturl, $boardurl;
235
236
	$scripturl = $boardurl . '/index.php';
237
238
	// These keys shouldn't be set...ever.
239
	if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']))
240
		die('Invalid request variable.');
0 ignored issues
show
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...
241
242
	// Save some memory.. (since we don't use these anyway.)
243
	unset($GLOBALS['HTTP_POST_VARS'], $GLOBALS['HTTP_POST_VARS']);
244
	unset($GLOBALS['HTTP_POST_FILES'], $GLOBALS['HTTP_POST_FILES']);
245
	unset($GLOBALS['_GET'], $GLOBALS['_POST'], $GLOBALS['_REQUEST'], $GLOBALS['_COOKIE'], $GLOBALS['_FILES']);
246
}
247
248
/**
249
 * The error handling function
250
 *
251
 * @param int $error_level One of the PHP error level constants (see )
252
 * @param string $error_string The error message
253
 * @param string $file The file where the error occurred
254
 * @param int $line What line of the specified file the error occurred on
255
 * @return void
256
 */
257
function smf_error_handler_cron($error_level, $error_string, $file, $line)
258
{
259
	global $modSettings;
260
261
	// Ignore errors if we're ignoring them or they are strict notices from PHP 5
262
	if (error_reporting() == 0)
263
		return;
264
265
	$error_type = 'cron';
266
267
	log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
268
269
	// If this is an E_ERROR or E_USER_ERROR.... die.  Violently so.
270
	if ($error_level % 255 == E_ERROR)
271
		die('No direct access...');
0 ignored issues
show
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...
272
}
273
274
/**
275
 * The exit function
276
 */
277
function obExit_cron()
278
{
279
	if (FROM_CLI)
280
		die(0);
0 ignored issues
show
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...
281
	else
282
	{
283
		header('content-type: image/gif');
284
		die("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B");
285
	}
286
}
287
288
// We would like this to be defined, but we don't want to have to load more stuff than necessary.
289
// Thus we declare it here, and any legitimate background task must implement this.
290
/**
291
 * Class SMF_BackgroundTask
292
 */
293
abstract class SMF_BackgroundTask
294
{
295
	/**
296
	 * Constants for notfication types.
297
	*/
298
	const RECEIVE_NOTIFY_EMAIL = 0x02;
299
	const RECEIVE_NOTIFY_ALERT = 0x01;
300
301
	/**
302
	 * @var array Holds the details for the task
303
	 */
304
	protected $_details;
305
306
	/**
307
	 * The constructor.
308
	 *
309
	 * @param array $details The details for the task
310
	 */
311
	public function __construct($details)
312
	{
313
		$this->_details = $details;
314
	}
315
316
	/**
317
	 * The function to actually execute a task
318
	 *
319
	 * @return mixed
320
	 */
321
	abstract public function execute();
322
}
323
324
?>