Passed
Pull Request — release-2.1 (#7180)
by John
05:54
created

read_tgz_file()   B

Complexity

Conditions 9
Paths 20

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 12
c 1
b 0
f 0
nc 20
nop 5
dl 0
loc 20
rs 8.0555
1
<?php
2
3
/**
4
 * This file's central purpose of existence is that of making the package
5
 * manager work nicely.  It contains functions for handling tar.gz and zip
6
 * files, as well as a simple xml parser to handle the xml package stuff.
7
 * Not to mention a few functions to make file handling easier.
8
 *
9
 * Simple Machines Forum (SMF)
10
 *
11
 * @package SMF
12
 * @author Simple Machines https://www.simplemachines.org
13
 * @copyright 2021 Simple Machines and individual contributors
14
 * @license https://www.simplemachines.org/about/smf/license.php BSD
15
 *
16
 * @version 2.1 RC4
17
 */
18
19
if (!defined('SMF'))
20
	die('No direct access...');
21
22
/**
23
 * Reads an archive from either a remote location or from the local filesystem.
24
 *
25
 * @param string $gzfilename The path to the tar.gz file
26
 * @param string $destination The path to the desitnation directory
27
 * @param bool $single_file If true returns the contents of the file specified by destination if it exists
28
 * @param bool $overwrite Whether to overwrite existing files
29
 * @param null|array $files_to_extract Specific files to extract
30
 * @return array|false An array of information about extracted files or false on failure
31
 */
32
function read_tgz_file($gzfilename, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
33
{
34
	$data = substr($gzfilename, 0, 7) == 'http://' || substr($gzfilename, 0, 8) == 'https://'
35
		? fetch_web_data($gzfilename)
36
		: file_get_contents($gzfilename);
37
38
	if ($data === false)
39
		return false;
40
41
	// Too short for magic numbers? No fortune cookie for you!
42
	if (strlen($data) < 2)
43
		return false;
44
45
	if ($data[0] == "\x1f" && $data[1] == "\x8b")
46
		return read_tgz_data($data, $destination, $single_file, $overwrite, $files_to_extract);
47
	// Okay, this ain't no tar.gz, but maybe it's a zip file.
48
	elseif ($data[0] == 'P' && $data[1] == 'K')
49
		return read_zip_data($data, $destination, $single_file, $overwrite, $files_to_extract);
50
51
	return false;
52
}
53
54
/**
55
 * Extracts a file or files from the .tar.gz contained in data.
56
 *
57
 * detects if the file is really a .zip file, and if so returns the result of read_zip_data
58
 *
59
 * if destination is null
60
 *	- returns a list of files in the archive.
61
 *
62
 * if single_file is true
63
 * - returns the contents of the file specified by destination, if it exists, or false.
64
 * - destination can start with * and / to signify that the file may come from any directory.
65
 * - destination should not begin with a / if single_file is true.
66
 *
67
 * overwrites existing files with newer modification times if and only if overwrite is true.
68
 * creates the destination directory if it doesn't exist, and is is specified.
69
 * requires zlib support be built into PHP.
70
 * returns an array of the files extracted.
71
 * if files_to_extract is not equal to null only extracts file within this array.
72
 *
73
 * @param string $data The gzipped tarball
74
 * @param null|string $destination The destination
75
 * @param bool $single_file Whether to only extract a single file
76
 * @param bool $overwrite Whether to overwrite existing data
77
 * @param null|array $files_to_extract If set, only extracts the specified files
78
 * @return array|false An array of information about the extracted files or false on failure
79
 */
80
function read_tgz_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
81
{
82
	// Make sure we have this loaded.
83
	loadLanguage('Packages');
84
85
	// This function sorta needs gzinflate!
86
	if (!function_exists('gzinflate'))
87
		fatal_lang_error('package_no_lib', 'critical', array('package_no_zlib', 'package_no_package_manager'));
88
89
	umask(0);
90
	if (!$single_file && $destination !== null && !file_exists($destination))
91
		mktree($destination, 0777);
92
93
	$flags = unpack('Ct/Cf', substr($data, 2, 2));
94
95
	// Not deflate!
96
	if ($flags['t'] != 8)
97
		return false;
98
	$flags = $flags['f'];
99
100
	$offset = 10;
101
	$octdec = array('mode', 'uid', 'gid', 'size', 'mtime', 'checksum');
102
103
	// "Read" the filename and comment.
104
	// @todo Might be mussed.
105
	if ($flags & 12)
106
	{
107
		while ($flags & 8 && $data[$offset++] != "\0")
108
			continue;
109
		while ($flags & 4 && $data[$offset++] != "\0")
110
			continue;
111
	}
112
113
	$crc = unpack('Vcrc32/Visize', substr($data, strlen($data) - 8, 8));
114
	$data = @gzinflate(substr($data, $offset, strlen($data) - 8 - $offset));
115
116
	// smf_crc32 and crc32 may not return the same results, so we accept either.
117
	if ($crc['crc32'] != smf_crc32($data) && $crc['crc32'] != crc32($data))
0 ignored issues
show
Bug introduced by
It seems like $data can also be of type false; however, parameter $string of crc32() 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

117
	if ($crc['crc32'] != smf_crc32($data) && $crc['crc32'] != crc32(/** @scrutinizer ignore-type */ $data))
Loading history...
Bug introduced by
It seems like $data can also be of type false; however, parameter $number of smf_crc32() 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

117
	if ($crc['crc32'] != smf_crc32(/** @scrutinizer ignore-type */ $data) && $crc['crc32'] != crc32($data))
Loading history...
118
		return false;
119
120
	$blocks = strlen($data) / 512 - 1;
0 ignored issues
show
Bug introduced by
It seems like $data can also be of type false; however, parameter $string of strlen() 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

120
	$blocks = strlen(/** @scrutinizer ignore-type */ $data) / 512 - 1;
Loading history...
121
	$offset = 0;
122
123
	$return = array();
124
125
	while ($offset < $blocks)
126
	{
127
		$header = substr($data, $offset << 9, 512);
0 ignored issues
show
Bug introduced by
It seems like $data can also be of type false; however, parameter $string of substr() 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

127
		$header = substr(/** @scrutinizer ignore-type */ $data, $offset << 9, 512);
Loading history...
128
		$current = unpack('a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100linkname/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor/a155path', $header);
129
130
		// Blank record?  This is probably at the end of the file.
131
		if (empty($current['filename']))
132
		{
133
			$offset += 512;
134
			continue;
135
		}
136
137
		foreach ($current as $k => $v)
138
		{
139
			if (in_array($k, $octdec))
140
				$current[$k] = octdec(trim($v));
141
			else
142
				$current[$k] = trim($v);
143
		}
144
145
		if ($current['type'] == '5' && substr($current['filename'], -1) != '/')
146
			$current['filename'] .= '/';
147
148
		$checksum = 256;
149
		for ($i = 0; $i < 148; $i++)
150
			$checksum += ord($header[$i]);
151
		for ($i = 156; $i < 512; $i++)
152
			$checksum += ord($header[$i]);
153
154
		if ($current['checksum'] != $checksum)
155
			break;
156
157
		$size = ceil($current['size'] / 512);
158
		$current['data'] = substr($data, ++$offset << 9, $current['size']);
159
		$offset += $size;
160
161
		// Not a directory and doesn't exist already...
162
		if (substr($current['filename'], -1, 1) != '/' && $destination !== null && !file_exists($destination . '/' . $current['filename']))
163
			$write_this = true;
164
		// File exists... check if it is newer.
165
		elseif (substr($current['filename'], -1, 1) != '/')
166
			$write_this = $overwrite || ($destination !== null && filemtime($destination . '/' . $current['filename']) < $current['mtime']);
167
		// Folder... create.
168
		elseif ($destination !== null && !$single_file)
169
		{
170
			// Protect from accidental parent directory writing...
171
			$current['filename'] = strtr($current['filename'], array('../' => '', '/..' => ''));
172
173
			if (!file_exists($destination . '/' . $current['filename']))
174
				mktree($destination . '/' . $current['filename'], 0777);
175
			$write_this = false;
176
		}
177
		else
178
			$write_this = false;
179
180
		if ($write_this && $destination !== null)
181
		{
182
			if (strpos($current['filename'], '/') !== false && !$single_file)
183
				mktree($destination . '/' . dirname($current['filename']), 0777);
184
185
			// Is this the file we're looking for?
186
			if ($single_file && ($destination == $current['filename'] || $destination == '*/' . basename($current['filename'])))
187
				return $current['data'];
188
			// If we're looking for another file, keep going.
189
			elseif ($single_file)
190
				continue;
191
			// Looking for restricted files?
192
			elseif ($files_to_extract !== null && !in_array($current['filename'], $files_to_extract))
193
				continue;
194
195
			package_put_contents($destination . '/' . $current['filename'], $current['data']);
196
		}
197
198
		if (substr($current['filename'], -1, 1) != '/')
199
			$return[] = array(
200
				'filename' => $current['filename'],
201
				'md5' => md5($current['data']),
202
				'preview' => substr($current['data'], 0, 100),
203
				'size' => $current['size'],
204
				'skipped' => false
205
			);
206
	}
207
208
	if ($destination !== null && !$single_file)
209
		package_flush_cache();
210
211
	if ($single_file)
212
		return false;
213
	else
214
		return $return;
215
}
216
217
/**
218
 * Extract zip data.
219
 *
220
 * If single_file is true, destination can start with * and / to signify that the file may come from any directory.
221
 * Destination should not begin with a / if single_file is true.
222
 *
223
 * @param string $data ZIP data
224
 * @param string $destination Null to display a listing of files in the archive, the destination for the files in the archive or the name of a single file to display (if $single_file is true)
225
 * @param boolean $single_file If true, returns the contents of the file specified by destination or false if the file can't be found (default value is false).
226
 * @param boolean $overwrite If true, will overwrite files with newer modication times. Default is false.
227
 * @param array $files_to_extract
228
 * @return mixed If destination is null, return a short array of a few file details optionally delimited by $files_to_extract. If $single_file is true, return contents of a file as a string; false otherwise
229
 */
230
function read_zip_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
231
{
232
	umask(0);
233
	if ($destination !== null && !file_exists($destination) && !$single_file)
234
		mktree($destination, 0777);
235
236
	// Search for the end of directory signature 0x06054b50.
237
	if (($data_ecr = strrpos($data, "\x50\x4b\x05\x06")) === false)
238
		return false;
239
	$return = array();
240
241
	// End of central directory record (EOCD)
242
	$cdir = unpack('vdisk/@4/vdisk_entries/ventries/@12/Voffset', $data, $data_ecr + 4);
243
244
	// We only support a single disk.
245
	if ($cdir['disk_entries'] != $cdir['entries'])
246
		return false;
247
248
	// First central file directory
249
	$pos_entry = $cdir['offset'];
250
251
	for ($i = 0; $i < $cdir['entries']; $i++)
252
	{
253
		// Central directory file header
254
		$header = unpack('Vcompressed_size/@8/vlen1/vlen2/vlen3/vdisk/@22/Voffset', $data, $pos_entry + 20);
255
256
		// Sanity check: same disk?
257
		if ($header['disk'] != $cdir['disk'])
258
			continue;
259
260
		// Next central file directory
261
		$pos_entry += 46 + $header['len1'] + $header['len2'] + $header['len3'];
262
263
		// Local file header (so called because it is in the same file as the data in multi-part archives)
264
		$file_info = unpack(
265
			'vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len',
266
			$data,
267
			$header['offset'] + 6
268
		);
269
270
		$file_info['filename'] = substr($data, $header['offset'] + 30, $file_info['filename_len']);
271
		$is_file = substr($file_info['filename'], -1) != '/';
272
273
		/*
274
		 * If the bit at offset 3 (0x08) of the general-purpose flags field
275
		 * is set, then the CRC-32 and file sizes are not known when the header
276
		 * is written. The fields in the local header are filled with zero, and
277
		 * the CRC-32 and size are appended in a 12-byte structure (optionally
278
		 * preceded by a 4-byte signature) immediately after the compressed data:
279
		 */
280
		if ($file_info['flag'] & 0x08)
281
		{
282
			$gplen = $header['offset'] + 30 + $file_info['filename_len'] + $file_info['extra_len'] + $header['compressed_size'];
283
284
			// The spec allows for an optional header in the general purpose record
285
			if (substr($data, $gplen, 4) === "\x50\x4b\x07\x08")
286
				$gplen += 4;
287
288
			if (($general_purpose = unpack('Vcrc/Vcompressed_size/Vsize', $data, $gplen)) !== false)
289
				$file_info = $general_purpose + $file_info;
290
		}
291
292
		$write_this = false;
293
		if ($destination !== null)
294
		{
295
			// If this is a file, and it doesn't exist.... happy days!
296
			if ($is_file)
297
				$write_this = !file_exists($destination . '/' . $file_info['filename']) || $overwrite;
298
			// This is a directory, so we're gonna want to create it. (probably...)
299
			elseif (!$single_file)
300
			{
301
				$file_info['filename'] = strtr($file_info['filename'], array('../' => '', '/..' => ''));
302
303
				if (!file_exists($destination . '/' . $file_info['filename']))
304
					mktree($destination . '/' . $file_info['filename'], 0777);
305
			}
306
		}
307
308
		// Get the actual compressed data.
309
		$file_info['data'] = substr(
310
			$data,
311
			$header['offset'] + 30 + $file_info['filename_len'] + $file_info['extra_len'],
312
			$file_info['compressed_size']
313
		);
314
315
		// Only for the deflate method (the most common)
316
		if ($file_info['compression'] == 8)
317
			$file_info['data'] = gzinflate($file_info['data']);
318
		// We do not support any other compresion methods.
319
		elseif ($file_info['compression'] != 0)
320
			continue;
321
322
		// PKZip/ITU-T V.42 CRC-32
323
		if (hash('crc32b', $file_info['data']) !== sprintf('%08x', $file_info['crc']))
324
			continue;
325
326
		// Okay! We can write this file, looks good from here...
327
		if ($write_this)
328
		{
329
			// If we're looking for a specific file, and this is it... ka-bam, baby.
330
			if ($single_file && ($destination == $file_info['filename'] || $destination == '*/' . basename($file_info['filename'])))
331
				return $file_info['data'];
332
			// Oh, another file? Fine. You don't like this file, do you?  I know how it is.  Yeah... just go away.  No, don't apologize. I know this file's just not *good enough* for you.
333
			elseif ($single_file || ($files_to_extract !== null && !in_array($file_info['filename'], $files_to_extract)))
334
				continue;
335
336
			if (!$single_file && strpos($file_info['filename'], '/') !== false)
337
				mktree($destination . '/' . dirname($file_info['filename']), 0777);
338
339
			package_put_contents($destination . '/' . $file_info['filename'], $file_info['data']);
340
		}
341
342
		if ($is_file)
343
			$return[] = array(
344
				'filename' => $file_info['filename'],
345
				'md5' => md5($file_info['data']),
346
				'preview' => substr($file_info['data'], 0, 100),
347
				'size' => $file_info['size'],
348
				'skipped' => false
349
			);
350
	}
351
352
	if ($destination !== null && !$single_file)
353
		package_flush_cache();
354
355
	return $single_file ? false : $return;
356
}
357
358
/**
359
 * Checks the existence of a remote file since file_exists() does not do remote.
360
 * will return false if the file is "moved permanently" or similar.
361
 *
362
 * @param string $url The URL to parse
363
 * @return bool Whether the specified URL exists
364
 */
365
function url_exists($url)
366
{
367
	$a_url = parse_iri($url);
368
369
	if (!isset($a_url['scheme']))
370
		return false;
371
372
	// Attempt to connect...
373
	$temp = '';
374
	$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 $error_code 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

374
	$fid = fsockopen($a_url['host'], !isset($a_url['port']) ? 80 : $a_url['port'], /** @scrutinizer ignore-type */ $temp, $temp, 8);
Loading history...
375
	if (!$fid)
0 ignored issues
show
introduced by
$fid is of type resource, thus it always evaluated to false.
Loading history...
376
		return false;
377
378
	fputs($fid, 'HEAD ' . $a_url['path'] . ' HTTP/1.0' . "\r\n" . 'Host: ' . $a_url['host'] . "\r\n\r\n");
379
	$head = fread($fid, 1024);
380
	fclose($fid);
381
382
	return preg_match('~^HTTP/.+\s+(20[01]|30[127])~i', $head) == 1;
383
}
384
385
/**
386
 * Loads and returns an array of installed packages.
387
 *
388
 *  default sort order is package_installed time
389
 *
390
 * @return array An array of info about installed packages
391
 */
392
function loadInstalledPackages()
393
{
394
	global $smcFunc;
395
396
	// Load the packages from the database - note this is ordered by install time to ensure latest package uninstalled first.
397
	$request = $smcFunc['db_query']('', '
398
		SELECT id_install, package_id, filename, name, version, time_installed
399
		FROM {db_prefix}log_packages
400
		WHERE install_state != {int:not_installed}
401
		ORDER BY time_installed DESC',
402
		array(
403
			'not_installed' => 0,
404
		)
405
	);
406
	$installed = array();
407
	$found = array();
408
	while ($row = $smcFunc['db_fetch_assoc']($request))
409
	{
410
		// Already found this? If so don't add it twice!
411
		if (in_array($row['package_id'], $found))
412
			continue;
413
414
		$found[] = $row['package_id'];
415
416
		$row = htmlspecialchars__recursive($row);
417
418
		$installed[] = array(
419
			'id' => $row['id_install'],
420
			'name' => $smcFunc['htmlspecialchars']($row['name']),
421
			'filename' => $row['filename'],
422
			'package_id' => $row['package_id'],
423
			'version' => $smcFunc['htmlspecialchars']($row['version']),
424
			'time_installed' => !empty($row['time_installed']) ? $row['time_installed'] : 0,
425
		);
426
	}
427
	$smcFunc['db_free_result']($request);
428
429
	return $installed;
430
}
431
432
/**
433
 * Loads a package's information and returns a representative array.
434
 * - expects the file to be a package in Packages/.
435
 * - returns a error string if the package-info is invalid.
436
 * - otherwise returns a basic array of id, version, filename, and similar information.
437
 * - an xmlArray is available in 'xml'.
438
 *
439
 * @param string $gzfilename The path to the file
440
 * @return array|string An array of info about the file or a string indicating an error
441
 */
442
function getPackageInfo($gzfilename)
443
{
444
	global $sourcedir, $packagesdir;
445
446
	// Extract package-info.xml from downloaded file. (*/ is used because it could be in any directory.)
447
	if (strpos($gzfilename, 'http://') !== false || strpos($gzfilename, 'https://') !== false)
448
		$packageInfo = read_tgz_data($gzfilename, 'package-info.xml', true);
449
	else
450
	{
451
		if (!file_exists($packagesdir . '/' . $gzfilename))
452
			return 'package_get_error_not_found';
453
454
		if (is_file($packagesdir . '/' . $gzfilename))
455
			$packageInfo = read_tgz_file($packagesdir . '/' . $gzfilename, '*/package-info.xml', true);
456
		elseif (file_exists($packagesdir . '/' . $gzfilename . '/package-info.xml'))
457
			$packageInfo = file_get_contents($packagesdir . '/' . $gzfilename . '/package-info.xml');
458
		else
459
			return 'package_get_error_missing_xml';
460
	}
461
462
	// Nothing?
463
	if (empty($packageInfo))
464
	{
465
		// Perhaps they are trying to install a theme, lets tell them nicely this is the wrong function
466
		$packageInfo = read_tgz_file($packagesdir . '/' . $gzfilename, '*/theme_info.xml', true);
467
		if (!empty($packageInfo))
468
			return 'package_get_error_is_theme';
469
		else
470
			return 'package_get_error_is_zero';
471
	}
472
473
	// Parse package-info.xml into an xmlArray.
474
	require_once($sourcedir . '/Class-Package.php');
475
	$packageInfo = new xmlArray($packageInfo);
0 ignored issues
show
Bug introduced by
It seems like $packageInfo can also be of type array; however, parameter $data of xmlArray::__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

475
	$packageInfo = new xmlArray(/** @scrutinizer ignore-type */ $packageInfo);
Loading history...
476
477
	// @todo Error message of some sort?
478
	if (!$packageInfo->exists('package-info[0]'))
479
		return 'package_get_error_packageinfo_corrupt';
480
481
	$packageInfo = $packageInfo->path('package-info[0]');
482
483
	$package = $packageInfo->to_array();
484
	$package = htmlspecialchars__recursive($package);
485
	$package['xml'] = $packageInfo;
486
	$package['filename'] = $gzfilename;
487
488
	// Don't want to mess with code...
489
	$types = array('install', 'uninstall', 'upgrade');
490
	foreach ($types as $type)
491
	{
492
		if (isset($package[$type]['code']))
493
		{
494
			$package[$type]['code'] = un_htmlspecialchars($package[$type]['code']);
495
		}
496
	}
497
498
	if (!isset($package['type']))
499
		$package['type'] = 'modification';
500
501
	return $package;
502
}
503
504
/**
505
 * Create a chmod control for chmoding files.
506
 *
507
 * @param array $chmodFiles Which files to chmod
508
 * @param array $chmodOptions Options for chmod
509
 * @param bool $restore_write_status Whether to restore write status
510
 * @return array An array of file info
511
 */
512
function create_chmod_control($chmodFiles = array(), $chmodOptions = array(), $restore_write_status = false)
513
{
514
	global $context, $modSettings, $package_ftp, $boarddir, $txt, $sourcedir, $scripturl;
515
516
	// If we're restoring the status of existing files prepare the data.
517
	if ($restore_write_status && isset($_SESSION['pack_ftp']) && !empty($_SESSION['pack_ftp']['original_perms']))
518
	{
519
		/**
520
		 * Get a listing of files that will need to be set back to the original state
521
		 *
522
		 * @param null $dummy1
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $dummy1 is correct as it would always require null to be passed?
Loading history...
523
		 * @param null $dummy2
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $dummy2 is correct as it would always require null to be passed?
Loading history...
524
		 * @param null $dummy3
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $dummy3 is correct as it would always require null to be passed?
Loading history...
525
		 * @param bool $do_change
526
		 * @return array An array of info about the files that need to be restored back to their original state
527
		 */
528
		function list_restoreFiles($dummy1, $dummy2, $dummy3, $do_change)
529
		{
530
			global $txt;
531
532
			$restore_files = array();
533
			foreach ($_SESSION['pack_ftp']['original_perms'] as $file => $perms)
534
			{
535
				// Check the file still exists, and the permissions were indeed different than now.
536
				$file_permissions = @fileperms($file);
537
				if (!file_exists($file) || $file_permissions == $perms)
538
				{
539
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
540
					continue;
541
				}
542
543
				// Are we wanting to change the permission?
544
				if ($do_change && isset($_POST['restore_files']) && in_array($file, $_POST['restore_files']))
545
				{
546
					// Use FTP if we have it.
547
					// @todo where does $package_ftp get set?
548
					if (!empty($package_ftp))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $package_ftp seems to never exist and therefore empty should always be true.
Loading history...
549
					{
550
						$ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
551
						$package_ftp->chmod($ftp_file, $perms);
552
					}
553
					else
554
						smf_chmod($file, $perms);
555
556
					$new_permissions = @fileperms($file);
557
					$result = $new_permissions == $perms ? 'success' : 'failure';
558
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
559
				}
560
				elseif ($do_change)
561
				{
562
					$new_permissions = '';
563
					$result = 'skipped';
564
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
565
				}
566
567
				// Record the results!
568
				$restore_files[] = array(
569
					'path' => $file,
570
					'old_perms_raw' => $perms,
571
					'old_perms' => substr(sprintf('%o', $perms), -4),
572
					'cur_perms' => substr(sprintf('%o', $file_permissions), -4),
0 ignored issues
show
Bug introduced by
It seems like $file_permissions can also be of type false; however, parameter $values of sprintf() does only seem to accept double|integer|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

572
					'cur_perms' => substr(sprintf('%o', /** @scrutinizer ignore-type */ $file_permissions), -4),
Loading history...
573
					'new_perms' => isset($new_permissions) ? substr(sprintf('%o', $new_permissions), -4) : '',
574
					'result' => isset($result) ? $result : '',
575
					'writable_message' => '<span style="color: ' . (@is_writable($file) ? 'green' : 'red') . '">' . (@is_writable($file) ? $txt['package_file_perms_writable'] : $txt['package_file_perms_not_writable']) . '</span>',
576
				);
577
			}
578
579
			return $restore_files;
580
		}
581
582
		$listOptions = array(
583
			'id' => 'restore_file_permissions',
584
			'title' => $txt['package_restore_permissions'],
585
			'get_items' => array(
586
				'function' => 'list_restoreFiles',
587
				'params' => array(
588
					!empty($_POST['restore_perms']),
589
				),
590
			),
591
			'columns' => array(
592
				'path' => array(
593
					'header' => array(
594
						'value' => $txt['package_restore_permissions_filename'],
595
					),
596
					'data' => array(
597
						'db' => 'path',
598
						'class' => 'smalltext',
599
					),
600
				),
601
				'old_perms' => array(
602
					'header' => array(
603
						'value' => $txt['package_restore_permissions_orig_status'],
604
					),
605
					'data' => array(
606
						'db' => 'old_perms',
607
						'class' => 'smalltext',
608
					),
609
				),
610
				'cur_perms' => array(
611
					'header' => array(
612
						'value' => $txt['package_restore_permissions_cur_status'],
613
					),
614
					'data' => array(
615
						'function' => function($rowData) use ($txt)
616
						{
617
							$formatTxt = $rowData['result'] == '' || $rowData['result'] == 'skipped' ? $txt['package_restore_permissions_pre_change'] : $txt['package_restore_permissions_post_change'];
618
							return sprintf($formatTxt, $rowData['cur_perms'], $rowData['new_perms'], $rowData['writable_message']);
619
						},
620
						'class' => 'smalltext',
621
					),
622
				),
623
				'check' => array(
624
					'header' => array(
625
						'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
626
						'class' => 'centercol',
627
					),
628
					'data' => array(
629
						'sprintf' => array(
630
							'format' => '<input type="checkbox" name="restore_files[]" value="%1$s">',
631
							'params' => array(
632
								'path' => false,
633
							),
634
						),
635
						'class' => 'centercol',
636
					),
637
				),
638
				'result' => array(
639
					'header' => array(
640
						'value' => $txt['package_restore_permissions_result'],
641
					),
642
					'data' => array(
643
						'function' => function($rowData) use ($txt)
644
						{
645
							return $txt['package_restore_permissions_action_' . $rowData['result']];
646
						},
647
						'class' => 'smalltext',
648
					),
649
				),
650
			),
651
			'form' => array(
652
				'href' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : $scripturl . '?action=admin;area=packages;sa=perms;restore;' . $context['session_var'] . '=' . $context['session_id'],
653
			),
654
			'additional_rows' => array(
655
				array(
656
					'position' => 'below_table_data',
657
					'value' => '<input type="submit" name="restore_perms" value="' . $txt['package_restore_permissions_restore'] . '" class="button">',
658
					'class' => 'titlebg',
659
				),
660
				array(
661
					'position' => 'after_title',
662
					'value' => '<span class="smalltext">' . $txt['package_restore_permissions_desc'] . '</span>',
663
					'class' => 'windowbg',
664
				),
665
			),
666
		);
667
668
		// Work out what columns and the like to show.
669
		if (!empty($_POST['restore_perms']))
670
		{
671
			$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']);
672
			unset($listOptions['columns']['check'], $listOptions['form'], $listOptions['additional_rows'][0]);
673
674
			$context['sub_template'] = 'show_list';
675
			$context['default_list'] = 'restore_file_permissions';
676
		}
677
		else
678
		{
679
			unset($listOptions['columns']['result']);
680
		}
681
682
		// Create the list for display.
683
		require_once($sourcedir . '/Subs-List.php');
684
		createList($listOptions);
685
686
		// If we just restored permissions then whereever we are, we are now done and dusted.
687
		if (!empty($_POST['restore_perms']))
688
			obExit();
689
	}
690
	// Otherwise, it's entirely irrelevant?
691
	elseif ($restore_write_status)
692
		return true;
693
694
	// This is where we report what we got up to.
695
	$return_data = array(
696
		'files' => array(
697
			'writable' => array(),
698
			'notwritable' => array(),
699
		),
700
	);
701
702
	// If we have some FTP information already, then let's assume it was required and try to get ourselves connected.
703
	if (!empty($_SESSION['pack_ftp']['connected']))
704
	{
705
		// Load the file containing the ftp_connection class.
706
		require_once($sourcedir . '/Class-Package.php');
707
708
		$package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
709
	}
710
711
	// Just got a submission did we?
712
	if (empty($package_ftp) && isset($_POST['ftp_username']))
713
	{
714
		require_once($sourcedir . '/Class-Package.php');
715
		$ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
716
717
		// We're connected, jolly good!
718
		if ($ftp->error === false)
0 ignored issues
show
introduced by
The condition $ftp->error === false is always false.
Loading history...
719
		{
720
			// Common mistake, so let's try to remedy it...
721
			if (!$ftp->chdir($_POST['ftp_path']))
722
			{
723
				$ftp_error = $ftp->last_message;
724
				$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
725
			}
726
727
			if (!in_array($_POST['ftp_path'], array('', '/')))
728
			{
729
				$ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
730
				if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || substr($_POST['ftp_path'], 0, 1) == '/'))
731
					$ftp_root = substr($ftp_root, 0, -1);
732
			}
733
			else
734
				$ftp_root = $boarddir;
735
736
			$_SESSION['pack_ftp'] = array(
737
				'server' => $_POST['ftp_server'],
738
				'port' => $_POST['ftp_port'],
739
				'username' => $_POST['ftp_username'],
740
				'password' => package_crypt($_POST['ftp_password']),
741
				'path' => $_POST['ftp_path'],
742
				'root' => $ftp_root,
743
				'connected' => true,
744
			);
745
746
			if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
747
				updateSettings(array('package_path' => $_POST['ftp_path']));
748
749
			// This is now the primary connection.
750
			$package_ftp = $ftp;
751
		}
752
	}
753
754
	// Now try to simply make the files writable, with whatever we might have.
755
	if (!empty($chmodFiles))
756
	{
757
		foreach ($chmodFiles as $k => $file)
758
		{
759
			// Sometimes this can somehow happen maybe?
760
			if (empty($file))
761
				unset($chmodFiles[$k]);
762
			// Already writable?
763
			elseif (@is_writable($file))
764
				$return_data['files']['writable'][] = $file;
765
			else
766
			{
767
				// Now try to change that.
768
				$return_data['files'][package_chmod($file, 'writable', true) ? 'writable' : 'notwritable'][] = $file;
769
			}
770
		}
771
	}
772
773
	// Have we still got nasty files which ain't writable? Dear me we need more FTP good sir.
774
	if (empty($package_ftp) && (!empty($return_data['files']['notwritable']) || !empty($chmodOptions['force_find_error'])))
775
	{
776
		if (!isset($ftp) || $ftp->error !== false)
777
		{
778
			if (!isset($ftp))
779
			{
780
				require_once($sourcedir . '/Class-Package.php');
781
				$ftp = new ftp_connection(null);
782
			}
783
			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...
784
				$ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
785
786
			list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
787
788
			if ($found_path)
789
				$_POST['ftp_path'] = $detect_path;
790
			elseif (!isset($_POST['ftp_path']))
791
				$_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
792
793
			if (!isset($_POST['ftp_username']))
794
				$_POST['ftp_username'] = $username;
795
		}
796
797
		$context['package_ftp'] = array(
798
			'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
799
			'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
800
			'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
801
			'path' => $_POST['ftp_path'],
802
			'error' => empty($ftp_error) ? null : $ftp_error,
803
			'destination' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : '',
804
		);
805
806
		// Which files failed?
807
		if (!isset($context['notwritable_files']))
808
			$context['notwritable_files'] = array();
809
		$context['notwritable_files'] = array_merge($context['notwritable_files'], $return_data['files']['notwritable']);
810
811
		// Sent here to die?
812
		if (!empty($chmodOptions['crash_on_error']))
813
		{
814
			$context['page_title'] = $txt['package_ftp_necessary'];
815
			$context['sub_template'] = 'ftp_required';
816
			obExit();
817
		}
818
	}
819
820
	return $return_data;
821
}
822
823
/**
824
 * Use FTP functions to work with a package download/install
825
 *
826
 * @param string $destination_url The destination URL
827
 * @param null|array $files The files to CHMOD
828
 * @param bool $return Whether to return an array of file info if there's an error
829
 * @return array An array of file info
830
 */
