Passed
Push — release-2.1 ( 0c2197...207d2d )
by Jeremy
05:47
created

create_chmod_control()   F

Complexity

Conditions 60
Paths > 20000

Size

Total Lines 309
Code Lines 168

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 60
eloc 168
c 0
b 0
f 0
nop 3
dl 0
loc 309
rs 0
nc 17031673

1 Method

Rating   Name   Duplication   Size   Complexity  
C list_restoreFiles() 0 52 14

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This 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 http://www.simplemachines.org
13
 * @copyright 2018 Simple Machines and individual contributors
14
 * @license http://www.simplemachines.org/about/smf/license.php BSD
15
 *
16
 * @version 2.1 Beta 4
17
 */
18
19
if (!defined('SMF'))
20
	die('No direct access...');
21
22
/**
23
 * Reads a .tar.gz file, filename, in and extracts file(s) from it.
24
 * essentially just a shortcut for read_tgz_data().
25
 *
26
 * @param string $gzfilename The path to the tar.gz file
27
 * @param string $destination The path to the desitnation directory
28
 * @param bool $single_file If true returns the contents of the file specified by destination if it exists
29
 * @param bool $overwrite Whether to overwrite existing files
30
 * @param null|array $files_to_extract Specific files to extract
31
 * @return array|false An array of information about extracted files or false on failure
32
 */
