Passed
Push — patch_1-1-7 ( 90a951...ab62ad )
by Emanuele
04:23 queued 03:46
created

compareVersions()   F

Complexity

Conditions 23
Paths 10537

Size

Total Lines 51
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 26
nc 10537
nop 2
dl 0
loc 51
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This contains functions for handling tar.gz and .zip files
5
 *
6
 * @name      ElkArte Forum
7
 * @copyright ElkArte Forum contributors
8
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
9
 *
10
 * This file contains code covered by:
11
 * copyright:	2011 Simple Machines (http://www.simplemachines.org)
12
 * license:  	BSD, See included LICENSE.TXT for terms and conditions.
13
 *
14
 * @version 1.1.4
15
 *
16
 */
17
18
/**
19
 * Reads a .tar.gz file, filename, in and extracts file(s) from it.
20
 * essentially just a shortcut for read_tgz_data().
21
 *
22
 * @package Packages
23
 * @param string $gzfilename
24
 * @param string $destination
25
 * @param bool $single_file = false
26
 * @param bool $overwrite = false
27
 * @param string[]|null $files_to_extract = null
28
 * @return array|false
29
 */
30
function read_tgz_file($gzfilename, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
31
{
32
	// From a web site
33
	if (substr($gzfilename, 0, 7) === 'http://' || substr($gzfilename, 0, 8) === 'https://')
34
	{
35
		$data = fetch_web_data($gzfilename);
36
37
		if ($data === false)
0 ignored issues
show
introduced by
The condition $data === false is always false.
Loading history...
38
			return false;
39
	}
40
	// Or a file on the system
41
	else
42
	{
43
		$data = @file_get_contents($gzfilename);
44
45
		if ($data === false)
46
			return false;
47
	}
48
49
	return read_tgz_data($data, $destination, $single_file, $overwrite, $files_to_extract);
50
}
51
52
/**
53
 * Extracts a file or files from the .tar.gz contained in data.
54
 *
55
 * - Detects if the file is really a .zip file, and if so returns the result of read_zip_data
56
 *
57
 * if destination is null
58
 * - returns a list of files in the archive.
59
 *
60
 * if single_file is true
61
 * - returns the contents of the file specified by destination, if it exists, or false.
62
 * - destination can start with * and / to signify that the file may come from any directory.
63
 * - destination should not begin with a / if single_file is true.
64
 *
65
 * - existing files with newer modification times if and only if overwrite is true.
66
 * - creates the destination directory if it doesn't exist, and is is specified.
67
 * - requires zlib support be built into PHP.
68
 * - returns an array of the files extracted on success
69
 * - if files_to_extract is not equal to null only extracts the files within this array.
70
 *
71
 * @package Packages
72
 * @param string $data
73
 * @param string $destination
74
 * @param bool $single_file = false,
75
 * @param bool $overwrite = false,
76
 * @param string[]|null $files_to_extract = null
77
 * @return array|false
78
 */
79
function read_tgz_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
80
{
81
	require_once(SUBSDIR . '/UnTgz.class.php');
82
	$untgz = new UnTgz($data, $destination, $single_file, $overwrite, $files_to_extract);
83
84
	// Choose the right method for the file
85
	if ($untgz->check_valid_tgz())
86
		return $untgz->read_tgz_data();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $untgz->read_tgz_data() also could return the type boolean which is incompatible with the documented return type array|false.
Loading history...
87
	else
88
	{
89
		unset($untgz);
90
		return read_zip_data($data, $destination, $single_file, $overwrite, $files_to_extract);
91
	}
92
}
93
94
/**
95
 * Extract zip data.
96
 *
97
 * - If destination is null, return a listing.
98
 *
99
 * @package Packages
100
 * @param string $data
101
 * @param string $destination
102
 * @param bool $single_file
103
 * @param bool $overwrite
104
 * @param string[]|null $files_to_extract
105
 * @return array|false
106
 */
107
function read_zip_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
108
{
109
	require_once(SUBSDIR . '/UnZip.class.php');
110
	$unzip = new UnZip($data, $destination, $single_file, $overwrite, $files_to_extract);
111
112
	return $unzip->read_zip_data();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $unzip->read_zip_data() also could return the type boolean which is incompatible with the documented return type array|false.
Loading history...
113
}
114
115
/**
116
 * Checks the existence of a remote file since file_exists() does not do remote.
117
 * will return false if the file is "moved permanently" or similar.
118
 *
119
 * @package Packages
120
 * @param string $url
121
 * @return boolean true if the remote url exists.
122
 */
123
function url_exists($url)
124
{
125
	$a_url = parse_url($url);
126
127
	if (!isset($a_url['scheme']))
128
		return false;
129
130
	// Attempt to connect...
131
	$temp = '';
132
	$fid = fsockopen($a_url['host'], !isset($a_url['port']) ? 80 : $a_url['port'], $temp, $temp, 8);
0 ignored issues
show
Bug introduced by
$temp of type string is incompatible with the type integer expected by parameter $errno of fsockopen(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

132
	$fid = fsockopen($a_url['host'], !isset($a_url['port']) ? 80 : $a_url['port'], /** @scrutinizer ignore-type */ $temp, $temp, 8);
Loading history...
133
134
	// Can't make a connection
135
	if (!$fid)
0 ignored issues
show
introduced by
$fid is of type false|resource, thus it always evaluated to false.
Loading history...
136
		return false;
137
138
	// See if the file is where its supposed to be
139
	fputs($fid, 'HEAD ' . $a_url['path'] . ' HTTP/1.0' . "\r\n" . 'Host: ' . $a_url['host'] . "\r\n\r\n");
140
	$head = fread($fid, 1024);
141
	fclose($fid);
142
143
	// Check for a return code that shows the file was there
144
	return preg_match('~^HTTP/.+\s+(20[01]|30[127])~i', $head) == 1;
145
}
146
147
/**
148
 * Loads and returns an array of installed packages.
149
 *
150
 * - Gets this information from packages/installed.list.
151
 * - Returns the array of data.
152
 * - Default sort order is package_installed time
153
 *
154
 * @package Packages
155
 * @return array
156
 */
157
function loadInstalledPackages()
158
{
159
	$db = database();
160
161
	// First, check that the database is valid, installed.list is still king.
162
	$install_file = implode('', file(BOARDDIR . '/packages/installed.list'));
0 ignored issues
show
Bug introduced by
It seems like file(BOARDDIR . '/packages/installed.list') can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

162
	$install_file = implode('', /** @scrutinizer ignore-type */ file(BOARDDIR . '/packages/installed.list'));
Loading history...
163
	if (trim($install_file) == '')
164
	{
165
		$db->query('', '
166
			UPDATE {db_prefix}log_packages
167
			SET install_state = {int:not_installed}',
168
			array(
169
				'not_installed' => 0,
170
			)
171
		);
172
173
		// Don't have anything left, so send an empty array.
174
		return array();
175
	}
176
177
	// Load the packages from the database - note this is ordered by install time to ensure latest package uninstalled first.
178
	$request = $db->query('', '
179
		SELECT id_install, package_id, filename, name, version
180
		FROM {db_prefix}log_packages
181
		WHERE install_state != {int:not_installed}
182
		ORDER BY time_installed DESC',
183
		array(
184
			'not_installed' => 0,
185
		)
186
	);
187
	$installed = array();
188
	$found = array();
189
	while ($row = $db->fetch_assoc($request))
190
	{
191
		// Already found this? If so don't add it twice!
192
		if (in_array($row['package_id'], $found))
193
			continue;
194
195
		$found[] = $row['package_id'];
196
197
		$installed[] = array(
198
			'id' => $row['id_install'],
199
			'name' => $row['name'],
200
			'filename' => $row['filename'],
201
			'package_id' => $row['package_id'],
202
			'version' => $row['version'],
203
		);
204
	}
205
	$db->free_result($request);
206
207
	return $installed;
208
}
209
210
/**
211
 * Loads a package's information and returns a representative array.
212
 *
213
 * - Expects the file to be a package in packages/.
214
 * - Returns a error string if the package-info is invalid.
215
 * - Otherwise returns a basic array of id, version, filename, and similar information.
216
 * - An Xml_Array is available in 'xml'.
217
 *
218
 * @package Packages
219
 * @param string $gzfilename
220
 *
221
 * @return array|string error string on error array on success
222
 */
223
function getPackageInfo($gzfilename)
224
{
225
	$gzfilename = trim($gzfilename);
226
227
	// Extract package-info.xml from downloaded file. (*/ is used because it could be in any directory.)
228
	if (preg_match('~^https?://~i', $gzfilename) === 1)
229
		$packageInfo = read_tgz_data(fetch_web_data($gzfilename, '', true), '*/package-info.xml', true);
230
	else
231
	{
232
		// It must be in the package directory then
233
		if (!file_exists(BOARDDIR . '/packages/' . $gzfilename))
234
			return 'package_get_error_not_found';
235
236
		// Make sure an package.xml file is available
237
		if (is_file(BOARDDIR . '/packages/' . $gzfilename))
238
			$packageInfo = read_tgz_file(BOARDDIR . '/packages/' . $gzfilename, '*/package-info.xml', true);
239
		elseif (file_exists(BOARDDIR . '/packages/' . $gzfilename . '/package-info.xml'))
240
			$packageInfo = file_get_contents(BOARDDIR . '/packages/' . $gzfilename . '/package-info.xml');
241
		else
242
			return 'package_get_error_missing_xml';
243
	}
244
245
	// Nothing?
246
	if (empty($packageInfo))
247
	{
248
		// Perhaps they are trying to install a theme, lets tell them nicely this is the wrong function
249
		$packageInfo = read_tgz_file(BOARDDIR . '/packages/' . $gzfilename, '*/theme_info.xml', true);
250
		if (!empty($packageInfo))
251
			return 'package_get_error_is_theme';
252
		else
253
			return 'package_get_error_is_zero';
254
	}
255
256
	// Parse package-info.xml into an Xml_Array.
257
	$packageInfo = new Xml_Array($packageInfo);
0 ignored issues
show
Bug introduced by
It seems like $packageInfo can also be of type array<mixed,mixed>; however, parameter $data of Xml_Array::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

257
	$packageInfo = new Xml_Array(/** @scrutinizer ignore-type */ $packageInfo);
Loading history...
258
259
	// @todo Error message of some sort?
260
	if (!$packageInfo->exists('package-info[0]'))
261
		return 'package_get_error_packageinfo_corrupt';
262
263
	$packageInfo = $packageInfo->path('package-info[0]');
264
265
	// Convert packageInfo to an array for use
266
	$package = htmlspecialchars__recursive($packageInfo->to_array());
267
	$package['xml'] = $packageInfo;
268
	$package['filename'] = $gzfilename;
269
270
	// Set a default type if none was supplied in the package
271
	if (!isset($package['type']))
272
		$package['type'] = 'modification';
273
274
	return $package;
275
}
276
277
/**
278
 * Create a chmod control for chmoding files.
279
 *
280
 * @package Packages
281
 * @param string[] $chmodFiles
282
 * @param mixed[] $chmodOptions
283
 * @param boolean $restore_write_status
284
 * @return array|boolean
285
 * @throws Elk_Exception
286
 */
287
function create_chmod_control($chmodFiles = array(), $chmodOptions = array(), $restore_write_status = false)
288
{
289
	global $context, $modSettings, $package_ftp, $txt, $scripturl;
290
291
	// If we're restoring the status of existing files prepare the data.
292
	if ($restore_write_status && isset($_SESSION['pack_ftp']) && !empty($_SESSION['pack_ftp']['original_perms']))
293
	{
294
		$listOptions = array(
295
			'id' => 'restore_file_permissions',
296
			'title' => $txt['package_restore_permissions'],
297
			'get_items' => array(
298
				'function' => 'list_restoreFiles',
299
				'params' => array(
300
					!empty($_POST['restore_perms']),
301
				),
302
			),
303
			'columns' => array(
304
				'path' => array(
305
					'header' => array(
306
						'value' => $txt['package_restore_permissions_filename'],
307
					),
308
					'data' => array(
309
						'db' => 'path',
310
						'class' => 'smalltext',
311
					),
312
				),
313
				'old_perms' => array(
314
					'header' => array(
315
						'value' => $txt['package_restore_permissions_orig_status'],
316
					),
317
					'data' => array(
318
						'db' => 'old_perms',
319
						'class' => 'smalltext',
320
					),
321
				),
322
				'cur_perms' => array(
323
					'header' => array(
324
						'value' => $txt['package_restore_permissions_cur_status'],
325
					),
326
					'data' => array(
327
						'function' => function ($rowData) {
328
							global $txt;
329
330
							$formatTxt = $rowData['result'] == '' || $rowData['result'] == 'skipped' ? $txt['package_restore_permissions_pre_change'] : $txt['package_restore_permissions_post_change'];
331
							return sprintf($formatTxt, $rowData['cur_perms'], $rowData['new_perms'], $rowData['writable_message']);
332
						},
333
						'class' => 'smalltext',
334
					),
335
				),
336
				'check' => array(
337
					'header' => array(
338
						'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
339
						'class' => 'centertext',
340
					),
341
					'data' => array(
342
						'sprintf' => array(
343
							'format' => '<input type="checkbox" name="restore_files[]" value="%1$s" class="input_check" />',
344
							'params' => array(
345
								'path' => false,
346
							),
347
						),
348
						'class' => 'centertext',
349
					),
350
				),
351
				'result' => array(
352
					'header' => array(
353
						'value' => $txt['package_restore_permissions_result'],
354
					),
355
					'data' => array(
356
						'function' => function ($rowData) {
357
							global $txt;
358
359
							return $txt['package_restore_permissions_action_' . $rowData['result']];
360
						},
361
						'class' => 'smalltext',
362
					),
363
				),
364
			),
365
			'form' => array(
366
				'href' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : $scripturl . '?action=admin;area=packages;sa=perms;restore;' . $context['session_var'] . '=' . $context['session_id'],
367
			),
368
			'additional_rows' => array(
369
				array(
370
					'position' => 'below_table_data',
371
					'value' => '<input type="submit" name="restore_perms" value="' . $txt['package_restore_permissions_restore'] . '" class="right_submit" />',
372
					'class' => 'category_header',
373
				),
374
				array(
375
					'position' => 'after_title',
376
					'value' => '<span class="smalltext">' . $txt['package_restore_permissions_desc'] . '</span>',
377
				),
378
			),
379
		);
380
381
		// Work out what columns and the like to show.
382
		if (!empty($_POST['restore_perms']))
383
		{
384
			$listOptions['additional_rows'][1]['value'] = sprintf($txt['package_restore_permissions_action_done'], $scripturl . '?action=admin;area=packages;sa=perms;' . $context['session_var'] . '=' . $context['session_id']);
385
			unset($listOptions['columns']['check'], $listOptions['form'], $listOptions['additional_rows'][0]);
386
387
			$context['sub_template'] = 'show_list';
388
			$context['default_list'] = 'restore_file_permissions';
389
		}
390
		else
391
		{
392
			unset($listOptions['columns']['result']);
393
		}
394
395
		// Create the list for display.
396
		createList($listOptions);
397
398
		// If we just restored permissions then wherever we are, we are now done and dusted.
399
		if (!empty($_POST['restore_perms']))
400
			obExit();
401
	}
402
	// Otherwise, it's entirely irrelevant?
403
	elseif ($restore_write_status)
404
		return true;
405
406
	// This is where we report what we got up to.
407
	$return_data = array(
408
		'files' => array(
409
			'writable' => array(),
410
			'notwritable' => array(),
411
		),
412
	);
413
414
	// If we have some FTP information already, then let's assume it was required and try to get ourselves connected.
415
	if (!empty($_SESSION['pack_ftp']['connected']))
416
	{
417
		$package_ftp = new Ftp_Connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
418
419
		// Check for a valid connection
420
		if ($package_ftp->error !== false)
421
			unset($package_ftp, $_SESSION['pack_ftp']);
422
	}
423
424
	// Just got a submission did we?
425
	if ((empty($package_ftp) || ($package_ftp->error !== false)) && isset($_POST['ftp_username']))
426
	{
427
		$ftp = new Ftp_Connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
428
429
		// We're connected, jolly good!
430
		if ($ftp->error === false)
431
		{
432
			// Common mistake, so let's try to remedy it...
433
			if (!$ftp->chdir($_POST['ftp_path']))
434
			{
435
				$ftp_error = $ftp->last_message;
436
				$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
437
			}
438
439
			if (!in_array($_POST['ftp_path'], array('', '/')))
440
			{
441
				$ftp_root = strtr(BOARDDIR, array($_POST['ftp_path'] => ''));
442
				if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || substr($_POST['ftp_path'], 0, 1) == '/'))
443
					$ftp_root = substr($ftp_root, 0, -1);
444
			}
445
			else
446
				$ftp_root = BOARDDIR;
447
448
			$_SESSION['pack_ftp'] = array(
449
				'server' => $_POST['ftp_server'],
450
				'port' => $_POST['ftp_port'],
451
				'username' => $_POST['ftp_username'],
452
				'password' => package_crypt($_POST['ftp_password']),
453
				'path' => $_POST['ftp_path'],
454
				'root' => $ftp_root,
455
				'connected' => true,
456
			);
457
458
			if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
459
				updateSettings(array('package_path' => $_POST['ftp_path']));
460
461
			// This is now the primary connection.
462
			$package_ftp = $ftp;
463
		}
464
	}
465
466
	// Now try to simply make the files writable, with whatever we might have.
467
	if (!empty($chmodFiles))
468
	{
469
		foreach ($chmodFiles as $k => $file)
470
		{
471
			// Sometimes this can somehow happen maybe?
472
			if (empty($file))
473
				unset($chmodFiles[$k]);
474
			// Already writable?
475
			elseif (@is_writable($file))
476
				$return_data['files']['writable'][] = $file;
477
			else
478
			{
479
				// Now try to change that.
480
				$return_data['files'][package_chmod($file, 'writable', true) ? 'writable' : 'notwritable'][] = $file;
481
			}
482
		}
483
	}
484
485
	// Have we still got nasty files which ain't writable? Dear me we need more FTP good sir.
486
	if (empty($package_ftp) && (!empty($return_data['files']['notwritable']) || !empty($chmodOptions['force_find_error'])))
487
	{
488
		if (!isset($ftp) || $ftp->error !== false)
489
		{
490
			if (!isset($ftp))
491
			{
492
				$ftp = new Ftp_Connection(null);
493
			}
494
			elseif ($ftp->error !== false && !isset($ftp_error))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ftp does not seem to be defined for all execution paths leading up to this point.
Loading history...
495
				$ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
496
497
			list ($username, $detect_path, $found_path) = $ftp->detect_path(BOARDDIR);
498
499
			if ($found_path)
500
				$_POST['ftp_path'] = $detect_path;
501
			elseif (!isset($_POST['ftp_path']))
502
				$_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
503
504
			if (!isset($_POST['ftp_username']))
505
				$_POST['ftp_username'] = $username;
506
		}
507
508
		$context['package_ftp'] = array(
509
			'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
510
			'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
511
			'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
512
			'path' => $_POST['ftp_path'],
513
			'error' => empty($ftp_error) ? null : $ftp_error,
514
			'destination' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : '',
515
		);
516
517
		// Which files failed?
518
		if (!isset($context['notwritable_files']))
519
			$context['notwritable_files'] = array();
520
		$context['notwritable_files'] = array_merge($context['notwritable_files'], $return_data['files']['notwritable']);
521
522
		// Sent here to die?
523
		if (!empty($chmodOptions['crash_on_error']))
524
		{
525
			$context['page_title'] = $txt['package_ftp_necessary'];
526
			$context['sub_template'] = 'ftp_required';
527
			obExit();
528
		}
529
	}
530
531
	return $return_data;
532
}
533
534
/**
535
 * Get a listing of files that will need to be set back to the original state
536
 *
537
 * @param string $dummy1
538
 * @param string $dummy2
539
 * @param string $dummy3
540
 * @param boolean $do_change
541
 */
542
function list_restoreFiles($dummy1, $dummy2, $dummy3, $do_change)
543
{
544
	global $txt, $package_ftp;
545
546
	$restore_files = array();
547
548
	foreach ($_SESSION['pack_ftp']['original_perms'] as $file => $perms)
549
	{
550
		// Check the file still exists, and the permissions were indeed different than now.
551
		$file_permissions = @fileperms($file);
552
		if (!file_exists($file) || $file_permissions == $perms)
553
		{
554
			unset($_SESSION['pack_ftp']['original_perms'][$file]);
555
			continue;
556
		}
557
558
		// Are we wanting to change the permission?
559
		if ($do_change && isset($_POST['restore_files']) && in_array($file, $_POST['restore_files']))
560
		{
561
			// Use FTP if we have it.
562
			if (!empty($package_ftp))
563
			{
564
				$ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
565
				$package_ftp->chmod($ftp_file, $perms);
566
			}
567
			else
568
				elk_chmod($file, $perms);
569
570
			$new_permissions = @fileperms($file);
571
			$result = $new_permissions == $perms ? 'success' : 'failure';
572
			unset($_SESSION['pack_ftp']['original_perms'][$file]);
573
		}
574
		elseif ($do_change)
575
		{
576
			$new_permissions = '';
577
			$result = 'skipped';
578
			unset($_SESSION['pack_ftp']['original_perms'][$file]);
579
		}
580
581
		// Record the results!
582
		$restore_files[] = array(
583
			'path' => $file,
584
			'old_perms_raw' => $perms,
585
			'old_perms' => substr(sprintf('%o', $perms), -4),
586
			'cur_perms' => substr(sprintf('%o', $file_permissions), -4),
587
			'new_perms' => isset($new_permissions) ? substr(sprintf('%o', $new_permissions), -4) : '',
588
			'result' => isset($result) ? $result : '',
589
			'writable_message' => '<span class="' . (@is_writable($file) ? 'success' : 'alert') . '">' . (@is_writable($file) ? $txt['package_file_perms_writable'] : $txt['package_file_perms_not_writable']) . '</span>',
590
		);
591
	}
592
593
	return $restore_files;
594
}
595
596
/**
597
 * Use FTP functions to work with a package download/install
598
 *
599
 * @package Packages
600
 * @param string $destination_url
601
 * @param string[]|null $files = none
602
 * @param bool $return = false
603
 * @throws Elk_Exception
604
 */
605
function packageRequireFTP($destination_url, $files = null, $return = false)
606
{
607
	global $context, $modSettings, $package_ftp, $txt;
608
609
	// Try to make them writable the manual way.
610
	if ($files !== null)
611
	{
612
		foreach ($files as $k => $file)
613
		{
614
			// If this file doesn't exist, then we actually want to look at the directory, no?
615
			if (!file_exists($file))
616
				$file = dirname($file);
617
618
			// This looks odd, but it's an attempt to work around PHP suExec.
619
			if (!@is_writable($file))
620
				elk_chmod($file, 0755);
621
			if (!@is_writable($file))
622
				elk_chmod($file, 0777);
623
			if (!@is_writable(dirname($file)))
624
				elk_chmod($file, 0755);
625
			if (!@is_writable(dirname($file)))
626
				elk_chmod($file, 0777);
627
628
			$fp = is_dir($file) ? @opendir($file) : @fopen($file, 'rb');
629
			if (@is_writable($file) && $fp)
630
			{
631
				unset($files[$k]);
632
				if (!is_dir($file))
633
					fclose($fp);
634
				else
635
					closedir($fp);
636
			}
637
		}
638
639
		// No FTP required!
640
		if (empty($files))
641
			return array();
642
	}
643
644
	// They've opted to not use FTP, and try anyway.
645
	if (isset($_SESSION['pack_ftp']) && $_SESSION['pack_ftp'] === false)
646
	{
647
		if ($files === null)
648
			return array();
649
650
		foreach ($files as $k => $file)
651
		{
652
			// This looks odd, but it's an attempt to work around PHP suExec.
653
			if (!file_exists($file))
654
			{
655
				mktree(dirname($file), 0755);
656
				@touch($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

656
				/** @scrutinizer ignore-unhandled */ @touch($file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
657
				elk_chmod($file, 0755);
658
			}
659
			if (!@is_writable($file))
660
				elk_chmod($file, 0777);
661
			if (!@is_writable(dirname($file)))
662
				elk_chmod(dirname($file), 0777);
663
664
			if (@is_writable($file))
665
				unset($files[$k]);
666
		}
667
668
		return $files;
669
	}
670
	elseif (isset($_SESSION['pack_ftp']))
671
	{
672
		$package_ftp = new Ftp_Connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
673
674
		if ($files === null)
675
			return array();
676
677
		foreach ($files as $k => $file)
678
		{
679
			$ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
680
681
			// This looks odd, but it's an attempt to work around PHP suExec.
682
			if (!file_exists($file))
683
			{
684
				mktree(dirname($file), 0755);
685
				$package_ftp->create_file($ftp_file);
686
				$package_ftp->chmod($ftp_file, 0755);
687
			}
688
689
			// Still not writable, true full permissions
690
			if (!@is_writable($file))
691
				$package_ftp->chmod($ftp_file, 0777);
692
693
			// Directory not writable, try to chmod to 777 then
694
			if (!@is_writable(dirname($file)))
695
				$package_ftp->chmod(dirname($ftp_file), 0777);
696
697
			if (@is_writable($file))
698
				unset($files[$k]);
699
		}
700
701
		return $files;
702
	}
703
704
	if (isset($_POST['ftp_none']))
705
	{
706
		$_SESSION['pack_ftp'] = false;
707
708
		$files = packageRequireFTP($destination_url, $files, $return);
709
		return $files;
710
	}
711
	elseif (isset($_POST['ftp_username']))
712
	{
713
		// Attempt to make a new FTP connection
714
		$ftp = new Ftp_Connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
715
716
		if ($ftp->error === false)
717
		{
718
			// Common mistake, so let's try to remedy it...
719
			if (!$ftp->chdir($_POST['ftp_path']))
720
			{
721
				$ftp_error = $ftp->last_message;
722
				$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
723
			}
724
		}
725
	}
726
727
	if (!isset($ftp) || $ftp->error !== false)
728
	{
729
		if (!isset($ftp))
730
		{
731
			$ftp = new Ftp_Connection(null);
732
		}
733
		elseif ($ftp->error !== false && !isset($ftp_error))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ftp does not seem to be defined for all execution paths leading up to this point.
Loading history...
734
			$ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
735
736
		list ($username, $detect_path, $found_path) = $ftp->detect_path(BOARDDIR);
737
738
		if ($found_path)
739
			$_POST['ftp_path'] = $detect_path;
740
		elseif (!isset($_POST['ftp_path']))
741
			$_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
742
743
		if (!isset($_POST['ftp_username']))
744
			$_POST['ftp_username'] = $username;
745
746
		$context['package_ftp'] = array(
747
			'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
748
			'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
749
			'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
750
			'path' => $_POST['ftp_path'],
751
			'error' => empty($ftp_error) ? null : $ftp_error,
752
			'destination' => $destination_url,
753
		);
754
755
		// If we're returning dump out here.
756
		if ($return)
757
			return $files;
758
759
		$context['page_title'] = $txt['package_ftp_necessary'];
760
		$context['sub_template'] = 'ftp_required';
761
		obExit();
762
	}
763
	else
764
	{
765
		if (!in_array($_POST['ftp_path'], array('', '/')))
766
		{
767
			$ftp_root = strtr(BOARDDIR, array($_POST['ftp_path'] => ''));
768
			if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || $_POST['ftp_path'][0] == '/'))
769
				$ftp_root = substr($ftp_root, 0, -1);
770
		}
771
		else
772
			$ftp_root = BOARDDIR;
773
774
		$_SESSION['pack_ftp'] = array(
775
			'server' => $_POST['ftp_server'],
776
			'port' => $_POST['ftp_port'],
777
			'username' => $_POST['ftp_username'],
778
			'password' => package_crypt($_POST['ftp_password']),
779
			'path' => $_POST['ftp_path'],
780
			'root' => $ftp_root,
781
		);
782
783
		if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
784
			updateSettings(array('package_path' => $_POST['ftp_path']));
785
786
		$files = packageRequireFTP($destination_url, $files, $return);
787
	}
788
789
	return $files;
790
}
791
792
/**
793
 * Parses the actions in package-info.xml file from packages.
794
 *
795
 * What it does:
796
 *
797
 * - Package should be an Xml_Array with package-info as its base.
798
 * - Testing_only should be true if the package should not actually be applied.
799
 * - Method can be upgrade, install, or uninstall.  Its default is install.
800
 * - Previous_version should be set to the previous installed version of this package, if any.
801
 * - Does not handle failure terribly well; testing first is always better.
802
 *
803
 * @package Packages
804
 * @param Xml_Array $packageXML
805
 * @param bool $testing_only = true
806
 * @param string $method = 'install' ('install', 'upgrade', or 'uninstall')
807
 * @param string $previous_version = ''
808
 * @return array an array of those changes made.
809
 */
810
function parsePackageInfo(&$packageXML, $testing_only = true, $method = 'install', $previous_version = '')
811
{
812
	global $context, $temp_path, $language;
813
814
	// Mayday!  That action doesn't exist!!
815
	if (empty($packageXML) || !$packageXML->exists($method))
816
		return array();
817
818
	// We haven't found the package script yet...
819
	$script = false;
820
	$the_version = strtr(FORUM_VERSION, array('ElkArte ' => ''));
821
822
	// Emulation support...
823
	if (!empty($_SESSION['version_emulate']))
824
		$the_version = $_SESSION['version_emulate'];
825
826
	// Single package emulation
827
	if (!empty($_REQUEST['ve']) && !empty($_REQUEST['package']))
828
	{
829
		$the_version = $_REQUEST['ve'];
830
		$_SESSION['single_version_emulate'][$_REQUEST['package']] = $the_version;
831
	}
832
	if (!empty($_REQUEST['package']) && (!empty($_SESSION['single_version_emulate'][$_REQUEST['package']])))
833
		$the_version = $_SESSION['single_version_emulate'][$_REQUEST['package']];
834
835
	// Get all the versions of this method and find the right one.
836
	$these_methods = $packageXML->set($method);
837
	foreach ($these_methods as $this_method)
838
	{
839
		// They specified certain versions this part is for.
840
		if ($this_method->exists('@for'))
841
		{
842
			// Don't keep going if this won't work for this version.
843
			if (!matchPackageVersion($the_version, $this_method->fetch('@for')))
844
				continue;
845
		}
846
847
		// Upgrades may go from a certain old version of the mod.
848
		if ($method == 'upgrade' && $this_method->exists('@from'))
849
		{
850
			// Well, this is for the wrong old version...
851
			if (!matchPackageVersion($previous_version, $this_method->fetch('@from')))
852
				continue;
853
		}
854
855
		// We've found it!
856
		$script = $this_method;
857
		break;
858
	}
859
860
	// Bad news, a matching script wasn't found!
861
	if ($script === false)
862
		return array();
863
864
	// Find all the actions in this method - in theory, these should only be allowed actions. (* means all.)
865
	$actions = $script->set('*');
866
	$return = array();
867
868
	$temp_auto = 0;
869
	$temp_path = BOARDDIR . '/packages/temp/' . (isset($context['base_path']) ? $context['base_path'] : '');
870
871
	$context['readmes'] = array();
872
	$context['licences'] = array();
873
	$has_redirect = false;
874
875
	// This is the testing phase... nothing shall be done yet.
876
	foreach ($actions as $action)
877
	{
878
		$actionType = $action->name();
879
880
		if (in_array($actionType, array('readme', 'code', 'database', 'modification', 'redirect', 'license')))
881
		{
882
			if ($actionType == 'redirect')
883
			{
884
				$has_redirect = true;
885
			}
886
887
			// Allow for translated readme and license files.
888
			if ($actionType == 'readme' || $actionType == 'license')
889
			{
890
				$type = $actionType . 's';
891
				if ($action->exists('@lang'))
892
				{
893
					// Auto-select the language based on either request variable or current language.
894
					if ((isset($_REQUEST['readme']) && $action->fetch('@lang') == $_REQUEST['readme']) || (isset($_REQUEST['license']) && $action->fetch('@lang') == $_REQUEST['license']) || (!isset($_REQUEST['readme']) && $action->fetch('@lang') == $language) || (!isset($_REQUEST['license']) && $action->fetch('@lang') == $language))
895
					{
896
						// In case the user put the blocks in the wrong order.
897
						if (isset($context[$type]['selected']) && $context[$type]['selected'] == 'default')
898
							$context[$type][] = 'default';
899
900
						$context[$type]['selected'] = htmlspecialchars($action->fetch('@lang'), ENT_COMPAT, 'UTF-8');
901
					}
902
					else
903
					{
904
						// We don't want this now, but we'll allow the user to select to read it.
905
						$context[$type][] = htmlspecialchars($action->fetch('@lang'), ENT_COMPAT, 'UTF-8');
906
						continue;
907
					}
908
				}
909
				// Fallback when we have no lang parameter.
910
				else
911
				{
912
					// Already selected one for use?
913
					if (isset($context[$type]['selected']))
914
					{
915
						$context[$type][] = 'default';
916
						continue;
917
					}
918
					else
919
						$context[$type]['selected'] = 'default';
920
				}
921
			}
922
923
			// @todo Make sure the file actually exists?  Might not work when testing?
924
			if ($action->exists('@type') && $action->fetch('@type') == 'inline')
925
			{
926
				$filename = $temp_path . '$auto_' . $temp_auto++ . (in_array($actionType, array('readme', 'redirect', 'license')) ? '.txt' : ($actionType == 'code' || $actionType == 'database' ? '.php' : '.mod'));
927
				package_put_contents($filename, $action->fetch('.'));
928
				$filename = strtr($filename, array($temp_path => ''));
929
			}
930
			else
931
				$filename = $action->fetch('.');
932
933
			$return[] = array(
934
				'type' => $actionType,
935
				'filename' => $filename,
936
				'description' => '',
937
				'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true',
938
				'redirect_url' => $action->exists('@url') ? $action->fetch('@url') : '',
939
				'redirect_timeout' => $action->exists('@timeout') ? (int) $action->fetch('@timeout') : 5000,
940
				'parse_bbc' => $action->exists('@parsebbc') && $action->fetch('@parsebbc') == 'true',
941
				'language' => (($actionType == 'readme' || $actionType == 'license') && $action->exists('@lang') && $action->fetch('@lang') == $language) ? $language : '',
942
			);
943
944
			continue;
945
		}
946
		elseif ($actionType == 'hook')
947
		{
948
			$return[] = array(
949
				'type' => $actionType,
950
				'function' => $action->exists('@function') ? $action->fetch('@function') : '',
951
				'hook' => $action->exists('@hook') ? $action->fetch('@hook') : $action->fetch('.'),
952
				'include_file' => $action->exists('@file') ? $action->fetch('@file') : '',
953
				'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true' ? true : false,
954
				'description' => '',
955
			);
956
			continue;
957
		}
958
		elseif ($actionType == 'credits')
959
		{
960
			// quick check of any supplied url
961
			$url = $action->exists('@url') ? $action->fetch('@url') : '';
962
			if (strlen(trim($url)) > 0)
963
			{
964
				$url = addProtocol($url, array('http://', 'https://'));
965
966
				if (strlen($url) < 8)
967
					$url = '';
968
			}
969
970
			$return[] = array(
971
				'type' => $actionType,
972
				'url' => $url,
973
				'license' => $action->exists('@license') ? $action->fetch('@license') : '',
974
				'copyright' => $action->exists('@copyright') ? $action->fetch('@copyright') : '',
975
				'title' => $action->fetch('.'),
976
			);
977
			continue;
978
		}
979
		elseif ($actionType == 'requires')
980
		{
981
			$return[] = array(
982
				'type' => $actionType,
983
				'id' => $action->exists('@id') ? $action->fetch('@id') : '',
984
				'version' => $action->exists('@version') ? $action->fetch('@version') : $action->fetch('.'),
985
				'description' => '',
986
			);
987
			continue;
988
		}
989
		elseif ($actionType == 'error')
990
		{
991
			$return[] = array(
992
				'type' => 'error',
993
			);
994
		}
995
		elseif (in_array($actionType, array('require-file', 'remove-file', 'require-dir', 'remove-dir', 'move-file', 'move-dir', 'create-file', 'create-dir')))
996
		{
997
			$this_action = &$return[];
998
			$this_action = array(
999
				'type' => $actionType,
1000
				'filename' => $action->fetch('@name'),
1001
				'description' => $action->fetch('.')
1002
			);
1003
1004
			// If there is a destination, make sure it makes sense.
1005
			if (substr($actionType, 0, 6) != 'remove')
1006
			{
1007
				$this_action['unparsed_destination'] = $action->fetch('@destination');
1008
				$this_action['destination'] = parse_path($action->fetch('@destination')) . '/' . basename($this_action['filename']);
1009
			}
1010
			else
1011
			{
1012
				$this_action['unparsed_filename'] = $this_action['filename'];
1013
				$this_action['filename'] = parse_path($this_action['filename']);
1014
			}
1015
1016
			// If we're moving or requiring (copying) a file.
1017
			if (substr($actionType, 0, 4) == 'move' || substr($actionType, 0, 7) == 'require')
1018
			{
1019
				if ($action->exists('@from'))
1020
				{
1021
					$this_action['source'] = parse_path($action->fetch('@from'));
1022
				}
1023
				else
1024
				{
1025
					$this_action['source'] = $temp_path . $this_action['filename'];
1026
				}
1027
			}
1028
1029
			// Check if these things can be done. (chmod's etc.)
1030
			if ($actionType == 'create-dir')
1031
			{
1032
				// Try to create a directory
1033
				if (!mktree($this_action['destination'], false))
1034
				{
1035
					$temp = $this_action['destination'];
1036
					while (!file_exists($temp) && strlen($temp) > 1)
1037
						$temp = dirname($temp);
1038
1039
					$return[] = array(
1040
						'type' => 'chmod',
1041
						'filename' => $temp
1042
					);
1043
				}
1044
			}
1045
			elseif ($actionType == 'create-file')
1046
			{
1047
				// Try to create a file in a known location
1048
				if (!mktree(dirname($this_action['destination']), false))
1049
				{
1050
					$temp = dirname($this_action['destination']);
1051
					while (!file_exists($temp) && strlen($temp) > 1)
1052
						$temp = dirname($temp);
1053
1054
					$return[] = array(
1055
						'type' => 'chmod',
1056
						'filename' => $temp
1057
					);
1058
				}
1059
1060
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1061
					$return[] = array(
1062
						'type' => 'chmod',
1063
						'filename' => $this_action['destination']
1064
					);
1065
			}
1066
			elseif ($actionType == 'require-dir')
1067
			{
1068
				if (!mktree($this_action['destination'], false))
1069
				{
1070
					$temp = $this_action['destination'];
1071
					while (!file_exists($temp) && strlen($temp) > 1)
1072
						$temp = dirname($temp);
1073
1074
					$return[] = array(
1075
						'type' => 'chmod',
1076
						'filename' => $temp
1077
					);
1078
				}
1079
			}
1080
			elseif ($actionType == 'require-file')
1081
			{
1082
				if ($action->exists('@theme'))
1083
					$this_action['theme_action'] = $action->fetch('@theme');
1084
1085
				if (!mktree(dirname($this_action['destination']), false))
1086
				{
1087
					$temp = dirname($this_action['destination']);
1088
					while (!file_exists($temp) && strlen($temp) > 1)
1089
						$temp = dirname($temp);
1090
1091
					$return[] = array(
1092
						'type' => 'chmod',
1093
						'filename' => $temp
1094
					);
1095
				}
1096
1097
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1098
					$return[] = array(
1099
						'type' => 'chmod',
1100
						'filename' => $this_action['destination']
1101
					);
1102
			}
1103
			elseif ($actionType == 'move-dir' || $actionType == 'move-file')
1104
			{
1105
				if (!mktree(dirname($this_action['destination']), false))
1106
				{
1107
					$temp = dirname($this_action['destination']);
1108
					while (!file_exists($temp) && strlen($temp) > 1)
1109
						$temp = dirname($temp);
1110
1111
					$return[] = array(
1112
						'type' => 'chmod',
1113
						'filename' => $temp
1114
					);
1115
				}
1116
1117
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1118
					$return[] = array(
1119
						'type' => 'chmod',
1120
						'filename' => $this_action['destination']
1121
					);
1122
			}
1123
			elseif ($actionType == 'remove-dir')
1124
			{
1125
				if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
1126
					$return[] = array(
1127
						'type' => 'chmod',
1128
						'filename' => $this_action['filename']
1129
					);
1130
			}
1131
			elseif ($actionType == 'remove-file')
1132
			{
1133
				if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
1134
					$return[] = array(
1135
						'type' => 'chmod',
1136
						'filename' => $this_action['filename']
1137
					);
1138
			}
1139
		}
1140
		else
1141
		{
1142
			$return[] = array(
1143
				'type' => 'error',
1144
				'error_msg' => 'unknown_action',
1145
				'error_var' => $actionType
1146
			);
1147
		}
1148
	}
1149
1150
	if (!$has_redirect)
1151
	{
1152
		$return[] = array(
1153
			'type' => 'redirect',
1154
			'filename' => '',
1155
			'description' => '',
1156
			'reverse' => false,
1157
			'redirect_url' => '$scripturl?action=admin;area=packages',
1158
			'redirect_timeout' => 5000,
1159
			'parse_bbc' => false,
1160
			'language' => '',
1161
		);
1162
	}
1163
1164
	// Only testing - just return a list of things to be done.
1165
	if ($testing_only)
1166
		return $return;
1167
1168
	umask(0);
1169
1170
	$failure = false;
1171
	$not_done = array(array('type' => '!'));
1172
	foreach ($return as $action)
1173
	{
1174
		if (in_array($action['type'], array('modification', 'code', 'database', 'redirect', 'hook', 'credits')))
1175
			$not_done[] = $action;
1176
1177
		if ($action['type'] == 'create-dir')
1178
		{
1179
			if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1180
				$failure |= !mktree($action['destination'], 0777);
1181
		}
1182
		elseif ($action['type'] == 'create-file')
1183
		{
1184
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1185
				$failure |= !mktree(dirname($action['destination']), 0777);
1186
1187
			// Create an empty file.
1188
			package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1189
1190
			if (!file_exists($action['destination']))
1191
				$failure = true;
1192
		}
1193
		elseif ($action['type'] == 'require-dir')
1194
		{
1195
			copytree($action['source'], $action['destination']);
1196
			// Any other theme folders?
1197
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1198
				foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1199
					copytree($action['source'], $theme_destination);
1200
		}
1201
		elseif ($action['type'] == 'require-file')
1202
		{
1203
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1204
				$failure |= !mktree(dirname($action['destination']), 0777);
1205
1206
			package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1207
1208
			$failure |= !copy($action['source'], $action['destination']);
1209
1210
			// Any other theme files?
1211
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1212
				foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1213
				{
1214
					if (!mktree(dirname($theme_destination), 0755) || !is_writable(dirname($theme_destination)))
1215
						$failure |= !mktree(dirname($theme_destination), 0777);
1216
1217
					package_put_contents($theme_destination, package_get_contents($action['source']), $testing_only);
1218
1219
					$failure |= !copy($action['source'], $theme_destination);
1220
				}
1221
		}
1222
		elseif ($action['type'] == 'move-file')
1223
		{
1224
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1225
				$failure |= !mktree(dirname($action['destination']), 0777);
1226
1227
			$failure |= !rename($action['source'], $action['destination']);
1228
		}
1229
		elseif ($action['type'] == 'move-dir')
1230
		{
1231
			if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1232
				$failure |= !mktree($action['destination'], 0777);
1233
1234
			$failure |= !rename($action['source'], $action['destination']);
1235
		}
1236
		elseif ($action['type'] == 'remove-dir')
1237
		{
1238
			deltree($action['filename']);
1239
1240
			// Any other theme folders?
1241
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1242
				foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1243
					deltree($theme_destination);
1244
		}
1245
		elseif ($action['type'] == 'remove-file')
1246
		{
1247
			// Make sure the file exists before deleting it.
1248
			if (file_exists($action['filename']))
1249
			{
1250
				package_chmod($action['filename']);
1251
				$failure |= !unlink($action['filename']);
1252
			}
1253
			// The file that was supposed to be deleted couldn't be found.
1254
			else
1255
				$failure = true;
1256
1257
			// Any other theme folders?
1258
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1259
				foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1260
					if (file_exists($theme_destination))
1261
						$failure |= !unlink($theme_destination);
1262
					else
1263
						$failure = true;
1264
		}
1265
	}
1266
1267
	return $not_done;
1268
}
1269
1270
/**
1271
 * Checks if version matches any of the versions in versions.
1272
 *
1273
 * - Supports comma separated version numbers, with or without whitespace.
1274
 * - Supports lower and upper bounds. (1.0-1.2)
1275
 * - Returns true if the version matched.
1276
 *
1277
 * @package Packages
1278
 * @param string $versions
1279
 * @param boolean $reset
1280
 * @param string $the_version
1281
 * @return string|boolean highest install value string or false
1282
 */
1283
function matchHighestPackageVersion($versions, $reset = false, $the_version)
1284
{
1285
	static $near_version = 0;
1286
1287
	if ($reset)
1288
		$near_version = 0;
1289
1290
	// Normalize the $versions
1291
	$versions = explode(',', str_replace(' ', '', strtolower($versions)));
1292
1293
	// If it is not ElkArte, let's just give up
1294
	list ($the_brand,) = explode(' ', FORUM_VERSION, 2);
1295
	if ($the_brand != 'ElkArte')
1296
		return false;
1297
1298
	// Loop through each version, save the highest we can find
1299
	foreach ($versions as $for)
1300
	{
1301
		// Adjust for those wild cards
1302
		if (strpos($for, '*') !== false)
1303
			$for = str_replace('*', '0', $for) . '-' . str_replace('*', '999', $for);
1304
1305
		// If we have a range, grab the lower value, done this way so it looks normal-er to the user e.g. 1.0 vs 1.0.99
1306
		if (strpos($for, '-') !== false)
1307
			list ($for,) = explode('-', $for);
1308
1309
		// Do the compare, if the for is greater, than what we have but not greater than what we are running .....
1310
		if (compareVersions($near_version, $for) === -1 && compareVersions($for, $the_version) !== 1)
1311
			$near_version = $for;
1312
	}
1313
1314
	return !empty($near_version) ? $near_version : false;
1315
}
1316
1317
/**
1318
 * Checks if the forum version matches any of the available versions from the package install xml.
1319
 *
1320
 * - Supports comma separated version numbers, with or without whitespace.
1321
 * - Supports lower and upper bounds. (1.0-1.2)
1322
 * - Returns true if the version matched.
1323
 *
1324
 * @package Packages
1325
 * @param string $version
1326
 * @param string $versions
1327
 * @return boolean
1328
 */
1329
function matchPackageVersion($version, $versions)
1330
{
1331
	// Make sure everything is lowercase and clean of spaces.
1332
	$version = str_replace(' ', '', strtolower($version));
1333
	$versions = explode(',', str_replace(' ', '', strtolower($versions)));
1334
1335
	// Perhaps we do accept anything?
1336
	if (in_array('all', $versions))
1337
		return true;
1338
1339
	// Loop through each version.
1340
	foreach ($versions as $for)
1341
	{
1342
		// Wild card spotted?
1343
		if (strpos($for, '*') !== false)
1344
			$for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
1345
1346
		// Do we have a range?
1347
		if (strpos($for, '-') !== false)
1348
		{
1349
			list ($lower, $upper) = explode('-', $for);
1350
1351
			// Compare the version against lower and upper bounds.
1352
			if (compareVersions($version, $lower) > -1 && compareVersions($version, $upper) < 1)
1353
				return true;
1354
		}
1355
		// Otherwise check if they are equal...
1356
		elseif (compareVersions($version, $for) === 0)
1357
			return true;
1358
	}
1359
1360
	return false;
1361
}
1362
1363
/**
1364
 * Compares two versions and determines if one is newer, older or the same, returns
1365
 *
1366
 * - (-1) if version1 is lower than version2
1367
 * - (0) if version1 is equal to version2
1368
 * - (1) if version1 is higher than version2
1369
 *
1370
 * @package Packages
1371
 * @param string $version1
1372
 * @param string $version2
1373
 * @return int (-1, 0, 1)
1374
 */
1375
function compareVersions($version1, $version2)
1376
{
1377
	static $categories;
1378
1379
	$versions = array();
1380
	foreach (array(1 => $version1, $version2) as $id => $version)
1381
	{
1382
		// Clean the version and extract the version parts.
1383
		$clean = str_replace(' ', '', strtolower($version));
1384
		preg_match('~(\d+)(?:\.(\d+|))?(?:\.)?(\d+|)(?:(alpha|beta|rc)(\d+|)(?:\.)?(\d+|))?(?:\s(dev))?(\d+|)~', $clean, $parts);
1385
1386
		// Build an array of parts.
1387
		$versions[$id] = array(
1388
			'major' => !empty($parts[1]) ? (int) $parts[1] : 0,
1389
			'minor' => !empty($parts[2]) ? (int) $parts[2] : 0,
1390
			'patch' => !empty($parts[3]) ? (int) $parts[3] : 0,
1391
			'type' => empty($parts[4]) && empty($parts[7]) ? 'stable' : (!empty($parts[7]) ? 'alpha' : $parts[4]),
1392
			'type_major' => !empty($parts[6]) ? (int) $parts[5] : 0,
1393
			'type_minor' => !empty($parts[6]) ? (int) $parts[6] : 0,
1394
			'dev' => !empty($parts[7]),
1395
		);
1396
	}
1397
1398
	// Are they the same, perhaps?
1399
	if ($versions[1] === $versions[2])
1400
		return 0;
1401
1402
	// Get version numbering categories...
1403
	if (!isset($categories))
1404
		$categories = array_keys($versions[1]);
1405
1406
	// Loop through each category.
1407
	foreach ($categories as $category)
1408
	{
1409
		// Is there something for us to calculate?
1410
		if ($versions[1][$category] !== $versions[2][$category])
1411
		{
1412
			// Dev builds are a problematic exception.
1413
			// (stable) dev < (stable) but (unstable) dev = (unstable)
1414
			if ($category == 'type')
1415
				return $versions[1][$category] > $versions[2][$category] ? ($versions[1]['dev'] ? -1 : 1) : ($versions[2]['dev'] ? 1 : -1);
1416
			elseif ($category == 'dev')
1417
				return $versions[1]['dev'] ? ($versions[2]['type'] == 'stable' ? -1 : 0) : ($versions[1]['type'] == 'stable' ? 1 : 0);
1418
			// Otherwise a simple comparison.
1419
			else
1420
				return $versions[1][$category] > $versions[2][$category] ? 1 : -1;
1421
		}
1422
	}
1423
1424
	// They are the same!
1425
	return 0;
1426
}
1427
1428
/**
1429
 * Parses special identifiers out of the specified path.
1430
 *
1431
 * @package Packages
1432
 * @param string $path
1433
 * @return string The parsed path
1434
 */
1435
function parse_path($path)
1436
{
1437
	global $modSettings, $settings, $temp_path;
1438
1439
	if (empty($path))
1440
		return '';
1441
1442
	$dirs = array(
1443
		'\\' => '/',
1444
		'BOARDDIR' => BOARDDIR,
1445
		'SOURCEDIR' => SOURCEDIR,
1446
		'SUBSDIR' => SUBSDIR,
1447
		'ADMINDIR' => ADMINDIR,
1448
		'CONTROLLERDIR' => CONTROLLERDIR,
1449
		'EXTDIR' => EXTDIR,
1450
		'ADDONSDIR' => ADDONSDIR,
1451
		'AVATARSDIR' => $modSettings['avatar_directory'],
1452
		'THEMEDIR' => $settings['default_theme_dir'],
1453
		'IMAGESDIR' => $settings['default_theme_dir'] . '/' . basename($settings['default_images_url']),
1454
		'LANGUAGEDIR' => $settings['default_theme_dir'] . '/languages',
1455
		'SMILEYDIR' => $modSettings['smileys_dir'],
1456
	);
1457
1458
	// Do we parse in a package directory?
1459
	if (!empty($temp_path))
1460
		$dirs['PACKAGE'] = $temp_path;
1461
1462
	if (strlen($path) == 0)
1463
		trigger_error('parse_path(): There should never be an empty filename', E_USER_ERROR);
1464
1465
	// Check if they are using some old software install paths
1466
	if (strpos($path, '$') === 0 && isset($dirs[strtoupper(substr($path, 1))]))
1467
		$path = strtoupper(substr($path, 1));
1468
1469
	return strtr($path, $dirs);
1470
}
1471
1472
/**
1473
 * Deletes all the files in a directory, and all the files in sub directories inside it.
1474
 *
1475
 * What it does:
1476
 *
1477
 * - Requires access to delete these files.
1478
 * - Recursively goes in to all sub directories looking for files to delete
1479
 * - Optionally removes the directory as well, otherwise will leave an empty tree behind
1480
 *
1481
 * @package Packages
1482
 * @param string $dir
1483
 * @param bool $delete_dir = true
1484
 */
1485
function deltree($dir, $delete_dir = true)
1486
{
1487
	global $package_ftp;
1488
1489
	if (!file_exists($dir))
1490
		return;
1491
1492
	// Read all the files in the directory
1493
	try
1494
	{
1495
		$entrynames = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
1496
		foreach ($entrynames as $entryname)
1497
		{
1498
			// Recursively dive in to each directory looking for files to delete
1499
			if ($entryname->isDir())
1500
				deltree($entryname->getPathname());
1501
			// A file, delete it by any means necessary
1502
			else
1503
			{
1504
				// Here, 755 doesn't really matter since we're deleting it anyway.
1505
				if (isset($package_ftp))
1506
				{
1507
					$ftp_file = strtr($entryname->getPathname(), array($_SESSION['pack_ftp']['root'] => ''));
1508
1509
					if (!$entryname->isWritable())
1510
						$package_ftp->chmod($ftp_file, 0777);
1511
1512
					$package_ftp->unlink($ftp_file);
1513
				}
1514
				else
1515
				{
1516
					if (!$entryname->isWritable())
1517
						elk_chmod($entryname->getPathname(), 0777);
1518
1519
					@unlink($entryname->getPathname());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1519
					/** @scrutinizer ignore-unhandled */ @unlink($entryname->getPathname());

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1520
				}
1521
			}
1522
		}
1523
	}
1524
	catch (UnexpectedValueException $e)
1525
	{
1526
		// Can't open the directory for reading, try FTP to remove it before quiting
1527
		if ($delete_dir && isset($package_ftp))
1528
		{
1529
			$ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1530
			if (!is_writable($dir . '/'))
1531
				$package_ftp->chmod($ftp_file, 0777);
1532
			$package_ftp->unlink($ftp_file);
1533
		}
1534
1535
		return;
1536
	}
1537
1538
	// Remove the directory entry as well?
1539
	if ($delete_dir)
1540
	{
1541
		if (isset($package_ftp))
1542
		{
1543
			$ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1544
1545
			if (!is_writable($dir . '/'))
1546
				$package_ftp->chmod($ftp_file, 0777);
1547
1548
			$package_ftp->unlink($ftp_file);
1549
		}
1550
		else
1551
		{
1552
			if (!is_writable($dir))
1553
				elk_chmod($dir, 0777);
1554
1555
			@rmdir($dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rmdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1555
			/** @scrutinizer ignore-unhandled */ @rmdir($dir);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1556
		}
1557
	}
1558
}
1559
1560
/**
1561
 * Creates the specified tree structure with the mode specified.
1562
 *
1563
 * - Creates every directory in path until it finds one that already exists.
1564
 *
1565
 * @package Packages
1566
 * @param string $strPath
1567
 * @param int|false $mode
1568
 * @return boolean true if successful, false otherwise
1569
 */
1570
function mktree($strPath, $mode)
1571
{
1572
	global $package_ftp;
1573
1574
	// If its already a directory
1575
	if (is_dir($strPath))
1576
	{
1577
		// Not writable, try to make it so with FTP or not
1578
		if (!is_writable($strPath) && $mode !== false)
1579
		{
1580
			if (isset($package_ftp))
1581
				$package_ftp->chmod(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')), $mode);
1582
			else
1583
				elk_chmod($strPath, $mode);
1584
		}
1585
1586
		// See if we can open it for access, return the result
1587
		$test = @opendir($strPath);
1588
		if ($test)
0 ignored issues
show
introduced by
$test is of type false|resource, thus it always evaluated to false.
Loading history...
1589
		{
1590
			closedir($test);
1591
			return is_writable($strPath);
1592
		}
1593
		else
1594
			return false;
1595
	}
1596
1597
	// Is this an invalid path and/or we can't make the directory?
1598
	if ($strPath == dirname($strPath) || !mktree(dirname($strPath), $mode))
1599
		return false;
1600
1601
	// Is the dir writable and do we have permission to attempt to make it so
1602
	if (!is_writable(dirname($strPath)) && $mode !== false)
1603
	{
1604
		if (isset($package_ftp))
1605
			$package_ftp->chmod(dirname(strtr($strPath, array($_SESSION['pack_ftp']['root'] => ''))), $mode);
1606
		else
1607
			elk_chmod(dirname($strPath), $mode);
1608
	}
1609
1610
	// Return an ftp control if using FTP
1611
	if ($mode !== false && isset($package_ftp))
1612
		return $package_ftp->create_dir(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')));
1613
	// Can't change the mode so just return the current availability
1614
	elseif ($mode === false)
1615
	{
1616
		$test = @opendir(dirname($strPath));
1617
		if ($test)
0 ignored issues
show
introduced by
$test is of type false|resource, thus it always evaluated to false.
Loading history...
1618
		{
1619
			closedir($test);
1620
			return true;
1621
		}
1622
		else
1623
			return false;
1624
	}
1625
	// Only one choice left and thats to try and make a directory
1626
	else
1627
	{
1628
		@mkdir($strPath, $mode);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1628
		/** @scrutinizer ignore-unhandled */ @mkdir($strPath, $mode);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1629
1630
		// Check and return if we were successful
1631
		$test = @opendir($strPath);
1632
		if ($test)
0 ignored issues
show
introduced by
$test is of type false|resource, thus it always evaluated to false.
Loading history...
1633
		{
1634
			closedir($test);
1635
			return true;
1636
		}
1637
		else
1638
			return false;
1639
	}
1640
}
1641
1642
/**
1643
 * Copies one directory structure over to another.
1644
 *
1645
 * - Requires the destination to be writable.
1646
 *
1647
 * @package Packages
1648
 * @param string $source
1649
 * @param string $destination
1650
 */
1651
function copytree($source, $destination)
1652
{
1653
	global $package_ftp;
1654
1655
	if (!file_exists($destination) || !is_writable($destination))
1656
		mktree($destination, 0755);
1657
1658
	if (!is_writable($destination))
1659
		mktree($destination, 0777);
1660
1661
	$current_dir = opendir($source);
1662
	if ($current_dir === false)
1663
		return;
1664
1665
	while ($entryname = readdir($current_dir))
1666
	{
1667
		if (in_array($entryname, array('.', '..')))
1668
			continue;
1669
1670
		if (isset($package_ftp))
1671
			$ftp_file = strtr($destination . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1672
1673
		if (is_file($source . '/' . $entryname))
1674
		{
1675
			if (isset($package_ftp) && !file_exists($destination . '/' . $entryname))
1676
				$package_ftp->create_file($ftp_file);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ftp_file does not seem to be defined for all execution paths leading up to this point.
Loading history...
1677
			elseif (!file_exists($destination . '/' . $entryname))
1678
				@touch($destination . '/' . $entryname);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1678
				/** @scrutinizer ignore-unhandled */ @touch($destination . '/' . $entryname);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1679
		}
1680
1681
		package_chmod($destination . '/' . $entryname);
1682
1683
		if (is_dir($source . '/' . $entryname))
1684
			copytree($source . '/' . $entryname, $destination . '/' . $entryname);
1685
		elseif (file_exists($destination . '/' . $entryname))
1686
			package_put_contents($destination . '/' . $entryname, package_get_contents($source . '/' . $entryname));
1687
		else
1688
			copy($source . '/' . $entryname, $destination . '/' . $entryname);
1689
	}
1690
1691
	closedir($current_dir);
1692
}
1693
1694
/**
1695
 * Create a tree listing for a given directory path
1696
 *
1697
 * @package Packages
1698
 * @param string $path
1699
 * @param string $sub_path = ''
1700
 * @return array
1701
 */
1702
function listtree($path, $sub_path = '')
1703
{
1704
	$data = array();
1705
1706
	$dir = @dir($path . $sub_path);
1707
	if (!$dir)
1708
		return array();
1709
1710
	while ($entry = $dir->read())
1711
	{
1712
		if ($entry == '.' || $entry == '..')
1713
			continue;
1714
1715
		if (is_dir($path . $sub_path . '/' . $entry))
1716
			$data = array_merge($data, listtree($path, $sub_path . '/' . $entry));
1717
		else
1718
			$data[] = array(
1719
				'filename' => $sub_path == '' ? $entry : $sub_path . '/' . $entry,
1720
				'size' => filesize($path . $sub_path . '/' . $entry),
1721
				'skipped' => false,
1722
			);
1723
	}
1724
	$dir->close();
1725
1726
	return $data;
1727
}
1728
1729
/**
1730
 * Parses a xml-style modification file (file).
1731
 *
1732
 * @package Packages
1733
 * @param string $file
1734
 * @param bool $testing = true tells it the modifications shouldn't actually be saved.
1735
 * @param bool $undo = false specifies that the modifications the file requests should be undone; this doesn't work with everything (regular expressions.)
1736
 * @param mixed[] $theme_paths = array()
1737
 * @return array an array of those changes made.
1738
 */
1739
function parseModification($file, $testing = true, $undo = false, $theme_paths = array())
1740
{
1741
	global $txt, $modSettings;
1742
1743
	detectServer()->setTimeLimit(600);
1744
1745
	$xml = new Xml_Array(strtr($file, array("\r" => '')));
1746
	$actions = array();
1747
	$everything_found = true;
1748
1749
	if (!$xml->exists('modification') || !$xml->exists('modification/file'))
1750
	{
1751
		$actions[] = array(
1752
			'type' => 'error',
1753
			'filename' => '-',
1754
			'debug' => $txt['package_modification_malformed']
1755
		);
1756
		return $actions;
1757
	}
1758
1759
	// Get the XML data.
1760
	$files = $xml->set('modification/file');
1761
1762
	// Use this for holding all the template changes in this mod.
1763
	$template_changes = array();
1764
1765
	// This is needed to hold the long paths, as they can vary...
1766
	$long_changes = array();
1767
1768
	// First, we need to build the list of all the files likely to get changed.
1769
	foreach ($files as $file)
0 ignored issues
show
introduced by
$file is overwriting one of the parameters of this function.
Loading history...
1770
	{
1771
		// What is the filename we're currently on?
1772
		$filename = parse_path(trim($file->fetch('@name')));
1773
1774
		// Now, we need to work out whether this is even a template file...
1775
		foreach ($theme_paths as $id => $theme)
1776
		{
1777
			// If this filename is relative, if so take a guess at what it should be.
1778
			$real_filename = $filename;
1779
			if (strpos($filename, 'themes') === 0)
1780
				$real_filename = BOARDDIR . '/' . $filename;
1781
1782
			if (strpos($real_filename, $theme['theme_dir']) === 0)
1783
			{
1784
				$template_changes[$id][] = substr($real_filename, strlen($theme['theme_dir']) + 1);
1785
				$long_changes[$id][] = $filename;
1786
			}
1787
		}
1788
	}
1789
1790
	// Custom themes to add.
1791
	$custom_themes_add = array();
1792
1793
	// If we have some template changes, we need to build a master link of what new ones are required for the custom themes.
1794
	if (!empty($template_changes[1]))
1795
	{
1796
		foreach ($theme_paths as $id => $theme)
1797
		{
1798
			// Default is getting done anyway, so no need for involvement here.
1799
			if ($id == 1)
1800
				continue;
1801
1802
			// For every template, do we want it? Yea, no, maybe?
1803
			foreach ($template_changes[1] as $index => $template_file)
1804
			{
1805
				// What, it exists and we haven't already got it?! Lordy, get it in!
1806
				if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id]) || !in_array($template_file, $template_changes[$id])))
1807
				{
1808
					// Now let's add it to the "todo" list.
1809
					$custom_themes_add[$long_changes[1][$index]][$id] = $theme['theme_dir'] . '/' . $template_file;
1810
				}
1811
			}
1812
		}
1813
	}
1814
1815
	foreach ($files as $file)
0 ignored issues
show
introduced by
$file is overwriting one of the parameters of this function.
Loading history...
1816
	{
1817
		// This is the actual file referred to in the XML document...
1818
		$files_to_change = array(
1819
			1 => parse_path(trim($file->fetch('@name'))),
1820
		);
1821
1822
		// Sometimes though, we have some additional files for other themes, if we have add them to the mix.
1823
		if (isset($custom_themes_add[$files_to_change[1]]))
1824
			$files_to_change += $custom_themes_add[$files_to_change[1]];
1825
1826
		// Now, loop through all the files we're changing, and, well, change them ;)
1827
		foreach ($files_to_change as $theme => $working_file)
1828
		{
1829
			if ($working_file[0] != '/' && $working_file[1] != ':')
1830
			{
1831
				trigger_error('parseModification(): The filename \'' . $working_file . '\' is not a full path!', E_USER_WARNING);
1832
1833
				$working_file = BOARDDIR . '/' . $working_file;
1834
			}
1835
1836
			// Doesn't exist - give an error or what?
1837
			if (!file_exists($working_file) && (!$file->exists('@error') || !in_array(trim($file->fetch('@error')), array('ignore', 'skip'))))
1838
			{
1839
				$actions[] = array(
1840
					'type' => 'missing',
1841
					'filename' => $working_file,
1842
					'debug' => $txt['package_modification_missing']
1843
				);
1844
1845
				$everything_found = false;
1846
				continue;
1847
			}
1848
			// Skip the file if it doesn't exist.
1849
			elseif (!file_exists($working_file) && $file->exists('@error') && trim($file->fetch('@error')) == 'skip')
1850
			{
1851
				$actions[] = array(
1852
					'type' => 'skipping',
1853
					'filename' => $working_file,
1854
				);
1855
				continue;
1856
			}
1857
			// Okay, we're creating this file then...?
1858
			elseif (!file_exists($working_file))
1859
				$working_data = '';
1860
			// Phew, it exists!  Load 'er up!
1861
			else
1862
				$working_data = str_replace("\r", '', package_get_contents($working_file));
1863
1864
			$actions[] = array(
1865
				'type' => 'opened',
1866
				'filename' => $working_file
1867
			);
1868
1869
			$operations = $file->exists('operation') ? $file->set('operation') : array();
1870
			foreach ($operations as $operation)
1871
			{
1872
				// Convert operation to an array.
1873
				$actual_operation = array(
1874
					'searches' => array(),
1875
					'error' => $operation->exists('@error') && in_array(trim($operation->fetch('@error')), array('ignore', 'fatal', 'required')) ? trim($operation->fetch('@error')) : 'fatal',
1876
				);
1877
1878
				// The 'add' parameter is used for all searches in this operation.
1879
				$add = $operation->exists('add') ? $operation->fetch('add') : '';
1880
1881
				// Grab all search items of this operation (in most cases just 1).
1882
				$searches = $operation->set('search');
1883
				foreach ($searches as $i => $search)
1884
					$actual_operation['searches'][] = array(
1885
						'position' => $search->exists('@position') && in_array(trim($search->fetch('@position')), array('before', 'after', 'replace', 'end')) ? trim($search->fetch('@position')) : 'replace',
1886
						'is_reg_exp' => $search->exists('@regexp') && trim($search->fetch('@regexp')) === 'true',
1887
						'loose_whitespace' => $search->exists('@whitespace') && trim($search->fetch('@whitespace')) === 'loose',
1888
						'search' => $search->fetch('.'),
1889
						'add' => $add,
1890
						'preg_search' => '',
1891
						'preg_replace' => '',
1892
					);
1893
1894
				// At least one search should be defined.
1895
				if (empty($actual_operation['searches']))
1896
				{
1897
					$actions[] = array(
1898
						'type' => 'failure',
1899
						'filename' => $working_file,
1900
						'search' => $search['search'],
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $search does not seem to be defined for all execution paths leading up to this point.
Loading history...
1901
						'is_custom' => $theme > 1 ? $theme : 0,
1902
					);
1903
1904
					// Skip to the next operation.
1905
					continue;
1906
				}
1907
1908
				// Reverse the operations in case of undoing stuff.
1909
				if ($undo)
1910
				{
1911
					foreach ($actual_operation['searches'] as $i => $search)
1912
					{
1913
						// Reverse modification of regular expressions are not allowed.
1914
						if ($search['is_reg_exp'])
1915
						{
1916
							if ($actual_operation['error'] === 'fatal')
1917
								$actions[] = array(
1918
									'type' => 'failure',
1919
									'filename' => $working_file,
1920
									'search' => $search['search'],
1921
									'is_custom' => $theme > 1 ? $theme : 0,
1922
								);
1923
1924
							// Continue to the next operation.
1925
							continue 2;
1926
						}
1927
1928
						// The replacement is now the search subject...
1929
						if ($search['position'] === 'replace' || $search['position'] === 'end')
1930
							$actual_operation['searches'][$i]['search'] = $search['add'];
1931
						else
1932
						{
1933
							// Reversing a before/after modification becomes a replacement.
1934
							$actual_operation['searches'][$i]['position'] = 'replace';
1935
1936
							if ($search['position'] === 'before')
1937
								$actual_operation['searches'][$i]['search'] .= $search['add'];
1938
							elseif ($search['position'] === 'after')
1939
								$actual_operation['searches'][$i]['search'] = $search['add'] . $search['search'];
1940
						}
1941
1942
						// ...and the search subject is now the replacement.
1943
						$actual_operation['searches'][$i]['add'] = $search['search'];
1944
					}
1945
				}
1946
1947
				// Sort the search list so the replaces come before the add before/after's.
1948
				if (count($actual_operation['searches']) !== 1)
1949
				{
1950
					$replacements = array();
1951
1952
					foreach ($actual_operation['searches'] as $i => $search)
1953
					{
1954
						if ($search['position'] === 'replace')
1955
						{
1956
							$replacements[] = $search;
1957
							unset($actual_operation['searches'][$i]);
1958
						}
1959
					}
1960
					$actual_operation['searches'] = array_merge($replacements, $actual_operation['searches']);
1961
				}
1962
1963
				// Create regular expression replacements from each search.
1964
				foreach ($actual_operation['searches'] as $i => $search)
1965
				{
1966
					// Not much needed if the search subject is already a regexp.
1967
					if ($search['is_reg_exp'])
1968
						$actual_operation['searches'][$i]['preg_search'] = $search['search'];
1969
					else
1970
					{
1971
						// Make the search subject fit into a regular expression.
1972
						$actual_operation['searches'][$i]['preg_search'] = preg_quote($search['search'], '~');
1973
1974
						// Using 'loose', a random amount of tabs and spaces may be used.
1975
						if ($search['loose_whitespace'])
1976
							$actual_operation['searches'][$i]['preg_search'] = preg_replace('~[ \t]+~', '[ \t]+', $actual_operation['searches'][$i]['preg_search']);
1977
					}
1978
1979
					// Shuzzup.  This is done so we can safely use a regular expression. ($0 is bad!!)
1980
					$actual_operation['searches'][$i]['preg_replace'] = strtr($search['add'], array('$' => '[$PACK' . 'AGE1$]', '\\' => '[$PACK' . 'AGE2$]'));
1981
1982
					// Before, so the replacement comes after the search subject :P
1983
					if ($search['position'] === 'before')
1984
					{
1985
						$actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
1986
						$actual_operation['searches'][$i]['preg_replace'] = '$1' . $actual_operation['searches'][$i]['preg_replace'];
1987
					}
1988
1989
					// After, after what?
1990
					elseif ($search['position'] === 'after')
1991
					{
1992
						$actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
1993
						$actual_operation['searches'][$i]['preg_replace'] .= '$1';
1994
					}
1995
1996
					// Position the replacement at the end of the file (or just before the closing PHP tags).
1997
					elseif ($search['position'] === 'end')
1998
					{
1999
						if ($undo)
2000
						{
2001
							$actual_operation['searches'][$i]['preg_replace'] = '';
2002
						}
2003
						else
2004
						{
2005
							$actual_operation['searches'][$i]['preg_search'] = '(\\n\\?\\>)?$';
2006
							$actual_operation['searches'][$i]['preg_replace'] .= '$1';
2007
						}
2008
					}
2009
2010
					// Testing 1, 2, 3...
2011
					$failed = preg_match('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $working_data) === 0;
2012
2013
					// Nope, search pattern not found.
2014
					if ($failed && $actual_operation['error'] === 'fatal')
2015
					{
2016
						$actions[] = array(
2017
							'type' => 'failure',
2018
							'filename' => $working_file,
2019
							'search' => $actual_operation['searches'][$i]['preg_search'],
2020
							'search_original' => $actual_operation['searches'][$i]['search'],
2021
							'replace_original' => $actual_operation['searches'][$i]['add'],
2022
							'position' => $search['position'],
2023
							'is_custom' => $theme > 1 ? $theme : 0,
2024
							'failed' => $failed,
2025
						);
2026
2027
						$everything_found = false;
2028
						continue;
2029
					}
2030
2031
					// Found, but in this case, that means failure!
2032
					elseif (!$failed && $actual_operation['error'] === 'required')
2033
					{
2034
						$actions[] = array(
2035
							'type' => 'failure',
2036
							'filename' => $working_file,
2037
							'search' => $actual_operation['searches'][$i]['preg_search'],
2038
							'search_original' => $actual_operation['searches'][$i]['search'],
2039
							'replace_original' => $actual_operation['searches'][$i]['add'],
2040
							'position' => $search['position'],
2041
							'is_custom' => $theme > 1 ? $theme : 0,
2042
							'failed' => $failed,
2043
						);
2044
2045
						$everything_found = false;
2046
						continue;
2047
					}
2048
2049
					// Replace it into nothing? That's not an option...unless it's an undoing end.
2050
					if ($search['add'] === '' && ($search['position'] !== 'end' || !$undo))
2051
						continue;
2052
2053
					// Finally, we're doing some replacements.
2054
					$working_data = preg_replace('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $actual_operation['searches'][$i]['preg_replace'], $working_data, 1);
2055
2056
					$actions[] = array(
2057
						'type' => 'replace',
2058
						'filename' => $working_file,
2059
						'search' => $actual_operation['searches'][$i]['preg_search'],
2060
						'replace' => $actual_operation['searches'][$i]['preg_replace'],
2061
						'search_original' => $actual_operation['searches'][$i]['search'],
2062
						'replace_original' => $actual_operation['searches'][$i]['add'],
2063
						'position' => $search['position'],
2064
						'failed' => $failed,
2065
						'ignore_failure' => $failed && $actual_operation['error'] === 'ignore',
2066
						'is_custom' => $theme > 1 ? $theme : 0,
2067
					);
2068
				}
2069
			}
2070
2071
			// Fix any little helper symbols ;).
2072
			$working_data = strtr($working_data, array('[$PACK' . 'AGE1$]' => '$', '[$PACK' . 'AGE2$]' => '\\'));
2073
2074
			package_chmod($working_file);
2075
2076
			if ((file_exists($working_file) && !is_writable($working_file)) || (!file_exists($working_file) && !is_writable(dirname($working_file))))
2077
				$actions[] = array(
2078
					'type' => 'chmod',
2079
					'filename' => $working_file
2080
				);
2081
2082
			if (basename($working_file) == 'Settings_bak.php')
2083
				continue;
2084
2085
			if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2086
			{
2087
				// No, no, not Settings.php!
2088
				if (basename($working_file) == 'Settings.php')
2089
					@copy($working_file, dirname($working_file) . '/Settings_bak.php');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for copy(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

2089
					/** @scrutinizer ignore-unhandled */ @copy($working_file, dirname($working_file) . '/Settings_bak.php');

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2090
				else
2091
					@copy($working_file, $working_file . '~');
2092
			}
2093
2094
			// Always call this, even if in testing, because it won't really be written in testing mode.
2095
			package_put_contents($working_file, $working_data, $testing);
2096
2097
			$actions[] = array(
2098
				'type' => 'saved',
2099
				'filename' => $working_file,
2100
				'is_custom' => $theme > 1 ? $theme : 0,
2101
			);
2102
		}
2103
	}
2104
2105
	$actions[] = array(
2106
		'type' => 'result',
2107
		'status' => $everything_found
2108
	);
2109
2110
	return $actions;
2111
}
2112
2113
/**
2114
 * Get the physical contents of a packages file
2115
 *
2116
 * @package Packages
2117
 * @param string $filename
2118
 * @return string
2119
 */
2120
function package_get_contents($filename)
2121
{
2122
	global $package_cache, $modSettings;
2123
2124
	if (!isset($package_cache))
2125
	{
2126
		$mem_check = detectServer()->setMemoryLimit('128M');
2127
2128
		// Windows doesn't seem to care about the memory_limit.
2129
		if (!empty($modSettings['package_disable_cache']) || $mem_check || stripos(PHP_OS, 'win') !== false)
2130
			$package_cache = array();
2131
		else
2132
			$package_cache = false;
2133
	}
2134
2135
	if (strpos($filename, 'packages/') !== false || $package_cache === false || !isset($package_cache[$filename]))
2136
		return file_get_contents($filename);
2137
	else
2138
		return $package_cache[$filename];
2139
}
2140
2141
/**
2142
 * Writes data to a file, almost exactly like the file_put_contents() function.
2143
 *
2144
 * - uses FTP to create/chmod the file when necessary and available.
2145
 * - uses text mode for text mode file extensions.
2146
 * - returns the number of bytes written.
2147
 *
2148
 * @package Packages
2149
 * @param string $filename
2150
 * @param string $data
2151
 * @param bool $testing
2152
 * @return int
2153
 */
2154
function package_put_contents($filename, $data, $testing = false)
2155
{
2156
	global $package_ftp, $package_cache, $modSettings;
2157
	static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2158
2159
	if (!isset($package_cache))
2160
	{
2161
		// Try to increase the memory limit - we don't want to run out of ram!
2162
		$mem_check = detectServer()->setMemoryLimit('128M');
2163
2164
		if (!empty($modSettings['package_disable_cache']) || $mem_check || stripos(PHP_OS, 'win') !== false)
2165
			$package_cache = array();
2166
		else
2167
			$package_cache = false;
2168
	}
2169
2170
	if (isset($package_ftp))
2171
		$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2172
2173
	if (!file_exists($filename) && isset($package_ftp))
2174
		$package_ftp->create_file($ftp_file);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ftp_file does not seem to be defined for all execution paths leading up to this point.
Loading history...
2175
	elseif (!file_exists($filename))
2176
		@touch($filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

2176
		/** @scrutinizer ignore-unhandled */ @touch($filename);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2177
2178
	package_chmod($filename);
2179
2180
	if (!$testing && (strpos($filename, 'packages/') !== false || $package_cache === false))
2181
	{
2182
		$fp = @fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2183
2184
		// We should show an error message or attempt a rollback, no?
2185
		if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
2186
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
2187
2188
		fwrite($fp, $data);
2189
		fclose($fp);
2190
	}
2191
	elseif (strpos($filename, 'packages/') !== false || $package_cache === false)
2192
		return strlen($data);
2193
	else
2194
	{
2195
		$package_cache[$filename] = $data;
2196
2197
		// Permission denied, eh?
2198
		$fp = @fopen($filename, 'r+');
2199
		if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
2200
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
2201
		fclose($fp);
2202
	}
2203
2204
	return strlen($data);
2205
}
2206
2207
/**
2208
 * Clears (removes the files) the current package cache (temp directory)
2209
 *
2210
 * @package Packages
2211
 * @param boolean $trash
2212
 */
2213
function package_flush_cache($trash = false)
2214
{
2215
	global $package_ftp, $package_cache;
2216
	static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2217
2218
	if (empty($package_cache))
2219
		return;
2220
2221
	// First, let's check permissions!
2222
	foreach ($package_cache as $filename => $data)
2223
	{
2224
		if (isset($package_ftp))
2225
			$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2226
2227
		if (!file_exists($filename) && isset($package_ftp))
2228
			$package_ftp->create_file($ftp_file);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ftp_file does not seem to be defined for all execution paths leading up to this point.
Loading history...
2229
		elseif (!file_exists($filename))
2230
			@touch($filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

2230
			/** @scrutinizer ignore-unhandled */ @touch($filename);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2231
2232
		$result = package_chmod($filename);
2233
2234
		// If we are not doing our test pass, then lets do a full write check
2235
		if (!$trash && !is_dir($filename))
2236
		{
2237
			// Acid test, can we really open this file for writing?
2238
			$fp = ($result) ? fopen($filename, 'r+') : $result;
2239
			if (!$fp)
2240
			{
2241
				// We should have package_chmod()'d them before, no?!
2242
				trigger_error('package_flush_cache(): some files are still not writable', E_USER_WARNING);
2243
				return;
2244
			}
2245
			fclose($fp);
2246
		}
2247
	}
2248
2249
	if ($trash)
2250
	{
2251
		$package_cache = array();
2252
		return;
2253
	}
2254
2255
	foreach ($package_cache as $filename => $data)
2256
	{
2257
		if (!is_dir($filename))
2258
		{
2259
			$fp = fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2260
			fwrite($fp, $data);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2260
			fwrite(/** @scrutinizer ignore-type */ $fp, $data);
Loading history...
2261
			fclose($fp);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2261
			fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
2262
		}
2263
	}
2264
2265
	$package_cache = array();
2266
}
2267
2268
/**
2269
 * Try to make a file writable.
2270
 *
2271
 * @package Packages
2272
 * @param string $filename
2273
 * @param string $perm_state = 'writable'
2274
 * @param bool $track_change = false
2275
 * @return boolean True if it worked, false if it didn't
2276
 */
2277
function package_chmod($filename, $perm_state = 'writable', $track_change = false)
2278
{
2279
	global $package_ftp;
2280
2281
	if (file_exists($filename) && is_writable($filename) && $perm_state == 'writable')
2282
		return true;
2283
2284
	// Start off checking without FTP.
2285
	if (!isset($package_ftp) || $package_ftp === false)
2286
	{
2287
		for ($i = 0; $i < 2; $i++)
2288
		{
2289
			$chmod_file = $filename;
2290
2291
			// Start off with a less aggressive test.
2292
			if ($i == 0)
2293
			{
2294
				// If this file doesn't exist, then we actually want to look at whatever parent directory does.
2295
				$subTraverseLimit = 2;
2296
				while (!file_exists($chmod_file) && $subTraverseLimit)
2297
				{
2298
					$chmod_file = dirname($chmod_file);
2299
					$subTraverseLimit--;
2300
				}
2301
2302
				// Keep track of the writable status here.
2303
				$file_permissions = @fileperms($chmod_file);
2304
			}
2305
			else
2306
			{
2307
				// This looks odd, but it's an attempt to work around PHP suExec.
2308
				if (!file_exists($chmod_file) && $perm_state == 'writable')
2309
				{
2310
					$file_permissions = @fileperms(dirname($chmod_file));
2311
2312
					mktree(dirname($chmod_file), 0755);
2313
					@touch($chmod_file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

2313
					/** @scrutinizer ignore-unhandled */ @touch($chmod_file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2314
					elk_chmod($chmod_file, 0755);
2315
				}
2316
				else
2317
					$file_permissions = @fileperms($chmod_file);
2318
			}
2319
2320
			// This looks odd, but it's another attempt to work around PHP suExec.
2321
			if ($perm_state != 'writable')
2322
				elk_chmod($chmod_file, $perm_state == 'execute' ? 0755 : 0644);
2323
			else
2324
			{
2325
				if (!@is_writable($chmod_file))
2326
					elk_chmod($chmod_file, 0755);
2327
				if (!@is_writable($chmod_file))
2328
					elk_chmod($chmod_file, 0777);
2329
				if (!@is_writable(dirname($chmod_file)))
2330
					elk_chmod($chmod_file, 0755);
2331
				if (!@is_writable(dirname($chmod_file)))
2332
					elk_chmod($chmod_file, 0777);
2333
			}
2334
2335
			// The ultimate writable test.
2336
			if ($perm_state == 'writable')
2337
			{
2338
				$fp = is_dir($chmod_file) ? @opendir($chmod_file) : @fopen($chmod_file, 'rb');
2339
				if (@is_writable($chmod_file) && $fp)
2340
				{
2341
					if (!is_dir($chmod_file))
2342
						fclose($fp);
2343
					else
2344
						closedir($fp);
2345
2346
					// It worked!
2347
					if ($track_change)
2348
						$_SESSION['pack_ftp']['original_perms'][$chmod_file] = $file_permissions;
2349
2350
					return true;
2351
				}
2352
			}
2353
			elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$chmod_file]))
2354
				unset($_SESSION['pack_ftp']['original_perms'][$chmod_file]);
2355
		}
2356
2357
		// If we're here we're a failure.
2358
		return false;
2359
	}
2360
	// Otherwise we do have FTP?
2361
	elseif ($package_ftp !== false && !empty($_SESSION['pack_ftp']))
2362
	{
2363
		$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2364
2365
		// This looks odd, but it's an attempt to work around PHP suExec.
2366
		if (!file_exists($filename) && $perm_state == 'writable')
2367
		{
2368
			$file_permissions = @fileperms(dirname($filename));
2369
2370
			mktree(dirname($filename), 0755);
2371
			$package_ftp->create_file($ftp_file);
2372
			$package_ftp->chmod($ftp_file, 0755);
2373
		}
2374
		else
2375
			$file_permissions = @fileperms($filename);
2376
2377
		if ($perm_state != 'writable')
2378
		{
2379
			$package_ftp->chmod($ftp_file, $perm_state == 'execute' ? 0755 : 0644);
2380
		}
2381
		else
2382
		{
2383
			if (!@is_writable($filename))
2384
				$package_ftp->chmod($ftp_file, 0777);
2385
			if (!@is_writable(dirname($filename)))
2386
				$package_ftp->chmod(dirname($ftp_file), 0777);
2387
		}
2388
2389
		if (@is_writable($filename))
2390
		{
2391
			if ($track_change)
2392
				$_SESSION['pack_ftp']['original_perms'][$filename] = $file_permissions;
2393
2394
			return true;
2395
		}
2396
		elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$filename]))
2397
			unset($_SESSION['pack_ftp']['original_perms'][$filename]);
2398
	}
2399
2400
	// Oh dear, we failed if we get here.
2401
	return false;
2402
}
2403
2404
/**
2405
 * Used to crypt the supplied ftp password in this session
2406
 *
2407
 * @package Packages
2408
 * @param string $pass
2409
 * @return string The encrypted password
2410
 */
2411
function package_crypt($pass)
2412
{
2413
	$n = strlen($pass);
2414
2415
	$salt = session_id();
2416
	while (strlen($salt) < $n)
2417
		$salt .= session_id();
2418
2419
	for ($i = 0; $i < $n; $i++)
2420
		$pass[$i] = chr(ord($pass[$i]) ^ (ord($salt[$i]) - 32));
2421
2422
	return $pass;
2423
}
2424
2425
/**
2426
 * Creates a site backup before installing a package just in case things don't go
2427
 * as planned.
2428
 *
2429
 * @package Packages
2430
 * @param string $id
2431
 */
2432
function package_create_backup($id = 'backup')
2433
{
2434
	$db = database();
2435
	$files = new ArrayIterator();
2436
	$use_relative_paths = empty($_REQUEST['use_full_paths']);
2437
2438
	// The files that reside outside of sources, in the base, we add manually
2439
	$base_files = array('index.php', 'SSI.php', 'agreement.txt', 'subscriptions.php',
2440
	'email_imap_cron.php', 'emailpost.php', 'emailtopic.php');
2441
	foreach ($base_files as $file)
2442
	{
2443
		if (file_exists(BOARDDIR . '/' . $file))
2444
			$files[$use_relative_paths ? $file : realpath(BOARDDIR . '/' . $file)] = BOARDDIR . '/' . $file;
2445
	}
2446
2447
	// Root directory where most of our files reside
2448
	$dirs = array(
2449
		SOURCEDIR => $use_relative_paths ? 'sources/' : strtr(SOURCEDIR . '/', '\\', '/')
2450
	);
2451
2452
	// Find all installed theme directories
2453
	$request = $db->query('', '
2454
		SELECT value
2455
		FROM {db_prefix}themes
2456
		WHERE id_member = {int:no_member}
2457
			AND variable = {string:theme_dir}',
2458
		array(
2459
			'no_member' => 0,
2460
			'theme_dir' => 'theme_dir',
2461
		)
2462
	);
2463
	while ($row = $db->fetch_assoc($request))
2464
		$dirs[$row['value']] = $use_relative_paths ? 'themes/' . basename($row['value']) . '/' : strtr($row['value'] . '/', '\\', '/');
2465
	$db->free_result($request);
2466
2467
	try
2468
	{
2469
		foreach ($dirs as $dir => $dest)
2470
		{
2471
			$iter = new RecursiveIteratorIterator(
2472
				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
2473
				RecursiveIteratorIterator::CHILD_FIRST,
2474
				RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
2475
			);
2476
2477
			foreach ($iter as $entry => $dir)
0 ignored issues
show
Comprehensibility Bug introduced by
$dir is overwriting a variable from outer foreach loop.
Loading history...
2478
			{
2479
				if ($dir->isDir())
2480
					continue;
2481
2482
				if (preg_match('~^(\.{1,2}|CVS|backup.*|help|images|.*\~)$~', $entry) != 0)
2483
					continue;
2484
2485
				$files[$use_relative_paths ? str_replace(realpath(BOARDDIR), '', $entry) : $entry] = $entry;
2486
			}
2487
		}
2488
2489
		// Make sure we have a backup directory and its writable
2490
		if (!file_exists(BOARDDIR . '/packages/backups'))
2491
			mktree(BOARDDIR . '/packages/backups', 0777);
2492
2493
		if (!is_writable(BOARDDIR . '/packages/backups'))
2494
			package_chmod(BOARDDIR . '/packages/backups');
2495
2496
		// Name the output file, yyyy-mm-dd_before_package_name.tar.gz
2497
		$output_file = BOARDDIR . '/packages/backups/' . strftime('%Y-%m-%d_') . preg_replace('~[$\\\\/:<>|?*"\']~', '', $id);
2498
		$output_ext = '.tar';
2499
2500
		if (file_exists($output_file . $output_ext . '.gz'))
2501
		{
2502
			$i = 2;
2503
			while (file_exists($output_file . '_' . $i . $output_ext . '.gz'))
2504
				$i++;
2505
			$output_file = $output_file . '_' . $i . $output_ext;
2506
		}
2507
		else
2508
			$output_file .= $output_ext;
2509
2510
		// Buy some more time so we have enough to create this archive
2511
		detectServer()->setTimeLimit(300);
2512
2513
		$a = new PharData($output_file);
2514
		$a->buildFromIterator($files);
2515
		$a->compress(Phar::GZ);
2516
2517
		/*
2518
		 * Destroying the local var tells PharData to close its internal
2519
		 * file pointer, enabling us to delete the uncompressed tarball.
2520
		 */
2521
		unset($a);
2522
		unlink($output_file);
2523
	}
2524
	catch (Exception $e)
2525
	{
2526
		Errors::instance()->log_error($e->getMessage(), 'backup');
2527
2528
		return false;
2529
	}
2530
2531
	return true;
2532
}
2533
2534
/**
2535
 * Get the contents of a URL, irrespective of allow_url_fopen.
2536
 *
2537
 * - reads the contents of an http or ftp address and returns the page in a string
2538
 * - will accept up to 3 page redirections (redirection_level in the function call is private)
2539
 * - if post_data is supplied, the value and length is posted to the given url as form data
2540
 * - URL must be supplied in lowercase
2541
 *
2542
 * @package Packages
2543
 * @param string $url
2544
 * @param string $post_data = ''
2545
 * @param bool $keep_alive = false
2546
 * @param int $redirection_level = 3
2547
 * @return string
2548
 */
2549
function fetch_web_data($url, $post_data = '', $keep_alive = false, $redirection_level = 3)
2550
{
2551
	global $webmaster_email;
2552
	static $keep_alive_dom = null, $keep_alive_fp = null;
2553
2554
	preg_match('~^(http|ftp)(s)?://([^/:]+)(:(\d+))?(.+)$~', $url, $match);
2555
2556
	// An FTP url. We should try connecting and RETRieving it...
2557
	if (empty($match[1]))
2558
		return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
2559
	elseif ($match[1] == 'ftp')
2560
	{
2561
		// Establish a connection and attempt to enable passive mode.
2562
		$ftp = new Ftp_Connection(($match[2] ? 'ssl://' : '') . $match[3], empty($match[5]) ? 21 : $match[5], 'anonymous', $webmaster_email);
2563
		if ($ftp->error !== false || !$ftp->passive())
2564
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
2565
2566
		// I want that one *points*!
2567
		fwrite($ftp->connection, 'RETR ' . $match[6] . "\r\n");
2568
2569
		// Since passive mode worked (or we would have returned already!) open the connection.
2570
		$fp = @fsockopen($ftp->pasv['ip'], $ftp->pasv['port'], $err, $err, 5);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $err seems to be never defined.
Loading history...
2571
		if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
2572
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
2573
2574
		// The server should now say something in acknowledgement.
2575
		$ftp->check_response(150);
2576
2577
		$data = '';
2578
		while (!feof($fp))
2579
			$data .= fread($fp, 4096);
2580
		fclose($fp);
2581
2582
		// All done, right?  Good.
2583
		$ftp->check_response(226);
2584
		$ftp->close();
2585
	}
2586
	// More likely a standard HTTP URL, first try to use cURL if available
2587
	elseif (isset($match[1]) && $match[1] === 'http' && function_exists('curl_init'))
2588
	{
2589
		$fetch_data = new Curl_Fetch_Webdata(array(), $redirection_level);
2590
		$fetch_data->get_url_data($url, $post_data);
2591
2592
		// no errors and a 200 result, then we have a good dataset, well we at least have data ;)
2593
		if ($fetch_data->result('code') == 200 && !$fetch_data->result('error'))
2594
			$data = $fetch_data->result('body');
2595
		else
2596
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
2597
	}
2598
	// This is more likely; a standard HTTP URL.
2599
	elseif (isset($match[1]) && $match[1] == 'http')
2600
	{
2601
		if ($keep_alive && $match[3] == $keep_alive_dom)
2602
			$fp = $keep_alive_fp;
2603
		if (empty($fp))
2604
		{
2605
			// Open the socket on the port we want...
2606
			$fp = @fsockopen(($match[2] ? 'ssl://' : '') . $match[3], empty($match[5]) ? ($match[2] ? 443 : 80) : $match[5], $err, $err, 5);
2607
			if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
2608
				return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
2609
		}
2610
2611
		if ($keep_alive)
2612
		{
2613
			$keep_alive_dom = $match[3];
2614
			$keep_alive_fp = $fp;
2615
		}
2616
2617
		// I want this, from there, and I'm not going to be bothering you for more (probably.)
2618
		if (empty($post_data))
2619
		{
2620
			fwrite($fp, 'GET ' . ($match[6] !== '/' ? str_replace(' ', '%20', $match[6]) : '/') . ' HTTP/1.1' . "\r\n");
2621
			fwrite($fp, 'Host: ' . $match[3] . (empty($match[5]) ? ($match[2] ? ':443' : '') : ':' . $match[5]) . "\r\n");
2622
			fwrite($fp, 'User-Agent: PHP/ELK' . "\r\n");
2623
			if ($keep_alive)
2624
				fwrite($fp, 'Connection: Keep-Alive' . "\r\n\r\n");
2625
			else
2626
				fwrite($fp, 'Connection: close' . "\r\n\r\n");
2627
		}
2628
		else
2629
		{
2630
			fwrite($fp, 'POST ' . ($match[6] !== '/' ? $match[6] : '') . ' HTTP/1.1' . "\r\n");
2631
			fwrite($fp, 'Host: ' . $match[3] . (empty($match[5]) ? ($match[2] ? ':443' : '') : ':' . $match[5]) . "\r\n");
2632
			fwrite($fp, 'User-Agent: PHP/ELK' . "\r\n");
2633
			if ($keep_alive)
2634
				fwrite($fp, 'Connection: Keep-Alive' . "\r\n");
2635
			else
2636
				fwrite($fp, 'Connection: close' . "\r\n");
2637
			fwrite($fp, 'Content-Type: application/x-www-form-urlencoded' . "\r\n");
2638
			fwrite($fp, 'Content-Length: ' . strlen($post_data) . "\r\n\r\n");
2639
			fwrite($fp, $post_data);
2640
		}
2641
2642
		$response = fgets($fp, 768);
2643
2644
		// Redirect in case this location is permanently or temporarily moved.
2645
		if ($redirection_level < 6 && preg_match('~^HTTP/\S+\s+30[127]~i', $response) === 1)
2646
		{
2647
			$location = '';
2648
			while (!feof($fp) && trim($header = fgets($fp, 4096)) != '')
2649
				if (strpos($header, 'Location:') !== false)
2650
					$location = trim(substr($header, strpos($header, ':') + 1));
2651
2652
			if (empty($location))
2653
				return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
2654
			else
2655
			{
2656
				if (!$keep_alive)
2657
					fclose($fp);
2658
				return fetch_web_data($location, $post_data, $keep_alive, $redirection_level + 1);
2659
			}
2660
		}
2661
2662
		// Make sure we get a 200 OK.
2663
		elseif (preg_match('~^HTTP/\S+\s+20[01]~i', $response) === 0)
2664
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
2665
2666
		// Skip the headers...
2667
		while (!feof($fp) && trim($header = fgets($fp, 4096)) != '')
2668
		{
2669
			if (preg_match('~content-length:\s*(\d+)~i', $header, $match) != 0)
2670
				$content_length = $match[1];
2671
			elseif (preg_match('~connection:\s*close~i', $header) != 0)
2672
			{
2673
				$keep_alive_dom = null;
2674
				$keep_alive = false;
2675
			}
2676
2677
			continue;
2678
		}
2679
2680
		$data = '';
2681
		if (isset($content_length))
2682
		{
2683
			while (!feof($fp) && strlen($data) < $content_length)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $content_length does not seem to be defined for all execution paths leading up to this point.
Loading history...
2684
				$data .= fread($fp, $content_length - strlen($data));
2685
		}
2686
		else
2687
		{
2688
			while (!feof($fp))
2689
				$data .= fread($fp, 4096);
2690
		}
2691
2692
		if (!$keep_alive)
2693
			fclose($fp);
2694
	}
2695
	else
2696
	{
2697
		// Umm, this shouldn't happen?
2698
		trigger_error('fetch_web_data(): Bad URL', E_USER_NOTICE);
2699
		$data = false;
2700
	}
2701
2702
	return $data;
2703
}
2704
2705
if (!function_exists('crc32_compat'))
2706
{
2707
	require_once(SUBSDIR . '/Compat.subs.php');
2708
}
2709
2710
/**
2711
 * Checks if a package is installed or not
2712
 *
2713
 * - If installed returns an array of themes, db changes and versions associated with
2714
 * the package id
2715
 *
2716
 * @package Packages
2717
 * @param string $id of package to check
2718
 * @param string|null $install_id to check
2719
 *
2720
 * @return array
2721
 */
2722
function isPackageInstalled($id, $install_id = null)
2723
{
2724
	$db = database();
2725
2726
	$result = array(
2727
		'package_id' => null,
2728
		'install_state' => null,
2729
		'old_themes' => null,
2730
		'old_version' => null,
2731
		'db_changes' => array()
2732
	);
2733
2734
	if (empty($id))
2735
		return $result;
2736
2737
	// See if it is installed?
2738
	$request = $db->query('', '
2739
		SELECT version, themes_installed, db_changes, package_id, install_state
2740
		FROM {db_prefix}log_packages
2741
		WHERE package_id = {string:current_package}
2742
			AND install_state != {int:not_installed}
2743
			' . (!empty($install_id) ? ' AND id_install = {int:install_id} ' : '') . '
2744
		ORDER BY time_installed DESC
2745
		LIMIT 1',
2746
		array(
2747
			'not_installed' => 0,
2748
			'current_package' => $id,
2749
			'install_id' => $install_id,
2750
		)
2751
	);
2752
	while ($row = $db->fetch_assoc($request))
2753
	{
2754
		$result = array(
2755
			'old_themes' => explode(',', $row['themes_installed']),
2756
			'old_version' => $row['version'],
2757
			'db_changes' => empty($row['db_changes']) ? array() : Util::unserialize($row['db_changes']),
2758
			'package_id' => $row['package_id'],
2759
			'install_state' => $row['install_state'],
2760
		);
2761
	}
2762
	$db->free_result($request);
2763
2764
	return $result;
2765
}
2766
2767
/**
2768
 * For uninstalling action, updates the log_packages install_state state to 0 (uninstalled)
2769
 *
2770
 * @package Packages
2771
 * @param string $id package_id to update
2772
 * @param string $install_id install id of the package
2773
 */
2774
function setPackageState($id, $install_id)
2775
{
2776
	global $user_info;
2777
2778
	$db = database();
2779
2780
	$db->query('', '
2781
		UPDATE {db_prefix}log_packages
2782
		SET install_state = {int:not_installed}, member_removed = {string:member_name}, id_member_removed = {int:current_member},
2783
			time_removed = {int:current_time}
2784
		WHERE package_id = {string:package_id}
2785
			AND id_install = {int:install_id}',
2786
		array(
2787
			'current_member' => $user_info['id'],
2788
			'not_installed' => 0,
2789
			'current_time' => time(),
2790
			'package_id' => $id,
2791
			'member_name' => $user_info['name'],
2792
			'install_id' => $install_id,
2793
		)
2794
	);
2795
}
2796
2797
/**
2798
 * Checks if a package is installed, and if so returns its version level
2799
 *
2800
 * @package Packages
2801
 * @param string $id
2802
 */
2803
function checkPackageDependency($id)
2804
{
2805
	$db = database();
2806
2807
	$request = $db->query('', '
2808
		SELECT version
2809
		FROM {db_prefix}log_packages
2810
		WHERE package_id = {string:current_package}
2811
			AND install_state != {int:not_installed}
2812
		ORDER BY time_installed DESC
2813
		LIMIT 1',
2814
		array(
2815
			'not_installed' => 0,
2816
			'current_package' => $id,
2817
		)
2818
	);
2819
	while ($row = $db->fetch_row($request))
2820
		list ($version) = $row;
2821
	$db->free_result($request);
2822
2823
	return $version;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $version does not seem to be defined for all execution paths leading up to this point.
Loading history...
2824
}
2825
2826
/**
2827
 * Adds a record to the log packages table
2828
 *
2829
 * @package Packages
2830
 * @param mixed[] $packageInfo
2831
 * @param string $failed_step_insert
2832
 * @param string $themes_installed
2833
 * @param string $db_changes
2834
 * @param bool $is_upgrade
2835
 * @param string $credits_tag
2836
 */
2837
function addPackageLog($packageInfo, $failed_step_insert, $themes_installed, $db_changes, $is_upgrade, $credits_tag)
2838
{
2839
	global $user_info;
2840
2841
	$db = database();
2842
2843
	$db->insert('', '{db_prefix}log_packages',
2844
		array(
2845
			'filename' => 'string', 'name' => 'string', 'package_id' => 'string', 'version' => 'string',
2846
			'id_member_installed' => 'int', 'member_installed' => 'string', 'time_installed' => 'int',
2847
			'install_state' => 'int', 'failed_steps' => 'string', 'themes_installed' => 'string',
2848
			'member_removed' => 'int', 'db_changes' => 'string', 'credits' => 'string',
2849
		),
2850
		array(
2851
			$packageInfo['filename'], $packageInfo['name'], $packageInfo['id'], $packageInfo['version'],
2852
			$user_info['id'], $user_info['name'], time(),
2853
			$is_upgrade ? 2 : 1, $failed_step_insert, $themes_installed,
2854
			0, $db_changes, $credits_tag,
2855
		),
2856
		array('id_install')
2857
	);
2858
}
2859
2860
/**
2861
 * Called from action_flush, used to flag all packages as uninstalled.
2862
 *
2863
 * @package Packages
2864
 */
2865
function setPackagesAsUninstalled()
2866
{
2867
	$db = database();
2868
2869
	// Set everything as uninstalled, just like that
2870
	$db->query('', '
2871
		UPDATE {db_prefix}log_packages
2872
		SET install_state = {int:not_installed}',
2873
		array(
2874
			'not_installed' => 0,
2875
		)
2876
	);
2877
}
2878
2879
/**
2880
 * Validates that the remote url is one of our known package servers
2881
 *
2882
 * @package Packages
2883
 * @param string $remote_url
2884
 */
2885
function isAuthorizedServer($remote_url)
2886
{
2887
	global $modSettings;
2888
2889
	// Know addon servers
2890
	$servers = Util::unserialize($modSettings['authorized_package_servers']);
2891
	if (empty($servers))
2892
		return false;
2893
2894
	foreach ($servers as $server)
2895
		if (preg_match('~^' . preg_quote($server) . '~', $remote_url) == 0)
2896
			return true;
2897
2898
	return false;
2899
}
2900
2901
/**
2902
 * Simple wrapper around chmod
2903
 *
2904
 * - Checks proper value for mode is supplied
2905
 * - Consolidates chmod error suppression to single function
2906
 *
2907
 * @param string $file
2908
 * @param string|int|null $mode
2909
 *
2910
 * @return bool
2911
 */
2912
function elk_chmod($file, $mode = null)
2913
{
2914
	$result = false;
2915
2916
	if (!isset($mode))
2917
	{
2918
		if (is_dir($file))
2919
		{
2920
			$mode = 0755;
2921
		}
2922
		else
2923
		{
2924
			$mode = 0664;
2925
		}
2926
	}
2927
2928
	// Make sure we have a form of 0777 or '777' or '0777' so its safe for intval '8'
2929
	if ($mode == decoct(octdec("$mode")))
0 ignored issues
show
Bug introduced by
It seems like octdec($mode) can also be of type double; however, parameter $number of decoct() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2929
	if ($mode == decoct(/** @scrutinizer ignore-type */ octdec("$mode")))
Loading history...
2930
		$result = @chmod($file, intval($mode, 8));
2931
2932
	return $result;
2933
}
2934