Passed
Pull Request — release-2.1 (#6996)
by John
04:19
created

read_zip_file()   F

Complexity

Conditions 29
Paths 3742

Size

Total Lines 102
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 29
eloc 59
c 0
b 0
f 0
nc 3742
nop 5
dl 0
loc 102
rs 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file's central purpose of existence is that of making the package
5
 * manager work nicely.  It contains functions for handling tar.gz and zip
6
 * files, as well as a simple xml parser to handle the xml package stuff.
7
 * Not to mention a few functions to make file handling easier.
8
 *
9
 * Simple Machines Forum (SMF)
10
 *
11
 * @package SMF
12
 * @author Simple Machines https://www.simplemachines.org
13
 * @copyright 2021 Simple Machines and individual contributors
14
 * @license https://www.simplemachines.org/about/smf/license.php BSD
15
 *
16
 * @version 2.1 RC4
17
 */
18
19
if (!defined('SMF'))
20
	die('No direct access...');
21
22
/**
23
 * Reads 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_lib', 'critical', array('package_no_zlib', 'package_no_package_manager'));
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');
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
	// This function sorta needs phar!
245
	if (!class_exists('PharData'))
246
		fatal_lang_error('package_no_lib', 'critical', array('package_no_phar', 'package_no_package_manager'));
247
248
	try
249
	{
250
		// This may not always be defined...
251
		$return = array();
252
253
		// Some hosted unix platforms require an extension; win may have .tmp & that works ok
254
		if (!in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), array('zip', 'tmp')))
255
			if (@rename($file, $file . '.zip'))
256
				$file = $file . '.zip';
257
258
		// Phar doesn't handle open_basedir restrictions very well and throws a PHP Warning. Ignore that.
259
		set_error_handler(
260
			function($errno, $errstr, $errfile, $errline)
261
			{
262
				// error was suppressed with the @-operator
263
				if (0 === error_reporting())
264
					return false;
265
266
				if (strpos($errstr, 'PharData::__construct(): open_basedir') === false)
267
					log_error($errstr, 'general', $errfile, $errline);
268
269
				return true;
270
			}
271
		);
272
		$archive = new PharData($file, RecursiveIteratorIterator::SELF_FIRST, null, Phar::ZIP);
273
		restore_error_handler();
274
275
		$iterator = new RecursiveIteratorIterator($archive, RecursiveIteratorIterator::SELF_FIRST);
276
277
		// go though each file in the archive
278
		foreach ($iterator as $file_info)
279
		{
280
			$i = $iterator->getSubPathname();
281
			// If this is a file, and it doesn't exist.... happy days!
282
			if (substr($i, -1) != '/' && !file_exists($destination . '/' . $i))
283
				$write_this = true;
284
			// If the file exists, we may not want to overwrite it.
285
			elseif (substr($i, -1) != '/')
286
				$write_this = $overwrite;
287
			else
288
				$write_this = false;
289
290
			// Get the actual compressed data.
291
			if (!$file_info->isDir())
292
				$file_data = file_get_contents($file_info);
293
			elseif ($destination !== null && !$single_file)
294
			{
295
				// Folder... create.
296
				if (!file_exists($destination . '/' . $i))
297
					mktree($destination . '/' . $i, 0777);
298
				$file_data = null;
299
			}
300
			else
301
				$file_data = null;
302
303
			// Okay!  We can write this file, looks good from here...
304
			if ($write_this && $destination !== null)
305
			{
306
				if (!$single_file && !is_dir($destination . '/' . dirname($i)))
307
					mktree($destination . '/' . dirname($i), 0777);
308
309
				// If we're looking for a specific file, and this is it... ka-bam, baby.
310
				if ($single_file && ($destination == $i || $destination == '*/' . basename($i)))
311
					return $file_data;
312
				// 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.
313
				elseif ($single_file)
314
					continue;
315
				// Don't really want this?
316
				elseif ($files_to_extract !== null && !in_array($i, $files_to_extract))
317
					continue;
318
319
				package_put_contents($destination . '/' . $i, $file_data);
320
			}
321
322
			if (substr($i, -1, 1) != '/')
323
				$return[] = array(
324
					'filename' => $i,
325
					'md5' => md5($file_data),
326
					'preview' => substr($file_data, 0, 100),
327
					'size' => strlen($file_data),
328
					'skipped' => false
329
				);
330
		}
331
332
		if ($destination !== null && !$single_file)
333
			package_flush_cache();
334
335
		if ($single_file)
336
			return false;
337
		else
338
			return $return;
339
	}
340
	catch (Exception $e)
341
	{
342
		log_error($e->getMessage(), 'general', $e->getFile(), $e->getLine());
343
		return false;
344
	}
345
}
346
347
/**
348
 * Extract zip data. .
349
 *
350
 * If single_file is true, destination can start with * and / to signify that the file may come from any directory.
351
 * Destination should not begin with a / if single_file is true.
352
 *
353
 * @param string $data ZIP data
354
 * @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)
355
 * @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).
356
 * @param boolean $overwrite If true, will overwrite files with newer modication times. Default is false.
357
 * @param array $files_to_extract
358
 * @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
359
 */
360
function read_zip_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
361
{
362
	umask(0);
363
	if ($destination !== null && !file_exists($destination) && !$single_file)
364
		mktree($destination, 0777);
365
366
	// Look for the end of directory signature 0x06054b50
367
	$data_ecr = explode("\x50\x4b\x05\x06", $data);
368
	if (!isset($data_ecr[1]))
369
		return false;
370
371
	$return = array();
372
373
	// Get all the basic zip file info since we are here
374
	$zip_info = unpack('vdisks/vrecords/vfiles/Vsize/Voffset/vcomment_length/', $data_ecr[1]);
375
376
	// Cut file at the central directory file header signature -- 0x02014b50, use unpack if you want any of the data, we don't
377
	$file_sections = explode("\x50\x4b\x01\x02", $data);
378
379
	// Cut the result on each local file header -- 0x04034b50 so we have each file in the archive as an element.
380
	$file_sections = explode("\x50\x4b\x03\x04", $file_sections[0]);
381
	array_shift($file_sections);
382
383
	// sections and count from the signature must match or the zip file is bad
384
	if (count($file_sections) != $zip_info['files'])
385
		return false;
386
387
	// go though each file in the archive
388
	foreach ($file_sections as $data)
389
	{
390
		// Get all the important file information.
391
		$file_info = unpack("vversion/vgeneral_purpose/vcompress_method/vfile_time/vfile_date/Vcrc/Vcompressed_size/Vsize/vfilename_length/vextrafield_length", $data);
392
		$file_info['filename'] = substr($data, 26, $file_info['filename_length']);
393
		$file_info['dir'] = $destination . '/' . dirname($file_info['filename']);
394
395
		// 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
396
		// In this case the CRC and size are instead appended in a 12-byte structure immediately after the compressed data
397
		if ($file_info['general_purpose'] & 0x0008)
398
		{
399
			$unzipped2 = unpack("Vcrc/Vcompressed_size/Vsize", substr($$data, -12));
400
			$file_info['crc'] = $unzipped2['crc'];
401
			$file_info['compressed_size'] = $unzipped2['compressed_size'];
402
			$file_info['size'] = $unzipped2['size'];
403
			unset($unzipped2);
404
		}
405
406
		// If this is a file, and it doesn't exist.... happy days!
407
		if (substr($file_info['filename'], -1) != '/' && !file_exists($destination . '/' . $file_info['filename']))
408
			$write_this = true;
409
		// If the file exists, we may not want to overwrite it.
410
		elseif (substr($file_info['filename'], -1) != '/')
411
			$write_this = $overwrite;
412
		// This is a directory, so we're gonna want to create it. (probably...)
413
		elseif ($destination !== null && !$single_file)
414
		{
415
			// Just a little accident prevention, don't mind me.
416
			$file_info['filename'] = strtr($file_info['filename'], array('../' => '', '/..' => ''));
417
418
			if (!file_exists($destination . '/' . $file_info['filename']))
419
				mktree($destination . '/' . $file_info['filename'], 0777);
420
			$write_this = false;
421
		}
422
		else
423
			$write_this = false;
424
425
		// Get the actual compressed data.
426
		$file_info['data'] = substr($data, 26 + $file_info['filename_length'] + $file_info['extrafield_length']);
427
428
		// Only inflate it if we need to ;)
429
		if (!empty($file_info['compress_method']) || ($file_info['compressed_size'] != $file_info['size']))
430
			$file_info['data'] = gzinflate($file_info['data']);
431
432
		// Okay!  We can write this file, looks good from here...
433
		if ($write_this && $destination !== null)
434
		{
435
			if ((strpos($file_info['filename'], '/') !== false && !$single_file) || (!$single_file && !is_dir($file_info['dir'])))
436
				mktree($file_info['dir'], 0777);
437
438
			// If we're looking for a specific file, and this is it... ka-bam, baby.
439
			if ($single_file && ($destination == $file_info['filename'] || $destination == '*/' . basename($file_info['filename'])))
440
				return $file_info['data'];
441
			// 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.
442
			elseif ($single_file)
443
				continue;
444
			// Don't really want this?
445
			elseif ($files_to_extract !== null && !in_array($file_info['filename'], $files_to_extract))
446
				continue;
447
448
			package_put_contents($destination . '/' . $file_info['filename'], $file_info['data']);
449
		}
450
451
		if (substr($file_info['filename'], -1, 1) != '/')
452
			$return[] = array(
453
				'filename' => $file_info['filename'],
454
				'md5' => md5($file_info['data']),
455
				'preview' => substr($file_info['data'], 0, 100),
456
				'size' => $file_info['size'],
457
				'skipped' => false
458
			);
459
	}
460
461
	if ($destination !== null && !$single_file)
462
		package_flush_cache();
463
464
	if ($single_file)
465
		return false;
466
	else
467
		return $return;
468
}
469
470
/**
471
 * Checks the existence of a remote file since file_exists() does not do remote.
472
 * will return false if the file is "moved permanently" or similar.
473
 *
474
 * @param string $url The URL to parse
475
 * @return bool Whether the specified URL exists
476
 */
477
function url_exists($url)
478
{
479
	$a_url = parse_url($url);
480
481
	if (!isset($a_url['scheme']))
482
		return false;
483
484
	// Attempt to connect...
485
	$temp = '';
486
	$fid = fsockopen($a_url['host'], !isset($a_url['port']) ? 80 : $a_url['port'], $temp, $temp, 8);
487
	if (!$fid)
488
		return false;
489
490
	fputs($fid, 'HEAD ' . $a_url['path'] . ' HTTP/1.0' . "\r\n" . 'Host: ' . $a_url['host'] . "\r\n\r\n");
491
	$head = fread($fid, 1024);
492
	fclose($fid);
493
494
	return preg_match('~^HTTP/.+\s+(20[01]|30[127])~i', $head) == 1;
495
}
496
497
/**
498
 * Loads and returns an array of installed packages.
499
 *
500
 *  default sort order is package_installed time
501
 *
502
 * @return array An array of info about installed packages
503
 */
504
function loadInstalledPackages()
505
{
506
	global $smcFunc;
507
508
	// Load the packages from the database - note this is ordered by install time to ensure latest package uninstalled first.
509
	$request = $smcFunc['db_query']('', '
510
		SELECT id_install, package_id, filename, name, version, time_installed
511
		FROM {db_prefix}log_packages
512
		WHERE install_state != {int:not_installed}
513
		ORDER BY time_installed DESC',
514
		array(
515
			'not_installed' => 0,
516
		)
517
	);
518
	$installed = array();
519
	$found = array();
520
	while ($row = $smcFunc['db_fetch_assoc']($request))
521
	{
522
		// Already found this? If so don't add it twice!
523
		if (in_array($row['package_id'], $found))
524
			continue;
525
526
		$found[] = $row['package_id'];
527
528
		$row = htmlspecialchars__recursive($row);
529
530
		$installed[] = array(
531
			'id' => $row['id_install'],
532
			'name' => $smcFunc['htmlspecialchars']($row['name']),
533
			'filename' => $row['filename'],
534
			'package_id' => $row['package_id'],
535
			'version' => $smcFunc['htmlspecialchars']($row['version']),
536
			'time_installed' => !empty($row['time_installed']) ? $row['time_installed'] : 0,
537
		);
538
	}
539
	$smcFunc['db_free_result']($request);
540
541
	return $installed;
542
}
543
544
/**
545
 * Loads a package's information and returns a representative array.
546
 * - expects the file to be a package in Packages/.
547
 * - returns a error string if the package-info is invalid.
548
 * - otherwise returns a basic array of id, version, filename, and similar information.
549
 * - an xmlArray is available in 'xml'.
550
 *
551
 * @param string $gzfilename The path to the file
552
 * @return array|string An array of info about the file or a string indicating an error
553
 */
