Completed
Pull Request — release-2.1 (#5644)
by Mathias
05:15
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
	// We will clean up $_GET shortly. But we want to this ASAP.
74
	$ts = isset($_GET['ts']) ? (int) $_GET['ts'] : 0;
75
	if ($ts <= 0 || $ts % 15 != 0 || time() - $ts < 0 || time() - $ts > 20)
76
		obExit_cron();
77
}
78
79
// Load the most important includes. In general, a background should be loading its own dependencies.
80
require_once($sourcedir . '/Errors.php');
81
require_once($sourcedir . '/Load.php');
82
require_once($sourcedir . '/Security.php');
83
require_once($sourcedir . '/Subs.php');
84
85
// Create a variable to store some SMF specific functions in.
86
$smcFunc = array();
87
88
// This is our general bootstrap, a la SSI.php but with a few differences.
89
unset ($db_show_debug);
90
loadDatabase();
91
reloadSettings();
92
93
// Just in case there's a problem...
94
set_error_handler('smf_error_handler_cron');
95
$sc = '';
96
$_SERVER['QUERY_STRING'] = '';
97
$_SERVER['REQUEST_URL'] = FROM_CLI ? 'CLI cron.php' : $boardurl . '/cron.php';
98
99
// Now 'clean the request' (or more accurately, ignore everything we're not going to use)
100
cleanRequest_cron();
101
102
// At this point we could reseed the RNG but I don't think we need to risk it being seeded *even more*.
103
// Meanwhile, time we got on with the real business here.
104
while ($task_details = fetch_task())
105
{
106
	$result = perform_task($task_details);
107
	if ($result)
108
	{
109
		$smcFunc['db_query']('', '
110
			DELETE FROM {db_prefix}background_tasks
111
			WHERE id_task = {int:task}',
112
			array(
113
				'task' => $task_details['id_task'],
114
			)
115
		);
116
	}
117
}
118
obExit_cron();
119
exit;
120
121
/**
122
 * The heart of this cron handler...
123
 *
124
 * @return bool|array False if there's nothing to do or an array of info about the task
125
 */
126
function fetch_task()
127
{
128
	global $smcFunc;
129
130
	// Check we haven't run over our time limit.
131
	if (microtime(true) - TIME_START > MAX_CRON_TIME)
132
		return false;
133
134
	// Try to find a task. Specifically, try to find one that hasn't been claimed previously, or failing that,
135
	// a task that was claimed but failed for whatever reason and failed long enough ago. We should not care
136
	// what task it is, merely that it is one in the queue, the order is irrelevant.
137
	$request = $smcFunc['db_query']('', '
138
		SELECT id_task, task_file, task_class, task_data, claimed_time
139
		FROM {db_prefix}background_tasks
140
		WHERE claimed_time < {int:claim_limit}
141
		LIMIT 1',
142
		array(
143
			'claim_limit' => time() - MAX_CLAIM_THRESHOLD,
144
		)
145
	);
146
	if ($row = $smcFunc['db_fetch_assoc']($request))
147
	{
148
		// We found one. Let's try and claim it immediately.
149
		$smcFunc['db_free_result']($request);
150
		$smcFunc['db_query']('', '
151
			UPDATE {db_prefix}background_tasks
152
			SET claimed_time = {int:new_claimed}
153
			WHERE id_task = {int:task}
154
				AND claimed_time = {int:old_claimed}',
155
			array(
156
				'new_claimed' => time(),
157
				'task' => $row['id_task'],
158
				'old_claimed' => $row['claimed_time'],
159
			)
160
		);
161
		// Could we claim it? If so, return it back.
162
		if ($smcFunc['db_affected_rows']() != 0)
163
		{
164
			// Update the time and go back.
165
			$row['claimed_time'] = time();
166
			return $row;
167
		}
168
		else
169
		{
170
			// Uh oh, we just missed it. Try to claim another one, and let it fall through if there aren't any.
171
			return fetch_task();
172
		}
173
	}
174
	else
175
	{
176
		// No dice. Clean up and go home.
177
		$smcFunc['db_free_result']($request);
178
		return false;
179
	}
180
}
181
182
/**
183
 * This actually handles the task
184
 *
185
 * @param array $task_details An array of info about the task
186
 * @return bool|void True if the task is invalid; otherwise calls the function to execute the task
187
 */
