Passed
Pull Request — release-2.1 (#5917)
by Mathias
05:40
created

smf_error_handler_cron()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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