554
function getPackageInfo($gzfilename)
555
{
556
	global $sourcedir, $packagesdir;
557
558
	// Extract package-info.xml from downloaded file. (*/ is used because it could be in any directory.)
559
	if (strpos($gzfilename, 'http://') !== false || strpos($gzfilename, 'https://') !== false)
560
		$packageInfo = read_tgz_data($gzfilename, 'package-info.xml', true);
561
	else
562
	{
563
		if (!file_exists($packagesdir . '/' . $gzfilename))
564
			return 'package_get_error_not_found';
565
566
		if (is_file($packagesdir . '/' . $gzfilename))
567
			$packageInfo = read_tgz_file($packagesdir . '/' . $gzfilename, '*/package-info.xml', true);
568
		elseif (file_exists($packagesdir . '/' . $gzfilename . '/package-info.xml'))
569
			$packageInfo = file_get_contents($packagesdir . '/' . $gzfilename . '/package-info.xml');
570
		else
571
			return 'package_get_error_missing_xml';
572
	}
573
574
	// Nothing?
575
	if (empty($packageInfo))
576
	{
577
		// Perhaps they are trying to install a theme, lets tell them nicely this is the wrong function
578
		$packageInfo = read_tgz_file($packagesdir . '/' . $gzfilename, '*/theme_info.xml', true);
579
		if (!empty($packageInfo))
580
			return 'package_get_error_is_theme';
581
		else
582
			return 'package_get_error_is_zero';
583
	}
584
585
	// Parse package-info.xml into an xmlArray.
586
	require_once($sourcedir . '/Class-Package.php');
587
	$packageInfo = new xmlArray($packageInfo);
588
589
	// @todo Error message of some sort?
590
	if (!$packageInfo->exists('package-info[0]'))
591
		return 'package_get_error_packageinfo_corrupt';
592
593
	$packageInfo = $packageInfo->path('package-info[0]');
594
595
	$package = $packageInfo->to_array();
596
	$package = htmlspecialchars__recursive($package);
597
	$package['xml'] = $packageInfo;
598
	$package['filename'] = $gzfilename;
599
600
	// Don't want to mess with code...
601
	$types = array('install', 'uninstall', 'upgrade');
602
	foreach ($types as $type)
603
	{
604
		if (isset($package[$type]['code']))
605
		{
606
			$package[$type]['code'] = un_htmlspecialchars($package[$type]['code']);
607
		}
608
	}
609
610
	if (!isset($package['type']))
611
		$package['type'] = 'modification';
612
613
	return $package;
614
}
615
616
/**
617
 * Create a chmod control for chmoding files.
618
 *
619
 * @param array $chmodFiles Which files to chmod
620
 * @param array $chmodOptions Options for chmod
621
 * @param bool $restore_write_status Whether to restore write status
622
 * @return array An array of file info
623
 */
624
function create_chmod_control($chmodFiles = array(), $chmodOptions = array(), $restore_write_status = false)
625
{
626
	global $context, $modSettings, $package_ftp, $boarddir, $txt, $sourcedir, $scripturl;
627
628
	// If we're restoring the status of existing files prepare the data.
629
	if ($restore_write_status && isset($_SESSION['pack_ftp']) && !empty($_SESSION['pack_ftp']['original_perms']))
630
	{
631
		/**
632
		 * Get a listing of files that will need to be set back to the original state
633
		 *
634
		 * @param null $dummy1
635
		 * @param null $dummy2
636
		 * @param null $dummy3
637
		 * @param bool $do_change
638
		 * @return array An array of info about the files that need to be restored back to their original state
639
		 */
640
		function list_restoreFiles($dummy1, $dummy2, $dummy3, $do_change)
641
		{
642
			global $txt;
643
644
			$restore_files = array();
645
			foreach ($_SESSION['pack_ftp']['original_perms'] as $file => $perms)
646
			{
647
				// Check the file still exists, and the permissions were indeed different than now.
648
				$file_permissions = @fileperms($file);
649
				if (!file_exists($file) || $file_permissions == $perms)
650
				{
651
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
652
					continue;
653
				}
654
655
				// Are we wanting to change the permission?
656
				if ($do_change && isset($_POST['restore_files']) && in_array($file, $_POST['restore_files']))
657
				{
658
					// Use FTP if we have it.
659
					// @todo where does $package_ftp get set?
660
					if (!empty($package_ftp))
661
					{
662
						$ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
663
						$package_ftp->chmod($ftp_file, $perms);
664
					}
665
					else
666
						smf_chmod($file, $perms);
667
668
					$new_permissions = @fileperms($file);
669
					$result = $new_permissions == $perms ? 'success' : 'failure';
670
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
671
				}
672
				elseif ($do_change)
673
				{
674
					$new_permissions = '';
675
					$result = 'skipped';
676
					unset($_SESSION['pack_ftp']['original_perms'][$file]);
677
				}
678
679
				// Record the results!
680
				$restore_files[] = array(
681
					'path' => $file,
682
					'old_perms_raw' => $perms,
683
					'old_perms' => substr(sprintf('%o', $perms), -4),
684
					'cur_perms' => substr(sprintf('%o', $file_permissions), -4),
685
					'new_perms' => isset($new_permissions) ? substr(sprintf('%o', $new_permissions), -4) : '',
686
					'result' => isset($result) ? $result : '',
687
					'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>',
688
				);
689
			}
690
691
			return $restore_files;
692
		}
693
694
		$listOptions = array(
695
			'id' => 'restore_file_permissions',
696
			'title' => $txt['package_restore_permissions'],
697
			'get_items' => array(
698
				'function' => 'list_restoreFiles',
699
				'params' => array(
700
					!empty($_POST['restore_perms']),
701
				),
702
			),
703
			'columns' => array(
704
				'path' => array(
705
					'header' => array(
706
						'value' => $txt['package_restore_permissions_filename'],
707
					),
708
					'data' => array(
709
						'db' => 'path',
710
						'class' => 'smalltext',
711
					),
712
				),
713
				'old_perms' => array(
714
					'header' => array(
715
						'value' => $txt['package_restore_permissions_orig_status'],
716
					),
717
					'data' => array(
718
						'db' => 'old_perms',
719
						'class' => 'smalltext',
720
					),
721
				),
722
				'cur_perms' => array(
723
					'header' => array(
724
						'value' => $txt['package_restore_permissions_cur_status'],
725
					),
726
					'data' => array(
727
						'function' => function($rowData) use ($txt)
728
						{
729
							$formatTxt = $rowData['result'] == '' || $rowData['result'] == 'skipped' ? $txt['package_restore_permissions_pre_change'] : $txt['package_restore_permissions_post_change'];
730
							return sprintf($formatTxt, $rowData['cur_perms'], $rowData['new_perms'], $rowData['writable_message']);
731
						},
732
						'class' => 'smalltext',
733
					),
734
				),
735
				'check' => array(
736
					'header' => array(
737
						'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
738
						'class' => 'centercol',
739
					),
740
					'data' => array(
741
						'sprintf' => array(
742
							'format' => '<input type="checkbox" name="restore_files[]" value="%1$s">',
743
							'params' => array(
744
								'path' => false,
745
							),
746
						),
747
						'class' => 'centercol',
748
					),
749
				),
750
				'result' => array(
751
					'header' => array(
752
						'value' => $txt['package_restore_permissions_result'],
753
					),
754
					'data' => array(
755
						'function' => function($rowData) use ($txt)
756
						{
757
							return $txt['package_restore_permissions_action_' . $rowData['result']];
758
						},
759
						'class' => 'smalltext',
760
					),
761
				),
762
			),
763
			'form' => array(
764
				'href' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : $scripturl . '?action=admin;area=packages;sa=perms;restore;' . $context['session_var'] . '=' . $context['session_id'],
765
			),
766
			'additional_rows' => array(
767
				array(
768
					'position' => 'below_table_data',
769
					'value' => '<input type="submit" name="restore_perms" value="' . $txt['package_restore_permissions_restore'] . '" class="button">',
770
					'class' => 'titlebg',
771
				),
772
				array(
773
					'position' => 'after_title',
774
					'value' => '<span class="smalltext">' . $txt['package_restore_permissions_desc'] . '</span>',
775
					'class' => 'windowbg',
776
				),
777
			),
778
		);
779
780
		// Work out what columns and the like to show.
781
		if (!empty($_POST['restore_perms']))
782
		{
783
			$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']);
784
			unset($listOptions['columns']['check'], $listOptions['form'], $listOptions['additional_rows'][0]);
785
786
			$context['sub_template'] = 'show_list';
787
			$context['default_list'] = 'restore_file_permissions';
788
		}
789
		else
790
		{
791
			unset($listOptions['columns']['result']);
792
		}
793
794
		// Create the list for display.
795
		require_once($sourcedir . '/Subs-List.php');
796
		createList($listOptions);
797
798
		// If we just restored permissions then whereever we are, we are now done and dusted.
799
		if (!empty($_POST['restore_perms']))
800
			obExit();
801
	}
802
	// Otherwise, it's entirely irrelevant?
803
	elseif ($restore_write_status)
804
		return true;
805
806
	// This is where we report what we got up to.
807
	$return_data = array(
808
		'files' => array(
809
			'writable' => array(),
810
			'notwritable' => array(),
811
		),
812
	);
813
814
	// If we have some FTP information already, then let's assume it was required and try to get ourselves connected.
815
	if (!empty($_SESSION['pack_ftp']['connected']))
816
	{
817
		// Load the file containing the ftp_connection class.
818
		require_once($sourcedir . '/Class-Package.php');
819
820
		$package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
821
	}
822
823
	// Just got a submission did we?
824
	if (empty($package_ftp) && isset($_POST['ftp_username']))
825
	{
826
		require_once($sourcedir . '/Class-Package.php');
827
		$ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
828
829
		// We're connected, jolly good!
830
		if ($ftp->error === false)
831
		{
832
			// Common mistake, so let's try to remedy it...
833
			if (!$ftp->chdir($_POST['ftp_path']))
834
			{
835
				$ftp_error = $ftp->last_message;
836
				$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
837
			}
838
839
			if (!in_array($_POST['ftp_path'], array('', '/')))
840
			{
841
				$ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
842
				if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || substr($_POST['ftp_path'], 0, 1) == '/'))
843
					$ftp_root = substr($ftp_root, 0, -1);
844
			}
845
			else
846
				$ftp_root = $boarddir;
847
848
			$_SESSION['pack_ftp'] = array(
849
				'server' => $_POST['ftp_server'],
850
				'port' => $_POST['ftp_port'],
851
				'username' => $_POST['ftp_username'],
852
				'password' => package_crypt($_POST['ftp_password']),
853
				'path' => $_POST['ftp_path'],
854
				'root' => $ftp_root,
855
				'connected' => true,
856
			);
857
858
			if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
859
				updateSettings(array('package_path' => $_POST['ftp_path']));
860
861
			// This is now the primary connection.
862
			$package_ftp = $ftp;
863
		}
864
	}
865
866
	// Now try to simply make the files writable, with whatever we might have.
867
	if (!empty($chmodFiles))
868
	{
869
		foreach ($chmodFiles as $k => $file)
870
		{
871
			// Sometimes this can somehow happen maybe?
872
			if (empty($file))
873
				unset($chmodFiles[$k]);
874
			// Already writable?
875
			elseif (@is_writable($file))
876
				$return_data['files']['writable'][] = $file;
877
			else
878
			{
879
				// Now try to change that.
880
				$return_data['files'][package_chmod($file, 'writable', true) ? 'writable' : 'notwritable'][] = $file;
881
			}
882
		}
883
	}
884
885
	// Have we still got nasty files which ain't writable? Dear me we need more FTP good sir.
886
	if (empty($package_ftp) && (!empty($return_data['files']['notwritable']) || !empty($chmodOptions['force_find_error'])))
887
	{
888
		if (!isset($ftp) || $ftp->error !== false)
889
		{
890
			if (!isset($ftp))
891
			{
892
				require_once($sourcedir . '/Class-Package.php');
893
				$ftp = new ftp_connection(null);
894
			}
895
			elseif ($ftp->error !== false && !isset($ftp_error))
896
				$ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
897
898
			list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
899
900
			if ($found_path)
901
				$_POST['ftp_path'] = $detect_path;
902
			elseif (!isset($_POST['ftp_path']))
903
				$_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
904
905
			if (!isset($_POST['ftp_username']))
906
				$_POST['ftp_username'] = $username;
907
		}
908
909
		$context['package_ftp'] = array(
910
			'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
911
			'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
912
			'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
913
			'path' => $_POST['ftp_path'],
914
			'error' => empty($ftp_error) ? null : $ftp_error,
915
			'destination' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : '',
916
		);
917
918
		// Which files failed?
919
		if (!isset($context['notwritable_files']))
920
			$context['notwritable_files'] = array();
921
		$context['notwritable_files'] = array_merge($context['notwritable_files'], $return_data['files']['notwritable']);
922
923
		// Sent here to die?
924
		if (!empty($chmodOptions['crash_on_error']))
925
		{
926
			$context['page_title'] = $txt['package_ftp_necessary'];
927
			$context['sub_template'] = 'ftp_required';
928
			obExit();
929
		}
930
	}
931
932
	return $return_data;
933
}
934
935
/**
936
 * Use FTP functions to work with a package download/install
937
 *
938
 * @param string $destination_url The destination URL
939
 * @param null|array $files The files to CHMOD
940
 * @param bool $return Whether to return an array of file info if there's an error
941
 * @return array An array of file info
942
 */