33
function read_tgz_file($gzfilename, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
34
{
35
	return read_tgz_data($gzfilename, $destination, $single_file, $overwrite, $files_to_extract);
36
}
37
38
/**
39
 * Extracts a file or files from the .tar.gz contained in data.
40
 *
41
 * detects if the file is really a .zip file, and if so returns the result of read_zip_data
42
 *
43
 * if destination is null
44
 *	- returns a list of files in the archive.
45
 *
46
 * if single_file is true
47
 * - returns the contents of the file specified by destination, if it exists, or false.
48
 * - destination can start with * and / to signify that the file may come from any directory.
49
 * - destination should not begin with a / if single_file is true.
50
 *
51
 * overwrites existing files with newer modification times if and only if overwrite is true.
52
 * creates the destination directory if it doesn't exist, and is is specified.
53
 * requires zlib support be built into PHP.
54
 * returns an array of the files extracted.
55
 * if files_to_extract is not equal to null only extracts file within this array.
56
 *
57
 * @param string $gzfilename The name of the file
58
 * @param string $destination The destination
59
 * @param bool $single_file Whether to only extract a single file
60
 * @param bool $overwrite Whether to overwrite existing data
61
 * @param null|array $files_to_extract If set, only extracts the specified files
62
 * @return array|false An array of information about the extracted files or false on failure
63
 */
64
function read_tgz_data($gzfilename, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
65
{
66
	// Make sure we have this loaded.
67
	loadLanguage('Packages');
68
69
	// This function sorta needs gzinflate!
70
	if (!function_exists('gzinflate'))
71
		fatal_lang_error('package_no_zlib', 'critical');
72
73
	if (substr($gzfilename, 0, 7) == 'http://' || substr($gzfilename, 0, 8) == 'https://')
74
	{
75
		$data = fetch_web_data($gzfilename);
76
77
		if ($data === false)
78
			return false;
79
	}
80
	else
81
	{
82
		$data = @file_get_contents($gzfilename);
83
84
		if ($data === false)
85
			return false;
86
	}
87
88
	umask(0);
89
	if (!$single_file && $destination !== null && !file_exists($destination))
90
		mktree($destination, 0777);
91
92
	// No signature?
93
	if (strlen($data) < 2)
94
		return false;
95
96
	$id = unpack('H2a/H2b', substr($data, 0, 2));
97
	if (strtolower($id['a'] . $id['b']) != '1f8b')
98
	{
99
		// Okay, this ain't no tar.gz, but maybe it's a zip file.
100
		if (substr($data, 0, 2) == 'PK')
101
			return read_zip_file($gzfilename, $destination, $single_file, $overwrite, $files_to_extract);
102
		else
103
			return false;
104
	}
105
106
	$flags = unpack('Ct/Cf', substr($data, 2, 2));
107
108
	// Not deflate!
109
	if ($flags['t'] != 8)
110
		return false;
111
	$flags = $flags['f'];
112
113
	$offset = 10;
114
	$octdec = array('mode', 'uid', 'gid', 'size', 'mtime', 'checksum', 'type');
115
116
	// "Read" the filename and comment.
117
	// @todo Might be mussed.
118
	if ($flags & 12)
119
	{
120
		while ($flags & 8 && $data{$offset++} != "\0")
121
			continue;
122
		while ($flags & 4 && $data{$offset++} != "\0")
123
			continue;
124
	}
125
126
	$crc = unpack('Vcrc32/Visize', substr($data, strlen($data) - 8, 8));
127
	$data = @gzinflate(substr($data, $offset, strlen($data) - 8 - $offset));
128
129
	// smf_crc32 and crc32 may not return the same results, so we accept either.
130
	if ($crc['crc32'] != smf_crc32($data) && $crc['crc32'] != crc32($data))
131
		return false;
132
133
	$blocks = strlen($data) / 512 - 1;
134
	$offset = 0;
135
136
	$return = array();
137
138
	while ($offset < $blocks)
139
	{
140
		$header = substr($data, $offset << 9, 512);
141
		$current = unpack('a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100linkname/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor/a155path', $header);
142
143
		// Blank record?  This is probably at the end of the file.
144
		if (empty($current['filename']))
145
		{
146
			$offset += 512;
147
			continue;
148
		}
149
150
		foreach ($current as $k => $v)
151
		{
152
			if (in_array($k, $octdec))
153
				$current[$k] = octdec(trim($v));
154
			else
155
				$current[$k] = trim($v);
156
		}
157
158
		if ($current['type'] == 5 && substr($current['filename'], -1) != '/')
159
			$current['filename'] .= '/';
160
161
		$checksum = 256;
162
		for ($i = 0; $i < 148; $i++)
163
			$checksum += ord($header{$i});
164
		for ($i = 156; $i < 512; $i++)
165
			$checksum += ord($header{$i});
166
167
		if ($current['checksum'] != $checksum)
168
			break;
169
170
		$size = ceil($current['size'] / 512);
171
		$current['data'] = substr($data, ++$offset << 9, $current['size']);
172
		$offset += $size;
173
174
		// Not a directory and doesn't exist already...
175
		if (substr($current['filename'], -1, 1) != '/' && !file_exists($destination . '/' . $current['filename']))
176
			$write_this = true;
177
		// File exists... check if it is newer.
178
		elseif (substr($current['filename'], -1, 1) != '/')
179
			$write_this = $overwrite || filemtime($destination . '/' . $current['filename']) < $current['mtime'];
180
		// Folder... create.
181
		elseif ($destination !== null && !$single_file)
182
		{
183
			// Protect from accidental parent directory writing...
184
			$current['filename'] = strtr($current['filename'], array('../' => '', '/..' => ''));
185
186
			if (!file_exists($destination . '/' . $current['filename']))
187
				mktree($destination . '/' . $current['filename'], 0777);
188
			$write_this = false;
189
		}
190
		else
191
			$write_this = false;
192
193
		if ($write_this && $destination !== null)
194
		{
195
			if (strpos($current['filename'], '/') !== false && !$single_file)
196
				mktree($destination . '/' . dirname($current['filename']), 0777);
197
198
			// Is this the file we're looking for?
199
			if ($single_file && ($destination == $current['filename'] || $destination == '*/' . basename($current['filename'])))
200
				return $current['data'];
201
			// If we're looking for another file, keep going.
202
			elseif ($single_file)
203
				continue;
204
			// Looking for restricted files?
205
			elseif ($files_to_extract !== null && !in_array($current['filename'], $files_to_extract))
206
				continue;
207
208
			package_put_contents($destination . '/' . $current['filename'], $current['data']);
209
		}
210
211
		if (substr($current['filename'], -1, 1) != '/')
212
			$return[] = array(
213
				'filename' => $current['filename'],
214
				'md5' => md5($current['data']),
215
				'preview' => substr($current['data'], 0, 100),
216
				'size' => $current['size'],
217
				'skipped' => false
218
			);
219
	}
220
221
	if ($destination !== null && !$single_file)
222
		package_flush_cache();
223
224
	if ($single_file)
225
		return false;
226
	else
227
		return $return;
228
}
229
230
/**
231
 * Extract zip data. A functional copy of {@list read_zip_data()}.
232
 *
233
 * @param string $file Input filename
234
 * @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)
235
 * @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).
236
 * @param boolean $overwrite If true, will overwrite files with newer modication times. Default is false.
237
 * @param array $files_to_extract Specific files to extract
238
 * @uses {@link PharData}
239
 * @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
240
 */
241
242
function read_zip_file($file, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
243
{
244
	try
245
	{
246
		// This may not always be defined...
247
		$return = array();
248
249
		// Some hosted unix platforms require an extension; win may have .tmp & that works ok
250
		if (!in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), array('zip', 'tmp')))
251
			if (@rename($file, $file . '.zip'))
252
				$file = $file . '.zip';
253
254
		// Phar doesn't handle open_basedir restrictions very well and throws a PHP Warning. Ignore that.
255
		set_error_handler(function($errno, $errstr, $errfile, $errline)
256
			{
257
				// error was suppressed with the @-operator
258
				if (0 === error_reporting()) {
259
					return false;
260
				}
261
				if (strpos($errstr, 'PharData::__construct(): open_basedir') === false)
262
					log_error($errstr, 'general', $errfile, $errline);
263
			}
264
		);
265
		$archive = new PharData($file, RecursiveIteratorIterator::SELF_FIRST, null, Phar::ZIP);
266
		restore_error_handler();
267
268
		$iterator = new RecursiveIteratorIterator($archive, RecursiveIteratorIterator::SELF_FIRST);
269
270
		// go though each file in the archive
271
		foreach ($iterator as $file_info)
272
			{
273
				$i = $iterator->getSubPathname();
0 ignored issues
show
Bug introduced by
The method getSubPathname() does not exist on RecursiveIteratorIterator. ( Ignorable by Annotation )

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

273
				/** @scrutinizer ignore-call */ 
274
    $i = $iterator->getSubPathname();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
274
				// If this is a file, and it doesn't exist.... happy days!
275
				if (substr($i, -1) != '/' && !file_exists($destination . '/' . $i))
276
					$write_this = true;
277
				// If the file exists, we may not want to overwrite it.
278
				elseif (substr($i, -1) != '/')
279
					$write_this = $overwrite;
280
				else
281
					$write_this = false;
282
283
				// Get the actual compressed data.
284
				if (!$file_info->isDir())
285
					$file_data = file_get_contents($file_info);
286
				elseif ($destination !== null && !$single_file)
287
				{
288
					// Folder... create.
289
					if (!file_exists($destination . '/' . $i))
290
						mktree($destination . '/' . $i, 0777);
291
					$file_data = null;
292
				}
293
				else
294
					$file_data = null;
295
296
				// Okay!  We can write this file, looks good from here...
297
				if ($write_this && $destination !== null)
298
				{
299
					if (!$single_file && !is_dir($destination . '/' . dirname($i)))
300
						mktree($destination . '/' . dirname($i), 0777);
301
302
					// If we're looking for a specific file, and this is it... ka-bam, baby.
303
					if ($single_file && ($destination == $i || $destination == '*/' . basename($i)))
304
						return $file_data;
305
					// 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.
306
					elseif ($single_file)
307
						continue;
308
					// Don't really want this?
309
					elseif ($files_to_extract !== null && !in_array($i, $files_to_extract))
310
						continue;
311
312
					package_put_contents($destination . '/' . $i, $file_data);
313
				}
314
315
				if (substr($i, -1, 1) != '/')
316
					$return[] = array(
317
						'filename' => $i,
318
						'md5' => md5($file_data),
319
						'preview' => substr($file_data, 0, 100),
320
						'size' => strlen($file_data),
321
						'skipped' => false
322
					);
323
			}
324
325
		if ($destination !== null && !$single_file)
326
			package_flush_cache();
327
328
		if ($single_file)
329
			return false;
330
		else
331
			return $return;
332
	}
333
	catch (Exception $e)
334
	{
335
		log_error($e->getMessage(), 'general', $e->getFile(), $e->getLine());
336
		return false;
337
	}
338
}
339
340
/**
341
 * Extract zip data. .
342
 *
343
 * If single_file is true, destination can start with * and / to signify that the file may come from any directory.
344
 * Destination should not begin with a / if single_file is true.
345
 *
346
 * @param string $data ZIP data
347
 * @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)
348
 * @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).
349
 * @param boolean $overwrite If true, will overwrite files with newer modication times. Default is false.
350
 * @param array $files_to_extract
351
 * @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
352
 */
353
function read_zip_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
354
{
355
	umask(0);
356
	if ($destination !== null && !file_exists($destination) && !$single_file)
357
		mktree($destination, 0777);
358
359
	// Look for the end of directory signature 0x06054b50
360
	$data_ecr = explode("\x50\x4b\x05\x06", $data);
361
	if (!isset($data_ecr[1]))
362
		return false;
363
364
	$return = array();
365
366
	// Get all the basic zip file info since we are here
367
	$zip_info = unpack('vdisks/vrecords/vfiles/Vsize/Voffset/vcomment_length/', $data_ecr[1]);
368
369
	// Cut file at the central directory file header signature -- 0x02014b50, use unpack if you want any of the data, we don't
370
	$file_sections = explode("\x50\x4b\x01\x02", $data);
371
372
	// Cut the result on each local file header -- 0x04034b50 so we have each file in the archive as an element.
373
	$file_sections = explode("\x50\x4b\x03\x04", $file_sections[0]);
374
	array_shift($file_sections);
375
376
	// sections and count from the signature must match or the zip file is bad
377
	if (count($file_sections) != $zip_info['files'])
378
		return false;
379
380
	// go though each file in the archive
381
	foreach ($file_sections as $data)
0 ignored issues
show
introduced by
$data is overwriting one of the parameters of this function.
Loading history...
382
	{
383
		// Get all the important file information.
384
		$file_info = unpack("vversion/vgeneral_purpose/vcompress_method/vfile_time/vfile_date/Vcrc/Vcompressed_size/Vsize/vfilename_length/vextrafield_length", $data);
385
		$file_info['filename'] = substr($data, 26, $file_info['filename_length']);
386
		$file_info['dir'] = $destination . '/' . dirname($file_info['filename']);
387
388
		// If bit 3 (0x08) of the general-purpose flag is set, then the CRC and file size were not available when the header was written
389
		// In this case the CRC and size are instead appended in a 12-byte structure immediately after the compressed data
390
		if ($file_info['general_purpose'] & 0x0008)
391
		{
392
			$unzipped2 = unpack("Vcrc/Vcompressed_size/Vsize", substr($$data, -12));
393
			$file_info['crc'] = $unzipped2['crc'];
394
			$file_info['compressed_size'] = $unzipped2['compressed_size'];
395
			$file_info['size'] = $unzipped2['size'];
396
			unset($unzipped2);
397
		}
398
399
		// If this is a file, and it doesn't exist.... happy days!
400
		if (substr($file_info['filename'], -1) != '/' && !file_exists($destination . '/' . $file_info['filename']))
401
			$write_this = true;
402
		// If the file exists, we may not want to overwrite it.
403
		elseif (substr($file_info['filename'], -1) != '/')
404
			$write_this = $overwrite;
405
		// This is a directory, so we're gonna want to create it. (probably...)
406
		elseif ($destination !== null && !$single_file)
407
		{
408
			// Just a little accident prevention, don't mind me.
409
			$file_info['filename'] = strtr($file_info['filename'], array('../' => '', '/..' => ''));
410
411
			if (!file_exists($destination . '/' . $file_info['filename']))
412
				mktree($destination . '/' . $file_info['filename'], 0777);
413
			$write_this = false;
414
		}
415
		else
416
			$write_this = false;
417
418
		// Get the actual compressed data.
419
		$file_info['data'] = substr($data, 26 + $file_info['filename_length'] + $file_info['extrafield_length']);
420
421
		// Only inflate it if we need to ;)
422
		if (!empty($file_info['compress_method']) || ($file_info['compressed_size'] != $file_info['size']))
423
			$file_info['data'] = gzinflate($file_info['data']);
424
425
		// Okay!  We can write this file, looks good from here...
426
		if ($write_this && $destination !== null)
427
		{
428
			if ((strpos($file_info['filename'], '/') !== false && !$single_file) || (!$single_file && !is_dir($file_info['dir'])))
429
				mktree($file_info['dir'], 0777);
430
431
			// If we're looking for a specific file, and this is it... ka-bam, baby.
432
			if ($single_file && ($destination == $file_info['filename'] || $destination == '*/' . basename($file_info['filename'])))
433
				return $file_info['data'];
434
			// 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.
435
			elseif ($single_file)
436
				continue;
437
			// Don't really want this?
438
			elseif ($files_to_extract !== null && !in_array($file_info['filename'], $files_to_extract))
439
				continue;
440
441
			package_put_contents($destination . '/' . $file_info['filename'], $file_info['data']);
442
		}
443
444
		if (substr($file_info['filename'], -1, 1) != '/')
445
			$return[] = array(
446
				'filename' => $file_info['filename'],
447
				'md5' => md5($file_info['data']),
448
				'preview' => substr($file_info['data'], 0, 100),
449
				'size' => $file_info['size'],
450
				'skipped' => false
451
			);
452
	}
453
454
	if ($destination !== null && !$single_file)
455
		package_flush_cache();
456
457
	if ($single_file)
458
		return false;
459
	else
460
		return $return;
461
}
462
463
/**
464
 * Checks the existence of a remote file since file_exists() does not do remote.
465
 * will return false if the file is "moved permanently" or similar.
466
 * @param string $url The URL to parse
467
 * @return bool Whether the specified URL exists
468
 */
469
function url_exists($url)
470
{
471
	$a_url = parse_url($url);
472
473
	if (!isset($a_url['scheme']))
474
		return false;
475
476
	// Attempt to connect...
477
	$temp = '';
478
	$fid = fsockopen($a_url['host'], !isset($a_url['port']) ? 80 : $a_url['port'], $temp, $temp, 8);
0 ignored issues
show
Bug introduced by
$temp of type string is incompatible with the type integer expected by parameter $errno of fsockopen(). ( Ignorable by Annotation )

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

478
	$fid = fsockopen($a_url['host'], !isset($a_url['port']) ? 80 : $a_url['port'], /** @scrutinizer ignore-type */ $temp, $temp, 8);
Loading history...
479
	if (!$fid)
0 ignored issues
show
introduced by
$fid is of type resource, thus it always evaluated to false.
Loading history...
480
		return false;
481
482
	fputs($fid, 'HEAD ' . $a_url['path'] . ' HTTP/1.0' . "\r\n" . 'Host: ' . $a_url['host'] . "\r\n\r\n");
483
	$head = fread($fid, 1024);
484
	fclose($fid);
485
486
	return preg_match('~^HTTP/.+\s+(20[01]|30[127])~i', $head) == 1;
487
}
488
489
/**
490
 * Loads and returns an array of installed packages.
491
 * - returns the array of data.
492
 * - default sort order is package_installed time
493
 *
494
 * @return array An array of info about installed packages
495
 */
496
function loadInstalledPackages()
497
{
498
	global $smcFunc;
499
500
	// Load the packages from the database - note this is ordered by install time to ensure latest package uninstalled first.
501
	$request = $smcFunc['db_query']('', '
502
		SELECT id_install, package_id, filename, name, version, time_installed
503
		FROM {db_prefix}log_packages
504
		WHERE install_state != {int:not_installed}
505
		ORDER BY time_installed DESC',
506
		array(
507
			'not_installed' => 0,
508
		)
509
	);
510
	$installed = array();
511
	$found = array();
512
	while ($row = $smcFunc['db_fetch_assoc']($request))
513
	{
514
		// Already found this? If so don't add it twice!
515
		if (in_array($row['package_id'], $found))
516
			continue;
517
518
		$found[] = $row['package_id'];
519
520
		$row = htmlspecialchars__recursive($row);
521
522
		$installed[] = array(
523
			'id' => $row['id_install'],
524
			'name' => $smcFunc['htmlspecialchars']($row['name']),
525
			'filename' => $row['filename'],
526
			'package_id' => $row['package_id'],
527
			'version' => $smcFunc['htmlspecialchars']($row['version']),
528
			'time_installed' => !empty($row['time_installed']) ? $row['time_installed'] : 0,
529
		);
530
	}
531
	$smcFunc['db_free_result']($request);
532
533
	return $installed;
534
}
535
536
/**
537
 * Loads a package's information and returns a representative array.
538
 * - expects the file to be a package in Packages/.
539
 * - returns a error string if the package-info is invalid.
540
 * - otherwise returns a basic array of id, version, filename, and similar information.
541
 * - an xmlArray is available in 'xml'.
542
 *
543
 * @param string $gzfilename The path to the file
544
 * @return array|string An array of info about the file or a string indicating an error
545
 */
546
function getPackageInfo($gzfilename)
547
{
548
	global $sourcedir, $packagesdir;
549
550
	// Extract package-info.xml from downloaded file. (*/ is used because it could be in any directory.)
551
	if (strpos($gzfilename, 'http://') !== false || strpos($gzfilename, 'https://') !== false)
552
		$packageInfo = read_tgz_data($gzfilename, 'package-info.xml', true);
553
	else
554
	{
555
		if (!file_exists($packagesdir . '/' . $gzfilename))
556
			return 'package_get_error_not_found';
557
558
		if (is_file($packagesdir . '/' . $gzfilename))
559
			$packageInfo = read_tgz_file($packagesdir . '/' . $gzfilename, '*/package-info.xml', true);
560
		elseif (file_exists($packagesdir . '/' . $gzfilename . '/package-info.xml'))
561
			$packageInfo = file_get_contents($packagesdir . '/' . $gzfilename . '/package-info.xml');
562
		else
563
			return 'package_get_error_missing_xml';
564
	}
565
566
	// Nothing?
567
	if (empty($packageInfo))
568
	{
569
		// Perhaps they are trying to install a theme, lets tell them nicely this is the wrong function
570
		$packageInfo = read_tgz_file($packagesdir . '/' . $gzfilename, '*/theme_info.xml', true);
571
		if (!empty($packageInfo))
572
			return 'package_get_error_is_theme';
573
		else
574
			return 'package_get_error_is_zero';
575
	}
576
577
	// Parse package-info.xml into an xmlArray.
578
	require_once($sourcedir . '/Class-Package.php');
579
	$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

579
	$packageInfo = new xmlArray(/** @scrutinizer ignore-type */ $packageInfo);
Loading history...
580
581
	// @todo Error message of some sort?
582
	if (!$packageInfo->exists('package-info[0]'))
583
		return 'package_get_error_packageinfo_corrupt';
584
585
	$packageInfo = $packageInfo->path('package-info[0]');
586
587
	$package = $packageInfo->to_array();
588
	$package = htmlspecialchars__recursive($package);
589
	$package['xml'] = $packageInfo;
590
	$package['filename'] = $gzfilename;
591
592
	// Don't want to mess with code...
593
	$types = array('install', 'uninstall', 'upgrade');
594
	foreach ($types as $type)
595
	{
596
		if (isset($package[$type]['code']))
597
		{
598
			$package[$type]['code'] = un_htmlspecialchars($package[$type]['code']);
599
		}
600
	}
601
602
	if (!isset($package['type']))
603
		$package['type'] = 'modification';
604
605
	return $package;
606
}
607
608
/**
609
 * Create a chmod control for chmoding files.
610
 *
611
 * @param array $chmodFiles Which files to chmod
612
 * @param array $chmodOptions Options for chmod
613
 * @param bool $restore_write_status Whether to restore write status
614
 * @return array An array of file info
615
 */
616
function create_chmod_control($chmodFiles = array(), $chmodOptions = array(), $restore_write_status = false)
617
{
618
	global $context, $modSettings, $package_ftp, $boarddir, $txt, $sourcedir, $scripturl;
619
620
	// If we're restoring the status of existing files prepare the data.
621
	if ($restore_write_status && isset($_SESSION['pack_ftp']) && !empty($_SESSION['pack_ftp']['original_perms']))
622
	{
623
		/**
624
		 * Get a listing of files that will need to be set back to the original state
625
		 *
626
		 * @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...
627
		 * @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...
628
		 * @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...
629
		 * @param bool $do_change
630
		 * @return array An array of info about the files that need to be restored back to their original state
631
		 */
632
		function list_restoreFiles($dummy1, $dummy2, $dummy3, $do_change)
633
		{
634
			global $txt;
635
636
			$restore_files = array();
637
			foreach ($_SESSION['pack_ftp']['original_perms'] as $file => $perms)
638
			{
639
				// Check the file still exists, and the permissions were indeed different than now.
640
				$file_permissions = @fileperms($file);
641
				if (!file_exists($file) || $file_permissions == $perms)
642
				{
643
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
644
					continue;
645
				}
646
647
				// Are we wanting to change the permission?
648
				if ($do_change && isset($_POST['restore_files']) && in_array($file, $_POST['restore_files']))
649
				{
650
					// Use FTP if we have it.
651
					// @todo where does $package_ftp get set?
652
					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...
653
					{
654
						$ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
655
						$package_ftp->chmod($ftp_file, $perms);
656
					}
657
					else
658
						smf_chmod($file, $perms);
659
660
					$new_permissions = @fileperms($file);
661
					$result = $new_permissions == $perms ? 'success' : 'failure';
662
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
663
				}
664
				elseif ($do_change)
665
				{
666
					$new_permissions = '';
667
					$result = 'skipped';
668
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
669
				}
670
671
				// Record the results!
672
				$restore_files[] = array(
673
					'path' => $file,
674
					'old_perms_raw' => $perms,
675
					'old_perms' => substr(sprintf('%o', $perms), -4),
676
					'cur_perms' => substr(sprintf('%o', $file_permissions), -4),
677
					'new_perms' => isset($new_permissions) ? substr(sprintf('%o', $new_permissions), -4) : '',
678
					'result' => isset($result) ? $result : '',
679
					'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>',
680
				);
681
			}
682
683
			return $restore_files;
684
		}
685
686
		$listOptions = array(
687
			'id' => 'restore_file_permissions',
688
			'title' => $txt['package_restore_permissions'],
689
			'get_items' => array(
690
				'function' => 'list_restoreFiles',
691
				'params' => array(
692
					!empty($_POST['restore_perms']),
693
				),
694
			),
695
			'columns' => array(
696
				'path' => array(
697
					'header' => array(
698
						'value' => $txt['package_restore_permissions_filename'],
699
					),
700
					'data' => array(
701
						'db' => 'path',
702
						'class' => 'smalltext',
703
					),
704
				),
705
				'old_perms' => array(
706
					'header' => array(
707
						'value' => $txt['package_restore_permissions_orig_status'],
708
					),
709
					'data' => array(
710
						'db' => 'old_perms',
711
						'class' => 'smalltext',
712
					),
713
				),
714
				'cur_perms' => array(
715
					'header' => array(
716
						'value' => $txt['package_restore_permissions_cur_status'],
717
					),
718
					'data' => array(
719
						'function' => function($rowData) use ($txt)
720
						{
721
							$formatTxt = $rowData['result'] == '' || $rowData['result'] == 'skipped' ? $txt['package_restore_permissions_pre_change'] : $txt['package_restore_permissions_post_change'];
722
							return sprintf($formatTxt, $rowData['cur_perms'], $rowData['new_perms'], $rowData['writable_message']);
723
						},
724
						'class' => 'smalltext',
725
					),
726
				),
727
				'check' => array(
728
					'header' => array(
729
						'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
730
						'class' => 'centercol',
731
					),
732
					'data' => array(
733
						'sprintf' => array(
734
							'format' => '<input type="checkbox" name="restore_files[]" value="%1$s">',
735
							'params' => array(
736
								'path' => false,
737
							),
738
						),
739
						'class' => 'centercol',
740
					),
741
				),
742
				'result' => array(
743
					'header' => array(
744
						'value' => $txt['package_restore_permissions_result'],
745
					),
746
					'data' => array(
747
						'function' => function($rowData) use ($txt)
748
						{
749
							return $txt['package_restore_permissions_action_' . $rowData['result']];
750
						},
751
						'class' => 'smalltext',
752
					),
753
				),
754
			),
755
			'form' => array(
756
				'href' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : $scripturl . '?action=admin;area=packages;sa=perms;restore;' . $context['session_var'] . '=' . $context['session_id'],
757
			),
758
			'additional_rows' => array(
759
				array(
760
					'position' => 'below_table_data',
761
					'value' => '<input type="submit" name="restore_perms" value="' . $txt['package_restore_permissions_restore'] . '" class="button">',
762
					'class' => 'titlebg',
763
				),
764
				array(
765
					'position' => 'after_title',
766
					'value' => '<span class="smalltext">' . $txt['package_restore_permissions_desc'] . '</span>',
767
					'class' => 'windowbg',
768
				),
769
			),
770
		);
771
772
		// Work out what columns and the like to show.
773
		if (!empty($_POST['restore_perms']))
774
		{
775
			$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']);
776
			unset($listOptions['columns']['check'], $listOptions['form'], $listOptions['additional_rows'][0]);
777
778
			$context['sub_template'] = 'show_list';
779
			$context['default_list'] = 'restore_file_permissions';
780
		}
781
		else
782
		{
783
			unset($listOptions['columns']['result']);
784
		}
785
786
		// Create the list for display.
787
		require_once($sourcedir . '/Subs-List.php');
788
		createList($listOptions);
789
790
		// If we just restored permissions then whereever we are, we are now done and dusted.
791
		if (!empty($_POST['restore_perms']))
792
			obExit();
793
	}
794
	// Otherwise, it's entirely irrelevant?
795
	elseif ($restore_write_status)
796
		return true;
797
798
	// This is where we report what we got up to.
799
	$return_data = array(
800
		'files' => array(
801
			'writable' => array(),
802
			'notwritable' => array(),
803
		),
804
	);
805
806
	// If we have some FTP information already, then let's assume it was required and try to get ourselves connected.
807
	if (!empty($_SESSION['pack_ftp']['connected']))
808
	{
809
		// Load the file containing the ftp_connection class.
810
		require_once($sourcedir . '/Class-Package.php');
811
812
		$package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
813
	}
814
815
	// Just got a submission did we?
816
	if (empty($package_ftp) && isset($_POST['ftp_username']))
817
	{
818
		require_once($sourcedir . '/Class-Package.php');
819
		$ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
820
821
		// We're connected, jolly good!
822
		if ($ftp->error === false)
0 ignored issues
show
introduced by
The condition $ftp->error === false is always false.
Loading history...
823
		{
824
			// Common mistake, so let's try to remedy it...
825
			if (!$ftp->chdir($_POST['ftp_path']))
826
			{
827
				$ftp_error = $ftp->last_message;
828
				$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
829
			}
830
831
			if (!in_array($_POST['ftp_path'], array('', '/')))
832
			{
833
				$ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
834
				if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || substr($_POST['ftp_path'], 0, 1) == '/'))
835
					$ftp_root = substr($ftp_root, 0, -1);
836
			}
837
			else
838
				$ftp_root = $boarddir;
839
840
			$_SESSION['pack_ftp'] = array(
841
				'server' => $_POST['ftp_server'],
842
				'port' => $_POST['ftp_port'],
843
				'username' => $_POST['ftp_username'],
844
				'password' => package_crypt($_POST['ftp_password']),
845
				'path' => $_POST['ftp_path'],
846
				'root' => $ftp_root,
847
				'connected' => true,
848
			);
849
850
			if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
851
				updateSettings(array('package_path' => $_POST['ftp_path']));
852
853
			// This is now the primary connection.
854
			$package_ftp = $ftp;
855
		}
856
	}