831
function packageRequireFTP($destination_url, $files = null, $return = false)
832
{
833
	global $context, $modSettings, $package_ftp, $boarddir, $txt, $sourcedir;
834
835
	// Try to make them writable the manual way.
836
	if ($files !== null)
837
	{
838
		foreach ($files as $k => $file)
839
		{
840
			// If this file doesn't exist, then we actually want to look at the directory, no?
841
			if (!file_exists($file))
842
				$file = dirname($file);
843
844
			// This looks odd, but it's an attempt to work around PHP suExec.
845
			if (!@is_writable($file))
846
				smf_chmod($file, 0755);
847
			if (!@is_writable($file))
848
				smf_chmod($file, 0777);
849
			if (!@is_writable(dirname($file)))
850
				smf_chmod($file, 0755);
851
			if (!@is_writable(dirname($file)))
852
				smf_chmod($file, 0777);
853
854
			$fp = is_dir($file) ? @opendir($file) : @fopen($file, 'rb');
855
			if (@is_writable($file) && $fp)
856
			{
857
				unset($files[$k]);
858
				if (!is_dir($file))
859
					fclose($fp);
860
				else
861
					closedir($fp);
862
			}
863
		}
864
865
		// No FTP required!
866
		if (empty($files))
867
			return array();
868
	}
869
870
	// They've opted to not use FTP, and try anyway.
871
	if (isset($_SESSION['pack_ftp']) && $_SESSION['pack_ftp'] == false)
872
	{
873
		if ($files === null)
874
			return array();
875
876
		foreach ($files as $k => $file)
877
		{
878
			// This looks odd, but it's an attempt to work around PHP suExec.
879
			if (!file_exists($file))
880
			{
881
				mktree(dirname($file), 0755);
882
				@touch($file);
883
				smf_chmod($file, 0755);
884
			}
885
886
			if (!@is_writable($file))
887
				smf_chmod($file, 0777);
888
			if (!@is_writable(dirname($file)))
889
				smf_chmod(dirname($file), 0777);
890
891
			if (@is_writable($file))
892
				unset($files[$k]);
893
		}
894
895
		return $files;
896
	}
897
	elseif (isset($_SESSION['pack_ftp']))
898
	{
899
		// Load the file containing the ftp_connection class.
900
		require_once($sourcedir . '/Class-Package.php');
901
902
		$package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
903
904
		if ($files === null)
905
			return array();
906
907
		foreach ($files as $k => $file)
908
		{
909
			$ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
910
911
			// This looks odd, but it's an attempt to work around PHP suExec.
912
			if (!file_exists($file))
913
			{
914
				mktree(dirname($file), 0755);
915
				$package_ftp->create_file($ftp_file);
916
				$package_ftp->chmod($ftp_file, 0755);
917
			}
918
919
			if (!@is_writable($file))
920
				$package_ftp->chmod($ftp_file, 0777);
921
			if (!@is_writable(dirname($file)))
922
				$package_ftp->chmod(dirname($ftp_file), 0777);
923
924
			if (@is_writable($file))
925
				unset($files[$k]);
926
		}
927
928
		return $files;
929
	}
930
931
	if (isset($_POST['ftp_none']))
932
	{
933
		$_SESSION['pack_ftp'] = false;
934
935
		$files = packageRequireFTP($destination_url, $files, $return);
936
		return $files;
937
	}
938
	elseif (isset($_POST['ftp_username']))
939
	{
940
		require_once($sourcedir . '/Class-Package.php');
941
		$ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
942
943
		if ($ftp->error === false)
0 ignored issues
show
introduced by
The condition $ftp->error === false is always false.
Loading history...
944
		{
945
			// Common mistake, so let's try to remedy it...
946
			if (!$ftp->chdir($_POST['ftp_path']))
947
			{
948
				$ftp_error = $ftp->last_message;
949
				$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
950
			}
951
		}
952
	}
953
954
	if (!isset($ftp) || $ftp->error !== false)
955
	{
956
		if (!isset($ftp))
957
		{
958
			require_once($sourcedir . '/Class-Package.php');
959
			$ftp = new ftp_connection(null);
960
		}
961
		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...
962
			$ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
963
964
		list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
965
966
		if ($found_path)
967
			$_POST['ftp_path'] = $detect_path;
968
		elseif (!isset($_POST['ftp_path']))
969
			$_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
970
971
		if (!isset($_POST['ftp_username']))
972
			$_POST['ftp_username'] = $username;
973
974
		$context['package_ftp'] = array(
975
			'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
976
			'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
977
			'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
978
			'path' => $_POST['ftp_path'],
979
			'error' => empty($ftp_error) ? null : $ftp_error,
980
			'destination' => $destination_url,
981
		);
982
983
		// If we're returning dump out here.
984
		if ($return)
985
			return $files;
986
987
		$context['page_title'] = $txt['package_ftp_necessary'];
988
		$context['sub_template'] = 'ftp_required';
989
		obExit();
990
	}
991
	else
992
	{
993
		if (!in_array($_POST['ftp_path'], array('', '/')))
994
		{
995
			$ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
996
			if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || $_POST['ftp_path'][0] == '/'))
997
				$ftp_root = substr($ftp_root, 0, -1);
998
		}