188
function perform_task($task_details)
189
{
190
	global $smcFunc, $sourcedir, $boarddir;
191
192
	// This indicates the file to load.
193
	if (!empty($task_details['task_file']))
194
	{
195
		$include = strtr(trim($task_details['task_file']), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir));
196
		if (file_exists($include))
197
			require_once($include);
198
	}
199
200
	if (empty($task_details['task_class']))
201
	{
202
		// This would be nice to translate but the language files aren't loaded for any specific language.
203
		log_error('Invalid background task specified (no class, ' . (empty($task_details['task_file']) ? ' no file' : ' to load ' . $task_details['task_file']) . ')');
204
		return true; // So we clear it from the queue.
205
	}
206
207
	// All background tasks need to be classes.
208
	elseif (class_exists($task_details['task_class']) && is_subclass_of($task_details['task_class'], 'SMF_BackgroundTask'))
209
	{
210
		$details = empty($task_details['task_data']) ? array() : $smcFunc['json_decode']($task_details['task_data'], true);
211
		$bgtask = new $task_details['task_class']($details);
212
		return $bgtask->execute();
213
	}
214
	else
215
	{
216
		log_error('Invalid background task specified: (class: ' . $task_details['task_class'] . ', ' . (empty($task_details['task_file']) ? ' no file' : ' to load ' . $task_details['task_file']) . ')');
217
		return true; // So we clear it from the queue.
218
	}
219
}
220
221
// These are all our helper functions that resemble their big brother counterparts. These are not so important.
222
/**
223
 * Cleans up the request variables
224
 *
225
 * @return void
226
 */
227
function cleanRequest_cron()
228
{
229
	global $scripturl, $boardurl;
230
231
	$scripturl = $boardurl . '/index.php';
232
233
	// These keys shouldn't be set...ever.
234
	if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']))
235
		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...
236
237
	// Save some memory.. (since we don't use these anyway.)
238
	unset($GLOBALS['HTTP_POST_VARS'], $GLOBALS['HTTP_POST_VARS']);
239
	unset($GLOBALS['HTTP_POST_FILES'], $GLOBALS['HTTP_POST_FILES']);
240
	unset($GLOBALS['_GET'], $GLOBALS['_POST'], $GLOBALS['_REQUEST'], $GLOBALS['_COOKIE'], $GLOBALS['_FILES']);
241
}
242
243
/**
244
 * The error handling function
245
 *
246
 * @param int $error_level One of the PHP error level constants (see )
247
 * @param string $error_string The error message
248
 * @param string $file The file where the error occurred
249
 * @param int $line What line of the specified file the error occurred on
250
 * @return void
251
 */
252
function smf_error_handler_cron($error_level, $error_string, $file, $line)
253
{
254
	global $modSettings;
255
256
	// Ignore errors if we're ignoring them or they are strict notices from PHP 5
257
	if (error_reporting() == 0)
258
		return;
259
260
	$error_type = 'cron';
261
262
	log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
263
264
	// If this is an E_ERROR or E_USER_ERROR.... die.  Violently so.
265
	if ($error_level % 255 == E_ERROR)
266
		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...
267
}
268
269
/**
270
 * The exit function
271
 */
272
function obExit_cron()
273
{
274
	if (FROM_CLI)
275
		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...
276
	else
277
	{
278
		header('content-type: image/gif');
279
		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");
280
	}
281
}
282
283
// We would like this to be defined, but we don't want to have to load more stuff than necessary.
284
// Thus we declare it here, and any legitimate background task must implement this.
285
/**
286
 * Class SMF_BackgroundTask
287
 */
288
abstract class SMF_BackgroundTask
289
{
290
	/**
291
	 * Constants for notfication types.
292
	*/
293
	const RECEIVE_NOTIFY_EMAIL = 0x02;
294
	const RECEIVE_NOTIFY_ALERT = 0x01;
295
296
	/**
297
	 * @var array Holds the details for the task
298
	 */
299
	protected $_details;
300
301
	/**
302
	 * The constructor.
303
	 *
304
	 * @param array $details The details for the task
305
	 */
306
	public function __construct($details)
307
	{
308
		$this->_details = $details;
309
	}
310
311
	/**
312
	 * The function to actually execute a task
313
	 *
314
	 * @return mixed
315
	 */
316
	abstract public function execute();
317
}
318
319
?>