857
858
	// Now try to simply make the files writable, with whatever we might have.
859
	if (!empty($chmodFiles))
860
	{
861
		foreach ($chmodFiles as $k => $file)
862
		{
863
			// Sometimes this can somehow happen maybe?
864
			if (empty($file))
865
				unset($chmodFiles[$k]);
866
			// Already writable?
867
			elseif (@is_writable($file))
868
				$return_data['files']['writable'][] = $file;
869
			else
870
			{
871
				// Now try to change that.
872
				$return_data['files'][package_chmod($file, 'writable', true) ? 'writable' : 'notwritable'][] = $file;
873
			}
874
		}
875
	}
876
877
	// Have we still got nasty files which ain't writable? Dear me we need more FTP good sir.
878
	if (empty($package_ftp) && (!empty($return_data['files']['notwritable']) || !empty($chmodOptions['force_find_error'])))
879
	{
880
		if (!isset($ftp) || $ftp->error !== false)
881
		{
882
			if (!isset($ftp))
883
			{
884
				require_once($sourcedir . '/Class-Package.php');
885
				$ftp = new ftp_connection(null);
886
			}
887
			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...
888
				$ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
889
890
			list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
891
892
			if ($found_path)
893
				$_POST['ftp_path'] = $detect_path;
894
			elseif (!isset($_POST['ftp_path']))
895
				$_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
896
897
			if (!isset($_POST['ftp_username']))
898
				$_POST['ftp_username'] = $username;
899
		}
900
901
		$context['package_ftp'] = array(
902
			'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
903
			'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
904
			'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
905
			'path' => $_POST['ftp_path'],
906
			'error' => empty($ftp_error) ? null : $ftp_error,
907
			'destination' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : '',
908
		);
909
910
		// Which files failed?
911
		if (!isset($context['notwritable_files']))
912
			$context['notwritable_files'] = array();
913
		$context['notwritable_files'] = array_merge($context['notwritable_files'], $return_data['files']['notwritable']);
914
915
		// Sent here to die?
916
		if (!empty($chmodOptions['crash_on_error']))
917
		{
918
			$context['page_title'] = $txt['package_ftp_necessary'];
919
			$context['sub_template'] = 'ftp_required';
920
			obExit();
921
		}
922
	}
923
924
	return $return_data;
925
}
926
927
/**
928
 * Use FTP functions to work with a package download/install
929
 *
930
 * @param string $destination_url The destination URL
931
 * @param null|array $files The files to CHMOD
932
 * @param bool $return Whether to return an array of file info if there's an error
933
 * @return array An array of file info
934
 */
935
function packageRequireFTP($destination_url, $files = null, $return = false)
936
{
937
	global $context, $modSettings, $package_ftp, $boarddir, $txt, $sourcedir;
938
939
	// Try to make them writable the manual way.
940
	if ($files !== null)
941
	{
942
		foreach ($files as $k => $file)
943
		{
944
			// If this file doesn't exist, then we actually want to look at the directory, no?
945
			if (!file_exists($file))
946
				$file = dirname($file);
947
948
			// This looks odd, but it's an attempt to work around PHP suExec.
949
			if (!@is_writable($file))
950
				smf_chmod($file, 0755);
951
			if (!@is_writable($file))
952
				smf_chmod($file, 0777);
953
			if (!@is_writable(dirname($file)))
954
				smf_chmod($file, 0755);
955
			if (!@is_writable(dirname($file)))
956
				smf_chmod($file, 0777);
957
958
			$fp = is_dir($file) ? @opendir($file) : @fopen($file, 'rb');
959
			if (@is_writable($file) && $fp)
960
			{
961
				unset($files[$k]);
962
				if (!is_dir($file))
963
					fclose($fp);
964
				else
965
					closedir($fp);
966
			}
967
		}
968
969
		// No FTP required!
970
		if (empty($files))
971
			return array();
972
	}
973
974
	// They've opted to not use FTP, and try anyway.
975
	if (isset($_SESSION['pack_ftp']) && $_SESSION['pack_ftp'] == false)
976
	{
977
		if ($files === null)
978
			return array();
979
980
		foreach ($files as $k => $file)
981
		{
982
			// This looks odd, but it's an attempt to work around PHP suExec.
983
			if (!file_exists($file))
984
			{
985
				mktree(dirname($file), 0755);
986
				@touch($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
987
				smf_chmod($file, 0755);
988
			}
989
990
			if (!@is_writable($file))
991
				smf_chmod($file, 0777);
992
			if (!@is_writable(dirname($file)))
993
				smf_chmod(dirname($file), 0777);
994
995
			if (@is_writable($file))
996
				unset($files[$k]);
997
		}
998
999
		return $files;
1000
	}
1001
	elseif (isset($_SESSION['pack_ftp']))
1002
	{
1003
		// Load the file containing the ftp_connection class.
1004
		require_once($sourcedir . '/Class-Package.php');
1005
1006
		$package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
1007
1008
		if ($files === null)
1009
			return array();
1010
1011
		foreach ($files as $k => $file)
1012
		{
1013
			$ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
1014
1015
			// This looks odd, but it's an attempt to work around PHP suExec.
1016
			if (!file_exists($file))
1017
			{
1018
				mktree(dirname($file), 0755);
1019
				$package_ftp->create_file($ftp_file);
1020
				$package_ftp->chmod($ftp_file, 0755);
1021
			}
1022
1023
			if (!@is_writable($file))
1024
				$package_ftp->chmod($ftp_file, 0777);
1025
			if (!@is_writable(dirname($file)))
1026
				$package_ftp->chmod(dirname($ftp_file), 0777);
1027
1028
			if (@is_writable($file))
1029
				unset($files[$k]);
1030
		}
1031
1032
		return $files;
1033
	}
1034
1035
	if (isset($_POST['ftp_none']))
1036
	{
1037
		$_SESSION['pack_ftp'] = false;
1038
1039
		$files = packageRequireFTP($destination_url, $files, $return);
1040
		return $files;
1041
	}
1042
	elseif (isset($_POST['ftp_username']))
1043
	{
1044
		require_once($sourcedir . '/Class-Package.php');
1045
		$ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
1046
1047
		if ($ftp->error === false)
0 ignored issues
show
introduced by
The condition $ftp->error === false is always false.
Loading history...
1048
		{
1049
			// Common mistake, so let's try to remedy it...
1050
			if (!$ftp->chdir($_POST['ftp_path']))
1051
			{
1052
				$ftp_error = $ftp->last_message;
1053
				$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
1054
			}
1055
		}
1056
	}
1057
1058
	if (!isset($ftp) || $ftp->error !== false)
1059
	{
1060
		if (!isset($ftp))
1061
		{
1062
			require_once($sourcedir . '/Class-Package.php');
1063
			$ftp = new ftp_connection(null);
1064
		}
1065
		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...
1066
			$ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
1067
1068
		list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
1069
1070
		if ($found_path)
1071
			$_POST['ftp_path'] = $detect_path;
1072
		elseif (!isset($_POST['ftp_path']))
1073
			$_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
1074
1075
		if (!isset($_POST['ftp_username']))
1076
			$_POST['ftp_username'] = $username;
1077
1078
		$context['package_ftp'] = array(
1079
			'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
1080
			'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
1081
			'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
1082
			'path' => $_POST['ftp_path'],
1083
			'error' => empty($ftp_error) ? null : $ftp_error,
1084
			'destination' => $destination_url,
1085
		);
1086
1087
		// If we're returning dump out here.
1088
		if ($return)
1089
			return $files;
1090
1091
		$context['page_title'] = $txt['package_ftp_necessary'];
1092
		$context['sub_template'] = 'ftp_required';
1093
		obExit();
1094
	}
1095
	else
1096
	{
1097
		if (!in_array($_POST['ftp_path'], array('', '/')))
1098
		{
1099
			$ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
1100
			if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || $_POST['ftp_path'][0] == '/'))
1101
				$ftp_root = substr($ftp_root, 0, -1);
1102
		}
1103
		else
1104
			$ftp_root = $boarddir;
1105
1106
		$_SESSION['pack_ftp'] = array(
1107
			'server' => $_POST['ftp_server'],
1108
			'port' => $_POST['ftp_port'],
1109
			'username' => $_POST['ftp_username'],
1110
			'password' => package_crypt($_POST['ftp_password']),
1111
			'path' => $_POST['ftp_path'],
1112
			'root' => $ftp_root,
1113
		);
1114
1115
		if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
1116
			updateSettings(array('package_path' => $_POST['ftp_path']));
1117
1118
		$files = packageRequireFTP($destination_url, $files, $return);
1119
	}
1120
1121
	return $files;
1122
}
1123
1124
/**
1125
 * Parses the actions in package-info.xml file from packages.
1126
 *
1127
 * - package should be an xmlArray with package-info as its base.
1128
 * - testing_only should be true if the package should not actually be applied.
1129
 * - method can be upgrade, install, or uninstall.  Its default is install.
1130
 * - previous_version should be set to the previous installed version of this package, if any.
1131
 * - does not handle failure terribly well; testing first is always better.
1132
 *
1133
 * @param xmlArray &$packageXML The info from the package-info file
1134
 * @param bool $testing_only Whether we're only testing
1135
 * @param string $method The method ('install', 'upgrade', or 'uninstall')
1136
 * @param string $previous_version The previous version of the mod, if method is 'upgrade'
1137
 * @return array An array of those changes made.
1138
 */