999
		else
1000
			$ftp_root = $boarddir;
1001
1002
		$_SESSION['pack_ftp'] = array(
1003
			'server' => $_POST['ftp_server'],
1004
			'port' => $_POST['ftp_port'],
1005
			'username' => $_POST['ftp_username'],
1006
			'password' => package_crypt($_POST['ftp_password']),
1007
			'path' => $_POST['ftp_path'],
1008
			'root' => $ftp_root,
1009
		);
1010
1011
		if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
1012
			updateSettings(array('package_path' => $_POST['ftp_path']));
1013
1014
		$files = packageRequireFTP($destination_url, $files, $return);
1015
	}
1016
1017
	return $files;
1018
}
1019
1020
/**
1021
 * Parses the actions in package-info.xml file from packages.
1022
 *
1023
 * - package should be an xmlArray with package-info as its base.
1024
 * - testing_only should be true if the package should not actually be applied.
1025
 * - method can be upgrade, install, or uninstall.  Its default is install.
1026
 * - previous_version should be set to the previous installed version of this package, if any.
1027
 * - does not handle failure terribly well; testing first is always better.
1028
 *
1029
 * @param xmlArray &$packageXML The info from the package-info file
1030
 * @param bool $testing_only Whether we're only testing
1031
 * @param string $method The method ('install', 'upgrade', or 'uninstall')
1032
 * @param string $previous_version The previous version of the mod, if method is 'upgrade'
1033
 * @return array An array of those changes made.
1034
 */
1035
function parsePackageInfo(&$packageXML, $testing_only = true, $method = 'install', $previous_version = '')
1036
{
1037
	global $packagesdir, $context, $temp_path, $language, $smcFunc;
1038
1039
	// Mayday!  That action doesn't exist!!
1040
	if (empty($packageXML) || !$packageXML->exists($method))
1041
		return array();
1042
1043
	// We haven't found the package script yet...
1044
	$script = false;
1045
	$the_version = SMF_VERSION;
1046
1047
	// Emulation support...
1048
	if (!empty($_SESSION['version_emulate']))
1049
		$the_version = $_SESSION['version_emulate'];
1050
1051
	// Single package emulation
1052
	if (!empty($_REQUEST['ve']) && !empty($_REQUEST['package']))
1053
	{
1054
		$the_version = $_REQUEST['ve'];
1055
		$_SESSION['single_version_emulate'][$_REQUEST['package']] = $the_version;
1056
	}
1057
	if (!empty($_REQUEST['package']) && (!empty($_SESSION['single_version_emulate'][$_REQUEST['package']])))
1058
		$the_version = $_SESSION['single_version_emulate'][$_REQUEST['package']];
1059
1060
	// Get all the versions of this method and find the right one.
1061
	$these_methods = $packageXML->set($method);
1062
	foreach ($these_methods as $this_method)
1063
	{
1064
		// They specified certain versions this part is for.
1065
		if ($this_method->exists('@for'))
1066
		{
1067
			// Don't keep going if this won't work for this version of SMF.
1068
			if (!matchPackageVersion($the_version, $this_method->fetch('@for')))
1069
				continue;
1070
		}
1071
1072
		// Upgrades may go from a certain old version of the mod.
1073
		if ($method == 'upgrade' && $this_method->exists('@from'))
1074
		{
1075
			// Well, this is for the wrong old version...
1076
			if (!matchPackageVersion($previous_version, $this_method->fetch('@from')))
1077
				continue;
1078
		}
1079
1080
		// We've found it!
1081
		$script = $this_method;
1082
		break;
1083
	}
1084
1085
	// Bad news, a matching script wasn't found!
1086
	if (!($script instanceof xmlArray))
1087
		return array();
1088
1089
	// Find all the actions in this method - in theory, these should only be allowed actions. (* means all.)
1090
	$actions = $script->set('*');
1091
	$return = array();
1092
1093
	$temp_auto = 0;
1094
	$temp_path = $packagesdir . '/temp/' . (isset($context['base_path']) ? $context['base_path'] : '');
1095
1096
	$context['readmes'] = array();
1097
	$context['licences'] = array();
1098
1099
	// This is the testing phase... nothing shall be done yet.
1100
	foreach ($actions as $action)
1101
	{
1102
		$actionType = $action->name();
1103
1104
		if (in_array($actionType, array('readme', 'code', 'database', 'modification', 'redirect', 'license')))
1105
		{
1106
			// Allow for translated readme and license files.
1107
			if ($actionType == 'readme' || $actionType == 'license')
1108
			{
1109
				$type = $actionType . 's';
1110
				if ($action->exists('@lang'))
1111
				{
1112
					// Auto-select the language based on either request variable or current language.
1113
					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))
1114
					{
1115
						// In case the user put the blocks in the wrong order.
1116
						if (isset($context[$type]['selected']) && $context[$type]['selected'] == 'default')
1117
							$context[$type][] = 'default';
1118
1119
						$context[$type]['selected'] = $smcFunc['htmlspecialchars']($action->fetch('@lang'));
1120
					}
1121
					else
1122
					{
1123
						// We don't want this now, but we'll allow the user to select to read it.
1124
						$context[$type][] = $smcFunc['htmlspecialchars']($action->fetch('@lang'));
1125
						continue;
1126
					}
1127
				}
1128
				// Fallback when we have no lang parameter.
1129
				else
1130
				{
1131
					// Already selected one for use?
1132
					if (isset($context[$type]['selected']))
1133
					{
1134
						$context[$type][] = 'default';
1135
						continue;
1136
					}
1137
					else
1138
						$context[$type]['selected'] = 'default';
1139
				}
1140
			}
1141
1142
			// @todo Make sure the file actually exists?  Might not work when testing?
1143
			if ($action->exists('@type') && $action->fetch('@type') == 'inline')
1144
			{
1145
				$filename = $temp_path . '$auto_' . $temp_auto++ . (in_array($actionType, array('readme', 'redirect', 'license')) ? '.txt' : ($actionType == 'code' || $actionType == 'database' ? '.php' : '.mod'));
1146
				package_put_contents($filename, $action->fetch('.'));
1147
				$filename = strtr($filename, array($temp_path => ''));
1148
			}
1149
			else
1150
				$filename = $action->fetch('.');
1151
1152
			$return[] = array(
1153
				'type' => $actionType,
1154
				'filename' => $filename,
1155
				'description' => '',
1156
				'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true',
1157
				'boardmod' => $action->exists('@format') && $action->fetch('@format') == 'boardmod',
1158
				'redirect_url' => $action->exists('@url') ? $action->fetch('@url') : '',
1159
				'redirect_timeout' => $action->exists('@timeout') ? (int) $action->fetch('@timeout') : '',
1160
				'parse_bbc' => $action->exists('@parsebbc') && $action->fetch('@parsebbc') == 'true',
1161
				'language' => (($actionType == 'readme' || $actionType == 'license') && $action->exists('@lang') && $action->fetch('@lang') == $language) ? $language : '',
1162
			);
1163
1164
			continue;
1165
		}
