Issues (1065)

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