1139
function parsePackageInfo(&$packageXML, $testing_only = true, $method = 'install', $previous_version = '')
1140
{
1141
	global $packagesdir, $forum_version, $context, $temp_path, $language, $smcFunc;
1142
1143
	// Mayday!  That action doesn't exist!!
1144
	if (empty($packageXML) || !$packageXML->exists($method))
1145
		return array();
1146
1147
	// We haven't found the package script yet...
1148
	$script = false;
1149
	$the_version = strtr($forum_version, array('SMF ' => ''));
1150
1151
	// Emulation support...
1152
	if (!empty($_SESSION['version_emulate']))
1153
		$the_version = $_SESSION['version_emulate'];
1154
1155
	// Single package emulation
1156
	if (!empty($_REQUEST['ve']) && !empty($_REQUEST['package']))
1157
	{
1158
		$the_version = $_REQUEST['ve'];
1159
		$_SESSION['single_version_emulate'][$_REQUEST['package']] = $the_version;
1160
	}
1161
	if (!empty($_REQUEST['package']) && (!empty($_SESSION['single_version_emulate'][$_REQUEST['package']])))
1162
		$the_version = $_SESSION['single_version_emulate'][$_REQUEST['package']];
1163
1164
	// Get all the versions of this method and find the right one.
1165
	$these_methods = $packageXML->set($method);
1166
	foreach ($these_methods as $this_method)
1167
	{
1168
		// They specified certain versions this part is for.
1169
		if ($this_method->exists('@for'))
1170
		{
1171
			// Don't keep going if this won't work for this version of SMF.
1172
			if (!matchPackageVersion($the_version, $this_method->fetch('@for')))
1173
				continue;
1174
		}
1175
1176
		// Upgrades may go from a certain old version of the mod.
1177
		if ($method == 'upgrade' && $this_method->exists('@from'))
1178
		{
1179
			// Well, this is for the wrong old version...
1180
			if (!matchPackageVersion($previous_version, $this_method->fetch('@from')))
1181
				continue;
1182
		}
1183
1184
		// We've found it!
1185
		$script = $this_method;
1186
		break;
1187
	}
1188
1189
	// Bad news, a matching script wasn't found!
1190
	if (!($script instanceof xmlArray))
1191
		return array();
1192
1193
	// Find all the actions in this method - in theory, these should only be allowed actions. (* means all.)
1194
	$actions = $script->set('*');
1195
	$return = array();
1196
1197
	$temp_auto = 0;
1198
	$temp_path = $packagesdir . '/temp/' . (isset($context['base_path']) ? $context['base_path'] : '');
1199
1200
	$context['readmes'] = array();
1201
	$context['licences'] = array();
1202
1203
	// This is the testing phase... nothing shall be done yet.
1204
	foreach ($actions as $action)
1205
	{
1206
		$actionType = $action->name();
1207
1208
		if (in_array($actionType, array('readme', 'code', 'database', 'modification', 'redirect', 'license')))
1209
		{
1210
			// Allow for translated readme and license files.
1211
			if ($actionType == 'readme' || $actionType == 'license')
1212
			{
1213
				$type = $actionType . 's';
1214
				if ($action->exists('@lang'))
1215
				{
1216
					// Auto-select the language based on either request variable or current language.
1217
					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))
1218
					{
1219
						// In case the user put the blocks in the wrong order.
1220
						if (isset($context[$type]['selected']) && $context[$type]['selected'] == 'default')
1221
							$context[$type][] = 'default';
1222
1223
						$context[$type]['selected'] = $smcFunc['htmlspecialchars']($action->fetch('@lang'));
1224
					}
1225
					else
1226
					{
1227
						// We don't want this now, but we'll allow the user to select to read it.
1228
						$context[$type][] = $smcFunc['htmlspecialchars']($action->fetch('@lang'));
1229
						continue;
1230
					}
1231
				}
1232
				// Fallback when we have no lang parameter.
1233
				else
1234
				{
1235
					// Already selected one for use?
1236
					if (isset($context[$type]['selected']))
1237
					{
1238
						$context[$type][] = 'default';
1239
						continue;
1240
					}
1241
					else
1242
						$context[$type]['selected'] = 'default';
1243
				}
1244
			}
1245
1246
			// @todo Make sure the file actually exists?  Might not work when testing?
1247
			if ($action->exists('@type') && $action->fetch('@type') == 'inline')
1248
			{
1249
				$filename = $temp_path . '$auto_' . $temp_auto++ . (in_array($actionType, array('readme', 'redirect', 'license')) ? '.txt' : ($actionType == 'code' || $actionType == 'database' ? '.php' : '.mod'));
1250
				package_put_contents($filename, $action->fetch('.'));
1251
				$filename = strtr($filename, array($temp_path => ''));
1252
			}
1253
			else
1254
				$filename = $action->fetch('.');
1255
1256
			$return[] = array(
1257
				'type' => $actionType,
1258
				'filename' => $filename,
1259
				'description' => '',
1260
				'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true',
1261
				'boardmod' => $action->exists('@format') && $action->fetch('@format') == 'boardmod',
1262
				'redirect_url' => $action->exists('@url') ? $action->fetch('@url') : '',
1263
				'redirect_timeout' => $action->exists('@timeout') ? (int) $action->fetch('@timeout') : '',
1264
				'parse_bbc' => $action->exists('@parsebbc') && $action->fetch('@parsebbc') == 'true',
1265
				'language' => (($actionType == 'readme' || $actionType == 'license') && $action->exists('@lang') && $action->fetch('@lang') == $language) ? $language : '',
1266
			);
1267
1268
			continue;
1269
		}
1270
		elseif ($actionType == 'hook')
1271
		{
1272
			$return[] = array(
1273
				'type' => $actionType,
1274
				'function' => $action->exists('@function') ? $action->fetch('@function') : '',
1275
				'hook' => $action->exists('@hook') ? $action->fetch('@hook') : $action->fetch('.'),
1276
				'include_file' => $action->exists('@file') ? $action->fetch('@file') : '',
1277
				'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true' ? true : false,
1278
				'object' => $action->exists('@object') && $action->fetch('@object') == 'true' ? true : false,
1279
				'description' => '',
1280
			);
1281
			continue;
1282
		}
1283
		elseif ($actionType == 'credits')
1284
		{
1285
			// quick check of any supplied url
1286
			$url = $action->exists('@url') ? $action->fetch('@url') : '';
1287
			if (strlen(trim($url)) > 0 && substr($url, 0, 7) !== 'http://' && substr($url, 0, 8) !== 'https://')
1288
			{
1289
				$url = 'http://' . $url;
1290
				if (strlen($url) < 8 || (substr($url, 0, 7) !== 'http://' && substr($url, 0, 8) !== 'https://'))
1291
					$url = '';
1292
			}
1293
1294
			$return[] = array(
1295
				'type' => $actionType,
1296
				'url' => $url,
1297
				'license' => $action->exists('@license') ? $action->fetch('@license') : '',
1298
				'licenseurl' => $action->exists('@licenseurl') ? $action->fetch('@licenseurl') : '',
1299
				'copyright' => $action->exists('@copyright') ? $action->fetch('@copyright') : '',
1300
				'title' => $action->fetch('.'),
1301
			);
1302
			continue;
1303
		}
1304
		elseif ($actionType == 'requires')
1305
		{
1306
			$return[] = array(
1307
				'type' => $actionType,
1308
				'id' => $action->exists('@id') ? $action->fetch('@id') : '',
1309
				'version' => $action->exists('@version') ? $action->fetch('@version') : $action->fetch('.'),
1310
				'description' => '',
1311
			);
1312
			continue;
1313
		}
1314
		elseif ($actionType == 'error')
1315
		{
1316
			$return[] = array(
1317
				'type' => 'error',
1318
			);
1319
		}
1320
		elseif (in_array($actionType, array('require-file', 'remove-file', 'require-dir', 'remove-dir', 'move-file', 'move-dir', 'create-file', 'create-dir')))
1321
		{
1322
			$this_action = &$return[];
1323
			$this_action = array(
1324
				'type' => $actionType,
1325
				'filename' => $action->fetch('@name'),
1326
				'description' => $action->fetch('.')
1327
			);
1328
1329
			// If there is a destination, make sure it makes sense.
1330
			if (substr($actionType, 0, 6) != 'remove')
1331
			{
1332
				$this_action['unparsed_destination'] = $action->fetch('@destination');
1333
				$this_action['destination'] = parse_path($action->fetch('@destination')) . '/' . basename($this_action['filename']);
1334
			}
1335
			else
1336
			{
1337
				$this_action['unparsed_filename'] = $this_action['filename'];
1338
				$this_action['filename'] = parse_path($this_action['filename']);
1339
			}
1340
1341
			// If we're moving or requiring (copying) a file.
1342
			if (substr($actionType, 0, 4) == 'move' || substr($actionType, 0, 7) == 'require')
1343
			{
1344
				if ($action->exists('@from'))
1345
					$this_action['source'] = parse_path($action->fetch('@from'));
1346
				else
1347
					$this_action['source'] = $temp_path . $this_action['filename'];
1348
			}
1349
1350
			// Check if these things can be done. (chmod's etc.)
1351
			if ($actionType == 'create-dir')
1352
			{
1353
				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

1353
				if (!mktree($this_action['destination'], /** @scrutinizer ignore-type */ false))
Loading history...
1354
				{
1355
					$temp = $this_action['destination'];
1356
					while (!file_exists($temp) && strlen($temp) > 1)
1357
						$temp = dirname($temp);
1358
1359
					$return[] = array(
1360
						'type' => 'chmod',
1361
						'filename' => $temp
1362
					);
1363
				}
1364
			}
1365
			elseif ($actionType == 'create-file')
1366
			{
1367
				if (!mktree(dirname($this_action['destination']), false))
1368
				{
1369
					$temp = dirname($this_action['destination']);
1370
					while (!file_exists($temp) && strlen($temp) > 1)
1371
						$temp = dirname($temp);
1372
1373
					$return[] = array(
1374
						'type' => 'chmod',
1375
						'filename' => $temp
1376
					);
1377
				}
1378
1379
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1380
					$return[] = array(
1381
						'type' => 'chmod',
1382
						'filename' => $this_action['destination']
1383
					);
1384
			}
1385
			elseif ($actionType == 'require-dir')
1386
			{
1387
				if (!mktree($this_action['destination'], false))
1388
				{
1389
					$temp = $this_action['destination'];
1390
					while (!file_exists($temp) && strlen($temp) > 1)
1391
						$temp = dirname($temp);
1392
1393
					$return[] = array(
1394
						'type' => 'chmod',
1395
						'filename' => $temp
1396
					);
1397
				}
1398
			}
1399
			elseif ($actionType == 'require-file')
1400
			{
1401
				if ($action->exists('@theme'))
1402
					$this_action['theme_action'] = $action->fetch('@theme');
1403
1404
				if (!mktree(dirname($this_action['destination']), false))
1405
				{
1406
					$temp = dirname($this_action['destination']);
1407
					while (!file_exists($temp) && strlen($temp) > 1)
1408
						$temp = dirname($temp);
1409
1410
					$return[] = array(
1411
						'type' => 'chmod',
1412
						'filename' => $temp
1413
					);
1414
				}
1415
1416
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1417
					$return[] = array(
1418
						'type' => 'chmod',
1419
						'filename' => $this_action['destination']
1420
					);
1421
			}
1422
			elseif ($actionType == 'move-dir' || $actionType == 'move-file')
1423
			{
1424
				if (!mktree(dirname($this_action['destination']), false))
1425
				{
1426
					$temp = dirname($this_action['destination']);
1427
					while (!file_exists($temp) && strlen($temp) > 1)
1428
						$temp = dirname($temp);
1429
1430
					$return[] = array(
1431
						'type' => 'chmod',
1432
						'filename' => $temp
1433
					);
1434
				}
1435
1436
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1437
					$return[] = array(
1438
						'type' => 'chmod',
1439
						'filename' => $this_action['destination']
1440
					);
1441
			}
1442
			elseif ($actionType == 'remove-dir')
1443
			{
1444
				if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
1445
					$return[] = array(
1446
						'type' => 'chmod',
1447
						'filename' => $this_action['filename']
1448
					);
1449
			}
1450
			elseif ($actionType == 'remove-file')
1451
			{
1452
				if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
1453
					$return[] = array(
1454
						'type' => 'chmod',
1455
						'filename' => $this_action['filename']
1456
					);
1457
			}
1458
		}
1459
		else
1460
		{
1461
			$return[] = array(
1462
				'type' => 'error',
1463
				'error_msg' => 'unknown_action',
1464
				'error_var' => $actionType
1465
			);
1466
		}
1467
	}
1468
1469
	// Only testing - just return a list of things to be done.
1470
	if ($testing_only)
1471
		return $return;
1472
1473
	umask(0);
1474
1475
	$failure = false;
1476
	$not_done = array(array('type' => '!'));
1477
	foreach ($return as $action)
1478
	{
1479
		if (in_array($action['type'], array('modification', 'code', 'database', 'redirect', 'hook', 'credits')))
1480
			$not_done[] = $action;
1481
1482
		if ($action['type'] == 'create-dir')
1483
		{
1484
			if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1485
				$failure |= !mktree($action['destination'], 0777);
1486
		}
1487
		elseif ($action['type'] == 'create-file')
1488
		{
1489
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1490
				$failure |= !mktree(dirname($action['destination']), 0777);
1491
1492
			// Create an empty file.
1493
			package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1494
1495
			if (!file_exists($action['destination']))
1496
				$failure = true;
1497
		}
1498
		elseif ($action['type'] == 'require-dir')
1499
		{
1500
			copytree($action['source'], $action['destination']);
1501
			// Any other theme folders?
1502
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1503
				foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1504
					copytree($action['source'], $theme_destination);
1505
		}
1506
		elseif ($action['type'] == 'require-file')
1507
		{
1508
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1509
				$failure |= !mktree(dirname($action['destination']), 0777);
1510
1511
			package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1512
1513
			$failure |= !copy($action['source'], $action['destination']);
1514
1515
			// Any other theme files?
1516
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1517
				foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1518
				{
1519
					if (!mktree(dirname($theme_destination), 0755) || !is_writable(dirname($theme_destination)))
1520
						$failure |= !mktree(dirname($theme_destination), 0777);
1521
1522
					package_put_contents($theme_destination, package_get_contents($action['source']), $testing_only);
1523
1524
					$failure |= !copy($action['source'], $theme_destination);
1525
				}
1526
		}
1527
		elseif ($action['type'] == 'move-file')
1528
		{
1529
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1530
				$failure |= !mktree(dirname($action['destination']), 0777);
1531
1532
			$failure |= !rename($action['source'], $action['destination']);
1533
		}
1534
		elseif ($action['type'] == 'move-dir')
1535
		{
1536
			if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1537
				$failure |= !mktree($action['destination'], 0777);
1538
1539
			$failure |= !rename($action['source'], $action['destination']);
1540
		}
1541
		elseif ($action['type'] == 'remove-dir')
1542
		{
1543
			deltree($action['filename']);
1544
1545
			// Any other theme folders?
1546
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1547
				foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1548
					deltree($theme_destination);
1549
		}
1550
		elseif ($action['type'] == 'remove-file')
1551
		{
1552
			// Make sure the file exists before deleting it.
1553
			if (file_exists($action['filename']))
1554
			{
1555
				package_chmod($action['filename']);
1556
				$failure |= !unlink($action['filename']);
1557
			}
1558
			// The file that was supposed to be deleted couldn't be found.
1559
			else
1560
				$failure = true;
1561
1562
			// Any other theme folders?
1563
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1564
				foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1565
					if (file_exists($theme_destination))
1566
						$failure |= !unlink($theme_destination);
1567
					else
1568
						$failure = true;
1569
		}
1570
	}