1166
		elseif ($actionType == 'hook')
1167
		{
1168
			$return[] = array(
1169
				'type' => $actionType,
1170
				'function' => $action->exists('@function') ? $action->fetch('@function') : '',
1171
				'hook' => $action->exists('@hook') ? $action->fetch('@hook') : $action->fetch('.'),
1172
				'include_file' => $action->exists('@file') ? $action->fetch('@file') : '',
1173
				'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true' ? true : false,
1174
				'object' => $action->exists('@object') && $action->fetch('@object') == 'true' ? true : false,
1175
				'description' => '',
1176
			);
1177
			continue;
1178
		}
1179
		elseif ($actionType == 'credits')
1180
		{
1181
			// quick check of any supplied url
1182
			$url = $action->exists('@url') ? $action->fetch('@url') : '';
1183
			if (strlen(trim($url)) > 0 && substr($url, 0, 7) !== 'http://' && substr($url, 0, 8) !== 'https://')
1184
			{
1185
				$url = 'http://' . $url;
1186
				if (strlen($url) < 8 || (substr($url, 0, 7) !== 'http://' && substr($url, 0, 8) !== 'https://'))
1187
					$url = '';
1188
			}
1189
1190
			$return[] = array(
1191
				'type' => $actionType,
1192
				'url' => $url,
1193
				'license' => $action->exists('@license') ? $action->fetch('@license') : '',
1194
				'licenseurl' => $action->exists('@licenseurl') ? $action->fetch('@licenseurl') : '',
1195
				'copyright' => $action->exists('@copyright') ? $action->fetch('@copyright') : '',
1196
				'title' => $action->fetch('.'),
1197
			);
1198
			continue;
1199
		}
1200
		elseif ($actionType == 'requires')
1201
		{
1202
			$return[] = array(
1203
				'type' => $actionType,
1204
				'id' => $action->exists('@id') ? $action->fetch('@id') : '',
1205
				'version' => $action->exists('@version') ? $action->fetch('@version') : $action->fetch('.'),
1206
				'description' => '',
1207
			);
1208
			continue;
1209
		}
1210
		elseif ($actionType == 'error')
1211
		{
1212
			$return[] = array(
1213
				'type' => 'error',
1214
			);
1215
		}
1216
		elseif (in_array($actionType, array('require-file', 'remove-file', 'require-dir', 'remove-dir', 'move-file', 'move-dir', 'create-file', 'create-dir')))
1217
		{
1218
			$this_action = &$return[];
1219
			$this_action = array(
1220
				'type' => $actionType,
1221
				'filename' => $action->fetch('@name'),
1222
				'description' => $action->fetch('.')
1223
			);
1224
1225
			// If there is a destination, make sure it makes sense.
1226
			if (substr($actionType, 0, 6) != 'remove')
1227
			{
1228
				$this_action['unparsed_destination'] = $action->fetch('@destination');
1229
				$this_action['destination'] = parse_path($action->fetch('@destination')) . '/' . basename($this_action['filename']);
1230
			}
1231
			else
1232
			{
1233
				$this_action['unparsed_filename'] = $this_action['filename'];
1234
				$this_action['filename'] = parse_path($this_action['filename']);
1235
			}
1236
1237
			// If we're moving or requiring (copying) a file.
1238
			if (substr($actionType, 0, 4) == 'move' || substr($actionType, 0, 7) == 'require')
1239
			{
1240
				if ($action->exists('@from'))
1241
					$this_action['source'] = parse_path($action->fetch('@from'));
1242
				else
1243
					$this_action['source'] = $temp_path . $this_action['filename'];
1244
			}
1245
1246
			// Check if these things can be done. (chmod's etc.)
1247
			if ($actionType == 'create-dir')
1248
			{
1249
				if (!mktree($this_action['destination'], false))
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type integer expected by parameter $mode of mktree(). ( Ignorable by Annotation )

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

1249
				if (!mktree($this_action['destination'], /** @scrutinizer ignore-type */ false))
Loading history...
1250
				{
1251
					$temp = $this_action['destination'];
1252
					while (!file_exists($temp) && strlen($temp) > 1)
1253
						$temp = dirname($temp);
1254
1255
					$return[] = array(
1256
						'type' => 'chmod',
1257
						'filename' => $temp
1258
					);
1259
				}
1260
			}
1261
			elseif ($actionType == 'create-file')
1262
			{
1263
				if (!mktree(dirname($this_action['destination']), false))
1264
				{
1265
					$temp = dirname($this_action['destination']);
1266
					while (!file_exists($temp) && strlen($temp) > 1)
1267
						$temp = dirname($temp);
1268
1269
					$return[] = array(
1270
						'type' => 'chmod',
1271
						'filename' => $temp
1272
					);
1273
				}
1274
1275
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1276
					$return[] = array(
1277
						'type' => 'chmod',
1278
						'filename' => $this_action['destination']
1279
					);
1280
			}
1281
			elseif ($actionType == 'require-dir')
1282
			{
1283
				if (!mktree($this_action['destination'], false))
1284
				{
1285
					$temp = $this_action['destination'];
1286
					while (!file_exists($temp) && strlen($temp) > 1)
1287
						$temp = dirname($temp);
1288
1289
					$return[] = array(
1290
						'type' => 'chmod',
1291
						'filename' => $temp
1292
					);
1293
				}
1294
			}
1295
			elseif ($actionType == 'require-file')
1296
			{
1297
				if ($action->exists('@theme'))
1298
					$this_action['theme_action'] = $action->fetch('@theme');
1299
1300
				if (!mktree(dirname($this_action['destination']), false))
1301
				{
1302
					$temp = dirname($this_action['destination']);
1303
					while (!file_exists($temp) && strlen($temp) > 1)
1304
						$temp = dirname($temp);
1305
1306
					$return[] = array(
1307
						'type' => 'chmod',
1308
						'filename' => $temp
1309
					);
1310
				}
1311
1312
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1313
					$return[] = array(
1314
						'type' => 'chmod',
1315
						'filename' => $this_action['destination']
1316
					);
1317
			}
1318
			elseif ($actionType == 'move-dir' || $actionType == 'move-file')
1319
			{
1320
				if (!mktree(dirname($this_action['destination']), false))
1321
				{
1322
					$temp = dirname($this_action['destination']);
1323
					while (!file_exists($temp) && strlen($temp) > 1)
1324
						$temp = dirname($temp);
1325
1326
					$return[] = array(
1327
						'type' => 'chmod',
1328
						'filename' => $temp
1329
					);
1330
				}
1331
1332
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1333
					$return[] = array(
1334
						'type' => 'chmod',
1335
						'filename' => $this_action['destination']
1336
					);
1337
			}
1338
			elseif ($actionType == 'remove-dir')
1339
			{
1340
				if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
1341
					$return[] = array(
1342
						'type' => 'chmod',
1343
						'filename' => $this_action['filename']
1344
					);
1345
			}
1346
			elseif ($actionType == 'remove-file')
1347
			{
1348
				if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
1349
					$return[] = array(
1350
						'type' => 'chmod',
1351
						'filename' => $this_action['filename']
1352
					);
1353
			}
1354
		}
1355
		else
1356
		{
1357
			$return[] = array(
1358
				'type' => 'error',
1359
				'error_msg' => 'unknown_action',
1360
				'error_var' => $actionType
1361
			);
1362
		}
1363
	}
1364
1365
	// Only testing - just return a list of things to be done.
1366
	if ($testing_only)
1367
		return $return;
1368
1369
	umask(0);
1370
1371
	$failure = false;
1372
	$not_done = array(array('type' => '!'));
1373
	foreach ($return as $action)
1374
	{
1375
		if (in_array($action['type'], array('modification', 'code', 'database', 'redirect', 'hook', 'credits')))
1376
			$not_done[] = $action;
1377
1378
		if ($action['type'] == 'create-dir')
1379
		{
1380
			if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1381
				$failure |= !mktree($action['destination'], 0777);
1382
		}
1383
		elseif ($action['type'] == 'create-file')
1384
		{
1385
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1386
				$failure |= !mktree(dirname($action['destination']), 0777);
1387
1388
			// Create an empty file.
1389
			package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1390
1391
			if (!file_exists($action['destination']))
1392
				$failure = true;
1393
		}
1394
		elseif ($action['type'] == 'require-dir')
1395
		{
1396
			copytree($action['source'], $action['destination']);
1397
			// Any other theme folders?
1398
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1399
				foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1400
					copytree($action['source'], $theme_destination);
1401
		}
1402
		elseif ($action['type'] == 'require-file')
1403
		{
1404
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1405
				$failure |= !mktree(dirname($action['destination']), 0777);
1406
1407
			package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1408
1409
			$failure |= !copy($action['source'], $action['destination']);
1410
1411
			// Any other theme files?
1412
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1413
				foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1414
				{
1415
					if (!mktree(dirname($theme_destination), 0755) || !is_writable(dirname($theme_destination)))
1416
						$failure |= !mktree(dirname($theme_destination), 0777);
1417
1418
					package_put_contents($theme_destination, package_get_contents($action['source']), $testing_only);
1419
1420
					$failure |= !copy($action['source'], $theme_destination);
1421
				}
1422
		}
1423
		elseif ($action['type'] == 'move-file')
1424
		{
1425
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1426
				$failure |= !mktree(dirname($action['destination']), 0777);
1427
1428
			$failure |= !rename($action['source'], $action['destination']);
1429
		}
1430
		elseif ($action['type'] == 'move-dir')
1431
		{
1432
			if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1433
				$failure |= !mktree($action['destination'], 0777);
1434
1435
			$failure |= !rename($action['source'], $action['destination']);
1436
		}
1437
		elseif ($action['type'] == 'remove-dir')
1438
		{
1439
			deltree($action['filename']);
1440
1441
			// Any other theme folders?
1442
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1443
				foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1444
					deltree($theme_destination);
1445
		}
1446
		elseif ($action['type'] == 'remove-file')
1447
		{
1448
			// Make sure the file exists before deleting it.
1449
			if (file_exists($action['filename']))
1450
			{
1451
				package_chmod($action['filename']);
1452
				$failure |= !unlink($action['filename']);
1453
			}
1454
			// The file that was supposed to be deleted couldn't be found.
1455
			else
1456
				$failure = true;
1457
1458
			// Any other theme folders?
1459
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1460
				foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1461
					if (file_exists($theme_destination))
1462
						$failure |= !unlink($theme_destination);
1463
					else
1464
						$failure = true;
1465
		}
1466
	}
1467
1468
	return $not_done;
1469
}
1470
1471
/**
1472
 * Checks if version matches any of the versions in `$versions`.
1473
 *
1474
 * - supports comma separated version numbers, with or without whitespace.
1475
 * - supports lower and upper bounds. (1.0-1.2)
1476
 * - returns true if the version matched.
1477
 *
1478
 * @param string $versions The versions that this package will install on
1479
 * @param boolean $reset Whether to reset $near_version
1480
 * @param string $the_version The forum version
1481
 * @return string|bool Highest install value string or false
1482
 */
1483
function matchHighestPackageVersion($versions, $reset, $the_version)
1484
{
1485
	static $near_version = 0;
1486
1487
	if ($reset)
1488
		$near_version = 0;
1489
1490
	// Normalize the $versions while we remove our previous Doh!
1491
	$versions = explode(',', str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($versions)));
1492
1493
	// Loop through each version, save the highest we can find
1494
	foreach ($versions as $for)
1495
	{
1496
		// Adjust for those wild cards
1497
		if (strpos($for, '*') !== false)
1498
			$for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
1499
1500
		// If we have a range, grab the lower value, done this way so it looks normal-er to the user e.g. 2.0 vs 2.0.99
1501
		if (strpos($for, '-') !== false)
1502
			list ($for, $higher) = explode('-', $for);
1503
1504
		// Do the compare, if the for is greater, than what we have but not greater than what we are running .....
1505
		if (compareVersions($near_version, $for) === -1 && compareVersions($for, $the_version) !== 1)
1506
			$near_version = $for;
1507
	}
1508
1509
	return !empty($near_version) ? $near_version : false;
1510
}
1511
1512
/**
1513
 * Checks if the forum version matches any of the available versions from the package install xml.
1514
 * - supports comma separated version numbers, with or without whitespace.
1515
 * - supports lower and upper bounds. (1.0-1.2)
1516
 * - returns true if the version matched.
1517
 *
1518
 * @param string $version The forum version
1519
 * @param string $versions The versions that this package will install on
1520
 * @return bool Whether the version matched
1521
 */
1522
function matchPackageVersion($version, $versions)
1523
{
1524
	// Make sure everything is lowercase and clean of spaces and unpleasant history.
1525
	$version = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
1526
	$versions = explode(',', str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($versions)));
1527
1528
	// Perhaps we do accept anything?
1529
	if (in_array('all', $versions))
1530
		return true;
1531
1532
	// Loop through each version.
1533
	foreach ($versions as $for)
1534
	{
1535
		// Wild card spotted?
1536
		if (strpos($for, '*') !== false)
1537
			$for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
1538
1539
		// Do we have a range?
1540
		if (strpos($for, '-') !== false)
1541
		{
1542
			list ($lower, $upper) = explode('-', $for);
1543
1544
			// Compare the version against lower and upper bounds.
1545
			if (compareVersions($version, $lower) > -1 && compareVersions($version, $upper) < 1)
1546
				return true;
1547
		}
1548
		// Otherwise check if they are equal...
1549
		elseif (compareVersions($version, $for) === 0)
1550
			return true;
1551
	}
1552
1553
	return false;
1554
}
1555
1556
/**
1557
 * Compares two versions and determines if one is newer, older or the same, returns
1558
 * - (-1) if version1 is lower than version2
1559
 * - (0) if version1 is equal to version2
1560
 * - (1) if version1 is higher than version2
1561
 *
1562
 * @param string $version1 The first version
1563
 * @param string $version2 The second version
1564
 * @return int -1 if version2 is greater than version1, 0 if they're equal, 1 if version1 is greater than version2
1565
 */