943
function packageRequireFTP($destination_url, $files = null, $return = false)
944
{
945
	global $context, $modSettings, $package_ftp, $boarddir, $txt, $sourcedir;
946
947
	// Try to make them writable the manual way.
948
	if ($files !== null)
949
	{
950
		foreach ($files as $k => $file)
951
		{
952
			// If this file doesn't exist, then we actually want to look at the directory, no?
953
			if (!file_exists($file))
954
				$file = dirname($file);
955
956
			// This looks odd, but it's an attempt to work around PHP suExec.
957
			if (!@is_writable($file))
958
				smf_chmod($file, 0755);
959
			if (!@is_writable($file))
960
				smf_chmod($file, 0777);
961
			if (!@is_writable(dirname($file)))
962
				smf_chmod($file, 0755);
963
			if (!@is_writable(dirname($file)))
964
				smf_chmod($file, 0777);
965
966
			$fp = is_dir($file) ? @opendir($file) : @fopen($file, 'rb');
967
			if (@is_writable($file) && $fp)
968
			{
969
				unset($files[$k]);
970
				if (!is_dir($file))
971
					fclose($fp);
972
				else
973
					closedir($fp);
974
			}
975
		}
976
977
		// No FTP required!
978
		if (empty($files))
979
			return array();
980
	}
981
982
	// They've opted to not use FTP, and try anyway.
983
	if (isset($_SESSION['pack_ftp']) && $_SESSION['pack_ftp'] == false)
984
	{
985
		if ($files === null)
986
			return array();
987
988
		foreach ($files as $k => $file)
989
		{
990
			// This looks odd, but it's an attempt to work around PHP suExec.
991
			if (!file_exists($file))
992
			{
993
				mktree(dirname($file), 0755);
994
				@touch($file);
995
				smf_chmod($file, 0755);
996
			}
997
998
			if (!@is_writable($file))
999
				smf_chmod($file, 0777);
1000
			if (!@is_writable(dirname($file)))
1001
				smf_chmod(dirname($file), 0777);
1002
1003
			if (@is_writable($file))
1004
				unset($files[$k]);
1005
		}
1006
1007
		return $files;
1008
	}
1009
	elseif (isset($_SESSION['pack_ftp']))
1010
	{
1011
		// Load the file containing the ftp_connection class.
1012
		require_once($sourcedir . '/Class-Package.php');
1013
1014
		$package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
1015
1016
		if ($files === null)
1017
			return array();
1018
1019
		foreach ($files as $k => $file)
1020
		{
1021
			$ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
1022
1023
			// This looks odd, but it's an attempt to work around PHP suExec.
1024
			if (!file_exists($file))
1025
			{
1026
				mktree(dirname($file), 0755);
1027
				$package_ftp->create_file($ftp_file);
1028
				$package_ftp->chmod($ftp_file, 0755);
1029
			}
1030
1031
			if (!@is_writable($file))
1032
				$package_ftp->chmod($ftp_file, 0777);
1033
			if (!@is_writable(dirname($file)))
1034
				$package_ftp->chmod(dirname($ftp_file), 0777);
1035
1036
			if (@is_writable($file))
1037
				unset($files[$k]);
1038
		}
1039
1040
		return $files;
1041
	}
1042
1043
	if (isset($_POST['ftp_none']))
1044
	{
1045
		$_SESSION['pack_ftp'] = false;
1046
1047
		$files = packageRequireFTP($destination_url, $files, $return);
1048
		return $files;
1049
	}
1050
	elseif (isset($_POST['ftp_username']))
1051
	{
1052
		require_once($sourcedir . '/Class-Package.php');
1053
		$ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
1054
1055
		if ($ftp->error === false)
1056
		{
1057
			// Common mistake, so let's try to remedy it...
1058
			if (!$ftp->chdir($_POST['ftp_path']))
1059
			{
1060
				$ftp_error = $ftp->last_message;
1061
				$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
1062
			}
1063
		}
1064
	}
1065
1066
	if (!isset($ftp) || $ftp->error !== false)
1067
	{
1068
		if (!isset($ftp))
1069
		{
1070
			require_once($sourcedir . '/Class-Package.php');
1071
			$ftp = new ftp_connection(null);
1072
		}
1073
		elseif ($ftp->error !== false && !isset($ftp_error))
1074
			$ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
1075
1076
		list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
1077
1078
		if ($found_path)
1079
			$_POST['ftp_path'] = $detect_path;
1080
		elseif (!isset($_POST['ftp_path']))
1081
			$_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
1082
1083
		if (!isset($_POST['ftp_username']))
1084
			$_POST['ftp_username'] = $username;
1085
1086
		$context['package_ftp'] = array(
1087
			'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
1088
			'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
1089
			'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
1090
			'path' => $_POST['ftp_path'],
1091
			'error' => empty($ftp_error) ? null : $ftp_error,
1092
			'destination' => $destination_url,
1093
		);
1094
1095
		// If we're returning dump out here.
1096
		if ($return)
1097
			return $files;
1098
1099
		$context['page_title'] = $txt['package_ftp_necessary'];
1100
		$context['sub_template'] = 'ftp_required';
1101
		obExit();
1102
	}
1103
	else
1104
	{
1105
		if (!in_array($_POST['ftp_path'], array('', '/')))
1106
		{
1107
			$ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
1108
			if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || $_POST['ftp_path'][0] == '/'))
1109
				$ftp_root = substr($ftp_root, 0, -1);
1110
		}
1111
		else
1112
			$ftp_root = $boarddir;
1113
1114
		$_SESSION['pack_ftp'] = array(
1115
			'server' => $_POST['ftp_server'],
1116
			'port' => $_POST['ftp_port'],
1117
			'username' => $_POST['ftp_username'],
1118
			'password' => package_crypt($_POST['ftp_password']),
1119
			'path' => $_POST['ftp_path'],
1120
			'root' => $ftp_root,
1121
		);
1122
1123
		if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
1124
			updateSettings(array('package_path' => $_POST['ftp_path']));
1125
1126
		$files = packageRequireFTP($destination_url, $files, $return);
1127
	}
1128
1129
	return $files;
1130
}
1131
1132
/**
1133
 * Parses the actions in package-info.xml file from packages.
1134
 *
1135
 * - package should be an xmlArray with package-info as its base.
1136
 * - testing_only should be true if the package should not actually be applied.
1137
 * - method can be upgrade, install, or uninstall.  Its default is install.
1138
 * - previous_version should be set to the previous installed version of this package, if any.
1139
 * - does not handle failure terribly well; testing first is always better.
1140
 *
1141
 * @param xmlArray &$packageXML The info from the package-info file
1142
 * @param bool $testing_only Whether we're only testing
1143
 * @param string $method The method ('install', 'upgrade', or 'uninstall')
1144
 * @param string $previous_version The previous version of the mod, if method is 'upgrade'
1145
 * @return array An array of those changes made.
1146
 */
1147
function parsePackageInfo(&$packageXML, $testing_only = true, $method = 'install', $previous_version = '')
1148
{
1149
	global $packagesdir, $context, $temp_path, $language, $smcFunc;
1150
1151
	// Mayday!  That action doesn't exist!!
1152
	if (empty($packageXML) || !$packageXML->exists($method))
1153
		return array();
1154
1155
	// We haven't found the package script yet...
1156
	$script = false;
1157
	$the_version = SMF_VERSION;
1158
1159
	// Emulation support...
1160
	if (!empty($_SESSION['version_emulate']))
1161
		$the_version = $_SESSION['version_emulate'];
1162
1163
	// Single package emulation
1164
	if (!empty($_REQUEST['ve']) && !empty($_REQUEST['package']))
1165
	{
1166
		$the_version = $_REQUEST['ve'];
1167
		$_SESSION['single_version_emulate'][$_REQUEST['package']] = $the_version;
1168
	}
1169
	if (!empty($_REQUEST['package']) && (!empty($_SESSION['single_version_emulate'][$_REQUEST['package']])))
1170
		$the_version = $_SESSION['single_version_emulate'][$_REQUEST['package']];
1171
1172
	// Get all the versions of this method and find the right one.
1173
	$these_methods = $packageXML->set($method);
1174
	foreach ($these_methods as $this_method)
1175
	{
1176
		// They specified certain versions this part is for.
1177
		if ($this_method->exists('@for'))
1178
		{
1179
			// Don't keep going if this won't work for this version of SMF.
1180
			if (!matchPackageVersion($the_version, $this_method->fetch('@for')))
1181
				continue;
1182
		}
1183
1184
		// Upgrades may go from a certain old version of the mod.
1185
		if ($method == 'upgrade' && $this_method->exists('@from'))
1186
		{
1187
			// Well, this is for the wrong old version...
1188
			if (!matchPackageVersion($previous_version, $this_method->fetch('@from')))
1189
				continue;
1190
		}
1191
1192
		// We've found it!
1193
		$script = $this_method;
1194
		break;
1195
	}
1196
1197
	// Bad news, a matching script wasn't found!
1198
	if (!($script instanceof xmlArray))
1199
		return array();
1200
1201
	// Find all the actions in this method - in theory, these should only be allowed actions. (* means all.)
1202
	$actions = $script->set('*');
1203
	$return = array();
1204
1205
	$temp_auto = 0;
1206
	$temp_path = $packagesdir . '/temp/' . (isset($context['base_path']) ? $context['base_path'] : '');
1207
1208
	$context['readmes'] = array();
1209
	$context['licences'] = array();
1210
1211
	// This is the testing phase... nothing shall be done yet.
1212
	foreach ($actions as $action)
1213
	{
1214
		$actionType = $action->name();
1215
1216
		if (in_array($actionType, array('readme', 'code', 'database', 'modification', 'redirect', 'license')))
1217
		{
1218
			// Allow for translated readme and license files.
1219
			if ($actionType == 'readme' || $actionType == 'license')
1220
			{
1221
				$type = $actionType . 's';
1222
				if ($action->exists('@lang'))
1223
				{
1224
					// Auto-select the language based on either request variable or current language.
1225
					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))
1226
					{
1227
						// In case the user put the blocks in the wrong order.
1228
						if (isset($context[$type]['selected']) && $context[$type]['selected'] == 'default')
1229
							$context[$type][] = 'default';
1230
1231
						$context[$type]['selected'] = $smcFunc['htmlspecialchars']($action->fetch('@lang'));
1232
					}
1233
					else
1234
					{
1235
						// We don't want this now, but we'll allow the user to select to read it.
1236
						$context[$type][] = $smcFunc['htmlspecialchars']($action->fetch('@lang'));
1237
						continue;
1238
					}
1239
				}
1240
				// Fallback when we have no lang parameter.
1241
				else
1242
				{
1243
					// Already selected one for use?
1244
					if (isset($context[$type]['selected']))
1245
					{
1246
						$context[$type][] = 'default';
1247
						continue;
1248
					}
1249
					else
1250
						$context[$type]['selected'] = 'default';
1251
				}
1252
			}
1253
1254
			// @todo Make sure the file actually exists?  Might not work when testing?
1255
			if ($action->exists('@type') && $action->fetch('@type') == 'inline')
1256
			{
1257
				$filename = $temp_path . '$auto_' . $temp_auto++ . (in_array($actionType, array('readme', 'redirect', 'license')) ? '.txt' : ($actionType == 'code' || $actionType == 'database' ? '.php' : '.mod'));
1258
				package_put_contents($filename, $action->fetch('.'));
1259
				$filename = strtr($filename, array($temp_path => ''));
1260
			}
1261
			else
1262
				$filename = $action->fetch('.');
1263
1264
			$return[] = array(
1265
				'type' => $actionType,
1266
				'filename' => $filename,
1267
				'description' => '',
1268
				'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true',
1269
				'boardmod' => $action->exists('@format') && $action->fetch('@format') == 'boardmod',
1270
				'redirect_url' => $action->exists('@url') ? $action->fetch('@url') : '',
1271
				'redirect_timeout' => $action->exists('@timeout') ? (int) $action->fetch('@timeout') : '',
1272
				'parse_bbc' => $action->exists('@parsebbc') && $action->fetch('@parsebbc') == 'true',
1273
				'language' => (($actionType == 'readme' || $actionType == 'license') && $action->exists('@lang') && $action->fetch('@lang') == $language) ? $language : '',
1274
			);
1275
1276
			continue;
1277
		}
1278
		elseif ($actionType == 'hook')
1279
		{
1280
			$return[] = array(
1281
				'type' => $actionType,
1282
				'function' => $action->exists('@function') ? $action->fetch('@function') : '',
1283
				'hook' => $action->exists('@hook') ? $action->fetch('@hook') : $action->fetch('.'),
1284
				'include_file' => $action->exists('@file') ? $action->fetch('@file') : '',
1285
				'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true' ? true : false,
1286
				'object' => $action->exists('@object') && $action->fetch('@object') == 'true' ? true : false,
1287
				'description' => '',
1288
			);
1289
			continue;
1290
		}
1291
		elseif ($actionType == 'credits')
1292
		{
1293
			// quick check of any supplied url
1294
			$url = $action->exists('@url') ? $action->fetch('@url') : '';
1295
			if (strlen(trim($url)) > 0 && substr($url, 0, 7) !== 'http://' && substr($url, 0, 8) !== 'https://')
1296
			{
1297
				$url = 'http://' . $url;
1298
				if (strlen($url) < 8 || (substr($url, 0, 7) !== 'http://' && substr($url, 0, 8) !== 'https://'))
1299
					$url = '';
1300
			}
1301
1302
			$return[] = array(
1303
				'type' => $actionType,
1304
				'url' => $url,
1305
				'license' => $action->exists('@license') ? $action->fetch('@license') : '',
1306
				'licenseurl' => $action->exists('@licenseurl') ? $action->fetch('@licenseurl') : '',
1307
				'copyright' => $action->exists('@copyright') ? $action->fetch('@copyright') : '',
1308
				'title' => $action->fetch('.'),
1309
			);
1310
			continue;
1311
		}
1312
		elseif ($actionType == 'requires')
1313
		{
1314
			$return[] = array(
1315
				'type' => $actionType,
1316
				'id' => $action->exists('@id') ? $action->fetch('@id') : '',
1317
				'version' => $action->exists('@version') ? $action->fetch('@version') : $action->fetch('.'),
1318
				'description' => '',
1319
			);
1320
			continue;
1321
		}
1322
		elseif ($actionType == 'error')
1323
		{
1324
			$return[] = array(
1325
				'type' => 'error',
1326
			);
1327
		}
1328
		elseif (in_array($actionType, array('require-file', 'remove-file', 'require-dir', 'remove-dir', 'move-file', 'move-dir', 'create-file', 'create-dir')))