1571
1572
	return $not_done;
1573
}
1574
1575
/**
1576
 * Checks if version matches any of the versions in versions.
1577
 * - supports comma separated version numbers, with or without whitespace.
1578
 * - supports lower and upper bounds. (1.0-1.2)
1579
 * - returns true if the version matched.
1580
 *
1581
 * @param string $versions The SMF versions
1582
 * @param boolean $reset Whether to reset $near_version
1583
 * @param string $the_version
1584
 * @return string|bool Highest install value string or false
1585
 */
1586
function matchHighestPackageVersion($versions, $reset = false, $the_version)
1587
{
1588
	static $near_version = 0;
1589
1590
	if ($reset)
1591
		$near_version = 0;
1592
1593
	// Normalize the $versions while we remove our previous Doh!
1594
	$versions = explode(',', str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($versions)));
1595
1596
	// Loop through each version, save the highest we can find
1597
	foreach ($versions as $for)
1598
	{
1599
		// Adjust for those wild cards
1600
		if (strpos($for, '*') !== false)
1601
			$for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
1602
1603
		// 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
1604
		if (strpos($for, '-') !== false)
1605
			list ($for, $higher) = explode('-', $for);
1606
1607
		// Do the compare, if the for is greater, than what we have but not greater than what we are running .....
1608
		if (compareVersions($near_version, $for) === -1 && compareVersions($for, $the_version) !== 1)
1609
			$near_version = $for;
1610
	}
1611
1612
	return !empty($near_version) ? $near_version : false;
1613
}
1614
1615
/**
1616
 * Checks if the forum version matches any of the available versions from the package install xml.
1617
 * - supports comma separated version numbers, with or without whitespace.
1618
 * - supports lower and upper bounds. (1.0-1.2)
1619
 * - returns true if the version matched.
1620
 *
1621
 * @param string $version The forum version
1622
 * @param string $versions The versions that this package will install on
1623
 * @return bool Whether the version matched
1624
 */
1625
function matchPackageVersion($version, $versions)
1626
{
1627
	// Make sure everything is lowercase and clean of spaces and unpleasant history.
1628
	$version = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
1629
	$versions = explode(',', str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($versions)));
1630
1631
	// Perhaps we do accept anything?
1632
	if (in_array('all', $versions))
1633
		return true;
1634
1635
	// Loop through each version.
1636
	foreach ($versions as $for)
1637
	{
1638
		// Wild card spotted?
1639
		if (strpos($for, '*') !== false)
1640
			$for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
1641
1642
		// Do we have a range?
1643
		if (strpos($for, '-') !== false)
1644
		{
1645
			list ($lower, $upper) = explode('-', $for);
1646
1647
			// Compare the version against lower and upper bounds.
1648
			if (compareVersions($version, $lower) > -1 && compareVersions($version, $upper) < 1)
1649
				return true;
1650
		}
1651
		// Otherwise check if they are equal...
1652
		elseif (compareVersions($version, $for) === 0)
1653
			return true;
1654
	}
1655
1656
	return false;
1657
}
1658
1659
/**
1660
 * Compares two versions and determines if one is newer, older or the same, returns
1661
 * - (-1) if version1 is lower than version2
1662
 * - (0) if version1 is equal to version2
1663
 * - (1) if version1 is higher than version2
1664
 *
1665
 * @param string $version1 The first version
1666
 * @param string $version2 The second version
1667
 * @return int -1 if version2 is greater than version1, 0 if they're equal, 1 if version1 is greater than version2
1668
 */
1669
function compareVersions($version1, $version2)
1670
{
1671
	static $categories;
1672
1673
	$versions = array();
1674
	foreach (array(1 => $version1, $version2) as $id => $version)
1675
	{
1676
		// Clean the version and extract the version parts.
1677
		$clean = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
1678
		preg_match('~(\d+)(?:\.(\d+|))?(?:\.)?(\d+|)(?:(alpha|beta|rc)(\d+|)(?:\.)?(\d+|))?(?:(dev))?(\d+|)~', $clean, $parts);
1679
1680
		// Build an array of parts.
1681
		$versions[$id] = array(
1682
			'major' => !empty($parts[1]) ? (int) $parts[1] : 0,
1683
			'minor' => !empty($parts[2]) ? (int) $parts[2] : 0,
1684
			'patch' => !empty($parts[3]) ? (int) $parts[3] : 0,
1685
			'type' => empty($parts[4]) ? 'stable' : $parts[4],
1686
			'type_major' => !empty($parts[5]) ? (int) $parts[5] : 0,
1687
			'type_minor' => !empty($parts[6]) ? (int) $parts[6] : 0,
1688
			'dev' => !empty($parts[7]),
1689
		);
1690
	}
1691
1692
	// Are they the same, perhaps?
1693
	if ($versions[1] === $versions[2])
1694
		return 0;
1695
1696
	// Get version numbering categories...
1697
	if (!isset($categories))
1698
		$categories = array_keys($versions[1]);
1699
1700
	// Loop through each category.
1701
	foreach ($categories as $category)
1702
	{
1703
		// Is there something for us to calculate?
1704
		if ($versions[1][$category] !== $versions[2][$category])
1705
		{
1706
			// Dev builds are a problematic exception.
1707
			// (stable) dev < (stable) but (unstable) dev = (unstable)
1708
			if ($category == 'type')
1709
				return $versions[1][$category] > $versions[2][$category] ? ($versions[1]['dev'] ? -1 : 1) : ($versions[2]['dev'] ? 1 : -1);
1710
			elseif ($category == 'dev')
1711
				return $versions[1]['dev'] ? ($versions[2]['type'] == 'stable' ? -1 : 0) : ($versions[1]['type'] == 'stable' ? 1 : 0);
1712
			// Otherwise a simple comparison.
1713
			else
1714
				return $versions[1][$category] > $versions[2][$category] ? 1 : -1;
1715
		}
1716
	}
1717
1718
	// They are the same!
1719
	return 0;
1720
}
1721
1722
/**
1723
 * Parses special identifiers out of the specified path.
1724
 *
1725
 * @param string $path The path
1726
 * @return string The parsed path
1727
 */
1728
function parse_path($path)
1729
{
1730
	global $modSettings, $boarddir, $sourcedir, $settings, $temp_path;
1731
1732
	$dirs = array(
1733
		'\\' => '/',
1734
		'$boarddir' => $boarddir,
1735
		'$sourcedir' => $sourcedir,
1736
		'$avatardir' => $modSettings['avatar_directory'],
1737
		'$avatars_dir' => $modSettings['avatar_directory'],
1738
		'$themedir' => $settings['default_theme_dir'],
1739
		'$imagesdir' => $settings['default_theme_dir'] . '/' . basename($settings['default_images_url']),
1740
		'$themes_dir' => $boarddir . '/Themes',
1741
		'$languagedir' => $settings['default_theme_dir'] . '/languages',
1742
		'$languages_dir' => $settings['default_theme_dir'] . '/languages',
1743
		'$smileysdir' => $modSettings['smileys_dir'],
1744
		'$smileys_dir' => $modSettings['smileys_dir'],
1745
	);
1746
1747
	// do we parse in a package directory?
1748
	if (!empty($temp_path))
1749
		$dirs['$package'] = $temp_path;
1750
1751
	if (strlen($path) == 0)
1752
		trigger_error('parse_path(): There should never be an empty filename', E_USER_ERROR);
1753
1754
	return strtr($path, $dirs);
1755
}
1756
1757
/**
1758
 * Deletes a directory, and all the files and direcories inside it.
1759
 * requires access to delete these files.
1760
 *
1761
 * @param string $dir A directory
1762
 * @param bool $delete_dir If false, only deletes everything inside the directory but not the directory itself
1763
 */