1566
function compareVersions($version1, $version2)
1567
{
1568
	static $categories;
1569
1570
	$versions = array();
1571
	foreach (array(1 => $version1, $version2) as $id => $version)
1572
	{
1573
		// Clean the version and extract the version parts.
1574
		$clean = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
1575
		preg_match('~(\d+)(?:\.(\d+|))?(?:\.)?(\d+|)(?:(alpha|beta|rc)(\d+|)(?:\.)?(\d+|))?(?:(dev))?(\d+|)~', $clean, $parts);
1576
1577
		// Build an array of parts.
1578
		$versions[$id] = array(
1579
			'major' => !empty($parts[1]) ? (int) $parts[1] : 0,
1580
			'minor' => !empty($parts[2]) ? (int) $parts[2] : 0,
1581
			'patch' => !empty($parts[3]) ? (int) $parts[3] : 0,
1582
			'type' => empty($parts[4]) ? 'stable' : $parts[4],
1583
			'type_major' => !empty($parts[5]) ? (int) $parts[5] : 0,
1584
			'type_minor' => !empty($parts[6]) ? (int) $parts[6] : 0,
1585
			'dev' => !empty($parts[7]),
1586
		);
1587
	}
1588
1589
	// Are they the same, perhaps?
1590
	if ($versions[1] === $versions[2])
1591
		return 0;
1592
1593
	// Get version numbering categories...
1594
	if (!isset($categories))
1595
		$categories = array_keys($versions[1]);
1596
1597
	// Loop through each category.
1598
	foreach ($categories as $category)
1599
	{
1600
		// Is there something for us to calculate?
1601
		if ($versions[1][$category] !== $versions[2][$category])
1602
		{
1603
			// Dev builds are a problematic exception.
1604
			// (stable) dev < (stable) but (unstable) dev = (unstable)
1605
			if ($category == 'type')
1606
				return $versions[1][$category] > $versions[2][$category] ? ($versions[1]['dev'] ? -1 : 1) : ($versions[2]['dev'] ? 1 : -1);
1607
			elseif ($category == 'dev')
1608
				return $versions[1]['dev'] ? ($versions[2]['type'] == 'stable' ? -1 : 0) : ($versions[1]['type'] == 'stable' ? 1 : 0);
1609
			// Otherwise a simple comparison.
1610
			else
1611
				return $versions[1][$category] > $versions[2][$category] ? 1 : -1;
1612
		}
1613
	}
1614
1615
	// They are the same!
1616
	return 0;
1617
}
1618
1619
/**
1620
 * Parses special identifiers out of the specified path.
1621
 *
1622
 * @param string $path The path
1623
 * @return string The parsed path
1624
 */
1625
function parse_path($path)
1626
{
1627
	global $modSettings, $boarddir, $sourcedir, $settings, $temp_path, $txt;
1628
1629
	$dirs = array(
1630
		'\\' => '/',
1631
		'$boarddir' => $boarddir,
1632
		'$sourcedir' => $sourcedir,
1633
		'$avatardir' => $modSettings['avatar_directory'],
1634
		'$avatars_dir' => $modSettings['avatar_directory'],
1635
		'$themedir' => $settings['default_theme_dir'],
1636
		'$imagesdir' => $settings['default_theme_dir'] . '/' . basename($settings['default_images_url']),
1637
		'$themes_dir' => $boarddir . '/Themes',
1638
		'$languagedir' => $settings['default_theme_dir'] . '/languages',
1639
		'$languages_dir' => $settings['default_theme_dir'] . '/languages',
1640
		'$smileysdir' => $modSettings['smileys_dir'],
1641
		'$smileys_dir' => $modSettings['smileys_dir'],
1642
	);
1643
1644
	// do we parse in a package directory?
1645
	if (!empty($temp_path))
1646
		$dirs['$package'] = $temp_path;
1647
1648
	if (strlen($path) == 0)
1649
	{
1650
		loadLanguage('Errors');
1651
		trigger_error($txt['parse_path_filename_required'], E_USER_ERROR);
1652
	}
1653
1654
	return strtr($path, $dirs);
1655
}
1656
1657
/**
1658
 * Deletes a directory, and all the files and direcories inside it.
1659
 * requires access to delete these files.
1660
 *
1661
 * @param string $dir A directory
1662
 * @param bool $delete_dir If false, only deletes everything inside the directory but not the directory itself
1663
 */
