Issues (1061)

Sources/Subs-Package.php (3 issues)

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