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