1664
function deltree($dir, $delete_dir = true)
1665
{
1666
	/** @var ftp_connection $package_ftp */
1667
	global $package_ftp;
1668
1669
	if (!file_exists($dir))
1670
		return;
1671
1672
	$current_dir = @opendir($dir);
1673
	if ($current_dir == false)
1674
	{
1675
		if ($delete_dir && isset($package_ftp))
1676
		{
1677
			$ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1678
			if (!is_dir($dir))
1679
				$package_ftp->chmod($ftp_file, 0777);
1680
			$package_ftp->unlink($ftp_file);
1681
		}
1682
1683
		return;
1684
	}
1685
1686
	while ($entryname = readdir($current_dir))
1687
	{
1688
		if (in_array($entryname, array('.', '..')))
1689
			continue;
1690
1691
		if (is_dir($dir . '/' . $entryname))
1692
			deltree($dir . '/' . $entryname);
1693
		else
1694
		{
1695
			// Here, 755 doesn't really matter since we're deleting it anyway.
1696
			if (isset($package_ftp))
1697
			{
1698
				$ftp_file = strtr($dir . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1699
1700
				if (!is_writable($dir . '/' . $entryname))
1701
					$package_ftp->chmod($ftp_file, 0777);
1702
				$package_ftp->unlink($ftp_file);
1703
			}
1704
			else
1705
			{
1706
				if (!is_writable($dir . '/' . $entryname))
1707
					smf_chmod($dir . '/' . $entryname, 0777);
1708
				unlink($dir . '/' . $entryname);
1709
			}
1710
		}
1711
	}
1712
1713
	closedir($current_dir);
1714
1715
	if ($delete_dir)
1716
	{
1717
		if (isset($package_ftp))
1718
		{
1719
			$ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1720
			if (!is_writable($dir . '/' . $entryname))
1721
				$package_ftp->chmod($ftp_file, 0777);
1722
			$package_ftp->unlink($ftp_file);
1723
		}
1724
		else
1725
		{
1726
			if (!is_writable($dir))
1727
				smf_chmod($dir, 0777);
1728
			@rmdir($dir);
1729
		}
1730
	}
1731
}
1732
1733
/**
1734
 * Creates the specified tree structure with the mode specified.
1735
 * creates every directory in path until it finds one that already exists.
1736
 *
1737
 * @param string $strPath The path
1738
 * @param int $mode The permission mode for CHMOD (0666, etc.)
1739
 * @return bool True if successful, false otherwise
1740
 */
1741
function mktree($strPath, $mode)
1742
{
1743
	/** @var ftp_connection $package_ftp */
1744
	global $package_ftp;
1745
1746
	if (is_dir($strPath))
1747
	{
1748
		if (!is_writable($strPath) && $mode !== false)
1749
		{
1750
			if (isset($package_ftp))
1751
				$package_ftp->chmod(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')), $mode);
1752
			else
1753
				smf_chmod($strPath, $mode);
1754
		}
1755
1756
		$test = @opendir($strPath);
1757
		if ($test)
0 ignored issues
show
introduced by
$test is of type false|resource, thus it always evaluated to false.
Loading history...
1758
		{
1759
			closedir($test);
1760
			return is_writable($strPath);
1761
		}
1762
		else
1763
			return false;
1764
	}
1765
	// Is this an invalid path and/or we can't make the directory?
1766
	if ($strPath == dirname($strPath) || !mktree(dirname($strPath), $mode))
1767
		return false;
1768
1769
	if (!is_writable(dirname($strPath)) && $mode !== false)
1770
	{
1771
		if (isset($package_ftp))
1772
			$package_ftp->chmod(dirname(strtr($strPath, array($_SESSION['pack_ftp']['root'] => ''))), $mode);
1773
		else
1774
			smf_chmod(dirname($strPath), $mode);
1775
	}
1776
1777
	if ($mode !== false && isset($package_ftp))
1778
		return $package_ftp->create_dir(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')));
1779
	elseif ($mode === false)
0 ignored issues
show
introduced by
The condition $mode === false is always false.
Loading history...
1780
	{
1781
		$test = @opendir(dirname($strPath));
1782
		if ($test)
1783
		{
1784
			closedir($test);
1785
			return true;
1786
		}
1787
		else
1788
			return false;
1789
	}
1790
	else
1791
	{
1792
		@mkdir($strPath, $mode);
1793
		$test = @opendir($strPath);
1794
		if ($test)
0 ignored issues
show
introduced by
$test is of type false|resource, thus it always evaluated to false.
Loading history...
1795
		{
1796
			closedir($test);
1797
			return true;
1798
		}
1799
		else
1800
			return false;
1801
	}
1802
}
1803
1804
/**
1805
 * Copies one directory structure over to another.
1806
 * requires the destination to be writable.
1807
 *
1808
 * @param string $source The directory to copy
1809
 * @param string $destination The directory to copy $source to
1810
 */
1811
function copytree($source, $destination)
1812
{
1813
	/** @var ftp_connection $package_ftp */
1814
	global $package_ftp;
1815
1816
	if (!file_exists($destination) || !is_writable($destination))
1817
		mktree($destination, 0755);
1818
	if (!is_writable($destination))
1819
		mktree($destination, 0777);
1820
1821
	$current_dir = opendir($source);
1822
	if ($current_dir == false)
1823
		return;
1824
1825
	while ($entryname = readdir($current_dir))
1826
	{
1827
		if (in_array($entryname, array('.', '..')))
1828
			continue;
1829
1830
		if (isset($package_ftp))
1831
			$ftp_file = strtr($destination . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1832
1833
		if (is_file($source . '/' . $entryname))
1834
		{
1835
			if (isset($package_ftp) && !file_exists($destination . '/' . $entryname))
1836
				$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...
1837
			elseif (!file_exists($destination . '/' . $entryname))
1838
				@touch($destination . '/' . $entryname);
1839
		}
1840
1841
		package_chmod($destination . '/' . $entryname);
1842
1843
		if (is_dir($source . '/' . $entryname))
1844
			copytree($source . '/' . $entryname, $destination . '/' . $entryname);
1845
		elseif (file_exists($destination . '/' . $entryname))
1846
			package_put_contents($destination . '/' . $entryname, package_get_contents($source . '/' . $entryname));
1847
		else
1848
			copy($source . '/' . $entryname, $destination . '/' . $entryname);
1849
	}
1850
1851
	closedir($current_dir);
1852
}
1853
1854
/**
1855
 * Create a tree listing for a given directory path
1856
 *
1857
 * @param string $path The path
1858
 * @param string $sub_path The sub-path
1859
 * @return array An array of information about the files at the specified path/subpath
1860
 */
1861
function listtree($path, $sub_path = '')
1862
{
1863
	$data = array();
1864
1865
	$dir = @dir($path . $sub_path);
1866
	if (!$dir)
1867
		return array();
1868
	while ($entry = $dir->read())
1869
	{
1870
		if ($entry == '.' || $entry == '..')
1871
			continue;
1872
1873
		if (is_dir($path . $sub_path . '/' . $entry))
1874
			$data = array_merge($data, listtree($path, $sub_path . '/' . $entry));
1875
		else
1876
			$data[] = array(
1877
				'filename' => $sub_path == '' ? $entry : $sub_path . '/' . $entry,
1878
				'size' => filesize($path . $sub_path . '/' . $entry),
1879
				'skipped' => false,
1880
			);
1881
	}
1882
	$dir->close();
1883
1884
	return $data;
1885
}
1886
1887
/**
1888
 * Parses a xml-style modification file (file).
1889
 *
1890
 * @param string $file The modification file to parse
1891
 * @param bool $testing Whether we're just doing a test
1892
 * @param bool $undo If true, specifies that the modifications should be undone. Used when uninstalling. Doesn't work with regex.
1893
 * @param array $theme_paths An array of information about custom themes to apply the changes to
1894
 * @return array An array of those changes made.
1895
 */
1896
function parseModification($file, $testing = true, $undo = false, $theme_paths = array())
1897
{
1898
	global $boarddir, $sourcedir, $txt, $modSettings;
1899
1900
	@set_time_limit(600);
1901
	require_once($sourcedir . '/Class-Package.php');
1902
	$xml = new xmlArray(strtr($file, array("\r" => '')));
1903
	$actions = array();
1904
	$everything_found = true;
1905
1906
	if (!$xml->exists('modification') || !$xml->exists('modification/file'))
1907
	{
1908
		$actions[] = array(
1909
			'type' => 'error',
1910
			'filename' => '-',
1911
			'debug' => $txt['package_modification_malformed']
1912
		);
1913
		return $actions;
1914
	}
1915
1916
	// Get the XML data.
1917
	$files = $xml->set('modification/file');
1918
1919
	// Use this for holding all the template changes in this mod.
1920
	$template_changes = array();
1921
	// This is needed to hold the long paths, as they can vary...
1922
	$long_changes = array();
1923
1924
	// First, we need to build the list of all the files likely to get changed.
1925
	foreach ($files as $file)
0 ignored issues
show
introduced by
$file is overwriting one of the parameters of this function.
Loading history...
1926
	{
1927
		// What is the filename we're currently on?
1928
		$filename = parse_path(trim($file->fetch('@name')));
1929
1930
		// Now, we need to work out whether this is even a template file...
1931
		foreach ($theme_paths as $id => $theme)
1932
		{
1933
			// If this filename is relative, if so take a guess at what it should be.
1934
			$real_filename = $filename;
1935
			if (strpos($filename, 'Themes') === 0)
1936
				$real_filename = $boarddir . '/' . $filename;
1937
1938
			if (strpos($real_filename, $theme['theme_dir']) === 0)
1939
			{
1940
				$template_changes[$id][] = substr($real_filename, strlen($theme['theme_dir']) + 1);
1941
				$long_changes[$id][] = $filename;
1942
			}
1943
		}
1944
	}
1945
1946
	// Custom themes to add.
1947
	$custom_themes_add = array();
1948
1949
	// If we have some template changes, we need to build a master link of what new ones are required for the custom themes.
1950
	if (!empty($template_changes[1]))
1951
	{
1952
		foreach ($theme_paths as $id => $theme)
1953
		{
1954
			// Default is getting done anyway, so no need for involvement here.
1955
			if ($id == 1)
1956
				continue;
1957
1958
			// For every template, do we want it? Yea, no, maybe?
1959
			foreach ($template_changes[1] as $index => $template_file)
1960
			{
1961
				// What, it exists and we haven't already got it?! Lordy, get it in!
1962
				if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id]) || !in_array($template_file, $template_changes[$id])))
1963
				{
1964
					// Now let's add it to the "todo" list.
1965
					$custom_themes_add[$long_changes[1][$index]][$id] = $theme['theme_dir'] . '/' . $template_file;
1966
				}
1967
			}
1968
		}
1969
	}
1970
1971
	foreach ($files as $file)
0 ignored issues
show
introduced by
$file is overwriting one of the parameters of this function.
Loading history...
1972
	{
1973
		// This is the actual file referred to in the XML document...
1974
		$files_to_change = array(
1975
			1 => parse_path(trim($file->fetch('@name'))),
1976
		);
1977
1978
		// Sometimes though, we have some additional files for other themes, if we have add them to the mix.
1979
		if (isset($custom_themes_add[$files_to_change[1]]))
1980
			$files_to_change += $custom_themes_add[$files_to_change[1]];
1981
1982
		// Now, loop through all the files we're changing, and, well, change them ;)
1983
		foreach ($files_to_change as $theme => $working_file)
1984
		{
1985
			if ($working_file[0] != '/' && $working_file[1] != ':')
1986
			{
1987
				loadLanguage('Errors');
1988
				trigger_error(sprintf($txt['parse_modification_filename_not_full_path'], $working_file), E_USER_WARNING);
1989
1990
				$working_file = $boarddir . '/' . $working_file;
1991
			}
1992
1993
			// Doesn't exist - give an error or what?
1994
			if (!file_exists($working_file) && (!$file->exists('@error') || !in_array(trim($file->fetch('@error')), array('ignore', 'skip'))))
1995
			{
1996
				$actions[] = array(
1997
					'type' => 'missing',
1998
					'filename' => $working_file,
1999
					'debug' => $txt['package_modification_missing']
2000
				);
2001
2002
				$everything_found = false;
2003
				continue;
2004
			}
2005
			// Skip the file if it doesn't exist.
2006
			elseif (!file_exists($working_file) && $file->exists('@error') && trim($file->fetch('@error')) == 'skip')
2007
			{
2008
				$actions[] = array(
2009
					'type' => 'skipping',
2010
					'filename' => $working_file,
2011
				);
2012
				continue;
2013
			}
2014
			// Okay, we're creating this file then...?
2015
			elseif (!file_exists($working_file))
2016
				$working_data = '';
2017
			// Phew, it exists!  Load 'er up!
2018
			else
2019
				$working_data = str_replace("\r", '', package_get_contents($working_file));
2020
2021
			$actions[] = array(
2022
				'type' => 'opened',
2023
				'filename' => $working_file
2024
			);
2025
2026
			$operations = $file->exists('operation') ? $file->set('operation') : array();
2027
			foreach ($operations as $operation)
2028
			{
2029
				// Convert operation to an array.
2030
				$actual_operation = array(
2031
					'searches' => array(),
2032
					'error' => $operation->exists('@error') && in_array(trim($operation->fetch('@error')), array('ignore', 'fatal', 'required')) ? trim($operation->fetch('@error')) : 'fatal',
2033
				);
2034
2035
				// The 'add' parameter is used for all searches in this operation.
2036
				$add = $operation->exists('add') ? $operation->fetch('add') : '';
2037
2038
				// Grab all search items of this operation (in most cases just 1).
2039
				$searches = $operation->set('search');
2040
				foreach ($searches as $i => $search)
2041
					$actual_operation['searches'][] = array(
2042
						'position' => $search->exists('@position') && in_array(trim($search->fetch('@position')), array('before', 'after', 'replace', 'end')) ? trim($search->fetch('@position')) : 'replace',
2043
						'is_reg_exp' => $search->exists('@regexp') && trim($search->fetch('@regexp')) === 'true',
2044
						'loose_whitespace' => $search->exists('@whitespace') && trim($search->fetch('@whitespace')) === 'loose',
2045
						'search' => $search->fetch('.'),
2046
						'add' => $add,
2047
						'preg_search' => '',
2048
						'preg_replace' => '',
2049
					);
2050
2051
				// At least one search should be defined.
2052
				if (empty($actual_operation['searches']))
2053
				{
2054
					$actions[] = array(
2055
						'type' => 'failure',
2056
						'filename' => $working_file,
2057
						'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...
2058
						'is_custom' => $theme > 1 ? $theme : 0,
2059
					);
2060
2061
					// Skip to the next operation.
2062
					continue;
2063
				}
2064
2065
				// Reverse the operations in case of undoing stuff.
2066
				if ($undo)
2067
				{
2068
					foreach ($actual_operation['searches'] as $i => $search)
2069
					{
2070
						// Reverse modification of regular expressions are not allowed.
2071
						if ($search['is_reg_exp'])
2072
						{
2073
							if ($actual_operation['error'] === 'fatal')
2074
								$actions[] = array(
2075
									'type' => 'failure',
2076
									'filename' => $working_file,
2077
									'search' => $search['search'],
2078
									'is_custom' => $theme > 1 ? $theme : 0,
2079
								);
2080
2081
							// Continue to the next operation.
2082
							continue 2;
2083
						}
2084
2085
						// The replacement is now the search subject...
2086
						if ($search['position'] === 'replace' || $search['position'] === 'end')
2087
							$actual_operation['searches'][$i]['search'] = $search['add'];
2088
						else
2089
						{
2090
							// Reversing a before/after modification becomes a replacement.
2091
							$actual_operation['searches'][$i]['position'] = 'replace';
2092
2093
							if ($search['position'] === 'before')
2094
								$actual_operation['searches'][$i]['search'] .= $search['add'];
2095
							elseif ($search['position'] === 'after')
2096
								$actual_operation['searches'][$i]['search'] = $search['add'] . $search['search'];
2097
						}
2098
2099
						// ...and the search subject is now the replacement.
2100
						$actual_operation['searches'][$i]['add'] = $search['search'];
2101
					}
2102
				}
2103
2104
				// Sort the search list so the replaces come before the add before/after's.
2105
				if (count($actual_operation['searches']) !== 1)
2106
				{
2107
					$replacements = array();
2108
2109
					foreach ($actual_operation['searches'] as $i => $search)
2110
					{
2111
						if ($search['position'] === 'replace')
2112
						{
2113
							$replacements[] = $search;
2114
							unset($actual_operation['searches'][$i]);
2115
						}
2116
					}
2117
					$actual_operation['searches'] = array_merge($replacements, $actual_operation['searches']);
2118
				}
2119
2120
				// Create regular expression replacements from each search.
2121
				foreach ($actual_operation['searches'] as $i => $search)
2122
				{
2123
					// Not much needed if the search subject is already a regexp.
2124
					if ($search['is_reg_exp'])
2125
						$actual_operation['searches'][$i]['preg_search'] = $search['search'];
2126
					else
2127
					{
2128
						// Make the search subject fit into a regular expression.
2129
						$actual_operation['searches'][$i]['preg_search'] = preg_quote($search['search'], '~');
2130
2131
						// Using 'loose', a random amount of tabs and spaces may be used.
2132
						if ($search['loose_whitespace'])
2133
							$actual_operation['searches'][$i]['preg_search'] = preg_replace('~[ \t]+~', '[ \t]+', $actual_operation['searches'][$i]['preg_search']);
2134
					}
2135
2136
					// Shuzzup.  This is done so we can safely use a regular expression. ($0 is bad!!)
2137
					$actual_operation['searches'][$i]['preg_replace'] = strtr($search['add'], array('$' => '[$PACK' . 'AGE1$]', '\\' => '[$PACK' . 'AGE2$]'));
2138
2139
					// Before, so the replacement comes after the search subject :P
2140
					if ($search['position'] === 'before')
2141
					{
2142
						$actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
2143
						$actual_operation['searches'][$i]['preg_replace'] = '$1' . $actual_operation['searches'][$i]['preg_replace'];
2144
					}
2145
2146
					// After, after what?
2147
					elseif ($search['position'] === 'after')
2148
					{
2149
						$actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
2150
						$actual_operation['searches'][$i]['preg_replace'] .= '$1';
2151
					}
2152
2153
					// Position the replacement at the end of the file (or just before the closing PHP tags).
2154
					elseif ($search['position'] === 'end')
2155
					{
2156
						if ($undo)
2157
						{
2158
							$actual_operation['searches'][$i]['preg_replace'] = '';
2159
						}
2160
						else
2161
						{
2162
							$actual_operation['searches'][$i]['preg_search'] = '(\\n\\?\\>)?$';
2163
							$actual_operation['searches'][$i]['preg_replace'] .= '$1';
2164
						}
2165
					}
2166
2167
					// Testing 1, 2, 3...
2168
					$failed = preg_match('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $working_data) === 0;
2169
2170
					// Nope, search pattern not found.
2171
					if ($failed && $actual_operation['error'] === 'fatal')
2172
					{
2173
						$actions[] = array(
2174
							'type' => 'failure',
2175
							'filename' => $working_file,
2176
							'search' => $actual_operation['searches'][$i]['preg_search'],
2177
							'search_original' => $actual_operation['searches'][$i]['search'],
2178
							'replace_original' => $actual_operation['searches'][$i]['add'],
2179
							'position' => $search['position'],
2180
							'is_custom' => $theme > 1 ? $theme : 0,
2181
							'failed' => $failed,
2182
						);
2183
2184
						$everything_found = false;
2185
						continue;
2186
					}
2187
2188
					// Found, but in this case, that means failure!
2189
					elseif (!$failed && $actual_operation['error'] === 'required')
2190
					{
2191
						$actions[] = array(
2192
							'type' => 'failure',
2193
							'filename' => $working_file,
2194
							'search' => $actual_operation['searches'][$i]['preg_search'],
2195
							'search_original' => $actual_operation['searches'][$i]['search'],
2196
							'replace_original' => $actual_operation['searches'][$i]['add'],
2197
							'position' => $search['position'],
2198
							'is_custom' => $theme > 1 ? $theme : 0,
2199
							'failed' => $failed,
2200
						);
2201
2202
						$everything_found = false;
2203
						continue;
2204
					}
2205
2206
					// Replace it into nothing? That's not an option...unless it's an undoing end.
2207
					if ($search['add'] === '' && ($search['position'] !== 'end' || !$undo))
2208
						continue;
2209
2210
					// Finally, we're doing some replacements.
2211
					$working_data = preg_replace('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $actual_operation['searches'][$i]['preg_replace'], $working_data, 1);
2212
2213
					$actions[] = array(
2214
						'type' => 'replace',
2215
						'filename' => $working_file,
2216
						'search' => $actual_operation['searches'][$i]['preg_search'],
2217
						'replace' => $actual_operation['searches'][$i]['preg_replace'],
2218
						'search_original' => $actual_operation['searches'][$i]['search'],
2219
						'replace_original' => $actual_operation['searches'][$i]['add'],
2220
						'position' => $search['position'],
2221
						'failed' => $failed,
2222
						'ignore_failure' => $failed && $actual_operation['error'] === 'ignore',
2223
						'is_custom' => $theme > 1 ? $theme : 0,
2224
					);
2225
				}
2226
			}
2227
2228
			// Fix any little helper symbols ;).
2229
			$working_data = strtr($working_data, array('[$PACK' . 'AGE1$]' => '$', '[$PACK' . 'AGE2$]' => '\\'));
2230
2231
			package_chmod($working_file);
2232
2233
			if ((file_exists($working_file) && !is_writable($working_file)) || (!file_exists($working_file) && !is_writable(dirname($working_file))))
2234
				$actions[] = array(
2235
					'type' => 'chmod',
2236
					'filename' => $working_file
2237
				);
2238
2239
			if (basename($working_file) == 'Settings_bak.php')
2240
				continue;
2241
2242
			if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2243
			{
2244
				// No, no, not Settings.php!
2245
				if (basename($working_file) == 'Settings.php')
2246
					@copy($working_file, dirname($working_file) . '/Settings_bak.php');
2247
				else
2248
					@copy($working_file, $working_file . '~');
2249
			}
2250
2251
			// Always call this, even if in testing, because it won't really be written in testing mode.
2252
			package_put_contents($working_file, $working_data, $testing);
2253
2254
			$actions[] = array(
2255
				'type' => 'saved',
2256
				'filename' => $working_file,
2257
				'is_custom' => $theme > 1 ? $theme : 0,
2258
			);
2259
		}
2260
	}
2261
2262
	$actions[] = array(
2263
		'type' => 'result',
2264
		'status' => $everything_found
2265
	);
2266
2267
	return $actions;
2268
}
2269
2270
/**
2271
 * Parses a boardmod-style (.mod) modification file
2272
 *
2273
 * @param string $file The modification file to parse
2274
 * @param bool $testing Whether we're just doing a test
2275
 * @param bool $undo If true, specifies that the modifications should be undone. Used when uninstalling.
2276
 * @param array $theme_paths An array of information about custom themes to apply the changes to
2277
 * @return array An array of those changes made.
2278
 */
2279
function parseBoardMod($file, $testing = true, $undo = false, $theme_paths = array())
2280
{
2281
	global $boarddir, $sourcedir, $settings, $modSettings, $txt;
2282
2283
	@set_time_limit(600);
2284
	$file = strtr($file, array("\r" => ''));
2285
2286
	$working_file = null;
2287
	$working_search = null;
2288
	$working_data = '';
2289
	$replace_with = null;
2290
2291
	$actions = array();
2292
	$everything_found = true;
2293
2294
	// This holds all the template changes in the standard mod file.
2295
	$template_changes = array();
2296
	// This is just the temporary file.
2297
	$temp_file = $file;
2298
	// This holds the actual changes on a step counter basis.
2299
	$temp_changes = array();
2300
	$counter = 0;
2301
	$step_counter = 0;
2302
2303
	// Before we do *anything*, let's build a list of what we're editing, as it's going to be used for other theme edits.
2304
	while (preg_match('~<(edit file|file|search|search for|add|add after|replace|add before|add above|above|before)>\n(.*?)\n</\\1>~is', $temp_file, $code_match) != 0)
2305
	{
2306
		$counter++;
2307
2308
		// Get rid of the old stuff.
2309
		$temp_file = substr_replace($temp_file, '', strpos($temp_file, $code_match[0]), strlen($code_match[0]));
2310
2311
		// No interest to us?
2312
		if ($code_match[1] != 'edit file' && $code_match[1] != 'file')
2313
		{
2314
			// It's a step, let's add that to the current steps.
2315
			if (isset($temp_changes[$step_counter]))
2316
				$temp_changes[$step_counter]['changes'][] = $code_match[0];
2317
			continue;
2318
		}
2319
2320
		// We've found a new edit - let's make ourself heard, kind of.
2321
		$step_counter = $counter;
2322
		$temp_changes[$step_counter] = array(
2323
			'title' => $code_match[0],
2324
			'changes' => array(),
2325
		);
2326
2327
		$filename = parse_path($code_match[2]);
2328
2329
		// Now, is this a template file, and if so, which?
2330
		foreach ($theme_paths as $id => $theme)
2331
		{
2332
			// If this filename is relative, if so take a guess at what it should be.
2333
			if (strpos($filename, 'Themes') === 0)
2334
				$filename = $boarddir . '/' . $filename;
2335
2336
			if (strpos($filename, $theme['theme_dir']) === 0)
2337
				$template_changes[$id][$counter] = substr($filename, strlen($theme['theme_dir']) + 1);
2338
		}
2339
	}
2340
2341
	// Reference for what theme ID this action belongs to.
2342
	$theme_id_ref = array();
2343
2344
	// Now we know what templates we need to touch, cycle through each theme and work out what we need to edit.
2345
	if (!empty($template_changes[1]))
2346
	{
2347
		foreach ($theme_paths as $id => $theme)
2348
		{
2349
			// Don't do default, it means nothing to me.
2350
			if ($id == 1)
2351
				continue;
2352
2353
			// Now, for each file do we need to edit it?
2354
			foreach ($template_changes[1] as $pos => $template_file)
2355
			{
2356
				// It does? Add it to the list darlin'.
2357
				if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id][$pos]) || !in_array($template_file, $template_changes[$id][$pos])))
2358
				{
2359
					// Actually add it to the mod file too, so we can see that it will work ;)
2360
					if (!empty($temp_changes[$pos]['changes']))
2361
					{
2362
						$file .= "\n\n" . '<edit file>' . "\n" . $theme['theme_dir'] . '/' . $template_file . "\n" . '</edit file>' . "\n\n" . implode("\n\n", $temp_changes[$pos]['changes']);
2363
						$theme_id_ref[$counter] = $id;
2364
						$counter += 1 + count($temp_changes[$pos]['changes']);
2365
					}
2366
				}
2367
			}
2368
		}