1764
function deltree($dir, $delete_dir = true)
1765
{
1766
	/** @var ftp_connection $package_ftp */
1767
	global $package_ftp;
1768
1769
	if (!file_exists($dir))
1770
		return;
1771
1772
	$current_dir = @opendir($dir);
1773
	if ($current_dir == false)
1774
	{
1775
		if ($delete_dir && isset($package_ftp))
1776
		{
1777
			$ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1778
			if (!is_dir($dir))
1779
				$package_ftp->chmod($ftp_file, 0777);
1780
			$package_ftp->unlink($ftp_file);
1781
		}
1782
1783
		return;
1784
	}
1785
1786
	while ($entryname = readdir($current_dir))
1787
	{
1788
		if (in_array($entryname, array('.', '..')))
1789
			continue;
1790
1791
		if (is_dir($dir . '/' . $entryname))
1792
			deltree($dir . '/' . $entryname);
1793
		else
1794
		{
1795
			// Here, 755 doesn't really matter since we're deleting it anyway.
1796
			if (isset($package_ftp))
1797
			{
1798
				$ftp_file = strtr($dir . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1799
1800
				if (!is_writable($dir . '/' . $entryname))
1801
					$package_ftp->chmod($ftp_file, 0777);
1802
				$package_ftp->unlink($ftp_file);
1803
			}
1804
			else
1805
			{
1806
				if (!is_writable($dir . '/' . $entryname))
1807
					smf_chmod($dir . '/' . $entryname, 0777);
1808
				unlink($dir . '/' . $entryname);
1809
			}
1810
		}
1811
	}
1812
1813
	closedir($current_dir);
1814
1815
	if ($delete_dir)
1816
	{
1817
		if (isset($package_ftp))
1818
		{
1819
			$ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1820
			if (!is_writable($dir . '/' . $entryname))
1821
				$package_ftp->chmod($ftp_file, 0777);
1822
			$package_ftp->unlink($ftp_file);
1823
		}
1824
		else
1825
		{
1826
			if (!is_writable($dir))
1827
				smf_chmod($dir, 0777);
1828
			@rmdir($dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rmdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1829
		}
1830
	}
1831
}
1832
1833
/**
1834
 * Creates the specified tree structure with the mode specified.
1835
 * creates every directory in path until it finds one that already exists.
1836
 *
1837
 * @param string $strPath The path
1838
 * @param int $mode The permission mode for CHMOD (0666, etc.)
1839
 * @return bool True if successful, false otherwise
1840
 */
1841
function mktree($strPath, $mode)
1842
{
1843
	/** @var ftp_connection $package_ftp */
1844
	global $package_ftp;
1845
1846
	if (is_dir($strPath))
1847
	{
1848
		if (!is_writable($strPath) && $mode !== false)
1849
		{
1850
			if (isset($package_ftp))
1851
				$package_ftp->chmod(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')), $mode);
1852
			else
1853
				smf_chmod($strPath, $mode);
1854
		}
1855
1856
		$test = @opendir($strPath);
1857
		if ($test)
0 ignored issues
show
introduced by
$test is of type false|resource, thus it always evaluated to false.
Loading history...
1858
		{
1859
			closedir($test);
1860
			return is_writable($strPath);
1861
		}
1862
		else
1863
			return false;
1864
	}
1865
	// Is this an invalid path and/or we can't make the directory?
1866
	if ($strPath == dirname($strPath) || !mktree(dirname($strPath), $mode))
1867
		return false;
1868
1869
	if (!is_writable(dirname($strPath)) && $mode !== false)
1870
	{
1871
		if (isset($package_ftp))
1872
			$package_ftp->chmod(dirname(strtr($strPath, array($_SESSION['pack_ftp']['root'] => ''))), $mode);
1873
		else
1874
			smf_chmod(dirname($strPath), $mode);
1875
	}
1876
1877
	if ($mode !== false && isset($package_ftp))
1878
		return $package_ftp->create_dir(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')));
1879
	elseif ($mode === false)
0 ignored issues
show
introduced by
The condition $mode === false is always false.
Loading history...
1880
	{
1881
		$test = @opendir(dirname($strPath));
1882
		if ($test)
1883
		{
1884
			closedir($test);
1885
			return true;
1886
		}
1887
		else
1888
			return false;
1889
	}
1890
	else
1891
	{
1892
		@mkdir($strPath, $mode);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1893
		$test = @opendir($strPath);
1894
		if ($test)
0 ignored issues
show
introduced by
$test is of type false|resource, thus it always evaluated to false.
Loading history...
1895
		{
1896
			closedir($test);
1897
			return true;
1898
		}
1899
		else
1900
			return false;
1901
	}
1902
}
1903
1904
/**
1905
 * Copies one directory structure over to another.
1906
 * requires the destination to be writable.
1907
 *
1908
 * @param string $source The directory to copy
1909
 * @param string $destination The directory to copy $source to
1910
 */
1911
function copytree($source, $destination)
1912
{
1913
	/** @var ftp_connection $package_ftp */
1914
	global $package_ftp;
1915
1916
	if (!file_exists($destination) || !is_writable($destination))
1917
		mktree($destination, 0755);
1918
	if (!is_writable($destination))
1919
		mktree($destination, 0777);
1920
1921
	$current_dir = opendir($source);
1922
	if ($current_dir == false)
1923
		return;
1924
1925
	while ($entryname = readdir($current_dir))
1926
	{
1927
		if (in_array($entryname, array('.', '..')))
1928
			continue;
1929
1930
		if (isset($package_ftp))
1931
			$ftp_file = strtr($destination . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1932
1933
		if (is_file($source . '/' . $entryname))
1934
		{
1935
			if (isset($package_ftp) && !file_exists($destination . '/' . $entryname))
1936
				$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...
1937
			elseif (!file_exists($destination . '/' . $entryname))
1938
				@touch($destination . '/' . $entryname);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1939
		}
1940
1941
		package_chmod($destination . '/' . $entryname);
1942
1943
		if (is_dir($source . '/' . $entryname))
1944
			copytree($source . '/' . $entryname, $destination . '/' . $entryname);
1945
		elseif (file_exists($destination . '/' . $entryname))
1946
			package_put_contents($destination . '/' . $entryname, package_get_contents($source . '/' . $entryname));
1947
		else
1948
			copy($source . '/' . $entryname, $destination . '/' . $entryname);
1949
	}
1950
1951
	closedir($current_dir);
1952
}
1953
1954
/**
1955
 * Create a tree listing for a given directory path
1956
 *
1957
 * @param string $path The path
1958
 * @param string $sub_path The sub-path
1959
 * @return array An array of information about the files at the specified path/subpath
1960
 */
1961
function listtree($path, $sub_path = '')
1962
{
1963
	$data = array();
1964
1965
	$dir = @dir($path . $sub_path);
1966
	if (!$dir)
0 ignored issues
show
introduced by
$dir is of type Directory, thus it always evaluated to true.
Loading history...
1967
		return array();
1968
	while ($entry = $dir->read())
1969
	{
1970
		if ($entry == '.' || $entry == '..')
1971
			continue;
1972
1973
		if (is_dir($path . $sub_path . '/' . $entry))
1974
			$data = array_merge($data, listtree($path, $sub_path . '/' . $entry));
1975
		else
1976
			$data[] = array(
1977
				'filename' => $sub_path == '' ? $entry : $sub_path . '/' . $entry,
1978
				'size' => filesize($path . $sub_path . '/' . $entry),
1979
				'skipped' => false,
1980
			);
1981
	}
1982
	$dir->close();
1983
1984
	return $data;
1985
}
1986
1987
/**
1988
 * Parses a xml-style modification file (file).
1989
 *
1990
 * @param string $file The modification file to parse
1991
 * @param bool $testing Whether we're just doing a test
1992
 * @param bool $undo If true, specifies that the modifications should be undone. Used when uninstalling. Doesn't work with regex.
1993
 * @param array $theme_paths An array of information about custom themes to apply the changes to
1994
 * @return array An array of those changes made.
1995
 */
1996
function parseModification($file, $testing = true, $undo = false, $theme_paths = array())
1997
{
1998
	global $boarddir, $sourcedir, $txt, $modSettings;
1999
2000
	@set_time_limit(600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

2000
	/** @scrutinizer ignore-unhandled */ @set_time_limit(600);

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2001
	require_once($sourcedir . '/Class-Package.php');
2002
	$xml = new xmlArray(strtr($file, array("\r" => '')));
2003
	$actions = array();
2004
	$everything_found = true;
2005
2006
	if (!$xml->exists('modification') || !$xml->exists('modification/file'))
2007
	{
2008
		$actions[] = array(
2009
			'type' => 'error',
2010
			'filename' => '-',
2011
			'debug' => $txt['package_modification_malformed']
2012
		);
2013
		return $actions;
2014
	}
2015
2016
	// Get the XML data.
2017
	$files = $xml->set('modification/file');
2018
2019
	// Use this for holding all the template changes in this mod.
2020
	$template_changes = array();
2021
	// This is needed to hold the long paths, as they can vary...
2022
	$long_changes = array();
2023
2024
	// First, we need to build the list of all the files likely to get changed.
2025
	foreach ($files as $file)
0 ignored issues
show
introduced by
$file is overwriting one of the parameters of this function.
Loading history...
2026
	{
2027
		// What is the filename we're currently on?
2028
		$filename = parse_path(trim($file->fetch('@name')));
2029
2030
		// Now, we need to work out whether this is even a template file...
2031
		foreach ($theme_paths as $id => $theme)
2032
		{
2033
			// If this filename is relative, if so take a guess at what it should be.
2034
			$real_filename = $filename;
2035
			if (strpos($filename, 'Themes') === 0)
2036
				$real_filename = $boarddir . '/' . $filename;
2037
2038
			if (strpos($real_filename, $theme['theme_dir']) === 0)
2039
			{
2040
				$template_changes[$id][] = substr($real_filename, strlen($theme['theme_dir']) + 1);
2041
				$long_changes[$id][] = $filename;
2042
			}
2043
		}
2044
	}
2045
2046
	// Custom themes to add.
2047
	$custom_themes_add = array();
2048
2049
	// If we have some template changes, we need to build a master link of what new ones are required for the custom themes.
2050
	if (!empty($template_changes[1]))
2051
	{
2052
		foreach ($theme_paths as $id => $theme)
2053
		{
2054
			// Default is getting done anyway, so no need for involvement here.
2055
			if ($id == 1)
2056
				continue;
2057
2058
			// For every template, do we want it? Yea, no, maybe?
2059
			foreach ($template_changes[1] as $index => $template_file)
2060
			{
2061
				// What, it exists and we haven't already got it?! Lordy, get it in!
2062
				if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id]) || !in_array($template_file, $template_changes[$id])))
2063
				{
2064
					// Now let's add it to the "todo" list.
2065
					$custom_themes_add[$long_changes[1][$index]][$id] = $theme['theme_dir'] . '/' . $template_file;
2066
				}
2067
			}
2068
		}
2069
	}
2070
2071
	foreach ($files as $file)
0 ignored issues
show
introduced by
$file is overwriting one of the parameters of this function.
Loading history...
2072
	{
2073
		// This is the actual file referred to in the XML document...
2074
		$files_to_change = array(
2075
			1 => parse_path(trim($file->fetch('@name'))),
2076
		);
2077
2078
		// Sometimes though, we have some additional files for other themes, if we have add them to the mix.
2079
		if (isset($custom_themes_add[$files_to_change[1]]))
2080
			$files_to_change += $custom_themes_add[$files_to_change[1]];
2081
2082
		// Now, loop through all the files we're changing, and, well, change them ;)
2083
		foreach ($files_to_change as $theme => $working_file)
2084
		{
2085
			if ($working_file[0] != '/' && $working_file[1] != ':')
2086
			{
2087
				trigger_error('parseModification(): The filename \'' . $working_file . '\' is not a full path!', E_USER_WARNING);
2088
2089
				$working_file = $boarddir . '/' . $working_file;
2090
			}
2091
2092
			// Doesn't exist - give an error or what?
2093
			if (!file_exists($working_file) && (!$file->exists('@error') || !in_array(trim($file->fetch('@error')), array('ignore', 'skip'))))
2094
			{
2095
				$actions[] = array(
2096
					'type' => 'missing',
2097
					'filename' => $working_file,
2098
					'debug' => $txt['package_modification_missing']
2099
				);
2100
2101
				$everything_found = false;
2102
				continue;
2103
			}
2104
			// Skip the file if it doesn't exist.
2105
			elseif (!file_exists($working_file) && $file->exists('@error') && trim($file->fetch('@error')) == 'skip')
2106
			{
2107
				$actions[] = array(
2108
					'type' => 'skipping',
2109
					'filename' => $working_file,
2110
				);
2111
				continue;
2112
			}
2113
			// Okay, we're creating this file then...?
2114
			elseif (!file_exists($working_file))
2115
				$working_data = '';
2116
			// Phew, it exists!  Load 'er up!
2117
			else
2118
				$working_data = str_replace("\r", '', package_get_contents($working_file));
2119
2120
			$actions[] = array(
2121
				'type' => 'opened',
2122
				'filename' => $working_file
2123
			);
2124
2125
			$operations = $file->exists('operation') ? $file->set('operation') : array();
2126
			foreach ($operations as $operation)
2127
			{
2128
				// Convert operation to an array.
2129
				$actual_operation = array(
2130
					'searches' => array(),
2131
					'error' => $operation->exists('@error') && in_array(trim($operation->fetch('@error')), array('ignore', 'fatal', 'required')) ? trim($operation->fetch('@error')) : 'fatal',
2132
				);
2133
2134
				// The 'add' parameter is used for all searches in this operation.
2135
				$add = $operation->exists('add') ? $operation->fetch('add') : '';
2136
2137
				// Grab all search items of this operation (in most cases just 1).
2138
				$searches = $operation->set('search');
2139
				foreach ($searches as $i => $search)
2140
					$actual_operation['searches'][] = array(
2141
						'position' => $search->exists('@position') && in_array(trim($search->fetch('@position')), array('before', 'after', 'replace', 'end')) ? trim($search->fetch('@position')) : 'replace',
2142
						'is_reg_exp' => $search->exists('@regexp') && trim($search->fetch('@regexp')) === 'true',
2143
						'loose_whitespace' => $search->exists('@whitespace') && trim($search->fetch('@whitespace')) === 'loose',
2144
						'search' => $search->fetch('.'),
2145
						'add' => $add,
2146
						'preg_search' => '',
2147
						'preg_replace' => '',
2148
					);
2149
2150
				// At least one search should be defined.
2151
				if (empty($actual_operation['searches']))
2152
				{
2153
					$actions[] = array(
2154
						'type' => 'failure',
2155
						'filename' => $working_file,
2156
						'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...
2157
						'is_custom' => $theme > 1 ? $theme : 0,
2158
					);
2159
2160
					// Skip to the next operation.
2161
					continue;
2162
				}
2163
2164
				// Reverse the operations in case of undoing stuff.
2165
				if ($undo)
2166
				{
2167
					foreach ($actual_operation['searches'] as $i => $search)
2168
					{
2169
						// Reverse modification of regular expressions are not allowed.
2170
						if ($search['is_reg_exp'])
2171
						{
2172
							if ($actual_operation['error'] === 'fatal')
2173
								$actions[] = array(
2174
									'type' => 'failure',
2175
									'filename' => $working_file,
2176
									'search' => $search['search'],
2177
									'is_custom' => $theme > 1 ? $theme : 0,
2178
								);
2179
2180
							// Continue to the next operation.
2181
							continue 2;
2182
						}
2183
2184
						// The replacement is now the search subject...
2185
						if ($search['position'] === 'replace' || $search['position'] === 'end')
2186
							$actual_operation['searches'][$i]['search'] = $search['add'];
2187
						else
2188
						{
2189
							// Reversing a before/after modification becomes a replacement.
2190
							$actual_operation['searches'][$i]['position'] = 'replace';
2191
2192
							if ($search['position'] === 'before')
2193
								$actual_operation['searches'][$i]['search'] .= $search['add'];
2194
							elseif ($search['position'] === 'after')
2195
								$actual_operation['searches'][$i]['search'] = $search['add'] . $search['search'];
2196
						}
2197
2198
						// ...and the search subject is now the replacement.
2199
						$actual_operation['searches'][$i]['add'] = $search['search'];
2200
					}
2201
				}
2202
2203
				// Sort the search list so the replaces come before the add before/after's.
2204
				if (count($actual_operation['searches']) !== 1)
2205
				{
2206
					$replacements = array();
2207
2208
					foreach ($actual_operation['searches'] as $i => $search)
2209
					{
2210
						if ($search['position'] === 'replace')
2211
						{
2212
							$replacements[] = $search;
2213
							unset($actual_operation['searches'][$i]);
2214
						}
2215
					}
2216
					$actual_operation['searches'] = array_merge($replacements, $actual_operation['searches']);
2217
				}
2218
2219
				// Create regular expression replacements from each search.
2220
				foreach ($actual_operation['searches'] as $i => $search)
2221
				{
2222
					// Not much needed if the search subject is already a regexp.
2223
					if ($search['is_reg_exp'])
2224
						$actual_operation['searches'][$i]['preg_search'] = $search['search'];
2225
					else
2226
					{
2227
						// Make the search subject fit into a regular expression.
2228
						$actual_operation['searches'][$i]['preg_search'] = preg_quote($search['search'], '~');
2229
2230
						// Using 'loose', a random amount of tabs and spaces may be used.
2231
						if ($search['loose_whitespace'])
2232
							$actual_operation['searches'][$i]['preg_search'] = preg_replace('~[ \t]+~', '[ \t]+', $actual_operation['searches'][$i]['preg_search']);
2233
					}
2234
2235
					// Shuzzup.  This is done so we can safely use a regular expression. ($0 is bad!!)
2236
					$actual_operation['searches'][$i]['preg_replace'] = strtr($search['add'], array('$' => '[$PACK' . 'AGE1$]', '\\' => '[$PACK' . 'AGE2$]'));
2237
2238
					// Before, so the replacement comes after the search subject :P
2239
					if ($search['position'] === 'before')
2240
					{
2241
						$actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
2242
						$actual_operation['searches'][$i]['preg_replace'] = '$1' . $actual_operation['searches'][$i]['preg_replace'];
2243
					}
2244
2245
					// After, after what?
2246
					elseif ($search['position'] === 'after')
2247
					{
2248
						$actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
2249
						$actual_operation['searches'][$i]['preg_replace'] .= '$1';
2250
					}
2251
2252
					// Position the replacement at the end of the file (or just before the closing PHP tags).
2253
					elseif ($search['position'] === 'end')
2254
					{
2255
						if ($undo)
2256
						{
2257
							$actual_operation['searches'][$i]['preg_replace'] = '';
2258
						}
2259
						else
2260
						{
2261
							$actual_operation['searches'][$i]['preg_search'] = '(\\n\\?\\>)?$';
2262
							$actual_operation['searches'][$i]['preg_replace'] .= '$1';
2263
						}
2264
					}
2265
2266
					// Testing 1, 2, 3...
2267
					$failed = preg_match('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $working_data) === 0;
2268
2269
					// Nope, search pattern not found.
2270
					if ($failed && $actual_operation['error'] === 'fatal')
2271
					{
2272
						$actions[] = array(
2273
							'type' => 'failure',
2274
							'filename' => $working_file,
2275
							'search' => $actual_operation['searches'][$i]['preg_search'],
2276
							'search_original' => $actual_operation['searches'][$i]['search'],
2277
							'replace_original' => $actual_operation['searches'][$i]['add'],
2278
							'position' => $search['position'],
2279
							'is_custom' => $theme > 1 ? $theme : 0,
2280
							'failed' => $failed,
2281
						);
2282
2283
						$everything_found = false;
2284
						continue;
2285
					}
2286
2287
					// Found, but in this case, that means failure!
2288
					elseif (!$failed && $actual_operation['error'] === 'required')
2289
					{
2290
						$actions[] = array(
2291
							'type' => 'failure',
2292
							'filename' => $working_file,
2293
							'search' => $actual_operation['searches'][$i]['preg_search'],
2294
							'search_original' => $actual_operation['searches'][$i]['search'],
2295
							'replace_original' => $actual_operation['searches'][$i]['add'],
2296
							'position' => $search['position'],
2297
							'is_custom' => $theme > 1 ? $theme : 0,
2298
							'failed' => $failed,
2299
						);
2300
2301
						$everything_found = false;
2302
						continue;
2303
					}
2304
2305
					// Replace it into nothing? That's not an option...unless it's an undoing end.
2306
					if ($search['add'] === '' && ($search['position'] !== 'end' || !$undo))
2307
						continue;
2308
2309
					// Finally, we're doing some replacements.
2310
					$working_data = preg_replace('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $actual_operation['searches'][$i]['preg_replace'], $working_data, 1);
2311
2312
					$actions[] = array(
2313
						'type' => 'replace',
2314
						'filename' => $working_file,
2315
						'search' => $actual_operation['searches'][$i]['preg_search'],
2316
						'replace' =>  $actual_operation['searches'][$i]['preg_replace'],
2317
						'search_original' => $actual_operation['searches'][$i]['search'],
2318
						'replace_original' => $actual_operation['searches'][$i]['add'],
2319
						'position' => $search['position'],
2320
						'failed' => $failed,
2321
						'ignore_failure' => $failed && $actual_operation['error'] === 'ignore',
2322
						'is_custom' => $theme > 1 ? $theme : 0,
2323
					);
2324
				}
2325
			}
2326
2327
			// Fix any little helper symbols ;).
2328
			$working_data = strtr($working_data, array('[$PACK' . 'AGE1$]' => '$', '[$PACK' . 'AGE2$]' => '\\'));
2329
2330
			package_chmod($working_file);
2331
2332
			if ((file_exists($working_file) && !is_writable($working_file)) || (!file_exists($working_file) && !is_writable(dirname($working_file))))
2333
				$actions[] = array(
2334
					'type' => 'chmod',
2335
					'filename' => $working_file
2336
				);
2337
2338
			if (basename($working_file) == 'Settings_bak.php')
2339
				continue;
2340
2341
			if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2342
			{
2343
				// No, no, not Settings.php!
2344
				if (basename($working_file) == 'Settings.php')
2345
					@copy($working_file, dirname($working_file) . '/Settings_bak.php');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for copy(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2346
				else
2347
					@copy($working_file, $working_file . '~');
2348
			}
2349
2350
			// Always call this, even if in testing, because it won't really be written in testing mode.
2351
			package_put_contents($working_file, $working_data, $testing);
2352
2353
			$actions[] = array(
2354
				'type' => 'saved',
2355
				'filename' => $working_file,
2356
				'is_custom' => $theme > 1 ? $theme : 0,
2357
			);
2358
		}
2359
	}
2360
2361
	$actions[] = array(
2362
		'type' => 'result',
2363
		'status' => $everything_found
2364
	);
2365
2366
	return $actions;
2367
}
2368
2369
/**
2370
 * Parses a boardmod-style (.mod) modification file
2371
 *
2372
 * @param string $file The modification file to parse
2373
 * @param bool $testing Whether we're just doing a test
2374
 * @param bool $undo If true, specifies that the modifications should be undone. Used when uninstalling.
2375
 * @param array $theme_paths An array of information about custom themes to apply the changes to
2376
 * @return array An array of those changes made.
2377
 */
2378
function parseBoardMod($file, $testing = true, $undo = false, $theme_paths = array())
2379
{
2380
	global $boarddir, $sourcedir, $settings, $modSettings;
2381
2382
	@set_time_limit(600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

2382
	/** @scrutinizer ignore-unhandled */ @set_time_limit(600);

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2383
	$file = strtr($file, array("\r" => ''));
2384
2385
	$working_file = null;
2386
	$working_search = null;
2387
	$working_data = '';
2388
	$replace_with = null;
2389
2390
	$actions = array();
2391
	$everything_found = true;
2392
2393
	// This holds all the template changes in the standard mod file.
2394
	$template_changes = array();
2395
	// This is just the temporary file.
2396
	$temp_file = $file;
2397
	// This holds the actual changes on a step counter basis.
2398
	$temp_changes = array();
2399
	$counter = 0;
2400
	$step_counter = 0;
2401
2402
	// 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.
2403
	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)
2404
	{
2405
		$counter++;
2406
2407
		// Get rid of the old stuff.
2408
		$temp_file = substr_replace($temp_file, '', strpos($temp_file, $code_match[0]), strlen($code_match[0]));
2409
2410
		// No interest to us?
2411
		if ($code_match[1] != 'edit file' && $code_match[1] != 'file')
2412
		{
2413
			// It's a step, let's add that to the current steps.
2414
			if (isset($temp_changes[$step_counter]))
2415
				$temp_changes[$step_counter]['changes'][] = $code_match[0];
2416
			continue;
2417
		}
2418
2419
		// We've found a new edit - let's make ourself heard, kind of.
2420
		$step_counter = $counter;
2421
		$temp_changes[$step_counter] = array(
2422
			'title' => $code_match[0],
2423
			'changes' => array(),
2424
		);
2425
2426
		$filename = parse_path($code_match[2]);
2427
2428
		// Now, is this a template file, and if so, which?
2429
		foreach ($theme_paths as $id => $theme)
2430
		{
2431
			// If this filename is relative, if so take a guess at what it should be.
2432
			if (strpos($filename, 'Themes') === 0)
2433
				$filename = $boarddir . '/' . $filename;
2434
2435
			if (strpos($filename, $theme['theme_dir']) === 0)
2436
				$template_changes[$id][$counter] = substr($filename, strlen($theme['theme_dir']) + 1);
2437
		}
2438
	}
2439
2440
	// Reference for what theme ID this action belongs to.
2441
	$theme_id_ref = array();
2442
2443
	// Now we know what templates we need to touch, cycle through each theme and work out what we need to edit.
2444
	if (!empty($template_changes[1]))
2445
	{
2446
		foreach ($theme_paths as $id => $theme)
2447
		{
2448
			// Don't do default, it means nothing to me.
2449
			if ($id == 1)
2450
				continue;
2451
2452
			// Now, for each file do we need to edit it?
2453
			foreach ($template_changes[1] as $pos => $template_file)
2454
			{
2455
				// It does? Add it to the list darlin'.
2456
				if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id][$pos]) || !in_array($template_file, $template_changes[$id][$pos])))
2457
				{
2458
					// Actually add it to the mod file too, so we can see that it will work ;)
2459
					if (!empty($temp_changes[$pos]['changes']))
2460
					{
2461
						$file .= "\n\n" . '<edit file>' . "\n" . $theme['theme_dir'] . '/' . $template_file . "\n" . '</edit file>' . "\n\n" . implode("\n\n", $temp_changes[$pos]['changes']);
2462
						$theme_id_ref[$counter] = $id;
2463
						$counter += 1 + count($temp_changes[$pos]['changes']);
2464
					}
2465
				}
2466
			}
2467
		}
2468
	}
2469
2470
	$counter = 0;
2471
	$is_custom = 0;
2472
	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)
2473
	{
2474
		// This is for working out what we should be editing.
2475
		$counter++;
2476
2477
		// Edit a specific file.
2478
		if ($code_match[1] == 'file' || $code_match[1] == 'edit file')
2479
		{
2480
			// Backup the old file.
2481
			if ($working_file !== null)
2482
			{
2483
				package_chmod($working_file);
2484
2485
				// Don't even dare.
2486
				if (basename($working_file) == 'Settings_bak.php')
2487
					continue;
2488
2489
				if (!is_writable($working_file))
2490
					$actions[] = array(
2491
						'type' => 'chmod',
2492
						'filename' => $working_file
2493
					);
2494
2495
				if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2496
				{
2497
					if (basename($working_file) == 'Settings.php')
2498
						@copy($working_file, dirname($working_file) . '/Settings_bak.php');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for copy(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2499
					else
2500
						@copy($working_file, $working_file . '~');
2501
				}
2502
2503
				package_put_contents($working_file, $working_data, $testing);
2504
			}
2505
2506
			if ($working_file !== null)
2507
				$actions[] = array(
2508
					'type' => 'saved',
2509
					'filename' => $working_file,
2510
					'is_custom' => $is_custom,
2511
				);
2512
2513
			// Is this "now working on" file a theme specific one?
2514
			$is_custom = isset($theme_id_ref[$counter - 1]) ? $theme_id_ref[$counter - 1] : 0;
2515
2516
			// Make sure the file exists!
2517
			$working_file = parse_path($code_match[2]);
2518
2519
			if ($working_file[0] != '/' && $working_file[1] != ':')
2520
			{
2521
				trigger_error('parseBoardMod(): The filename \'' . $working_file . '\' is not a full path!', E_USER_WARNING);
2522
2523
				$working_file = $boarddir . '/' . $working_file;
2524
			}
2525
2526
			if (!file_exists($working_file))
2527
			{
2528
				$places_to_check = array($boarddir, $sourcedir, $settings['default_theme_dir'], $settings['default_theme_dir'] . '/languages');
2529
2530
				foreach ($places_to_check as $place)
2531
					if (file_exists($place . '/' . $working_file))
2532
					{
2533
						$working_file = $place . '/' . $working_file;
2534
						break;
2535
					}
2536
			}
2537
2538
			if (file_exists($working_file))
2539
			{
2540
				// Load the new file.
2541
				$working_data = str_replace("\r", '', package_get_contents($working_file));
2542
2543
				$actions[] = array(
2544
					'type' => 'opened',
2545
					'filename' => $working_file
2546
				);
2547
			}
2548
			else
2549
			{
2550
				$actions[] = array(
2551
					'type' => 'missing',
2552
					'filename' => $working_file
2553
				);
2554
2555
				$working_file = null;
2556
				$everything_found = false;
2557
			}
2558
2559
			// Can't be searching for something...
2560
			$working_search = null;
2561
		}
2562
		// Search for a specific string.
2563
		elseif (($code_match[1] == 'search' || $code_match[1] == 'search for') && $working_file !== null)
2564
		{
2565
			if ($working_search !== null)
2566
			{
2567
				$actions[] = array(
2568
					'type' => 'error',
2569
					'filename' => $working_file
2570
				);
2571
2572
				$everything_found = false;
2573
			}
2574
2575
			$working_search = $code_match[2];
2576
		}
2577
		// Must've already loaded a search string.
2578
		elseif ($working_search !== null)
2579
		{
2580
			// This is the base string....
2581
			$replace_with = $code_match[2];
2582
2583
			// Add this afterward...
2584
			if ($code_match[1] == 'add' || $code_match[1] == 'add after')
2585
				$replace_with = $working_search . "\n" . $replace_with;
2586
			// Add this beforehand.
2587
			elseif ($code_match[1] == 'before' || $code_match[1] == 'add before' || $code_match[1] == 'above' || $code_match[1] == 'add above')
2588
				$replace_with .= "\n" . $working_search;
2589
			// Otherwise.. replace with $replace_with ;).
2590
		}
2591
2592
		// If we have a search string, replace string, and open file..
2593
		if ($working_search !== null && $replace_with !== null && $working_file !== null)
2594
		{
2595
			// Make sure it's somewhere in the string.
2596
			if ($undo)
2597
			{
2598
				$temp = $replace_with;
2599
				$replace_with = $working_search;
2600
				$working_search = $temp;
2601
			}
2602
2603
			if (strpos($working_data, $working_search) !== false)
2604
			{
2605
				$working_data = str_replace($working_search, $replace_with, $working_data);
2606
2607
				$actions[] = array(
2608
					'type' => 'replace',
2609
					'filename' => $working_file,
2610
					'search' => $working_search,
2611
					'replace' => $replace_with,
2612
					'search_original' => $working_search,
2613
					'replace_original' => $replace_with,
2614
					'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
2615
					'is_custom' => $is_custom,
2616
					'failed' => false,
2617
				);
2618
			}
2619
			// It wasn't found!
2620
			else
2621
			{
2622
				$actions[] = array(
2623
					'type' => 'failure',
2624
					'filename' => $working_file,
2625
					'search' => $working_search,
2626
					'is_custom' => $is_custom,
2627
					'search_original' => $working_search,
2628
					'replace_original' => $replace_with,
2629
					'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
2630
					'is_custom' => $is_custom,
2631
					'failed' => true,
2632
				);
2633
2634
				$everything_found = false;
2635
			}
2636
2637
			// These don't hold any meaning now.
2638
			$working_search = null;
2639
			$replace_with = null;
2640
		}
2641
2642
		// Get rid of the old tag.
2643
		$file = substr_replace($file, '', strpos($file, $code_match[0]), strlen($code_match[0]));
2644
	}
2645
2646
	// Backup the old file.
2647
	if ($working_file !== null)
2648
	{
2649
		package_chmod($working_file);
2650
2651
		if (!is_writable($working_file))
2652
			$actions[] = array(
2653
				'type' => 'chmod',
2654
				'filename' => $working_file
2655
			);
2656
2657
		if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2658
		{
2659
			if (basename($working_file) == 'Settings.php')
2660
				@copy($working_file, dirname($working_file) . '/Settings_bak.php');
2661
			else
2662
				@copy($working_file, $working_file . '~');
2663
		}
2664
2665
		package_put_contents($working_file, $working_data, $testing);
2666
	}
2667
2668
	if ($working_file !== null)
2669
		$actions[] = array(
2670
			'type' => 'saved',
2671
			'filename' => $working_file,
2672
			'is_custom' => $is_custom,
2673
		);
2674
2675
	$actions[] = array(
2676
		'type' => 'result',
2677
		'status' => $everything_found
2678
	);
2679
2680
	return $actions;
2681
}
2682
2683
/**
2684
 * Get the physical contents of a packages file
2685
 *
2686
 * @param string $filename The package file
2687
 * @return string The contents of the specified file
2688
 */
2689
function package_get_contents($filename)
2690
{
2691
	global $package_cache, $modSettings;
2692
2693
	if (!isset($package_cache))
2694
	{
2695
		$mem_check = setMemoryLimit('128M');
2696
2697
		// Windows doesn't seem to care about the memory_limit.
2698
		if (!empty($modSettings['package_disable_cache']) || $mem_check || stripos(PHP_OS, 'win') !== false)
2699
			$package_cache = array();
2700
		else
2701
			$package_cache = false;
2702
	}
2703
2704
	if (strpos($filename, 'Packages/') !== false || $package_cache === false || !isset($package_cache[$filename]))
2705
		return file_get_contents($filename);
2706
	else
2707
		return $package_cache[$filename];
2708
}
2709
2710
/**
2711
 * Writes data to a file, almost exactly like the file_put_contents() function.
2712
 * uses FTP to create/chmod the file when necessary and available.
2713
 * uses text mode for text mode file extensions.
2714
 * returns the number of bytes written.
2715
 *
2716
 * @param string $filename The name of the file
2717
 * @param string $data The data to write to the file
2718
 * @param bool $testing Whether we're just testing things
2719
 * @return int The length of the data written (in bytes)
2720
 */
2721
function package_put_contents($filename, $data, $testing = false)
2722
{
2723
	/** @var ftp_connection $package_ftp */
2724
	global $package_ftp, $package_cache, $modSettings;
2725
	static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2726
2727
	if (!isset($package_cache))
2728
	{
2729
		// Try to increase the memory limit - we don't want to run out of ram!
2730
		$mem_check = setMemoryLimit('128M');
2731
2732
		if (!empty($modSettings['package_disable_cache']) || $mem_check || stripos(PHP_OS, 'win') !== false)
2733
			$package_cache = array();
2734
		else
2735
			$package_cache = false;
2736
	}
2737
2738
	if (isset($package_ftp))
2739
		$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2740
2741
	if (!file_exists($filename) && isset($package_ftp))
2742
		$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...
2743
	elseif (!file_exists($filename))
2744
		@touch($filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2745
2746
	package_chmod($filename);
2747
2748
	if (!$testing && (strpos($filename, 'Packages/') !== false || $package_cache === false))
2749
	{
2750
		$fp = @fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2751
2752
		// We should show an error message or attempt a rollback, no?
2753
		if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
2754
			return false;
2755
2756
		fwrite($fp, $data);
2757
		fclose($fp);
2758
	}
2759
	elseif (strpos($filename, 'Packages/') !== false || $package_cache === false)
2760
		return strlen($data);
2761
	else
2762
	{
2763
		$package_cache[$filename] = $data;
2764
2765
		// Permission denied, eh?
2766
		$fp = @fopen($filename, 'r+');
2767
		if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
2768
			return false;
2769
		fclose($fp);
2770
	}
2771
2772
	return strlen($data);
2773
}
2774
2775
/**
2776
 * Flushes the cache from memory to the filesystem
2777
 *
2778
 * @param bool $trash
2779
 */
2780
function package_flush_cache($trash = false)
2781
{
2782
	/** @var ftp_connection $package_ftp */
2783
	global $package_ftp, $package_cache;
2784
	static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2785
2786
	if (empty($package_cache))
2787
		return;
2788
2789
	// First, let's check permissions!
2790
	foreach ($package_cache as $filename => $data)
2791
	{
2792
		if (isset($package_ftp))
2793
			$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2794
2795
		if (!file_exists($filename) && isset($package_ftp))
2796
			$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...
2797
		elseif (!file_exists($filename))
2798
			@touch($filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2799
2800
		$result = package_chmod($filename);
2801
2802
		// if we are not doing our test pass, then lets do a full write check
2803
		// bypass directories when doing this test
2804
		if ((!$trash) && !is_dir($filename))
2805
		{
2806
			// acid test, can we really open this file for writing?
2807
			$fp = ($result) ? fopen($filename, 'r+') : $result;
2808
			if (!$fp)
2809
			{
2810
				// We should have package_chmod()'d them before, no?!
2811
				trigger_error('package_flush_cache(): some files are still not writable', E_USER_WARNING);
2812
				return;
2813
			}
2814
			fclose($fp);
2815
		}
2816
	}
2817
2818
	if ($trash)
2819
	{
2820
		$package_cache = array();
2821
		return;
2822
	}
2823
2824
	// Write the cache to disk here.
2825
	// Bypass directories when doing so - no data to write & the fopen will crash.
2826
	foreach ($package_cache as $filename => $data)
2827
	{
2828
		if (!is_dir($filename))
2829
		{
2830
			$fp = fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2831
			fwrite($fp, $data);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

2832
			fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
2833
		}
2834
	}
2835
2836
	$package_cache = array();
2837
}
2838
2839
/**
2840
 * Try to make a file writable.
2841
 *
2842
 * @param string $filename The name of the file
2843
 * @param string $perm_state The permission state - can be either 'writable' or 'execute'
2844
 * @param bool $track_change Whether to track this change
2845
 * @return boolean True if it worked, false if it didn't
2846
 */
2847
function package_chmod($filename, $perm_state = 'writable', $track_change = false)
2848
{
2849
	/** @var ftp_connection $package_ftp */
2850
	global $package_ftp;
2851
2852
	if (file_exists($filename) && is_writable($filename) && $perm_state == 'writable')
2853
		return true;
2854
2855
	// Start off checking without FTP.
2856
	if (!isset($package_ftp) || $package_ftp === false)
2857
	{
2858
		for ($i = 0; $i < 2; $i++)
2859
		{
2860
			$chmod_file = $filename;
2861
2862
			// Start off with a less aggressive test.
2863
			if ($i == 0)
2864
			{
2865
				// If this file doesn't exist, then we actually want to look at whatever parent directory does.
2866
				$subTraverseLimit = 2;
2867
				while (!file_exists($chmod_file) && $subTraverseLimit)
2868
				{
2869
					$chmod_file = dirname($chmod_file);
2870
					$subTraverseLimit--;
2871
				}
2872
2873
				// Keep track of the writable status here.
2874
				$file_permissions = @fileperms($chmod_file);
2875
			}
2876
			else
2877
			{
2878
				// This looks odd, but it's an attempt to work around PHP suExec.
2879
				if (!file_exists($chmod_file) && $perm_state == 'writable')
2880
				{
2881
					$file_permissions = @fileperms(dirname($chmod_file));
2882
2883
					mktree(dirname($chmod_file), 0755);
2884
					@touch($chmod_file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2885
					smf_chmod($chmod_file, 0755);
2886
				}
2887
				else
2888
					$file_permissions = @fileperms($chmod_file);
2889
			}
2890
2891
			// This looks odd, but it's another attempt to work around PHP suExec.
2892
			if ($perm_state != 'writable')
2893
				smf_chmod($chmod_file, $perm_state == 'execute' ? 0755 : 0644);
2894
			else
2895
			{
2896
				if (!@is_writable($chmod_file))
2897
					smf_chmod($chmod_file, 0755);
2898
				if (!@is_writable($chmod_file))
2899
					smf_chmod($chmod_file, 0777);
2900
				if (!@is_writable(dirname($chmod_file)))
2901
					smf_chmod($chmod_file, 0755);
2902
				if (!@is_writable(dirname($chmod_file)))
2903
					smf_chmod($chmod_file, 0777);
2904
			}
2905
2906
			// The ultimate writable test.
2907
			if ($perm_state == 'writable')
2908
			{
2909
				$fp = is_dir($chmod_file) ? @opendir($chmod_file) : @fopen($chmod_file, 'rb');
2910
				if (@is_writable($chmod_file) && $fp)
2911
				{
2912
					if (!is_dir($chmod_file))
2913
						fclose($fp);
2914
					else
2915
						closedir($fp);
2916
2917
					// It worked!
2918
					if ($track_change)
2919
						$_SESSION['pack_ftp']['original_perms'][$chmod_file] = $file_permissions;
2920
2921
					return true;
2922
				}
2923
			}
2924
			elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$chmod_file]))
2925
				unset($_SESSION['pack_ftp']['original_perms'][$chmod_file]);
2926
		}
2927
2928
		// If we're here we're a failure.
2929
		return false;
2930
	}
2931
	// Otherwise we do have FTP?
2932
	elseif ($package_ftp !== false && !empty($_SESSION['pack_ftp']))
2933
	{
2934
		$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2935
2936
		// This looks odd, but it's an attempt to work around PHP suExec.
2937
		if (!file_exists($filename) && $perm_state == 'writable')
2938
		{
2939
			$file_permissions = @fileperms(dirname($filename));
2940
2941
			mktree(dirname($filename), 0755);
2942
			$package_ftp->create_file($ftp_file);
2943
			$package_ftp->chmod($ftp_file, 0755);
2944
		}
2945
		else
2946
			$file_permissions = @fileperms($filename);
2947
2948
		if ($perm_state != 'writable')
2949
		{
2950
			$package_ftp->chmod($ftp_file, $perm_state == 'execute' ? 0755 : 0644);
2951
		}
2952
		else
2953
		{
2954
			if (!@is_writable($filename))
2955
				$package_ftp->chmod($ftp_file, 0777);
2956
			if (!@is_writable(dirname($filename)))
2957
				$package_ftp->chmod(dirname($ftp_file), 0777);
2958
		}
2959
2960
		if (@is_writable($filename))
2961
		{
2962
			if ($track_change)
2963
				$_SESSION['pack_ftp']['original_perms'][$filename] = $file_permissions;
2964
2965
			return true;
2966
		}
2967
		elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$filename]))