1329
		{
1330
			$this_action = &$return[];
1331
			$this_action = array(
1332
				'type' => $actionType,
1333
				'filename' => $action->fetch('@name'),
1334
				'description' => $action->fetch('.')
1335
			);
1336
1337
			// If there is a destination, make sure it makes sense.
1338
			if (substr($actionType, 0, 6) != 'remove')
1339
			{
1340
				$this_action['unparsed_destination'] = $action->fetch('@destination');
1341
				$this_action['destination'] = parse_path($action->fetch('@destination')) . '/' . basename($this_action['filename']);
1342
			}
1343
			else
1344
			{
1345
				$this_action['unparsed_filename'] = $this_action['filename'];
1346
				$this_action['filename'] = parse_path($this_action['filename']);
1347
			}
1348
1349
			// If we're moving or requiring (copying) a file.
1350
			if (substr($actionType, 0, 4) == 'move' || substr($actionType, 0, 7) == 'require')
1351
			{
1352
				if ($action->exists('@from'))
1353
					$this_action['source'] = parse_path($action->fetch('@from'));
1354
				else
1355
					$this_action['source'] = $temp_path . $this_action['filename'];
1356
			}
1357
1358
			// Check if these things can be done. (chmod's etc.)
1359
			if ($actionType == 'create-dir')
1360
			{
1361
				if (!mktree($this_action['destination'], false))
1362
				{
1363
					$temp = $this_action['destination'];
1364
					while (!file_exists($temp) && strlen($temp) > 1)
1365
						$temp = dirname($temp);
1366
1367
					$return[] = array(
1368
						'type' => 'chmod',
1369
						'filename' => $temp
1370
					);
1371
				}
1372
			}
1373
			elseif ($actionType == 'create-file')
1374
			{
1375
				if (!mktree(dirname($this_action['destination']), false))
1376
				{
1377
					$temp = dirname($this_action['destination']);
1378
					while (!file_exists($temp) && strlen($temp) > 1)
1379
						$temp = dirname($temp);
1380
1381
					$return[] = array(
1382
						'type' => 'chmod',
1383
						'filename' => $temp
1384
					);
1385
				}
1386
1387
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1388
					$return[] = array(
1389
						'type' => 'chmod',
1390
						'filename' => $this_action['destination']
1391
					);
1392
			}
1393
			elseif ($actionType == 'require-dir')
1394
			{
1395
				if (!mktree($this_action['destination'], false))
1396
				{
1397
					$temp = $this_action['destination'];
1398
					while (!file_exists($temp) && strlen($temp) > 1)
1399
						$temp = dirname($temp);
1400
1401
					$return[] = array(
1402
						'type' => 'chmod',
1403
						'filename' => $temp
1404
					);
1405
				}
1406
			}
1407
			elseif ($actionType == 'require-file')
1408
			{
1409
				if ($action->exists('@theme'))
1410
					$this_action['theme_action'] = $action->fetch('@theme');
1411
1412
				if (!mktree(dirname($this_action['destination']), false))
1413
				{
1414
					$temp = dirname($this_action['destination']);
1415
					while (!file_exists($temp) && strlen($temp) > 1)
1416
						$temp = dirname($temp);
1417
1418
					$return[] = array(
1419
						'type' => 'chmod',
1420
						'filename' => $temp
1421
					);
1422
				}
1423
1424
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1425
					$return[] = array(
1426
						'type' => 'chmod',
1427
						'filename' => $this_action['destination']
1428
					);
1429
			}
1430
			elseif ($actionType == 'move-dir' || $actionType == 'move-file')
1431
			{
1432
				if (!mktree(dirname($this_action['destination']), false))
1433
				{
1434
					$temp = dirname($this_action['destination']);
1435
					while (!file_exists($temp) && strlen($temp) > 1)
1436
						$temp = dirname($temp);
1437
1438
					$return[] = array(
1439
						'type' => 'chmod',
1440
						'filename' => $temp
1441
					);
1442
				}
1443
1444
				if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1445
					$return[] = array(
1446
						'type' => 'chmod',
1447
						'filename' => $this_action['destination']
1448
					);
1449
			}
1450
			elseif ($actionType == 'remove-dir')
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
			elseif ($actionType == 'remove-file')
1459
			{
1460
				if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
1461
					$return[] = array(
1462
						'type' => 'chmod',
1463
						'filename' => $this_action['filename']
1464
					);
1465
			}
1466
		}
1467
		else
1468
		{
1469
			$return[] = array(
1470
				'type' => 'error',
1471
				'error_msg' => 'unknown_action',
1472
				'error_var' => $actionType
1473
			);
1474
		}
1475
	}
1476
1477
	// Only testing - just return a list of things to be done.
1478
	if ($testing_only)
1479
		return $return;
1480
1481
	umask(0);
1482
1483
	$failure = false;
1484
	$not_done = array(array('type' => '!'));
1485
	foreach ($return as $action)
1486
	{
1487
		if (in_array($action['type'], array('modification', 'code', 'database', 'redirect', 'hook', 'credits')))
1488
			$not_done[] = $action;
1489
1490
		if ($action['type'] == 'create-dir')
1491
		{
1492
			if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1493
				$failure |= !mktree($action['destination'], 0777);
1494
		}
1495
		elseif ($action['type'] == 'create-file')
1496
		{
1497
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1498
				$failure |= !mktree(dirname($action['destination']), 0777);
1499
1500
			// Create an empty file.
1501
			package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1502
1503
			if (!file_exists($action['destination']))
1504
				$failure = true;
1505
		}
1506
		elseif ($action['type'] == 'require-dir')
1507
		{
1508
			copytree($action['source'], $action['destination']);
1509
			// Any other theme folders?
1510
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1511
				foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1512
					copytree($action['source'], $theme_destination);
1513
		}
1514
		elseif ($action['type'] == 'require-file')
1515
		{
1516
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1517
				$failure |= !mktree(dirname($action['destination']), 0777);
1518
1519
			package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1520
1521
			$failure |= !copy($action['source'], $action['destination']);
1522
1523
			// Any other theme files?
1524
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1525
				foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1526
				{
1527
					if (!mktree(dirname($theme_destination), 0755) || !is_writable(dirname($theme_destination)))
1528
						$failure |= !mktree(dirname($theme_destination), 0777);
1529
1530
					package_put_contents($theme_destination, package_get_contents($action['source']), $testing_only);
1531
1532
					$failure |= !copy($action['source'], $theme_destination);
1533
				}
1534
		}
1535
		elseif ($action['type'] == 'move-file')
1536
		{
1537
			if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1538
				$failure |= !mktree(dirname($action['destination']), 0777);
1539
1540
			$failure |= !rename($action['source'], $action['destination']);
1541
		}
1542
		elseif ($action['type'] == 'move-dir')
1543
		{
1544
			if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1545
				$failure |= !mktree($action['destination'], 0777);
1546
1547
			$failure |= !rename($action['source'], $action['destination']);
1548
		}
1549
		elseif ($action['type'] == 'remove-dir')
1550
		{
1551
			deltree($action['filename']);
1552
1553
			// Any other theme folders?
1554
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1555
				foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1556
					deltree($theme_destination);
1557
		}
1558
		elseif ($action['type'] == 'remove-file')
1559
		{
1560
			// Make sure the file exists before deleting it.
1561
			if (file_exists($action['filename']))
1562
			{
1563
				package_chmod($action['filename']);
1564
				$failure |= !unlink($action['filename']);
1565
			}
1566
			// The file that was supposed to be deleted couldn't be found.
1567
			else
1568
				$failure = true;
1569
1570
			// Any other theme folders?
1571
			if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1572
				foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1573
					if (file_exists($theme_destination))
1574
						$failure |= !unlink($theme_destination);
1575
					else
1576
						$failure = true;
1577
		}
1578
	}
1579
1580
	return $not_done;
1581
}
1582
1583
/**
1584
 * Checks if version matches any of the versions in `$versions`.
1585
 *
1586
 * - supports comma separated version numbers, with or without whitespace.
1587
 * - supports lower and upper bounds. (1.0-1.2)
1588
 * - returns true if the version matched.
1589
 *
1590
 * @param string $versions The versions that this package will install on
1591
 * @param boolean $reset Whether to reset $near_version
1592
 * @param string $the_version The forum version
1593
 * @return string|bool Highest install value string or false
1594
 */
1595
function matchHighestPackageVersion($versions, $reset, $the_version)
1596
{
1597
	static $near_version = 0;
1598
1599
	if ($reset)
1600
		$near_version = 0;
1601
1602
	// Normalize the $versions while we remove our previous Doh!
1603
	$versions = explode(',', str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($versions)));
1604
1605
	// Loop through each version, save the highest we can find
1606
	foreach ($versions as $for)
1607
	{
1608
		// Adjust for those wild cards
1609
		if (strpos($for, '*') !== false)
1610
			$for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
1611
1612
		// 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
1613
		if (strpos($for, '-') !== false)
1614
			list ($for, $higher) = explode('-', $for);
1615
1616
		// Do the compare, if the for is greater, than what we have but not greater than what we are running .....
1617
		if (compareVersions($near_version, $for) === -1 && compareVersions($for, $the_version) !== 1)
1618
			$near_version = $for;
1619
	}
1620
1621
	return !empty($near_version) ? $near_version : false;
1622
}
1623
1624
/**
1625
 * Checks if the forum version matches any of the available versions from the package install xml.
1626
 * - supports comma separated version numbers, with or without whitespace.
1627
 * - supports lower and upper bounds. (1.0-1.2)
1628
 * - returns true if the version matched.
1629
 *
1630
 * @param string $version The forum version
1631
 * @param string $versions The versions that this package will install on
1632
 * @return bool Whether the version matched
1633
 */
1634
function matchPackageVersion($version, $versions)
1635
{
1636
	// Make sure everything is lowercase and clean of spaces and unpleasant history.
1637
	$version = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
1638
	$versions = explode(',', str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($versions)));
1639
1640
	// Perhaps we do accept anything?
1641
	if (in_array('all', $versions))
1642
		return true;
1643
1644
	// Loop through each version.
1645
	foreach ($versions as $for)
1646
	{
1647
		// Wild card spotted?
1648
		if (strpos($for, '*') !== false)
1649
			$for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
1650
1651
		// Do we have a range?
1652
		if (strpos($for, '-') !== false)
1653
		{
1654
			list ($lower, $upper) = explode('-', $for);
1655
1656
			// Compare the version against lower and upper bounds.
1657
			if (compareVersions($version, $lower) > -1 && compareVersions($version, $upper) < 1)
1658
				return true;
1659
		}
1660
		// Otherwise check if they are equal...
1661
		elseif (compareVersions($version, $for) === 0)
1662
			return true;
1663
	}
1664
1665
	return false;
1666
}
1667
1668
/**
1669
 * Compares two versions and determines if one is newer, older or the same, returns
1670
 * - (-1) if version1 is lower than version2
1671
 * - (0) if version1 is equal to version2
1672
 * - (1) if version1 is higher than version2
1673
 *
1674
 * @param string $version1 The first version
1675
 * @param string $version2 The second version
1676
 * @return int -1 if version2 is greater than version1, 0 if they're equal, 1 if version1 is greater than version2
1677
 */
1678
function compareVersions($version1, $version2)
1679
{
1680
	static $categories;
1681
1682
	$versions = array();
1683
	foreach (array(1 => $version1, $version2) as $id => $version)
1684
	{
1685
		// Clean the version and extract the version parts.
1686
		$clean = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
1687
		preg_match('~(\d+)(?:\.(\d+|))?(?:\.)?(\d+|)(?:(alpha|beta|rc)(\d+|)(?:\.)?(\d+|))?(?:(dev))?(\d+|)~', $clean, $parts);
1688
1689
		// Build an array of parts.
1690
		$versions[$id] = array(
1691
			'major' => !empty($parts[1]) ? (int) $parts[1] : 0,
1692
			'minor' => !empty($parts[2]) ? (int) $parts[2] : 0,
1693
			'patch' => !empty($parts[3]) ? (int) $parts[3] : 0,
1694
			'type' => empty($parts[4]) ? 'stable' : $parts[4],
1695
			'type_major' => !empty($parts[5]) ? (int) $parts[5] : 0,
1696
			'type_minor' => !empty($parts[6]) ? (int) $parts[6] : 0,
1697
			'dev' => !empty($parts[7]),
1698
		);
1699
	}
1700
1701
	// Are they the same, perhaps?
1702
	if ($versions[1] === $versions[2])
1703
		return 0;
1704
1705
	// Get version numbering categories...
1706
	if (!isset($categories))
1707
		$categories = array_keys($versions[1]);
1708
1709
	// Loop through each category.
1710
	foreach ($categories as $category)
1711
	{
1712
		// Is there something for us to calculate?
1713
		if ($versions[1][$category] !== $versions[2][$category])
1714
		{
1715
			// Dev builds are a problematic exception.
1716
			// (stable) dev < (stable) but (unstable) dev = (unstable)
1717
			if ($category == 'type')
1718
				return $versions[1][$category] > $versions[2][$category] ? ($versions[1]['dev'] ? -1 : 1) : ($versions[2]['dev'] ? 1 : -1);
1719
			elseif ($category == 'dev')
1720
				return $versions[1]['dev'] ? ($versions[2]['type'] == 'stable' ? -1 : 0) : ($versions[1]['type'] == 'stable' ? 1 : 0);
1721
			// Otherwise a simple comparison.
1722
			else
1723
				return $versions[1][$category] > $versions[2][$category] ? 1 : -1;
1724
		}
1725
	}
1726
1727
	// They are the same!
1728
	return 0;
1729
}
1730
1731
/**
1732
 * Parses special identifiers out of the specified path.
1733
 *
1734
 * @param string $path The path
1735
 * @return string The parsed path
1736
 */