2369
	}
2370
2371
	$counter = 0;
2372
	$is_custom = 0;
2373
	while (preg_match('~<(edit file|file|search|search for|add|add after|replace|add before|add above|above|before)>\n(.*?)\n</\\1>~is', $file, $code_match) != 0)
2374
	{
2375
		// This is for working out what we should be editing.
2376
		$counter++;
2377
2378
		// Edit a specific file.
2379
		if ($code_match[1] == 'file' || $code_match[1] == 'edit file')
2380
		{
2381
			// Backup the old file.
2382
			if ($working_file !== null)
2383
			{
2384
				package_chmod($working_file);
2385
2386
				// Don't even dare.
2387
				if (basename($working_file) == 'Settings_bak.php')
0 ignored issues
show
Bug introduced by
$working_file of type null is incompatible with the type string expected by parameter $path of basename(). ( Ignorable by Annotation )

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

2387
				if (basename(/** @scrutinizer ignore-type */ $working_file) == 'Settings_bak.php')
Loading history...
2388
					continue;
2389
2390
				if (!is_writable($working_file))
0 ignored issues
show
Bug introduced by
$working_file of type null is incompatible with the type string expected by parameter $filename of is_writable(). ( Ignorable by Annotation )

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

2390
				if (!is_writable(/** @scrutinizer ignore-type */ $working_file))
Loading history...
2391
					$actions[] = array(
2392
						'type' => 'chmod',
2393
						'filename' => $working_file
2394
					);
2395
2396
				if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
0 ignored issues
show
Bug introduced by
$working_file of type null is incompatible with the type string expected by parameter $filename of file_exists(). ( Ignorable by Annotation )

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

2396
				if (!$testing && !empty($modSettings['package_make_backups']) && file_exists(/** @scrutinizer ignore-type */ $working_file))
Loading history...
2397
				{
2398
					if (basename($working_file) == 'Settings.php')
2399
						@copy($working_file, dirname($working_file) . '/Settings_bak.php');
0 ignored issues
show
Bug introduced by
$working_file of type null is incompatible with the type string expected by parameter $path of dirname(). ( Ignorable by Annotation )

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

2399
						@copy($working_file, dirname(/** @scrutinizer ignore-type */ $working_file) . '/Settings_bak.php');
Loading history...
Bug introduced by
$working_file of type null is incompatible with the type string expected by parameter $from of copy(). ( Ignorable by Annotation )

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

2399
						@copy(/** @scrutinizer ignore-type */ $working_file, dirname($working_file) . '/Settings_bak.php');
Loading history...
2400
					else
2401
						@copy($working_file, $working_file . '~');
2402
				}
2403
2404
				package_put_contents($working_file, $working_data, $testing);
2405
			}
2406
2407
			if ($working_file !== null)
2408
				$actions[] = array(
2409
					'type' => 'saved',
2410
					'filename' => $working_file,
2411
					'is_custom' => $is_custom,
2412
				);
2413
2414
			// Is this "now working on" file a theme specific one?
2415
			$is_custom = isset($theme_id_ref[$counter - 1]) ? $theme_id_ref[$counter - 1] : 0;
2416
2417
			// Make sure the file exists!
2418
			$working_file = parse_path($code_match[2]);
2419
2420
			if ($working_file[0] != '/' && $working_file[1] != ':')
2421
			{
2422
				loadLanguage('Errors');
2423
				trigger_error(sprintf($txt['parse_boardmod_filename_not_full_path'], $working_file), E_USER_WARNING);
2424
2425
				$working_file = $boarddir . '/' . $working_file;
2426
			}
2427
2428
			if (!file_exists($working_file))
2429
			{
2430
				$places_to_check = array($boarddir, $sourcedir, $settings['default_theme_dir'], $settings['default_theme_dir'] . '/languages');
2431
2432
				foreach ($places_to_check as $place)
2433
					if (file_exists($place . '/' . $working_file))
2434
					{
2435
						$working_file = $place . '/' . $working_file;
2436
						break;
2437
					}
2438
			}
2439
2440
			if (file_exists($working_file))
2441
			{
2442
				// Load the new file.
2443
				$working_data = str_replace("\r", '', package_get_contents($working_file));
2444
2445
				$actions[] = array(
2446
					'type' => 'opened',
2447
					'filename' => $working_file
2448
				);
2449
			}
2450
			else
2451
			{
2452
				$actions[] = array(
2453
					'type' => 'missing',
2454
					'filename' => $working_file
2455
				);
2456
2457
				$working_file = null;
2458
				$everything_found = false;
2459
			}
2460
2461
			// Can't be searching for something...
2462
			$working_search = null;
2463
		}
2464
		// Search for a specific string.
2465
		elseif (($code_match[1] == 'search' || $code_match[1] == 'search for') && $working_file !== null)
2466
		{
2467
			if ($working_search !== null)
2468
			{
2469
				$actions[] = array(
2470
					'type' => 'error',
2471
					'filename' => $working_file
2472
				);
2473
2474
				$everything_found = false;
2475
			}
2476
2477
			$working_search = $code_match[2];
2478
		}
2479
		// Must've already loaded a search string.
2480
		elseif ($working_search !== null)
2481
		{
2482
			// This is the base string....
2483
			$replace_with = $code_match[2];
2484
2485
			// Add this afterward...
2486
			if ($code_match[1] == 'add' || $code_match[1] == 'add after')
2487
				$replace_with = $working_search . "\n" . $replace_with;
2488
			// Add this beforehand.
2489
			elseif ($code_match[1] == 'before' || $code_match[1] == 'add before' || $code_match[1] == 'above' || $code_match[1] == 'add above')
2490
				$replace_with .= "\n" . $working_search;
2491
			// Otherwise.. replace with $replace_with ;).
2492
		}
2493
2494
		// If we have a search string, replace string, and open file..
2495
		if ($working_search !== null && $replace_with !== null && $working_file !== null)
2496
		{
2497
			// Make sure it's somewhere in the string.
2498
			if ($undo)
2499
			{
2500
				$temp = $replace_with;
2501
				$replace_with = $working_search;
2502
				$working_search = $temp;
2503
			}
2504
2505
			if (strpos($working_data, $working_search) !== false)
2506
			{
2507
				$working_data = str_replace($working_search, $replace_with, $working_data);
2508
2509
				$actions[] = array(
2510
					'type' => 'replace',
2511
					'filename' => $working_file,
2512
					'search' => $working_search,
2513
					'replace' => $replace_with,
2514
					'search_original' => $working_search,
2515
					'replace_original' => $replace_with,
2516
					'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
2517
					'is_custom' => $is_custom,
2518
					'failed' => false,
2519
				);
2520
			}
2521
			// It wasn't found!
2522
			else
2523
			{
2524
				$actions[] = array(
2525
					'type' => 'failure',
2526
					'filename' => $working_file,
2527
					'search' => $working_search,
2528
					'is_custom' => $is_custom,
2529
					'search_original' => $working_search,
2530
					'replace_original' => $replace_with,
2531
					'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
2532
					'is_custom' => $is_custom,
2533
					'failed' => true,
2534
				);
2535
2536
				$everything_found = false;
2537
			}
2538
2539
			// These don't hold any meaning now.
2540
			$working_search = null;
2541
			$replace_with = null;
2542
		}
2543
2544
		// Get rid of the old tag.
2545
		$file = substr_replace($file, '', strpos($file, $code_match[0]), strlen($code_match[0]));
2546
	}
2547
2548
	// Backup the old file.
2549
	if ($working_file !== null)
2550
	{
2551
		package_chmod($working_file);
2552
2553
		if (!is_writable($working_file))
2554
			$actions[] = array(
2555
				'type' => 'chmod',
2556
				'filename' => $working_file
2557
			);
2558
2559
		if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2560
		{
2561
			if (basename($working_file) == 'Settings.php')
2562
				@copy($working_file, dirname($working_file) . '/Settings_bak.php');
2563
			else
2564
				@copy($working_file, $working_file . '~');
2565
		}
2566
2567
		package_put_contents($working_file, $working_data, $testing);
2568
	}
2569
2570
	if ($working_file !== null)
2571
		$actions[] = array(
2572
			'type' => 'saved',
2573
			'filename' => $working_file,
2574
			'is_custom' => $is_custom,
2575
		);
2576
2577
	$actions[] = array(
2578
		'type' => 'result',
2579
		'status' => $everything_found
2580
	);
2581
2582
	return $actions;
2583
}
2584
2585
/**
2586
 * Get the physical contents of a packages file
2587
 *
2588
 * @param string $filename The package file
2589
 * @return string The contents of the specified file
2590
 */
2591
function package_get_contents($filename)
2592
{
2593
	global $package_cache, $modSettings;
2594
2595
	if (!isset($package_cache))
2596
	{
2597
		$mem_check = setMemoryLimit('128M');
2598
2599
		// Windows doesn't seem to care about the memory_limit.
2600
		if (!empty($modSettings['package_disable_cache']) || $mem_check || stripos(PHP_OS, 'win') !== false)
2601
			$package_cache = array();
2602
		else
2603
			$package_cache = false;
2604
	}
2605
2606
	if (strpos($filename, 'Packages/') !== false || $package_cache === false || !isset($package_cache[$filename]))
2607
		return file_get_contents($filename);
2608
	else
2609
		return $package_cache[$filename];
2610
}
2611
2612
/**
2613
 * Writes data to a file, almost exactly like the file_put_contents() function.
2614
 * uses FTP to create/chmod the file when necessary and available.
2615
 * uses text mode for text mode file extensions.
2616
 * returns the number of bytes written.
2617
 *
2618
 * @param string $filename The name of the file
2619
 * @param string $data The data to write to the file
2620
 * @param bool $testing Whether we're just testing things
2621
 * @return int The length of the data written (in bytes)
2622
 */
2623
function package_put_contents($filename, $data, $testing = false)
2624
{
2625
	/** @var ftp_connection $package_ftp */
2626
	global $package_ftp, $package_cache, $modSettings;
2627
	static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2628
2629
	if (!isset($package_cache))
2630
	{
2631
		// Try to increase the memory limit - we don't want to run out of ram!
2632
		$mem_check = setMemoryLimit('128M');
2633
2634
		if (!empty($modSettings['package_disable_cache']) || $mem_check || stripos(PHP_OS, 'win') !== false)
2635
			$package_cache = array();
2636
		else
2637
			$package_cache = false;
2638
	}
2639
2640
	if (isset($package_ftp))
2641
		$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2642
2643
	if (!file_exists($filename) && isset($package_ftp))
2644
		$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...
2645
	elseif (!file_exists($filename))
2646
		@touch($filename);
2647
2648
	package_chmod($filename);
2649
2650
	if (!$testing && (strpos($filename, 'Packages/') !== false || $package_cache === false))
2651
	{
2652
		$fp = @fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2653
2654
		// We should show an error message or attempt a rollback, no?
2655
		if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
2656
			return false;
2657
2658
		fwrite($fp, $data);
2659
		fclose($fp);
2660
	}
2661
	elseif (strpos($filename, 'Packages/') !== false || $package_cache === false)
2662
		return strlen($data);
2663
	else
2664
	{
2665
		$package_cache[$filename] = $data;
2666
2667
		// Permission denied, eh?
2668
		$fp = @fopen($filename, 'r+');
2669
		if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
2670
			return false;
2671
		fclose($fp);
2672
	}
2673
2674
	return strlen($data);
2675
}
2676
2677
/**
2678
 * Flushes the cache from memory to the filesystem
2679
 *
2680
 * @param bool $trash
2681
 */
2682
function package_flush_cache($trash = false)
2683
{
2684
	/** @var ftp_connection $package_ftp */
2685
	global $package_ftp, $package_cache, $txt;
2686
	static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2687
2688
	if (empty($package_cache))
2689
		return;
2690
2691
	// First, let's check permissions!
2692
	foreach ($package_cache as $filename => $data)
2693
	{
2694
		if (isset($package_ftp))
2695
			$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2696
2697
		if (!file_exists($filename) && isset($package_ftp))
2698
			$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...
2699
		elseif (!file_exists($filename))
2700
			@touch($filename);
2701
2702
		$result = package_chmod($filename);
2703
2704
		// if we are not doing our test pass, then lets do a full write check
2705
		// bypass directories when doing this test
2706
		if ((!$trash) && !is_dir($filename))
2707
		{
2708
			// acid test, can we really open this file for writing?
2709
			$fp = ($result) ? fopen($filename, 'r+') : $result;
2710
			if (!$fp)
2711
			{
2712
				// We should have package_chmod()'d them before, no?!
2713
				loadLanguage('Errors');
2714
				trigger_error($txt['package_flush_cache_not_writable'], E_USER_WARNING);
2715
				return;
2716
			}
2717
			fclose($fp);
2718
		}
2719
	}
2720
2721
	if ($trash)
2722
	{
2723
		$package_cache = array();
2724
		return;
2725
	}
2726
2727
	// Write the cache to disk here.
2728
	// Bypass directories when doing so - no data to write & the fopen will crash.
2729
	foreach ($package_cache as $filename => $data)
2730
	{
2731
		if (!is_dir($filename))
2732
		{
2733
			$fp = fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2734
			fwrite($fp, $data);
2735
			fclose($fp);
2736
		}
2737
	}
2738
2739
	$package_cache = array();
2740
}
2741
2742
/**
2743
 * Try to make a file writable.
2744
 *
2745
 * @param string $filename The name of the file
2746
 * @param string $perm_state The permission state - can be either 'writable' or 'execute'
2747
 * @param bool $track_change Whether to track this change
2748
 * @return boolean True if it worked, false if it didn't
2749
 */