2968
			unset($_SESSION['pack_ftp']['original_perms'][$filename]);
2969
	}
2970
2971
	// Oh dear, we failed if we get here.
2972
	return false;
2973
}
2974
2975
/**
2976
 * Used to crypt the supplied ftp password in this session
2977
 *
2978
 * @param string $pass The password
2979
 * @return string The encrypted password
2980
 */
2981
function package_crypt($pass)
2982
{
2983
	$n = strlen($pass);
2984
2985
	$salt = session_id();
2986
	while (strlen($salt) < $n)
2987
		$salt .= session_id();
2988
2989
	for ($i = 0; $i < $n; $i++)
2990
		$pass{$i} = chr(ord($pass{$i}) ^ (ord($salt{$i}) - 32));
2991
2992
	return $pass;
2993
}
2994
2995
/**
2996
 * Creates a backup of forum files prior to modifying them
2997
 * @param string $id The name of the backup
2998
 * @return bool True if it worked, false if it didn't
2999
 */
3000
function package_create_backup($id = 'backup')
3001
{
3002
	global $sourcedir, $boarddir, $packagesdir, $smcFunc;
3003
3004
	$files = array();
3005
3006
	$base_files = array('index.php', 'SSI.php', 'agreement.txt', 'cron.php', 'ssi_examples.php', 'ssi_examples.shtml', 'subscriptions.php');
3007
	foreach ($base_files as $file)
3008
	{
3009
		if (file_exists($boarddir . '/' . $file))
3010
			$files[empty($_REQUEST['use_full_paths']) ? $file : $boarddir . '/' . $file] = $boarddir . '/' . $file;
3011
	}
3012
3013
	$dirs = array(
3014
		$sourcedir => empty($_REQUEST['use_full_paths']) ? 'Sources/' : strtr($sourcedir . '/', '\\', '/')
3015
	);
3016
3017
	$request = $smcFunc['db_query']('', '
3018
		SELECT value
3019
		FROM {db_prefix}themes
3020
		WHERE id_member = {int:no_member}
3021
			AND variable = {string:theme_dir}',
3022
		array(
3023
			'no_member' => 0,
3024
			'theme_dir' => 'theme_dir',
3025
		)
3026
	);
3027
	while ($row = $smcFunc['db_fetch_assoc']($request))
3028
		$dirs[$row['value']] = empty($_REQUEST['use_full_paths']) ? 'Themes/' . basename($row['value']) . '/' : strtr($row['value'] . '/', '\\', '/');
3029
	$smcFunc['db_free_result']($request);
3030
3031
	try
3032
	{
3033
		foreach ($dirs as $dir => $dest)
3034
		{
3035
			$iter = new RecursiveIteratorIterator(
3036
				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
3037
				RecursiveIteratorIterator::CHILD_FIRST,
3038
				RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
3039
			);
3040
3041
			foreach ($iter as $entry => $dir)
0 ignored issues
show
Comprehensibility Bug introduced by
$dir is overwriting a variable from outer foreach loop.
Loading history...
3042
			{
3043
				if ($dir->isDir())
3044
					continue;
3045
3046
				if (preg_match('~^(\.{1,2}|CVS|backup.*|help|images|.*\~)$~', $entry) != 0)
3047
					continue;
3048
3049
				$files[empty($_REQUEST['use_full_paths']) ? str_replace(realpath($boarddir), '', $entry) : $entry] = $entry;
3050
			}
3051
		}
3052
		$obj = new ArrayObject($files);
3053
		$iterator = $obj->getIterator();
3054
3055
		if (!file_exists($packagesdir . '/backups'))
3056
			mktree($packagesdir . '/backups', 0777);
3057
		if (!is_writable($packagesdir . '/backups'))
3058
			package_chmod($packagesdir . '/backups');
3059
		$output_file = $packagesdir . '/backups/' . strftime('%Y-%m-%d_') . preg_replace('~[$\\\\/:<>|?*"\']~', '', $id);
3060
		$output_ext = '.tar';
3061
		$output_ext_target = '.tar.gz';
3062
3063
		if (file_exists($output_file . $output_ext_target))
3064
		{
3065
			$i = 2;
3066
			while (file_exists($output_file . '_' . $i . $output_ext_target))
3067
				$i++;
3068
			$output_file = $output_file . '_' . $i . $output_ext;
3069
		}
3070
		else
3071
			$output_file .= $output_ext;
3072
3073
		@set_time_limit(300);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

3073
		/** @scrutinizer ignore-unhandled */ @set_time_limit(300);

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3074
		if (function_exists('apache_reset_timeout'))
3075
			@apache_reset_timeout();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for apache_reset_timeout(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

3075
			/** @scrutinizer ignore-unhandled */ @apache_reset_timeout();

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3076
3077
		$a = new PharData($output_file);
3078
		$a->buildFromIterator($iterator);
3079
		$a->compress(Phar::GZ);
3080
3081
		/*
3082
		 * Destroying the local var tells PharData to close its internal
3083
		 * file pointer, enabling us to delete the uncompressed tarball.
3084
		 */
3085
		unset($a);
3086
		unlink($output_file);
3087
	}
3088
	catch (Exception $e)
3089
	{
3090
		log_error($e->getMessage(), 'backup');
3091
3092
		return false;
3093
	}
3094
3095
	return true;
3096
}
3097
3098
if (!function_exists('smf_crc32'))
3099
{
3100
	/**
3101
	 * crc32 doesn't work as expected on 64-bit functions - make our own.
3102
	 * https://php.net/crc32#79567
3103
	 *
3104
	 * @param string $number
3105
	 * @return string The crc32
3106
	 */
3107
	function smf_crc32($number)
3108
	{
3109
		$crc = crc32($number);
3110
3111
		if ($crc & 0x80000000)
3112
		{
3113
			$crc ^= 0xffffffff;
3114
			$crc += 1;
3115
			$crc = -$crc;
3116
		}
3117
3118
		return $crc;
3119
	}
3120
}
3121
3122
?>