1737
function parse_path($path)
1738
{
1739
	global $modSettings, $boarddir, $sourcedir, $settings, $temp_path, $txt;
1740
1741
	$dirs = array(
1742
		'\\' => '/',
1743
		'$boarddir' => $boarddir,
1744
		'$sourcedir' => $sourcedir,
1745
		'$avatardir' => $modSettings['avatar_directory'],
1746
		'$avatars_dir' => $modSettings['avatar_directory'],
1747
		'$themedir' => $settings['default_theme_dir'],
1748
		'$imagesdir' => $settings['default_theme_dir'] . '/' . basename($settings['default_images_url']),
1749
		'$themes_dir' => $boarddir . '/Themes',
1750
		'$languagedir' => $settings['default_theme_dir'] . '/languages',
1751
		'$languages_dir' => $settings['default_theme_dir'] . '/languages',
1752
		'$smileysdir' => $modSettings['smileys_dir'],
1753
		'$smileys_dir' => $modSettings['smileys_dir'],
1754
	);
1755
1756
	// do we parse in a package directory?
1757
	if (!empty($temp_path))
1758
		$dirs['$package'] = $temp_path;
1759
1760
	if (strlen($path) == 0)
1761
	{
1762
		loadLanguage('Errors');
1763
		trigger_error($txt['parse_path_filename_required'], E_USER_ERROR);
1764
	}
1765
1766
	return strtr($path, $dirs);
1767
}
1768
1769
/**
1770
 * Deletes a directory, and all the files and direcories inside it.
1771
 * requires access to delete these files.
1772
 *
1773
 * @param string $dir A directory
1774
 * @param bool $delete_dir If false, only deletes everything inside the directory but not the directory itself
1775
 */