2750
function package_chmod($filename, $perm_state = 'writable', $track_change = false)
2751
{
2752
	/** @var ftp_connection $package_ftp */
2753
	global $package_ftp;
2754
2755
	if (file_exists($filename) && is_writable($filename) && $perm_state == 'writable')
2756
		return true;
2757
2758
	// Start off checking without FTP.
2759
	if (!isset($package_ftp) || $package_ftp === false)
2760
	{
2761
		for ($i = 0; $i < 2; $i++)
2762
		{
2763
			$chmod_file = $filename;
2764
2765
			// Start off with a less aggressive test.
2766
			if ($i == 0)
2767
			{
2768
				// If this file doesn't exist, then we actually want to look at whatever parent directory does.
2769
				$subTraverseLimit = 2;
2770
				while (!file_exists($chmod_file) && $subTraverseLimit)
2771
				{
2772
					$chmod_file = dirname($chmod_file);
2773
					$subTraverseLimit--;
2774
				}
2775
2776
				// Keep track of the writable status here.
2777
				$file_permissions = @fileperms($chmod_file);
2778
			}
2779
			else
2780
			{
2781
				// This looks odd, but it's an attempt to work around PHP suExec.
2782
				if (!file_exists($chmod_file) && $perm_state == 'writable')
2783
				{
2784
					$file_permissions = @fileperms(dirname($chmod_file));
2785
2786
					mktree(dirname($chmod_file), 0755);
2787
					@touch($chmod_file);
2788
					smf_chmod($chmod_file, 0755);
2789
				}
2790
				else
2791
					$file_permissions = @fileperms($chmod_file);
2792
			}
2793
2794
			// This looks odd, but it's another attempt to work around PHP suExec.
2795
			if ($perm_state != 'writable')
2796
				smf_chmod($chmod_file, $perm_state == 'execute' ? 0755 : 0644);
2797
			else
2798
			{
2799
				if (!@is_writable($chmod_file))
2800
					smf_chmod($chmod_file, 0755);
2801
				if (!@is_writable($chmod_file))
2802
					smf_chmod($chmod_file, 0777);
2803
				if (!@is_writable(dirname($chmod_file)))
2804
					smf_chmod($chmod_file, 0755);
2805
				if (!@is_writable(dirname($chmod_file)))
2806
					smf_chmod($chmod_file, 0777);
2807
			}
2808
2809
			// The ultimate writable test.
2810
			if ($perm_state == 'writable')
2811
			{
2812
				$fp = is_dir($chmod_file) ? @opendir($chmod_file) : @fopen($chmod_file, 'rb');
2813
				if (@is_writable($chmod_file) && $fp)
2814
				{
2815
					if (!is_dir($chmod_file))
2816
						fclose($fp);
2817
					else
2818
						closedir($fp);
2819
2820
					// It worked!
2821
					if ($track_change)
2822
						$_SESSION['pack_ftp']['original_perms'][$chmod_file] = $file_permissions;
2823
2824
					return true;
2825
				}
2826
			}
2827
			elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$chmod_file]))
2828
				unset($_SESSION['pack_ftp']['original_perms'][$chmod_file]);
2829
		}
2830
2831
		// If we're here we're a failure.
2832
		return false;
2833
	}
2834
	// Otherwise we do have FTP?
2835
	elseif ($package_ftp !== false && !empty($_SESSION['pack_ftp']))
2836
	{
2837
		$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2838
2839
		// This looks odd, but it's an attempt to work around PHP suExec.
2840
		if (!file_exists($filename) && $perm_state == 'writable')
2841
		{
2842
			$file_permissions = @fileperms(dirname($filename));
2843
2844
			mktree(dirname($filename), 0755);
2845
			$package_ftp->create_file($ftp_file);
2846
			$package_ftp->chmod($ftp_file, 0755);
2847
		}
2848
		else
2849
			$file_permissions = @fileperms($filename);
2850
2851
		if ($perm_state != 'writable')
2852
		{
2853
			$package_ftp->chmod($ftp_file, $perm_state == 'execute' ? 0755 : 0644);
2854
		}
2855
		else
2856
		{
2857
			if (!@is_writable($filename))
2858
				$package_ftp->chmod($ftp_file, 0777);
2859
			if (!@is_writable(dirname($filename)))
2860
				$package_ftp->chmod(dirname($ftp_file), 0777);
2861
		}
2862
2863
		if (@is_writable($filename))
2864
		{
2865
			if ($track_change)
2866
				$_SESSION['pack_ftp']['original_perms'][$filename] = $file_permissions;
2867
2868
			return true;
2869
		}
2870
		elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$filename]))
2871
			unset($_SESSION['pack_ftp']['original_perms'][$filename]);
2872
	}
2873
2874
	// Oh dear, we failed if we get here.
2875
	return false;
2876
}
2877
2878
/**
2879
 * Used to crypt the supplied ftp password in this session
2880
 *
2881
 * @param string $pass The password
2882
 * @return string The encrypted password
2883
 */
2884
function package_crypt($pass)
2885
{
2886
	$n = strlen($pass);
2887
2888
	$salt = session_id();
2889
	while (strlen($salt) < $n)
2890
		$salt .= session_id();
2891
2892
	for ($i = 0; $i < $n; $i++)
2893
		$pass[$i] = chr(ord($pass[$i]) ^ (ord($salt[$i]) - 32));
2894
2895
	return $pass;
2896
}
2897
2898
/**
2899
 * @param string $dir
2900
 * @param string $filename The filename without an extension
2901
 * @param string $ext
2902
 * @return string The filename with a number appended but no extension
2903
 * @since 2.1
2904
 */
2905
function package_unique_filename($dir, $filename, $ext)
2906
{
2907
	if (file_exists($dir . '/' . $filename . '.' . $ext))
2908
	{
2909
		$i = 1;
2910
		while (file_exists($dir . '/' . $filename . '_' . $i . '.' . $ext))
2911
			$i++;
2912
		$filename .= '_' . $i;
2913
	}
2914
2915
	return $filename;
2916
}
2917
2918
/**
2919
 * Creates a backup of forum files prior to modifying them
2920
 *
2921
 * @param string $id The name of the backup
2922
 * @return bool True if it worked, false if it didn't
2923
 */
2924
function package_create_backup($id = 'backup')
2925
{
2926
	global $sourcedir, $boarddir, $packagesdir, $smcFunc;
2927
2928
	$files = array();
2929
2930
	$base_files = array('index.php', 'SSI.php', 'agreement.txt', 'cron.php', 'ssi_examples.php', 'ssi_examples.shtml', 'subscriptions.php');
2931
	foreach ($base_files as $file)
2932
	{
2933
		if (file_exists($boarddir . '/' . $file))
2934
			$files[empty($_REQUEST['use_full_paths']) ? $file : $boarddir . '/' . $file] = $boarddir . '/' . $file;
2935
	}
2936
2937
	$dirs = array(
2938
		$sourcedir => empty($_REQUEST['use_full_paths']) ? 'Sources/' : strtr($sourcedir . '/', '\\', '/')
2939
	);
2940
2941
	$request = $smcFunc['db_query']('', '
2942
		SELECT value
2943
		FROM {db_prefix}themes
2944
		WHERE id_member = {int:no_member}
2945
			AND variable = {string:theme_dir}',
2946
		array(
2947
			'no_member' => 0,
2948
			'theme_dir' => 'theme_dir',
2949
		)
2950
	);
2951
	while ($row = $smcFunc['db_fetch_assoc']($request))
2952
		$dirs[$row['value']] = empty($_REQUEST['use_full_paths']) ? 'Themes/' . basename($row['value']) . '/' : strtr($row['value'] . '/', '\\', '/');
2953
	$smcFunc['db_free_result']($request);
2954
2955
	try
2956
	{
2957
		foreach ($dirs as $dir => $dest)
2958
		{
2959
			$iter = new RecursiveIteratorIterator(
2960
				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
2961
				RecursiveIteratorIterator::CHILD_FIRST,
2962
				RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
2963
			);
2964
2965
			foreach ($iter as $entry => $dir)
0 ignored issues
show
Comprehensibility Bug introduced by
$dir is overwriting a variable from outer foreach loop.
Loading history...
2966
			{
2967
				if ($dir->isDir())
2968
					continue;
2969
2970
				if (preg_match('~^(\.{1,2}|CVS|backup.*|help|images|.*\~)$~', $entry) != 0)
0 ignored issues
show
Bug introduced by
It seems like $entry can also be of type null and true; however, parameter $subject of preg_match() 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

2970
				if (preg_match('~^(\.{1,2}|CVS|backup.*|help|images|.*\~)$~', /** @scrutinizer ignore-type */ $entry) != 0)
Loading history...
2971
					continue;
2972
2973
				$files[empty($_REQUEST['use_full_paths']) ? str_replace(realpath($boarddir), '', $entry) : $entry] = $entry;
2974
			}
2975
		}
2976
		$obj = new ArrayObject($files);
2977
		$iterator = $obj->getIterator();
2978
2979
		if (!file_exists($packagesdir . '/backups'))
2980
			mktree($packagesdir . '/backups', 0777);
2981
		if (!is_writable($packagesdir . '/backups'))
2982
			package_chmod($packagesdir . '/backups');
2983
		$output_file = $packagesdir . '/backups/' . strftime('%Y-%m-%d_') . preg_replace('~[$\\\\/:<>|?*"\']~', '', $id);
2984
		$output_ext = '.tar';
2985
		$output_ext_target = '.tar.gz';
2986
2987
		if (file_exists($output_file . $output_ext_target))
2988
		{
2989
			$i = 2;
2990
			while (file_exists($output_file . '_' . $i . $output_ext_target))
2991
				$i++;
2992
			$output_file = $output_file . '_' . $i . $output_ext;
2993
		}
2994
		else
2995
			$output_file .= $output_ext;
2996
2997
		@set_time_limit(300);
2998
		if (function_exists('apache_reset_timeout'))
2999
			@apache_reset_timeout();
3000
3001
		// Phar doesn't handle open_basedir restrictions very well and throws a PHP Warning. Ignore that.
3002
		set_error_handler(
3003
			function($errno, $errstr, $errfile, $errline)
3004
			{
3005
				// error was suppressed with the @-operator
3006
				if (0 === error_reporting())
3007
					return false;
3008
3009
				if (strpos($errstr, 'PharData::__construct(): open_basedir') === false && strpos($errstr, 'PharData::compress(): open_basedir') === false)
3010
					log_error($errstr, 'general', $errfile, $errline);
3011
3012
				return true;
3013
			}
3014
		);
3015
		$a = new PharData($output_file);
3016
		$a->buildFromIterator($iterator);
3017
		$a->compress(Phar::GZ);
3018
		restore_error_handler();
3019
3020
		/*
3021
		 * Destroying the local var tells PharData to close its internal
3022
		 * file pointer, enabling us to delete the uncompressed tarball.
3023
		 */
3024
		unset($a);
3025
		unlink($output_file);
3026
	}
3027
	catch (Exception $e)
3028
	{
3029
		log_error($e->getMessage(), 'backup');
3030
3031
		return false;
3032
	}
3033
3034
	return true;
3035
}
3036
3037
if (!function_exists('smf_crc32'))
3038
{
3039
	/**
3040
	 * crc32 doesn't work as expected on 64-bit functions - make our own.
3041
	 * https://php.net/crc32#79567
3042
	 *
3043
	 * @param string $number
3044
	 * @return string The crc32
3045
	 */
3046
	function smf_crc32($number)
3047
	{
3048
		$crc = crc32($number);
3049
3050
		if ($crc & 0x80000000)
3051
		{
3052
			$crc ^= 0xffffffff;
3053
			$crc += 1;
3054
			$crc = -$crc;
3055
		}
3056
3057
		return $crc;
3058
	}
3059
}
3060
3061
/**
3062
 * Validate a package during install
3063
 *
3064
 * @param array $package Package data
3065
 * @return array Results from the package validation.
3066
 */
3067
function package_validate_installtest($package)
3068
{
3069
	global $context;
3070
3071
	// Don't validate directories.
3072
	$context['package_sha256_hash'] = is_dir($package['file_name']) ? null : hash_file('sha256', $package['file_name']);
3073
3074
	$sendData = array(array(
3075
		'sha256_hash' => $context['package_sha256_hash'],
3076
		'file_name' => basename($package['file_name']),
3077
		'custom_id' => $package['custom_id'],
3078
		'custom_type' => $package['custom_type'],
3079
	));
3080
3081
	return package_validate_send($sendData);
3082
}
3083
3084
/**
3085
 * Validate multiple packages.
3086
 *
3087
 * @param array $packages Package data
3088
 * @return array Results from the package validation.
3089
 */
3090
function package_validate($packages)
3091
{
3092
	global $context, $smcFunc;
3093
3094
	// Setup our send data.
3095
	$sendData = array();
3096
3097
	// Go through all packages and get them ready to send up.
3098
	foreach ($packages as $id_package => $package)
3099
	{
3100
		$sha256_hash = hash_file('sha256', $package);
3101
		$packageInfo = getPackageInfo($package);
3102
3103
		$packageID = '';
3104
		if (isset($packageInfo['id']))
3105
			$packageID = $packageInfo['id'];
3106
3107
		$packageType = 'modification';
3108
		if (isset($package['type']))
3109
			$packageType = $package['type'];
3110
3111
		$sendData[] = array(
3112
			'sha256_hash' => $sha256_hash,
3113
			'file_name' => basename($package),
3114
			'custom_id' => $packageID,
3115
			'custom_type' => $packageType,
3116
		);
3117
	}
3118
3119
	return package_validate_send($sendData);
3120
}
3121
3122
/**
3123
 * Sending data off to validate packages.
3124
 *
3125
 * @param array $sendData Json encoded data to be sent to the validation servers.
3126
 * @return array Results from the package validation.
3127
 */
3128
function package_validate_send($sendData)
3129
{
3130
	global $context, $smcFunc;
3131
3132
	// First lets get all package servers into here.
3133
	if (empty($context['package_servers']))
3134
	{
3135
		$request = $smcFunc['db_query']('', '
3136
			SELECT id_server, name, validation_url, extra
3137
			FROM {db_prefix}package_servers
3138
			WHERE validation_url != {string:empty}',
3139
			array(
3140
				'empty' => '',
3141
		));
3142
		$context['package_servers'] = array();
3143
		while ($row = $smcFunc['db_fetch_assoc']($request))
3144
			$context['package_servers'][$row['id_server']] = $row;
3145
		$smcFunc['db_free_result']($request);
3146
	}
3147
3148
	$the_version = SMF_VERSION;
3149
	if (!empty($_SESSION['version_emulate']))
3150
		$the_version = $_SESSION['version_emulate'];
3151
3152
	// Test each server.
3153
	$return_data = array();
3154
	foreach ($context['package_servers'] as $id_server => $server)
3155
	{
3156
		$return_data[$id_server] = array();
3157
3158
		// Sub out any variables we support in the validation url.
3159
		$validate_url = strtr($server['validation_url'], array(
3160
			'{SMF_VERSION}' => urlencode($the_version)
3161
		));
3162
3163
		$results = fetch_web_data($validate_url, 'data=' . json_encode($sendData));
3164
3165
		$parsed_data = $smcFunc['json_decode']($results, true);
3166
		if (is_array($parsed_data) && isset($parsed_data['data']) && is_array($parsed_data['data']))
3167
		{
3168
			foreach ($parsed_data['data'] as $sha256_hash => $status)
3169
			{
3170
				if ((string) $status === 'blacklist')
3171
					$context['package_blacklist_found'] = true;
3172
3173
				$return_data[$id_server][(string) $sha256_hash] = 'package_validation_status_' . ((string) $status);
3174
			}
3175
		}
3176
	}
3177
3178
	return $return_data;
3179
}
3180
3181
?>