matchHighestPackageVersion()   B
last analyzed

Complexity

Conditions 8
Paths 36

Size

Total Lines 27
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 12
c 0
b 0
f 0
nop 3
dl 0
loc 27
rs 8.4444
nc 36
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 2022 Simple Machines and individual contributors
14
 * @license https://www.simplemachines.org/about/smf/license.php BSD
15
 *
16
 * @version 2.1.2
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', substr($data, $data_ecr + 4, 16));
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', substr($data, $pos_entry + 20, 26));
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
			substr($data, $header['offset'] + 6, 24)
267
		);
268
269
		$file_info['filename'] = substr($data, $header['offset'] + 30, $file_info['filename_len']);
270
		$is_file = substr($file_info['filename'], -1) != '/';
271
272
		/*
273
		 * If the bit at offset 3 (0x08) of the general-purpose flags field
274
		 * is set, then the CRC-32 and file sizes are not known when the header
275
		 * is written. The fields in the local header are filled with zero, and
276
		 * the CRC-32 and size are appended in a 12-byte structure (optionally
277
		 * preceded by a 4-byte signature) immediately after the compressed data:
278
		 */
279
		if ($file_info['flag'] & 0x08)
280
		{
281
			$gplen = $header['offset'] + 30 + $file_info['filename_len'] + $file_info['extra_len'] + $header['compressed_size'];
282
283
			// The spec allows for an optional header in the general purpose record
284
			if (substr($data, $gplen, 4) === "\x50\x4b\x07\x08")
285
				$gplen += 4;
286
287
			if (($general_purpose = unpack('Vcrc/Vcompressed_size/Vsize', substr($data, $gplen, 12))) !== false)
288
				$file_info = $general_purpose + $file_info;
289
		}
290
291
		$write_this = false;
292
		if ($destination !== null)
293
		{
294
			// If this is a file, and it doesn't exist.... happy days!
295
			if ($is_file)
296
				$write_this = !file_exists($destination . '/' . $file_info['filename']) || $overwrite;
297
			// This is a directory, so we're gonna want to create it. (probably...)
298
			elseif (!$single_file)
299
			{
300
				$file_info['filename'] = strtr($file_info['filename'], array('../' => '', '/..' => ''));
301
302
				if (!file_exists($destination . '/' . $file_info['filename']))
303
					mktree($destination . '/' . $file_info['filename'], 0777);
304
			}
305
		}
306
307
		// Get the actual compressed data.
308
		$file_info['data'] = substr(
309
			$data,
310
			$header['offset'] + 30 + $file_info['filename_len'] + $file_info['extra_len'],
311
			$file_info['compressed_size']
312
		);
313
314
		// Only for the deflate method (the most common)
315
		if ($file_info['compression'] == 8)
316
			$file_info['data'] = gzinflate($file_info['data']);
317
		// We do not support any other compresion methods.
318
		elseif ($file_info['compression'] != 0)
319
			continue;
320
321
		// PKZip/ITU-T V.42 CRC-32
322
		if (hash('crc32b', $file_info['data']) !== sprintf('%08x', $file_info['crc']))
323
			continue;
324
325
		// Okay! We can write this file, looks good from here...
326
		if ($write_this)
327
		{
328
			// If we're looking for a specific file, and this is it... ka-bam, baby.
329
			if ($single_file && ($destination == $file_info['filename'] || $destination == '*/' . basename($file_info['filename'])))
330
				return $file_info['data'];
331
			// 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.
332
			elseif ($single_file || ($files_to_extract !== null && !in_array($file_info['filename'], $files_to_extract)))
333
				continue;
334
335
			if (!$single_file && strpos($file_info['filename'], '/') !== false)
336
				mktree($destination . '/' . dirname($file_info['filename']), 0777);
337
338
			package_put_contents($destination . '/' . $file_info['filename'], $file_info['data']);
339
		}
340
341
		if ($is_file)
342
			$return[] = array(
343
				'filename' => $file_info['filename'],
344
				'md5' => md5($file_info['data']),
345
				'preview' => substr($file_info['data'], 0, 100),
346
				'size' => $file_info['size'],
347
				'skipped' => false
348
			);
349
	}
350
351
	if ($destination !== null && !$single_file)
352
		package_flush_cache();
353
354
	return $single_file ? false : $return;
355
}
356
357
/**
358
 * Checks the existence of a remote file since file_exists() does not do remote.
359
 * will return false if the file is "moved permanently" or similar.
360
 *
361
 * @param string $url The URL to parse
362
 * @return bool Whether the specified URL exists
363
 */
364
function url_exists($url)
365
{
366
	$a_url = parse_iri($url);
367
368
	if (!isset($a_url['scheme']))
369
		return false;
370
371
	// Attempt to connect...
372
	$temp = '';
373
	$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

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

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

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

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

2386
				if (basename(/** @scrutinizer ignore-type */ $working_file) == 'Settings_bak.php')
Loading history...
2387
					continue;
2388
2389
				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

2389
				if (!is_writable(/** @scrutinizer ignore-type */ $working_file))
Loading history...
2390
					$actions[] = array(
2391
						'type' => 'chmod',
2392
						'filename' => $working_file
2393
					);
2394
2395
				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

2395
				if (!$testing && !empty($modSettings['package_make_backups']) && file_exists(/** @scrutinizer ignore-type */ $working_file))
Loading history...
2396
				{
2397
					if (basename($working_file) == 'Settings.php')
2398
						@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 $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

2398
						@copy(/** @scrutinizer ignore-type */ $working_file, dirname($working_file) . '/Settings_bak.php');
Loading history...
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

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

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