1776
function deltree($dir, $delete_dir = true)
1777
{
1778
	/** @var ftp_connection $package_ftp */
1779
	global $package_ftp;
1780
1781
	if (!file_exists($dir))
1782
		return;
1783
1784
	$current_dir = @opendir($dir);
1785
	if ($current_dir == false)
1786
	{
1787
		if ($delete_dir && isset($package_ftp))
1788
		{
1789
			$ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1790
			if (!is_dir($dir))
1791
				$package_ftp->chmod($ftp_file, 0777);
1792
			$package_ftp->unlink($ftp_file);
1793
		}
1794
1795
		return;
1796
	}
1797
1798
	while ($entryname = readdir($current_dir))
1799
	{
1800
		if (in_array($entryname, array('.', '..')))
1801
			continue;
1802
1803
		if (is_dir($dir . '/' . $entryname))
1804
			deltree($dir . '/' . $entryname);
1805
		else
1806
		{
1807
			// Here, 755 doesn't really matter since we're deleting it anyway.
1808
			if (isset($package_ftp))
1809
			{
1810
				$ftp_file = strtr($dir . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1811
1812
				if (!is_writable($dir . '/' . $entryname))
1813
					$package_ftp->chmod($ftp_file, 0777);
1814
				$package_ftp->unlink($ftp_file);
1815
			}
1816
			else
1817
			{
1818
				if (!is_writable($dir . '/' . $entryname))
1819
					smf_chmod($dir . '/' . $entryname, 0777);
1820
				unlink($dir . '/' . $entryname);
1821
			}
1822
		}
1823
	}
1824
1825
	closedir($current_dir);
1826
1827
	if ($delete_dir)
1828
	{
1829
		if (isset($package_ftp))
1830
		{
1831
			$ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1832
			if (!is_writable($dir . '/' . $entryname))
1833
				$package_ftp->chmod($ftp_file, 0777);
1834
			$package_ftp->unlink($ftp_file);
1835
		}
1836
		else
1837
		{
1838
			if (!is_writable($dir))
1839
				smf_chmod($dir, 0777);
1840
			@rmdir($dir);
1841
		}
1842
	}
1843
}
1844
1845
/**
1846
 * Creates the specified tree structure with the mode specified.
1847
 * creates every directory in path until it finds one that already exists.
1848
 *
1849
 * @param string $strPath The path
1850
 * @param int $mode The permission mode for CHMOD (0666, etc.)
1851
 * @return bool True if successful, false otherwise
1852
 */
1853
function mktree($strPath, $mode)
1854
{
1855
	/** @var ftp_connection $package_ftp */
1856
	global $package_ftp;
1857
1858
	if (is_dir($strPath))
1859
	{
1860
		if (!is_writable($strPath) && $mode !== false)
1861
		{
1862
			if (isset($package_ftp))
1863
				$package_ftp->chmod(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')), $mode);
1864
			else
1865
				smf_chmod($strPath, $mode);
1866
		}
1867
1868
		$test = @opendir($strPath);
1869
		if ($test)
1870
		{
1871
			closedir($test);
1872
			return is_writable($strPath);
1873
		}
1874
		else
1875
			return false;
1876
	}
1877
	// Is this an invalid path and/or we can't make the directory?
1878
	if ($strPath == dirname($strPath) || !mktree(dirname($strPath), $mode))
1879
		return false;
1880
1881
	if (!is_writable(dirname($strPath)) && $mode !== false)
1882
	{
1883
		if (isset($package_ftp))
1884
			$package_ftp->chmod(dirname(strtr($strPath, array($_SESSION['pack_ftp']['root'] => ''))), $mode);
1885
		else
1886
			smf_chmod(dirname($strPath), $mode);
1887
	}
1888
1889
	if ($mode !== false && isset($package_ftp))
1890
		return $package_ftp->create_dir(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')));
1891
	elseif ($mode === false)
1892
	{
1893
		$test = @opendir(dirname($strPath));
1894
		if ($test)
1895
		{
1896
			closedir($test);
1897
			return true;
1898
		}
1899
		else
1900
			return false;
1901
	}
1902
	else
1903
	{
1904
		@mkdir($strPath, $mode);
1905
		$test = @opendir($strPath);
1906
		if ($test)
1907
		{
1908
			closedir($test);
1909
			return true;
1910
		}
1911
		else
1912
			return false;
1913
	}
1914
}
1915
1916
/**
1917
 * Copies one directory structure over to another.
1918
 * requires the destination to be writable.
1919
 *
1920
 * @param string $source The directory to copy
1921
 * @param string $destination The directory to copy $source to
1922
 */
1923
function copytree($source, $destination)
1924
{
1925
	/** @var ftp_connection $package_ftp */
1926
	global $package_ftp;
1927
1928
	if (!file_exists($destination) || !is_writable($destination))
1929
		mktree($destination, 0755);
1930
	if (!is_writable($destination))
1931
		mktree($destination, 0777);
1932
1933
	$current_dir = opendir($source);
1934
	if ($current_dir == false)
1935
		return;
1936
1937
	while ($entryname = readdir($current_dir))
1938
	{
1939
		if (in_array($entryname, array('.', '..')))
1940
			continue;
1941
1942
		if (isset($package_ftp))
1943
			$ftp_file = strtr($destination . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1944
1945
		if (is_file($source . '/' . $entryname))
1946
		{
1947
			if (isset($package_ftp) && !file_exists($destination . '/' . $entryname))
1948
				$package_ftp->create_file($ftp_file);
1949
			elseif (!file_exists($destination . '/' . $entryname))
1950
				@touch($destination . '/' . $entryname);
1951
		}
1952
1953
		package_chmod($destination . '/' . $entryname);
1954
1955
		if (is_dir($source . '/' . $entryname))
1956
			copytree($source . '/' . $entryname, $destination . '/' . $entryname);
1957
		elseif (file_exists($destination . '/' . $entryname))
1958
			package_put_contents($destination . '/' . $entryname, package_get_contents($source . '/' . $entryname));
1959
		else
1960
			copy($source . '/' . $entryname, $destination . '/' . $entryname);
1961
	}
1962
1963
	closedir($current_dir);
1964
}
1965
1966
/**
1967
 * Create a tree listing for a given directory path
1968
 *
1969
 * @param string $path The path
1970
 * @param string $sub_path The sub-path
1971
 * @return array An array of information about the files at the specified path/subpath
1972
 */
1973
function listtree($path, $sub_path = '')
1974
{
1975
	$data = array();
1976
1977
	$dir = @dir($path . $sub_path);
1978
	if (!$dir)
1979
		return array();
1980
	while ($entry = $dir->read())
1981
	{
1982
		if ($entry == '.' || $entry == '..')
1983
			continue;
1984
1985
		if (is_dir($path . $sub_path . '/' . $entry))
1986
			$data = array_merge($data, listtree($path, $sub_path . '/' . $entry));
1987
		else
1988
			$data[] = array(
1989
				'filename' => $sub_path == '' ? $entry : $sub_path . '/' . $entry,
1990
				'size' => filesize($path . $sub_path . '/' . $entry),
1991
				'skipped' => false,
1992
			);
1993
	}
1994
	$dir->close();
1995
1996
	return $data;
1997
}
1998
1999
/**
2000
 * Parses a xml-style modification file (file).
2001
 *
2002
 * @param string $file The modification file to parse
2003
 * @param bool $testing Whether we're just doing a test
2004
 * @param bool $undo If true, specifies that the modifications should be undone. Used when uninstalling. Doesn't work with regex.
2005
 * @param array $theme_paths An array of information about custom themes to apply the changes to
2006
 * @return array An array of those changes made.
2007
 */
2008
function parseModification($file, $testing = true, $undo = false, $theme_paths = array())
2009
{
2010
	global $boarddir, $sourcedir, $txt, $modSettings;
2011
2012
	@set_time_limit(600);
2013
	require_once($sourcedir . '/Class-Package.php');
2014
	$xml = new xmlArray(strtr($file, array("\r" => '')));
2015
	$actions = array();
2016
	$everything_found = true;
2017
2018
	if (!$xml->exists('modification') || !$xml->exists('modification/file'))
2019
	{
2020
		$actions[] = array(
2021
			'type' => 'error',
2022
			'filename' => '-',
2023
			'debug' => $txt['package_modification_malformed']
2024
		);
2025
		return $actions;
2026
	}
2027
2028
	// Get the XML data.
2029
	$files = $xml->set('modification/file');
2030
2031
	// Use this for holding all the template changes in this mod.
2032
	$template_changes = array();
2033
	// This is needed to hold the long paths, as they can vary...
2034
	$long_changes = array();
2035
2036
	// First, we need to build the list of all the files likely to get changed.
2037
	foreach ($files as $file)
2038
	{
2039
		// What is the filename we're currently on?
2040
		$filename = parse_path(trim($file->fetch('@name')));
2041
2042
		// Now, we need to work out whether this is even a template file...
2043
		foreach ($theme_paths as $id => $theme)
2044
		{
2045
			// If this filename is relative, if so take a guess at what it should be.
2046
			$real_filename = $filename;
2047
			if (strpos($filename, 'Themes') === 0)
2048
				$real_filename = $boarddir . '/' . $filename;
2049
2050
			if (strpos($real_filename, $theme['theme_dir']) === 0)
2051
			{
2052
				$template_changes[$id][] = substr($real_filename, strlen($theme['theme_dir']) + 1);
2053
				$long_changes[$id][] = $filename;
2054
			}
2055
		}
2056
	}
2057
2058
	// Custom themes to add.
2059
	$custom_themes_add = array();
2060
2061
	// If we have some template changes, we need to build a master link of what new ones are required for the custom themes.
2062
	if (!empty($template_changes[1]))
2063
	{
2064
		foreach ($theme_paths as $id => $theme)
2065
		{
2066
			// Default is getting done anyway, so no need for involvement here.
2067
			if ($id == 1)
2068
				continue;
2069
2070
			// For every template, do we want it? Yea, no, maybe?
2071
			foreach ($template_changes[1] as $index => $template_file)
2072
			{
2073
				// What, it exists and we haven't already got it?! Lordy, get it in!
2074
				if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id]) || !in_array($template_file, $template_changes[$id])))
2075
				{
2076
					// Now let's add it to the "todo" list.
2077
					$custom_themes_add[$long_changes[1][$index]][$id] = $theme['theme_dir'] . '/' . $template_file;
2078
				}
2079
			}
2080
		}
2081
	}
2082
2083
	foreach ($files as $file)
2084
	{
2085
		// This is the actual file referred to in the XML document...
2086
		$files_to_change = array(
2087
			1 => parse_path(trim($file->fetch('@name'))),
2088
		);
2089
2090
		// Sometimes though, we have some additional files for other themes, if we have add them to the mix.
2091
		if (isset($custom_themes_add[$files_to_change[1]]))
2092
			$files_to_change += $custom_themes_add[$files_to_change[1]];
2093
2094
		// Now, loop through all the files we're changing, and, well, change them ;)
2095
		foreach ($files_to_change as $theme => $working_file)
2096
		{
2097
			if ($working_file[0] != '/' && $working_file[1] != ':')
2098
			{
2099
				loadLanguage('Errors');
2100
				trigger_error(sprintf($txt['parse_modification_filename_not_full_path'], $working_file), E_USER_WARNING);
2101
2102
				$working_file = $boarddir . '/' . $working_file;
2103
			}
2104
2105
			// Doesn't exist - give an error or what?
2106
			if (!file_exists($working_file) && (!$file->exists('@error') || !in_array(trim($file->fetch('@error')), array('ignore', 'skip'))))
2107
			{
2108
				$actions[] = array(
2109
					'type' => 'missing',
2110
					'filename' => $working_file,
2111
					'debug' => $txt['package_modification_missing']
2112
				);
2113
2114
				$everything_found = false;
2115
				continue;
2116
			}
2117
			// Skip the file if it doesn't exist.
2118
			elseif (!file_exists($working_file) && $file->exists('@error') && trim($file->fetch('@error')) == 'skip')
2119
			{
2120
				$actions[] = array(
2121
					'type' => 'skipping',
2122
					'filename' => $working_file,
2123
				);
2124
				continue;
2125
			}
2126
			// Okay, we're creating this file then...?
2127
			elseif (!file_exists($working_file))
2128
				$working_data = '';
2129
			// Phew, it exists!  Load 'er up!
2130
			else
2131
				$working_data = str_replace("\r", '', package_get_contents($working_file));
2132
2133
			$actions[] = array(
2134
				'type' => 'opened',
2135
				'filename' => $working_file
2136
			);
2137
2138
			$operations = $file->exists('operation') ? $file->set('operation') : array();
2139
			foreach ($operations as $operation)
2140
			{
2141
				// Convert operation to an array.
2142
				$actual_operation = array(
2143
					'searches' => array(),
2144
					'error' => $operation->exists('@error') && in_array(trim($operation->fetch('@error')), array('ignore', 'fatal', 'required')) ? trim($operation->fetch('@error')) : 'fatal',
2145
				);
2146
2147
				// The 'add' parameter is used for all searches in this operation.
2148
				$add = $operation->exists('add') ? $operation->fetch('add') : '';
2149
2150
				// Grab all search items of this operation (in most cases just 1).
2151
				$searches = $operation->set('search');
2152
				foreach ($searches as $i => $search)
2153
					$actual_operation['searches'][] = array(
2154
						'position' => $search->exists('@position') && in_array(trim($search->fetch('@position')), array('before', 'after', 'replace', 'end')) ? trim($search->fetch('@position')) : 'replace',
2155
						'is_reg_exp' => $search->exists('@regexp') && trim($search->fetch('@regexp')) === 'true',
2156
						'loose_whitespace' => $search->exists('@whitespace') && trim($search->fetch('@whitespace')) === 'loose',
2157
						'search' => $search->fetch('.'),
2158
						'add' => $add,
2159
						'preg_search' => '',
2160
						'preg_replace' => '',
2161
					);
2162
2163
				// At least one search should be defined.
2164
				if (empty($actual_operation['searches']))
2165
				{
2166
					$actions[] = array(
2167
						'type' => 'failure',
2168
						'filename' => $working_file,
2169
						'search' => $search['search'],
2170
						'is_custom' => $theme > 1 ? $theme : 0,
2171
					);
2172
2173
					// Skip to the next operation.
2174
					continue;
2175
				}
2176
2177
				// Reverse the operations in case of undoing stuff.
2178
				if ($undo)
2179
				{
2180
					foreach ($actual_operation['searches'] as $i => $search)
2181
					{
2182
						// Reverse modification of regular expressions are not allowed.
2183
						if ($search['is_reg_exp'])
2184
						{
2185
							if ($actual_operation['error'] === 'fatal')
2186
								$actions[] = array(
2187
									'type' => 'failure',
2188
									'filename' => $working_file,
2189
									'search' => $search['search'],
2190
									'is_custom' => $theme > 1 ? $theme : 0,
2191
								);
2192
2193
							// Continue to the next operation.
2194
							continue 2;
2195
						}
2196
2197
						// The replacement is now the search subject...
2198
						if ($search['position'] === 'replace' || $search['position'] === 'end')
2199
							$actual_operation['searches'][$i]['search'] = $search['add'];
2200
						else
2201
						{
2202
							// Reversing a before/after modification becomes a replacement.
2203
							$actual_operation['searches'][$i]['position'] = 'replace';
2204
2205
							if ($search['position'] === 'before')
2206
								$actual_operation['searches'][$i]['search'] .= $search['add'];
2207
							elseif ($search['position'] === 'after')
2208
								$actual_operation['searches'][$i]['search'] = $search['add'] . $search['search'];
2209
						}
2210
2211
						// ...and the search subject is now the replacement.
2212
						$actual_operation['searches'][$i]['add'] = $search['search'];
2213
					}
2214
				}
2215
2216
				// Sort the search list so the replaces come before the add before/after's.
2217
				if (count($actual_operation['searches']) !== 1)
2218
				{
2219
					$replacements = array();
2220
2221
					foreach ($actual_operation['searches'] as $i => $search)
2222
					{
2223
						if ($search['position'] === 'replace')
2224
						{
2225
							$replacements[] = $search;
2226
							unset($actual_operation['searches'][$i]);
2227
						}
2228
					}
2229
					$actual_operation['searches'] = array_merge($replacements, $actual_operation['searches']);
2230
				}
2231
2232
				// Create regular expression replacements from each search.
2233
				foreach ($actual_operation['searches'] as $i => $search)
2234
				{
2235
					// Not much needed if the search subject is already a regexp.
2236
					if ($search['is_reg_exp'])
2237
						$actual_operation['searches'][$i]['preg_search'] = $search['search'];
2238
					else
2239
					{
2240
						// Make the search subject fit into a regular expression.
2241
						$actual_operation['searches'][$i]['preg_search'] = preg_quote($search['search'], '~');
2242
2243
						// Using 'loose', a random amount of tabs and spaces may be used.
2244
						if ($search['loose_whitespace'])
2245
							$actual_operation['searches'][$i]['preg_search'] = preg_replace('~[ \t]+~', '[ \t]+', $actual_operation['searches'][$i]['preg_search']);
2246
					}
2247
2248
					// Shuzzup.  This is done so we can safely use a regular expression. ($0 is bad!!)
2249
					$actual_operation['searches'][$i]['preg_replace'] = strtr($search['add'], array('$' => '[$PACK' . 'AGE1$]', '\\' => '[$PACK' . 'AGE2$]'));
2250
2251
					// Before, so the replacement comes after the search subject :P
2252
					if ($search['position'] === 'before')
2253
					{
2254
						$actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
2255
						$actual_operation['searches'][$i]['preg_replace'] = '$1' . $actual_operation['searches'][$i]['preg_replace'];
2256
					}
2257
2258
					// After, after what?
2259
					elseif ($search['position'] === 'after')
2260
					{
2261
						$actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
2262
						$actual_operation['searches'][$i]['preg_replace'] .= '$1';
2263
					}
2264
2265
					// Position the replacement at the end of the file (or just before the closing PHP tags).
2266
					elseif ($search['position'] === 'end')
2267
					{
2268
						if ($undo)
2269
						{
2270
							$actual_operation['searches'][$i]['preg_replace'] = '';
2271
						}
2272
						else
2273
						{
2274
							$actual_operation['searches'][$i]['preg_search'] = '(\\n\\?\\>)?$';
2275
							$actual_operation['searches'][$i]['preg_replace'] .= '$1';
2276
						}
2277
					}
2278
2279
					// Testing 1, 2, 3...
2280
					$failed = preg_match('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $working_data) === 0;
2281
2282
					// Nope, search pattern not found.
2283
					if ($failed && $actual_operation['error'] === 'fatal')
2284
					{
2285
						$actions[] = array(
2286
							'type' => 'failure',
2287
							'filename' => $working_file,
2288
							'search' => $actual_operation['searches'][$i]['preg_search'],
2289
							'search_original' => $actual_operation['searches'][$i]['search'],
2290
							'replace_original' => $actual_operation['searches'][$i]['add'],
2291
							'position' => $search['position'],
2292
							'is_custom' => $theme > 1 ? $theme : 0,
2293
							'failed' => $failed,
2294
						);
2295
2296
						$everything_found = false;
2297
						continue;
2298
					}
2299
2300
					// Found, but in this case, that means failure!
2301
					elseif (!$failed && $actual_operation['error'] === 'required')
2302
					{
2303
						$actions[] = array(
2304
							'type' => 'failure',
2305
							'filename' => $working_file,
2306
							'search' => $actual_operation['searches'][$i]['preg_search'],
2307
							'search_original' => $actual_operation['searches'][$i]['search'],
2308
							'replace_original' => $actual_operation['searches'][$i]['add'],
2309
							'position' => $search['position'],
2310
							'is_custom' => $theme > 1 ? $theme : 0,
2311
							'failed' => $failed,
2312
						);
2313
2314
						$everything_found = false;
2315
						continue;
2316
					}
2317
2318
					// Replace it into nothing? That's not an option...unless it's an undoing end.
2319
					if ($search['add'] === '' && ($search['position'] !== 'end' || !$undo))
2320
						continue;
2321
2322
					// Finally, we're doing some replacements.
2323
					$working_data = preg_replace('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $actual_operation['searches'][$i]['preg_replace'], $working_data, 1);
2324
2325
					$actions[] = array(
2326
						'type' => 'replace',
2327
						'filename' => $working_file,
2328
						'search' => $actual_operation['searches'][$i]['preg_search'],
2329
						'replace' => $actual_operation['searches'][$i]['preg_replace'],
2330
						'search_original' => $actual_operation['searches'][$i]['search'],
2331
						'replace_original' => $actual_operation['searches'][$i]['add'],
2332
						'position' => $search['position'],
2333
						'failed' => $failed,
2334
						'ignore_failure' => $failed && $actual_operation['error'] === 'ignore',
2335
						'is_custom' => $theme > 1 ? $theme : 0,
2336
					);
2337
				}
2338
			}
2339
2340
			// Fix any little helper symbols ;).
2341
			$working_data = strtr($working_data, array('[$PACK' . 'AGE1$]' => '$', '[$PACK' . 'AGE2$]' => '\\'));
2342
2343
			package_chmod($working_file);
2344
2345
			if ((file_exists($working_file) && !is_writable($working_file)) || (!file_exists($working_file) && !is_writable(dirname($working_file))))
2346
				$actions[] = array(
2347
					'type' => 'chmod',
2348
					'filename' => $working_file
2349
				);
2350
2351
			if (basename($working_file) == 'Settings_bak.php')
2352
				continue;
2353
2354
			if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2355
			{
2356
				// No, no, not Settings.php!
2357
				if (basename($working_file) == 'Settings.php')
2358
					@copy($working_file, dirname($working_file) . '/Settings_bak.php');
2359
				else
2360
					@copy($working_file, $working_file . '~');
2361
			}
2362
2363
			// Always call this, even if in testing, because it won't really be written in testing mode.
2364
			package_put_contents($working_file, $working_data, $testing);
2365
2366
			$actions[] = array(
2367
				'type' => 'saved',
2368
				'filename' => $working_file,
2369
				'is_custom' => $theme > 1 ? $theme : 0,
2370
			);
2371
		}
2372
	}
2373
2374
	$actions[] = array(
2375
		'type' => 'result',
2376
		'status' => $everything_found
2377
	);
2378
2379
	return $actions;
2380
}
2381
2382
/**
2383
 * Parses a boardmod-style (.mod) modification file
2384
 *
2385
 * @param string $file The modification file to parse
2386
 * @param bool $testing Whether we're just doing a test
2387
 * @param bool $undo If true, specifies that the modifications should be undone. Used when uninstalling.
2388
 * @param array $theme_paths An array of information about custom themes to apply the changes to
2389
 * @return array An array of those changes made.
2390
 */
2391
function parseBoardMod($file, $testing = true, $undo = false, $theme_paths = array())
2392
{
2393
	global $boarddir, $sourcedir, $settings, $modSettings, $txt;
2394
2395
	@set_time_limit(600);
2396
	$file = strtr($file, array("\r" => ''));
2397
2398
	$working_file = null;
2399
	$working_search = null;
2400
	$working_data = '';
2401
	$replace_with = null;
2402
2403
	$actions = array();
2404
	$everything_found = true;
2405
2406
	// This holds all the template changes in the standard mod file.
2407
	$template_changes = array();
2408
	// This is just the temporary file.
2409
	$temp_file = $file;
2410
	// This holds the actual changes on a step counter basis.
2411
	$temp_changes = array();
2412
	$counter = 0;
2413
	$step_counter = 0;
2414
2415
	// 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.
2416
	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)
2417
	{
2418
		$counter++;
2419
2420
		// Get rid of the old stuff.
2421
		$temp_file = substr_replace($temp_file, '', strpos($temp_file, $code_match[0]), strlen($code_match[0]));
2422
2423
		// No interest to us?
2424
		if ($code_match[1] != 'edit file' && $code_match[1] != 'file')
2425
		{
2426
			// It's a step, let's add that to the current steps.
2427
			if (isset($temp_changes[$step_counter]))
2428
				$temp_changes[$step_counter]['changes'][] = $code_match[0];
2429
			continue;
2430
		}
2431
2432
		// We've found a new edit - let's make ourself heard, kind of.
2433
		$step_counter = $counter;
2434
		$temp_changes[$step_counter] = array(
2435
			'title' => $code_match[0],
2436
			'changes' => array(),
2437
		);
2438
2439
		$filename = parse_path($code_match[2]);
2440
2441
		// Now, is this a template file, and if so, which?
2442
		foreach ($theme_paths as $id => $theme)
2443
		{
2444
			// If this filename is relative, if so take a guess at what it should be.
2445
			if (strpos($filename, 'Themes') === 0)
2446
				$filename = $boarddir . '/' . $filename;
2447
2448
			if (strpos($filename, $theme['theme_dir']) === 0)
2449
				$template_changes[$id][$counter] = substr($filename, strlen($theme['theme_dir']) + 1);
2450
		}
2451
	}
2452
2453
	// Reference for what theme ID this action belongs to.
2454
	$theme_id_ref = array();
2455
2456
	// Now we know what templates we need to touch, cycle through each theme and work out what we need to edit.
2457
	if (!empty($template_changes[1]))
2458
	{
2459
		foreach ($theme_paths as $id => $theme)
2460
		{
2461
			// Don't do default, it means nothing to me.
2462
			if ($id == 1)
2463
				continue;
2464
2465
			// Now, for each file do we need to edit it?
2466
			foreach ($template_changes[1] as $pos => $template_file)
2467
			{
2468
				// It does? Add it to the list darlin'.
2469
				if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id][$pos]) || !in_array($template_file, $template_changes[$id][$pos])))
2470
				{
2471
					// Actually add it to the mod file too, so we can see that it will work ;)
2472
					if (!empty($temp_changes[$pos]['changes']))
2473
					{
2474
						$file .= "\n\n" . '<edit file>' . "\n" . $theme['theme_dir'] . '/' . $template_file . "\n" . '</edit file>' . "\n\n" . implode("\n\n", $temp_changes[$pos]['changes']);
2475
						$theme_id_ref[$counter] = $id;
2476
						$counter += 1 + count($temp_changes[$pos]['changes']);
2477
					}
2478
				}
2479
			}
