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