2480
		}
2481
	}
2482
2483
	$counter = 0;
2484
	$is_custom = 0;
2485
	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)
2486
	{
2487
		// This is for working out what we should be editing.
2488
		$counter++;
2489
2490
		// Edit a specific file.
2491
		if ($code_match[1] == 'file' || $code_match[1] == 'edit file')
2492
		{
2493
			// Backup the old file.
2494
			if ($working_file !== null)
2495
			{
2496
				package_chmod($working_file);
2497
2498
				// Don't even dare.
2499
				if (basename($working_file) == 'Settings_bak.php')
2500
					continue;
2501
2502
				if (!is_writable($working_file))
2503
					$actions[] = array(
2504
						'type' => 'chmod',
2505
						'filename' => $working_file
2506
					);
2507
2508
				if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2509
				{
2510
					if (basename($working_file) == 'Settings.php')
2511
						@copy($working_file, dirname($working_file) . '/Settings_bak.php');
2512
					else
2513
						@copy($working_file, $working_file . '~');
2514
				}
2515
2516
				package_put_contents($working_file, $working_data, $testing);
2517
			}
2518
2519
			if ($working_file !== null)
2520
				$actions[] = array(
2521
					'type' => 'saved',
2522
					'filename' => $working_file,
2523
					'is_custom' => $is_custom,
2524
				);
2525
2526
			// Is this "now working on" file a theme specific one?
2527
			$is_custom = isset($theme_id_ref[$counter - 1]) ? $theme_id_ref[$counter - 1] : 0;
2528
2529
			// Make sure the file exists!
2530
			$working_file = parse_path($code_match[2]);
2531
2532
			if ($working_file[0] != '/' && $working_file[1] != ':')
2533
			{
2534
				loadLanguage('Errors');
2535
				trigger_error(sprintf($txt['parse_boardmod_filename_not_full_path'], $working_file), E_USER_WARNING);
2536
2537
				$working_file = $boarddir . '/' . $working_file;
2538
			}
2539
2540
			if (!file_exists($working_file))
2541
			{
2542
				$places_to_check = array($boarddir, $sourcedir, $settings['default_theme_dir'], $settings['default_theme_dir'] . '/languages');
2543
2544
				foreach ($places_to_check as $place)
2545
					if (file_exists($place . '/' . $working_file))
2546
					{
2547
						$working_file = $place . '/' . $working_file;
2548
						break;
2549
					}
2550
			}
2551
2552
			if (file_exists($working_file))
2553
			{
2554
				// Load the new file.
2555
				$working_data = str_replace("\r", '', package_get_contents($working_file));
2556
2557
				$actions[] = array(
2558
					'type' => 'opened',
2559
					'filename' => $working_file
2560
				);
2561
			}
2562
			else
2563
			{
2564
				$actions[] = array(
2565
					'type' => 'missing',
2566
					'filename' => $working_file
2567
				);
2568
2569
				$working_file = null;
2570
				$everything_found = false;
2571
			}
2572
2573
			// Can't be searching for something...
2574
			$working_search = null;
2575
		}
2576
		// Search for a specific string.
2577
		elseif (($code_match[1] == 'search' || $code_match[1] == 'search for') && $working_file !== null)
2578
		{
2579
			if ($working_search !== null)
2580
			{
2581
				$actions[] = array(
2582
					'type' => 'error',
2583
					'filename' => $working_file
2584
				);
2585
2586
				$everything_found = false;
2587
			}
2588
2589
			$working_search = $code_match[2];
2590
		}
2591
		// Must've already loaded a search string.
2592
		elseif ($working_search !== null)
2593
		{
2594
			// This is the base string....
2595
			$replace_with = $code_match[2];
2596
2597
			// Add this afterward...
2598
			if ($code_match[1] == 'add' || $code_match[1] == 'add after')
2599
				$replace_with = $working_search . "\n" . $replace_with;
2600
			// Add this beforehand.
2601
			elseif ($code_match[1] == 'before' || $code_match[1] == 'add before' || $code_match[1] == 'above' || $code_match[1] == 'add above')
2602
				$replace_with .= "\n" . $working_search;
2603
			// Otherwise.. replace with $replace_with ;).
2604
		}
2605
2606
		// If we have a search string, replace string, and open file..
2607
		if ($working_search !== null && $replace_with !== null && $working_file !== null)
2608
		{
2609
			// Make sure it's somewhere in the string.
2610
			if ($undo)
2611
			{
2612
				$temp = $replace_with;
2613
				$replace_with = $working_search;
2614
				$working_search = $temp;
2615
			}
2616
2617
			if (strpos($working_data, $working_search) !== false)
2618
			{
2619
				$working_data = str_replace($working_search, $replace_with, $working_data);
2620
2621
				$actions[] = array(
2622
					'type' => 'replace',
2623
					'filename' => $working_file,
2624
					'search' => $working_search,
2625
					'replace' => $replace_with,
2626
					'search_original' => $working_search,
2627
					'replace_original' => $replace_with,
2628
					'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
2629
					'is_custom' => $is_custom,
2630
					'failed' => false,
2631
				);
2632
			}
2633
			// It wasn't found!
2634
			else
2635
			{
2636
				$actions[] = array(
2637
					'type' => 'failure',
2638
					'filename' => $working_file,
2639
					'search' => $working_search,
2640
					'is_custom' => $is_custom,
2641
					'search_original' => $working_search,
2642
					'replace_original' => $replace_with,
2643
					'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
2644
					'is_custom' => $is_custom,
2645
					'failed' => true,
2646
				);
2647
2648
				$everything_found = false;
2649
			}
2650
2651
			// These don't hold any meaning now.
2652
			$working_search = null;
2653
			$replace_with = null;
2654
		}
2655
2656
		// Get rid of the old tag.
2657
		$file = substr_replace($file, '', strpos($file, $code_match[0]), strlen($code_match[0]));
2658
	}
2659
2660
	// Backup the old file.
2661
	if ($working_file !== null)
2662
	{
2663
		package_chmod($working_file);
2664
2665
		if (!is_writable($working_file))
2666
			$actions[] = array(
2667
				'type' => 'chmod',
2668
				'filename' => $working_file
2669
			);
2670
2671
		if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2672
		{
2673
			if (basename($working_file) == 'Settings.php')
2674
				@copy($working_file, dirname($working_file) . '/Settings_bak.php');
2675
			else
2676
				@copy($working_file, $working_file . '~');
2677
		}
2678
2679
		package_put_contents($working_file, $working_data, $testing);
2680
	}
2681
2682
	if ($working_file !== null)
2683
		$actions[] = array(
2684
			'type' => 'saved',
2685
			'filename' => $working_file,
2686
			'is_custom' => $is_custom,
2687
		);
2688
2689
	$actions[] = array(
2690
		'type' => 'result',
2691
		'status' => $everything_found
2692
	);
2693
2694
	return $actions;
2695
}
2696
2697
/**
2698
 * Get the physical contents of a packages file
2699
 *
2700
 * @param string $filename The package file
2701
 * @return string The contents of the specified file
2702
 */
2703
function package_get_contents($filename)
2704
{
2705
	global $package_cache, $modSettings;
2706
2707
	if (!isset($package_cache))
2708
	{
2709
		$mem_check = setMemoryLimit('128M');
2710
2711
		// Windows doesn't seem to care about the memory_limit.
2712
		if (!empty($modSettings['package_disable_cache']) || $mem_check || stripos(PHP_OS, 'win') !== false)
2713
			$package_cache = array();
2714
		else
2715
			$package_cache = false;
2716
	}
2717
2718
	if (strpos($filename, 'Packages/') !== false || $package_cache === false || !isset($package_cache[$filename]))
2719
		return file_get_contents($filename);
2720
	else
2721
		return $package_cache[$filename];
2722
}
2723
2724
/**
2725
 * Writes data to a file, almost exactly like the file_put_contents() function.
2726
 * uses FTP to create/chmod the file when necessary and available.
2727
 * uses text mode for text mode file extensions.
2728
 * returns the number of bytes written.
2729
 *
2730
 * @param string $filename The name of the file
2731
 * @param string $data The data to write to the file
2732
 * @param bool $testing Whether we're just testing things
2733
 * @return int The length of the data written (in bytes)
2734
 */
2735
function package_put_contents($filename, $data, $testing = false)
2736
{
2737
	/** @var ftp_connection $package_ftp */
2738
	global $package_ftp, $package_cache, $modSettings;
2739
	static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2740
2741
	if (!isset($package_cache))
2742
	{
2743
		// Try to increase the memory limit - we don't want to run out of ram!
2744
		$mem_check = setMemoryLimit('128M');
2745
2746
		if (!empty($modSettings['package_disable_cache']) || $mem_check || stripos(PHP_OS, 'win') !== false)
2747
			$package_cache = array();
2748
		else
2749
			$package_cache = false;
2750
	}
2751
2752
	if (isset($package_ftp))
2753
		$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2754
2755
	if (!file_exists($filename) && isset($package_ftp))
2756
		$package_ftp->create_file($ftp_file);
2757
	elseif (!file_exists($filename))
2758
		@touch($filename);
2759
2760
	package_chmod($filename);
2761
2762
	if (!$testing && (strpos($filename, 'Packages/') !== false || $package_cache === false))
2763
	{
2764
		$fp = @fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2765
2766
		// We should show an error message or attempt a rollback, no?
2767
		if (!$fp)
2768
			return false;
2769
2770
		fwrite($fp, $data);
2771
		fclose($fp);
2772
	}
2773
	elseif (strpos($filename, 'Packages/') !== false || $package_cache === false)
2774
		return strlen($data);
2775
	else
2776
	{
2777
		$package_cache[$filename] = $data;
2778
2779
		// Permission denied, eh?
2780
		$fp = @fopen($filename, 'r+');
2781
		if (!$fp)
2782
			return false;
2783
		fclose($fp);
2784
	}
2785
2786
	return strlen($data);
2787
}
2788
2789
/**
2790
 * Flushes the cache from memory to the filesystem
2791
 *
2792
 * @param bool $trash
2793
 */
2794
function package_flush_cache($trash = false)
2795
{
2796
	/** @var ftp_connection $package_ftp */
2797
	global $package_ftp, $package_cache, $txt;
2798
	static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2799
2800
	if (empty($package_cache))
2801
		return;
2802
2803
	// First, let's check permissions!
2804
	foreach ($package_cache as $filename => $data)
2805
	{
2806
		if (isset($package_ftp))
2807
			$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2808
2809
		if (!file_exists($filename) && isset($package_ftp))
2810
			$package_ftp->create_file($ftp_file);
2811
		elseif (!file_exists($filename))
2812
			@touch($filename);
2813
2814
		$result = package_chmod($filename);
2815
2816
		// if we are not doing our test pass, then lets do a full write check
2817
		// bypass directories when doing this test
2818
		if ((!$trash) && !is_dir($filename))
2819
		{
2820
			// acid test, can we really open this file for writing?
2821
			$fp = ($result) ? fopen($filename, 'r+') : $result;
2822
			if (!$fp)
2823
			{
2824
				// We should have package_chmod()'d them before, no?!
2825
				loadLanguage('Errors');
2826
				trigger_error($txt['package_flush_cache_not_writable'], E_USER_WARNING);
2827
				return;
2828
			}
2829
			fclose($fp);
2830
		}
2831
	}
2832
2833
	if ($trash)
2834
	{
2835
		$package_cache = array();
2836
		return;
2837
	}
2838
2839
	// Write the cache to disk here.
2840
	// Bypass directories when doing so - no data to write & the fopen will crash.
2841
	foreach ($package_cache as $filename => $data)
2842
	{
2843
		if (!is_dir($filename))
2844
		{
2845
			$fp = fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2846
			fwrite($fp, $data);
2847
			fclose($fp);
2848
		}
2849
	}
2850
2851
	$package_cache = array();
2852
}
2853
2854
/**
2855
 * Try to make a file writable.
2856
 *
2857
 * @param string $filename The name of the file
2858
 * @param string $perm_state The permission state - can be either 'writable' or 'execute'
2859
 * @param bool $track_change Whether to track this change
2860
 * @return boolean True if it worked, false if it didn't
2861
 */
2862
function package_chmod($filename, $perm_state = 'writable', $track_change = false)
2863
{
2864
	/** @var ftp_connection $package_ftp */
2865
	global $package_ftp;
2866
2867
	if (file_exists($filename) && is_writable($filename) && $perm_state == 'writable')
2868
		return true;
2869
2870
	// Start off checking without FTP.
2871
	if (!isset($package_ftp) || $package_ftp === false)
2872
	{
2873
		for ($i = 0; $i < 2; $i++)
2874
		{
2875
			$chmod_file = $filename;
2876
2877
			// Start off with a less aggressive test.
2878
			if ($i == 0)
2879
			{
2880
				// If this file doesn't exist, then we actually want to look at whatever parent directory does.
2881
				$subTraverseLimit = 2;
2882
				while (!file_exists($chmod_file) && $subTraverseLimit)
2883
				{
2884
					$chmod_file = dirname($chmod_file);
2885
					$subTraverseLimit--;
2886
				}
2887
2888
				// Keep track of the writable status here.
2889
				$file_permissions = @fileperms($chmod_file);
2890
			}
2891
			else
2892
			{
2893
				// This looks odd, but it's an attempt to work around PHP suExec.
2894
				if (!file_exists($chmod_file) && $perm_state == 'writable')
2895
				{
2896
					$file_permissions = @fileperms(dirname($chmod_file));
2897
2898
					mktree(dirname($chmod_file), 0755);
2899
					@touch($chmod_file);
2900
					smf_chmod($chmod_file, 0755);
2901
				}
2902
				else
2903
					$file_permissions = @fileperms($chmod_file);
2904
			}
2905
2906
			// This looks odd, but it's another attempt to work around PHP suExec.
2907
			if ($perm_state != 'writable')
2908
				smf_chmod($chmod_file, $perm_state == 'execute' ? 0755 : 0644);
2909
			else
2910
			{
2911
				if (!@is_writable($chmod_file))
2912
					smf_chmod($chmod_file, 0755);
2913
				if (!@is_writable($chmod_file))
2914
					smf_chmod($chmod_file, 0777);
2915
				if (!@is_writable(dirname($chmod_file)))
2916
					smf_chmod($chmod_file, 0755);
2917
				if (!@is_writable(dirname($chmod_file)))
2918
					smf_chmod($chmod_file, 0777);
2919
			}
2920
2921
			// The ultimate writable test.
2922
			if ($perm_state == 'writable')
2923
			{
2924
				$fp = is_dir($chmod_file) ? @opendir($chmod_file) : @fopen($chmod_file, 'rb');
2925
				if (@is_writable($chmod_file) && $fp)
2926
				{
2927
					if (!is_dir($chmod_file))
2928
						fclose($fp);
2929
					else
2930
						closedir($fp);
2931
2932
					// It worked!
2933
					if ($track_change)
2934
						$_SESSION['pack_ftp']['original_perms'][$chmod_file] = $file_permissions;
2935
2936
					return true;
2937
				}
2938
			}
2939
			elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$chmod_file]))
2940
				unset($_SESSION['pack_ftp']['original_perms'][$chmod_file]);
2941
		}
2942
2943
		// If we're here we're a failure.
2944
		return false;
2945
	}
2946
	// Otherwise we do have FTP?
2947
	elseif ($package_ftp !== false && !empty($_SESSION['pack_ftp']))
2948
	{
2949
		$ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2950
2951
		// This looks odd, but it's an attempt to work around PHP suExec.
2952
		if (!file_exists($filename) && $perm_state == 'writable')
2953
		{
2954
			$file_permissions = @fileperms(dirname($filename));
2955
2956
			mktree(dirname($filename), 0755);
2957
			$package_ftp->create_file($ftp_file);
2958
			$package_ftp->chmod($ftp_file, 0755);
2959
		}
2960
		else
2961
			$file_permissions = @fileperms($filename);
2962
2963
		if ($perm_state != 'writable')
2964
		{
2965
			$package_ftp->chmod($ftp_file, $perm_state == 'execute' ? 0755 : 0644);
2966
		}
2967
		else
2968
		{
2969
			if (!@is_writable($filename))
2970
				$package_ftp->chmod($ftp_file, 0777);
2971
			if (!@is_writable(dirname($filename)))
2972
				$package_ftp->chmod(dirname($ftp_file), 0777);
2973
		}
2974
2975
		if (@is_writable($filename))
2976
		{
2977
			if ($track_change)
2978
				$_SESSION['pack_ftp']['original_perms'][$filename] = $file_permissions;
2979
2980
			return true;
2981
		}
2982
		elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$filename]))
2983
			unset($_SESSION['pack_ftp']['original_perms'][$filename]);
2984
	}
2985
2986
	// Oh dear, we failed if we get here.
2987
	return false;
2988
}
2989
2990
/**
2991
 * Used to crypt the supplied ftp password in this session
2992
 *
2993
 * @param string $pass The password
2994
 * @return string The encrypted password
2995
 */
2996
function package_crypt($pass)
2997
{
2998
	$n = strlen($pass);
2999
3000
	$salt = session_id();
3001
	while (strlen($salt) < $n)
3002
		$salt .= session_id();
3003
3004
	for ($i = 0; $i < $n; $i++)
3005
		$pass[$i] = chr(ord($pass[$i]) ^ (ord($salt[$i]) - 32));
3006
3007
	return $pass;
3008
}
3009
3010
/**
3011
 * @param string $dir
3012
 * @param string $filename The filename without an extension
3013
 * @param string $ext
3014
 * @return string The filename with a number appended but no extension
3015
 * @since 2.1
3016
 */
3017
function package_unique_filename($dir, $filename, $ext)
3018
{
3019
	if (file_exists($dir . '/' . $filename . $ext))
3020
	{
3021
		$i = 1;
3022
		while (file_exists($dir . '/' . $filename . '_' . $i . $ext))
3023
			$i++;
3024
		$filename .= . '_' . $i;
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected '.' on line 3024 at column 15
Loading history...
3025
	}
3026
3027
	return $filename;
3028
}
3029
3030
/**
3031
 * Creates a backup of forum files prior to modifying them
3032
 *
3033
 * @param string $id The name of the backup
3034
 * @return bool True if it worked, false if it didn't
3035
 */
3036
function package_create_backup($id = 'backup')
3037
{
3038
	global $sourcedir, $boarddir, $packagesdir, $smcFunc;
3039
3040
	$files = array();
3041
3042
	$base_files = array('index.php', 'SSI.php', 'agreement.txt', 'cron.php', 'ssi_examples.php', 'ssi_examples.shtml', 'subscriptions.php');
3043
	foreach ($base_files as $file)
3044
	{
3045
		if (file_exists($boarddir . '/' . $file))
3046
			$files[empty($_REQUEST['use_full_paths']) ? $file : $boarddir . '/' . $file] = $boarddir . '/' . $file;
3047
	}
3048
3049
	$dirs = array(
3050
		$sourcedir => empty($_REQUEST['use_full_paths']) ? 'Sources/' : strtr($sourcedir . '/', '\\', '/')
3051
	);
3052
3053
	$request = $smcFunc['db_query']('', '
3054
		SELECT value
3055
		FROM {db_prefix}themes
3056
		WHERE id_member = {int:no_member}
3057
			AND variable = {string:theme_dir}',
3058
		array(
3059
			'no_member' => 0,
3060
			'theme_dir' => 'theme_dir',
3061
		)
3062
	);
3063
	while ($row = $smcFunc['db_fetch_assoc']($request))
3064
		$dirs[$row['value']] = empty($_REQUEST['use_full_paths']) ? 'Themes/' . basename($row['value']) . '/' : strtr($row['value'] . '/', '\\', '/');
3065
	$smcFunc['db_free_result']($request);
3066
3067
	try
3068
	{
3069
		foreach ($dirs as $dir => $dest)
3070
		{
3071
			$iter = new RecursiveIteratorIterator(
3072
				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
3073
				RecursiveIteratorIterator::CHILD_FIRST,
3074
				RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
3075
			);
3076
3077
			foreach ($iter as $entry => $dir)
3078
			{
3079
				if ($dir->isDir())
3080
					continue;
3081
3082
				if (preg_match('~^(\.{1,2}|CVS|backup.*|help|images|.*\~)$~', $entry) != 0)
3083
					continue;
3084
3085
				$files[empty($_REQUEST['use_full_paths']) ? str_replace(realpath($boarddir), '', $entry) : $entry] = $entry;
3086
			}
3087
		}
3088
		$obj = new ArrayObject($files);
3089
		$iterator = $obj->getIterator();
3090
3091
		if (!file_exists($packagesdir . '/backups'))
3092
			mktree($packagesdir . '/backups', 0777);
3093
		if (!is_writable($packagesdir . '/backups'))
3094
			package_chmod($packagesdir . '/backups');
3095
		$output_file = $packagesdir . '/backups/' . strftime('%Y-%m-%d_') . preg_replace('~[$\\\\/:<>|?*"\']~', '', $id);
3096
		$output_ext = '.tar';
3097
		$output_ext_target = '.tar.gz';
3098
3099
		if (file_exists($output_file . $output_ext_target))
3100
		{
3101
			$i = 2;
3102
			while (file_exists($output_file . '_' . $i . $output_ext_target))
3103
				$i++;
3104
			$output_file = $output_file . '_' . $i . $output_ext;
3105
		}
3106
		else
3107
			$output_file .= $output_ext;
3108
3109
		@set_time_limit(300);
3110
		if (function_exists('apache_reset_timeout'))
3111
			@apache_reset_timeout();
3112
3113
		// Phar doesn't handle open_basedir restrictions very well and throws a PHP Warning. Ignore that.
3114
		set_error_handler(
3115
			function($errno, $errstr, $errfile, $errline)
3116
			{
3117
				// error was suppressed with the @-operator
3118
				if (0 === error_reporting())
3119
					return false;
3120
3121
				if (strpos($errstr, 'PharData::__construct(): open_basedir') === false && strpos($errstr, 'PharData::compress(): open_basedir') === false)
3122
					log_error($errstr, 'general', $errfile, $errline);
3123
3124
				return true;
3125
			}
3126
		);
3127
		$a = new PharData($output_file);
3128
		$a->buildFromIterator($iterator);
3129
		$a->compress(Phar::GZ);
3130
		restore_error_handler();
3131
3132
		/*
3133
		 * Destroying the local var tells PharData to close its internal
3134
		 * file pointer, enabling us to delete the uncompressed tarball.
3135
		 */
3136
		unset($a);
3137
		unlink($output_file);
3138
	}
3139
	catch (Exception $e)
3140
	{
3141
		log_error($e->getMessage(), 'backup');
3142
3143
		return false;
3144
	}
3145
3146
	return true;
3147
}
3148
3149
if (!function_exists('smf_crc32'))
3150
{
3151
	/**
3152
	 * crc32 doesn't work as expected on 64-bit functions - make our own.
3153
	 * https://php.net/crc32#79567
3154
	 *
3155
	 * @param string $number
3156
	 * @return string The crc32
3157
	 */
3158
	function smf_crc32($number)
3159
	{
3160
		$crc = crc32($number);
3161
3162
		if ($crc & 0x80000000)
3163
		{
3164
			$crc ^= 0xffffffff;
3165
			$crc += 1;
3166
			$crc = -$crc;
3167
		}
3168
3169
		return $crc;
3170
	}
3171
}
3172
3173
/**
3174
 * Validate a package during install
3175
 *
3176
 * @param array $package Package data
3177
 * @return array Results from the package validation.
3178
 */
3179
function package_validate_installtest($package)
3180
{
3181
	global $context;
3182
3183
	$context['package_sha256_hash'] = hash_file('sha256', $package['file_name']);
3184
	$sendData = array(array(
3185
		'sha256_hash' => $context['package_sha256_hash'],
3186
		'file_name' => basename($package['file_name']),
3187
		'custom_id' => $package['custom_id'],
3188
		'custom_type' => $package['custom_type'],
3189
	));
3190
3191
	return package_validate_send($sendData);
3192
}
3193
3194
/**
3195
 * Validate multiple packages.
3196
 *
3197
 * @param array $packages Package data
3198
 * @return array Results from the package validation.
3199
 */
3200
function package_validate($packages)
3201
{
3202
	global $context, $smcFunc;
3203
3204
	// Setup our send data.
3205
	$sendData = array();
3206
3207
	// Go through all packages and get them ready to send up.
3208
	foreach ($packages as $id_package => $package)
3209
	{
3210
		$sha256_hash = hash_file('sha256', $package);
3211
		$packageInfo = getPackageInfo($package);
3212
3213
		$packageID = '';
3214
		if (isset($packageInfo['id']))
3215
			$packageID = $packageInfo['id'];
3216
3217
		$packageType = 'modification';
3218
		if (isset($package['type']))
3219
			$packageType = $package['type'];
3220
3221
		$sendData[] = array(
3222
			'sha256_hash' => $sha256_hash,
3223
			'file_name' => basename($package),
3224
			'custom_id' => $packageID,
3225
			'custom_type' => $packageType,
3226
		);
3227
	}
3228
3229
	return package_validate_send($sendData);
3230
}
3231
3232
/**
3233
 * Sending data off to validate packages.
3234
 *
3235
 * @param array $sendData Json encoded data to be sent to the validation servers.
3236
 * @return array Results from the package validation.
3237
 */
3238
function package_validate_send($sendData)
3239
{
3240
	global $context, $smcFunc;
3241
3242
	// First lets get all package servers into here.
3243
	if (empty($context['package_servers']))
3244
	{
3245
		$request = $smcFunc['db_query']('', '
3246
			SELECT id_server, name, validation_url, extra
3247
			FROM {db_prefix}package_servers
3248
			WHERE validation_url != {string:empty}',
3249
			array(
3250
				'empty' => '',
3251
		));
3252
		$context['package_servers'] = array();
3253
		while ($row = $smcFunc['db_fetch_assoc']($request))
3254
			$context['package_servers'][$row['id_server']] = $row;
3255
		$smcFunc['db_free_result']($request);
3256
	}
3257
3258
	$the_version = SMF_VERSION;
3259
	if (!empty($_SESSION['version_emulate']))
3260
		$the_version = $_SESSION['version_emulate'];
3261
3262
	// Test each server.
3263
	$return_data = array();
3264
	foreach ($context['package_servers'] as $id_server => $server)
3265
	{
3266
		$return_data[$id_server] = array();
3267
3268
		// Sub out any variables we support in the validation url.
3269
		$validate_url = strtr($server['validation_url'], array(
3270
			'{SMF_VERSION}' => urlencode($the_version)
3271
		));
3272
3273
		$results = fetch_web_data($validate_url, 'data=' . json_encode($sendData));
3274
3275
		$parsed_data = $smcFunc['json_decode']($results, true);
3276
		if (is_array($parsed_data) && isset($parsed_data['data']) && is_array($parsed_data['data']))
3277
		{
3278
			foreach ($parsed_data['data'] as $sha256_hash => $status)
3279
			{
3280
				if ((string) $status === 'blacklist')
3281
					$context['package_blacklist_found'] = true;
3282
3283
				$return_data[$id_server][(string) $sha256_hash] = 'package_validation_status_' . ((string) $status);
3284
			}
3285
		}
3286
	}
3287
3288
	return $return_data;
3289
}
3290
3291
?>