Project

General

Profile

Download (42.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6
 *   This file contains various functions used by the pfSense package system.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11
 * Copyright (C) 2010 Ermal Lu?i
12
 * Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
13
 * All rights reserved.
14
 * Redistribution and use in source and binary forms, with or without
15
 * modification, are permitted provided that the following conditions are met:
16
 *
17
 * 1. Redistributions of source code must retain the above copyright notice,
18
 * this list of conditions and the following disclaimer.
19
 *
20
 * 2. Redistributions in binary form must reproduce the above copyright
21
 * notice, this list of conditions and the following disclaimer in the
22
 * documentation and/or other materials provided with the distribution.
23
 *
24
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
25
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
26
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
28
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33
 * POSSIBILITY OF SUCH DAMAGE.
34
 *
35
 */
36

    
37
/*
38
	pfSense_BUILDER_BINARIES:	/usr/bin/cd	/usr/bin/tar	/usr/sbin/fifolog_create	/bin/chmod
39
	pfSense_BUILDER_BINARIES:	/usr/sbin/pkg_add	/usr/sbin/pkg_info	/usr/sbin/pkg_delete	/bin/rm
40
	pfSense_MODULE:	pkg
41
*/
42

    
43
require_once("globals.inc");
44
require_once("xmlrpc.inc");
45
require_once("service-utils.inc");
46
if(file_exists("/cf/conf/use_xmlreader"))
47
	require_once("xmlreader.inc");
48
else
49
	require_once("xmlparse.inc");
50
require_once("service-utils.inc");
51
require_once("pfsense-utils.inc");
52

    
53
if(!function_exists("update_status")) {
54
	function update_status($status) {
55
		echo $status . "\n";
56
	}
57
}
58
if(!function_exists("update_output_window")) {
59
	function update_output_window($status) {
60
		echo $status . "\n";
61
	}
62
}
63

    
64
if (!function_exists("pkg_debug")) {
65
	/* set up logging if needed */
66
	function pkg_debug($msg) {
67
		global $g, $debug, $fd_log;
68

    
69
		if (!$debug)
70
			return;
71

    
72
		if (!$fd_log) {
73
			if (!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$package}.log", "w"))
74
				update_output_window("Warning, could not open log for writing.");
75
		}
76
		@fwrite($fd_log, $msg);
77
	}
78
}
79

    
80
$vardb = "/var/db/pkg";
81
safe_mkdir($vardb);
82
$g['platform'] = trim(file_get_contents("/etc/platform"));
83

    
84
conf_mount_rw();
85
if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
86
	safe_mkdir("/usr/local/pkg");
87
	safe_mkdir("/usr/local/pkg/pf");	
88
}
89
conf_mount_ro();
90

    
91
/****f* pkg-utils/remove_package
92
 * NAME
93
 *   remove_package - Removes package from FreeBSD if it exists
94
 * INPUTS
95
 *   $packagestring	- name/string to check for
96
 * RESULT
97
 *   none
98
 * NOTES
99
 *   
100
 ******/
101
function remove_freebsd_package($packagestring) {
102
	exec("/usr/sbin/pkg_delete -x {$packagestring} 2>>/tmp/pkg_delete_errors.txt");
103
}
104

    
105
/****f* pkg-utils/is_package_installed
106
 * NAME
107
 *   is_package_installed - Check whether a package is installed.
108
 * INPUTS
109
 *   $packagename	- name of the package to check
110
 * RESULT
111
 *   boolean	- true if the package is installed, false otherwise
112
 * NOTES
113
 *   This function is deprecated - get_pkg_id() can already check for installation.
114
 ******/
115
function is_package_installed($packagename) {
116
	$pkg = get_pkg_id($packagename);
117
	if($pkg == -1)
118
		return false;
119
	return true;
120
}
121

    
122
/****f* pkg-utils/get_pkg_id
123
 * NAME
124
 *   get_pkg_id - Find a package's numeric ID.
125
 * INPUTS
126
 *   $pkg_name	- name of the package to check
127
 * RESULT
128
 *   integer    - -1 if package is not found, >-1 otherwise
129
 ******/
130
function get_pkg_id($pkg_name) {
131
	global $config;
132

    
133
	if (is_array($config['installedpackages']['package'])) {
134
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
135
			if($pkg['name'] == $pkg_name)
136
				return $idx;
137
		}
138
	}
139
	return -1;
140
}
141

    
142
/****f* pkg-utils/get_pkg_info
143
 * NAME
144
 *   get_pkg_info - Retrieve package information from pfsense.com.
145
 * INPUTS
146
 *   $pkgs - 'all' to retrieve all packages, an array containing package names otherwise
147
 *   $info - 'all' to retrieve all information, an array containing keys otherwise
148
 * RESULT
149
 *   $raw_versions - Array containing retrieved information, indexed by package name.
150
 ******/
151
function get_pkg_info($pkgs = 'all', $info = 'all') {
152
	global $g;
153

    
154
	$freebsd_version = php_uname("r");
155
	$freebsd_machine = php_uname("m");
156
	$params = array(
157
		"pkg" => $pkgs, 
158
		"info" => $info, 
159
		"freebsd_version" => $freebsd_version[0],
160
		"freebsd_machine" => $freebsd_machine
161
	);
162
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
163
	return $resp ? $resp : array();
164
}
165

    
166
function get_pkg_sizes($pkgs = 'all') {
167
	global $config, $g;
168

    
169
	$freebsd_version = php_uname("r");
170
	$freebsd_machine = php_uname("m");
171
	$params = array(
172
		"pkg" => $pkgs, 
173
		"freebsd_version" => $freebsd_version,
174
		"freebsd_machine" => $freebsd_machine
175
	);
176
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
177
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
178
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
179
	$resp = $cli->send($msg, 10);
180
	if(!is_object($resp))
181
		log_error("Could not get response from XMLRPC server!");
182
 	else if (!$resp->faultCode()) {
183
		$raw_versions = $resp->value();
184
		return xmlrpc_value_to_php($raw_versions);
185
	}
186

    
187
	return array();
188
}
189

    
190
/*
191
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
192
 * This function may also print output to the terminal indicating progress.
193
 */
194
function resync_all_package_configs($show_message = false) {
195
	global $config, $pkg_interface, $g;
196

    
197
	log_error("Resyncing configuration for all packages.");
198

    
199
	if (!is_array($config['installedpackages']['package']))
200
		return;
201

    
202
	if($show_message == true)
203
		echo "Syncing packages:";
204

    
205
	conf_mount_rw();
206

    
207
	foreach($config['installedpackages']['package'] as $idx => $package) {
208
		if (empty($package['name']))
209
			continue;
210
		if($show_message == true)
211
			echo " " . $package['name'];
212
		get_pkg_depends($package['name'], "all");
213
		if($g['booting'] != true)
214
			stop_service($package['name']);
215
		sync_package($idx, true, true);
216
		if($pkg_interface == "console") 
217
			echo "\nSyncing packages:";
218
	}
219

    
220
	if($show_message == true)
221
		echo " done.\n";
222

    
223
	@unlink("/conf/needs_package_sync");
224
	conf_mount_ro();
225
}
226

    
227
/*
228
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
229
 *				package is installed.
230
 */
231
function is_freebsd_pkg_installed($pkg) {
232
	if(!$pkg) 
233
		return;
234
	$output = "";
235
	exec("/usr/sbin/pkg_info -E \"{$pkg}*\"", $output, $retval);
236

    
237
	return (intval($retval) == 0);
238
}
239

    
240
/*
241
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
242
 *
243
 * $filetype = "all" || ".xml", ".tgz", etc.
244
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
245
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
246
 *
247
 */
248
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
249
	global $config;
250

    
251
	$pkg_id = get_pkg_id($pkg_name);
252
	if($pkg_id == -1)
253
		return -1; // This package doesn't really exist - exit the function.
254
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
255
		return; // No package belongs to the pkg_id passed to this function.
256

    
257
	$package =& $config['installedpackages']['package'][$pkg_id];
258
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
259
		log_error("The {$package['name']} package is missing required dependencies and is being reinstalled." . $package['configurationfile']);
260
		uninstall_package($package['name']);
261
		if (install_package($package['name']) < 0) {
262
			log_error("Failed reinstalling package {$package['name']}.");
263
			return false;
264
		}
265
	}
266
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
267
	if (!empty($pkg_xml['additional_files_needed'])) {
268
		foreach($pkg_xml['additional_files_needed'] as $item) {
269
			if ($return_nosync == 0 && isset($item['nosync']))
270
				continue; // Do not return depends with nosync set if not required.
271
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
272
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
273
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file)))
274
					continue;
275
			if ($item['prefix'] != "")
276
				$prefix = $item['prefix'];
277
			else
278
				$prefix = "/usr/local/pkg/";
279
			// Ensure that the prefix exists to avoid installation errors.
280
			if(!is_dir($prefix)) 
281
				exec("/bin/mkdir -p {$prefix}");
282
			if(!file_exists($prefix . $depend_file))
283
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
284
			switch ($format) {
285
			case "files":
286
				$depends[] = $prefix . $depend_file;
287
				break;
288
			case "names":
289
				switch ($filetype) {
290
				case "all":
291
					if(preg_match("/\.xml/i", $depend_file)) {
292
						$depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui");
293
						if (!empty($depend_xml))
294
							$depends[] = $depend_xml['name'];
295
					} else
296
						$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
297
					break;
298
				case ".xml":
299
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
300
					if (!empty($depend_xml))
301
						$depends[] = $depend_xml['name'];
302
					break;
303
				default:
304
					$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
305
					break;
306
				}
307
			}
308
		}
309
		return $depends;
310
	}
311
}
312

    
313
function uninstall_package($pkg_name) {
314
	global $config, $static_output;
315
	global $builder_package_install;
316

    
317
	// Back up /usr/local/lib libraries first if
318
	// not running from the builder code.
319
	// also take into account rrd binaries
320
	if(!$builder_package_install) {
321
		if(!file_exists("/tmp/pkg_libs.tgz")) {
322
			$static_output .= "Backing up libraries... ";
323
			update_output_window($static_output);
324
			exec("/usr/bin/tar czPf /tmp/pkg_libs.tgz `/bin/cat /etc/pfSense_md5.txt | /usr/bin/grep 'local/lib' | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1`");
325
			exec("/usr/bin/tar czPf /tmp/pkg_bins.tgz `/bin/cat /etc/pfSense_md5.txt | /usr/bin/grep 'rrd' | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1`");
326
			$static_output .= "\n";
327
		}
328
	}
329

    
330
	stop_service($pkg_name);
331

    
332
	$id = get_pkg_id($pkg_name);
333
	if ($id >= 0) {
334
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
335
		$static_output .= "Removing package...\n";
336
		update_output_window($static_output);
337
		if (is_array($pkg_depends)) {
338
			foreach ($pkg_depends as $pkg_depend)
339
				delete_package($pkg_depend);
340
		}
341
	}
342
	delete_package_xml($pkg_name);
343

    
344
	// Restore libraries that we backed up if not 
345
	// running from the builder code.
346
	if(!$builder_package_install) {
347
		$static_output .= "Cleaning up... ";
348
		update_output_window($static_output);
349
		exec("/usr/bin/tar xzPfU /tmp/pkg_libs.tgz -C /");
350
		exec("/usr/bin/tar xzPfU /tmp/pkg_bins.tgz -C /");
351
		@unlink("/tmp/pkg_libs.tgz");
352
		@unlink("/tmp/pkg_bins.tgz");
353
	}
354
}
355

    
356
function force_remove_package($pkg_name) {
357
	delete_package_xml($pkg_name);
358
}
359

    
360
/*
361
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
362
 */
363
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
364
	global $config, $config_parsed;
365
	global $builder_package_install;
366
	
367
	// If this code is being called by pfspkg_installer 
368
	// which the builder system uses then return (ignore).
369
	if($builder_package_install)
370
		return;
371
	
372
	if(empty($config['installedpackages']['package']))
373
		return;
374
	if(!is_numeric($pkg_name)) {
375
		$pkg_id = get_pkg_id($pkg_name);
376
		if($pkg_id == -1)
377
			return -1; // This package doesn't really exist - exit the function.
378
	} else {
379
		$pkg_id = $pkg_name;
380
		if(empty($config['installedpackages']['package'][$pkg_id]))
381
			return;  // No package belongs to the pkg_id passed to this function.
382
	}
383
        if (is_array($config['installedpackages']['package'][$pkg_id]))
384
		$package =& $config['installedpackages']['package'][$pkg_id];
385
        else
386
		return; /* empty package tag */
387
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
388
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
389
		force_remove_package($package['name']);
390
		return -1;
391
	}
392
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
393
	if(isset($pkg_config['nosync']))
394
		return;
395
	/* Bring in package include files */
396
	if (!empty($pkg_config['include_file'])) {
397
		$include_file = $pkg_config['include_file'];
398
		if (file_exists($include_file))
399
			require_once($include_file);
400
		else {
401
			/* XXX: What the heck is this?! */
402
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
403
			uninstall_package($package['name']);
404
			if (install_package($package['name']) < 0) {
405
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
406
				return -1;
407
			}
408
		}
409
	}
410

    
411
	if(!empty($pkg_config['custom_php_global_functions']))
412
		eval($pkg_config['custom_php_global_functions']);
413
	if(!empty($pkg_config['custom_php_resync_config_command']))
414
		eval($pkg_config['custom_php_resync_config_command']);
415
	if($sync_depends == true) {
416
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
417
		if(is_array($depends)) {
418
			foreach($depends as $item) {
419
				if(!file_exists($item)) {
420
					require_once("notices.inc");
421
					file_notice($package['name'], "The {$package['name']} package is missing required dependencies and must be reinstalled.", "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1);
422
					log_error("Could not find {$item}. Reinstalling package.");
423
					uninstall_package($pkg_name);
424
					if (install_package($pkg_name) < 0) {
425
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
426
						return -1;
427
					}
428
				} else {
429
					$item_config = parse_xml_config_pkg($item, "packagegui");
430
					if (empty($item_config))
431
						continue;
432
					if(isset($item_config['nosync']))
433
						continue;
434
					if (!empty($item_config['include_file'])) {
435
						if (file_exists($item_config['include_file']))	
436
							require_once($item_config['include_file']);
437
						else {
438
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
439
							continue;
440
						}
441
					}
442
					if($item_config['custom_php_global_functions'] <> "")
443
						eval($item_config['custom_php_global_functions']);
444
					if($item_config['custom_php_resync_config_command'] <> "")
445
						eval($item_config['custom_php_resync_config_command']);
446
					if($show_message == true)
447
						print " " . $item_config['name'];
448
				}
449
			}
450
		}
451
	}
452
}
453

    
454
/*
455
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
456
 * 			a progress bar and output window.
457
 */
458
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
459
	global $static_output, $g;
460

    
461
	if (($g['platform'] == "nanobsd") || ($g['platform'] == "embedded")) {
462
		$pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ ";
463
		$pkgstagingdir = "/root/tmp";
464
		if (!is_dir($pkgstagingdir))
465
			mkdir($pkgstagingdir);
466
		$pkgstaging = "-t {$pkgstagingdir}/instmp.XXXXXX";
467
		$fetchdir = $pkgstagingdir;
468
	} else {
469
		$fetchdir = $g['tmp_path'];
470
	}
471

    
472
	$osname = php_uname("s");
473
	$arch =  php_uname("m");
474
	$rel = strtolower(php_uname("r"));
475
	if (substr_count($rel, '-') > 1)
476
		$rel = substr($rel, 0, strrpos($rel, "-"));
477
	$priv_url = "http://ftp2.{$osname}.org/pub/{$osname}/ports/{$arch}/packages-{$rel}/All";
478
	if (empty($base_url))
479
		$base_url = $priv_url;
480
	if (substr($base_url, -1) == "/")
481
		$base_url = substr($base_url, 0, -1);
482
	$fetchto = "{$fetchdir}/apkg_{$filename}";
483
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... ";
484
	update_output_window($static_output);
485
	if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
486
		if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
487
			$static_output .= " could not download from there or {$priv_url}/{$filename}.\n";
488
			update_output_window($static_output);
489
			return false;
490
		} else if ($base_url == $priv_url) {
491
			$static_output .= " failed to download.\n";
492
			update_output_window($static_output);
493
			return false;
494
		} else {
495
			$static_output .= " [{$osname} repository]\n";
496
			update_output_window($static_output);
497
		}
498
	}
499
	$static_output .= " (extracting)\n";
500
	update_output_window($static_output);
501
	$slaveout = "";
502
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
503
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
504
	if ($raw_depends_list != "") {
505
		$pkg_extension = ".tbz";
506
		foreach($raw_depends_list as $adepend) {
507
			$working_depend = explode(" ", trim($adepend, "\n"));
508
			if (substr($working_depend[1], -4) != ".tbz")
509
				$depend_filename = $working_depend[1] . $pkg_extension;
510
			else
511
				$depend_filename = $working_depend[1];
512
			if (!is_freebsd_pkg_installed($working_depend[1])) {
513
				if (pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url) == false)
514
					return false;
515
			} else {
516
				pkg_debug($working_depend[1] . "\n");
517
			}
518
		}
519
	}
520

    
521
	$pkgaddout = "";
522
	exec("{$pkgtmpdir}/usr/sbin/pkg_add {$pkgstaging} -fv {$fetchto} 2>&1", $pkgaddout);
523
	pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\npkg_add successfully completed.\n");
524

    
525
	return true;
526
}
527

    
528
function install_package($package, $pkg_info = "") {
529
	global $g, $config, $static_output, $pkg_interface;
530

    
531
	/* safe side. Write config below will send to ro again. */
532
	conf_mount_rw();
533

    
534
	if($pkg_interface == "console") 	
535
		echo "\n";
536
	/* fetch package information if needed */
537
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
538
		$pkg_info = get_pkg_info(array($package));
539
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
540
		if (empty($pkg_info)) {
541
			conf_mount_ro();
542
			return -1;
543
		}
544
	}
545
	pkg_debug("Beginning package installation.\n");
546
	log_error('Beginning package installation for ' . $pkg_info['name'] . '.');
547
	$static_output .= "Beginning package installation for " . $pkg_info['name'] . "...";
548
	update_status($static_output);
549
	/* fetch the package's configuration file */
550
	if($pkg_info['config_file'] != "") {
551
		$static_output .= "\nDownloading package configuration file... ";
552
		update_output_window($static_output);
553
		pkg_debug("Downloading package configuration file...\n");
554
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
555
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
556
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
557
			pkg_debug("ERROR! Unable to fetch package configuration file. Aborting installation.\n");
558
			if($pkg_interface == "console")
559
				print "\nERROR! Unable to fetch package configuration file. Aborting package installation.\n";
560
			else {
561
				$static_output .= "failed!\n\nInstallation aborted.\n";
562
				update_output_window($static_output);
563
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
564
			}
565
			conf_mount_ro();
566
			return -1;
567
		}
568
		$static_output .= "done.\n";
569
		update_output_window($static_output);
570
	}
571
	/* add package information to config.xml */
572
	$pkgid = get_pkg_id($pkg_info['name']);
573
	$static_output .= "Saving updated package information... ";
574
	update_output_window($static_output);
575
	if($pkgid == -1) {
576
		$config['installedpackages']['package'][] = $pkg_info;
577
		$changedesc = "Installed {$pkg_info['name']} package.";
578
		$to_output = "done.\n";
579
	} else {
580
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
581
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
582
		$to_output = "overwrite!\n";
583
	}
584

    
585
	if(file_exists('/conf/needs_package_sync'))
586
		@unlink('/conf/needs_package_sync');
587
	write_config("Intermediate config write during package install for {$pkg_info['name']}.");
588
	conf_mount_rw(); //Compensate write_config() sending to _ro
589

    
590
	$static_output .= $to_output;
591
	update_output_window($static_output);
592
	/* install other package components */
593
	if (!install_package_xml($package)) {
594
		uninstall_package($package);
595
		write_config($changedesc);
596
		conf_mount_rw(); //Compensate write_config() sending to _ro
597
		$static_output .= "Failed to install package.\n";
598
		update_output_window($static_output);
599
		return -1;
600
	} else {
601
		$static_output .= "Writing configuration... ";
602
		update_output_window($static_output);
603
		write_config($changedesc);
604
		conf_mount_rw(); //Compensate write_config() sending to _ro
605
		$static_output .= "done.\n";
606
		update_output_window($static_output);
607
		if($pkg_info['after_install_info']) 
608
			update_output_window($pkg_info['after_install_info']);	
609
	}
610
	conf_mount_ro();
611
}
612

    
613
function get_after_install_info($package) {
614
	global $pkg_info;
615
	/* fetch package information if needed */
616
	if(!$pkg_info or !is_array($pkg_info[$package])) {
617
		$pkg_info = get_pkg_info(array($package));
618
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
619
	}
620
	if($pkg_info['after_install_info'])
621
		return $pkg_info['after_install_info'];
622
}
623

    
624
function eval_once($toeval) {
625
	global $evaled;
626
	if(!$evaled) $evaled = array();
627
	$evalmd5 = md5($toeval);
628
	if(!in_array($evalmd5, $evaled)) {
629
		@eval($toeval);
630
		$evaled[] = $evalmd5;
631
	}
632
	return;
633
}
634

    
635
function install_package_xml($pkg) {
636
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
637

    
638
	if(($pkgid = get_pkg_id($pkg)) == -1) {
639
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
640
		update_output_window($static_output);
641
		if($pkg_interface <> "console") {
642
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
643
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
644
		}
645
		sleep(1);
646
		return false;
647
	} else
648
		$pkg_info = $config['installedpackages']['package'][$pkgid];
649

    
650
	/* pkg_add the package and its dependencies */
651
	if($pkg_info['depends_on_package_base_url'] != "") {
652
		if($pkg_interface == "console") 
653
			echo "\n";
654
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
655
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
656
		$static_orig = $static_output;
657
		$static_output .= "\n";
658
		update_output_window($static_output);
659
		foreach((array) $pkg_info['depends_on_package'] as $pkgdep) {
660
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
661
			$static_output = $static_orig . "\nChecking for package installation... ";
662
			update_output_window($static_output);
663
			if (!is_freebsd_pkg_installed($pkg_name)) {
664
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
665
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
666
					update_output_window($static_output);
667
					pkg_debug("Package WAS NOT installed properly.\n");
668
					if($pkg_interface <> "console") {
669
						echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
670
						echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
671
					}
672
					sleep(1);
673
					return false;
674
				}
675
			}
676
		}
677
	}
678
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
679
	if(file_exists("/usr/local/pkg/" . $configfile)) {
680
		$static_output .= "Loading package configuration... ";
681
		update_output_window($static_output);
682
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
683
		$static_output .= "done.\n";
684
		update_output_window($static_output);
685
		$static_output .= "Configuring package components...\n";
686
		if (!empty($pkg_config['filter_rules_needed']))
687
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
688
		update_output_window($static_output);
689
		/* modify system files */
690
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
691
			$static_output .= "System files... ";
692
			update_output_window($static_output);
693
			foreach($pkg_config['modify_system']['item'] as $ms) {
694
				if($ms['textneeded']) {
695
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
696
				}
697
			}
698
			$static_output .= "done.\n";
699
			update_output_window($static_output);
700
		}
701
		/* download additional files */
702
		if(is_array($pkg_config['additional_files_needed'])) {
703
			$static_output .= "Additional files... ";
704
			$static_orig = $static_output;
705
			update_output_window($static_output);
706
			foreach($pkg_config['additional_files_needed'] as $afn) {
707
				$filename = get_filename_from_url($afn['item'][0]);
708
				if($afn['chmod'] <> "")
709
					$pkg_chmod = $afn['chmod'];
710
				else
711
					$pkg_chmod = "";
712

    
713
				if($afn['prefix'] <> "")
714
					$prefix = $afn['prefix'];
715
				else
716
					$prefix = "/usr/local/pkg/";
717

    
718
				if(!is_dir($prefix)) 
719
					safe_mkdir($prefix);
720
 				$static_output .= $filename . " ";
721
				update_output_window($static_output);
722
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
723
					$static_output .= "failed.\n";
724
					@unlink($prefix . $filename);
725
					update_output_window($static_output);
726
					return false;
727
				}
728
				if(stristr($filename, ".tgz") <> "") {
729
					pkg_debug("Extracting tarball to -C for " . $filename . "...\n");
730
					$tarout = "";
731
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
732
					pkg_debug(print_r($tarout, true) . "\n");
733
				}
734
				if($pkg_chmod <> "") {
735
					pkg_debug("Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
736
					@chmod($prefix . $filename, $pkg_chmod);
737
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
738
				}
739
				$static_output = $static_orig;
740
                                update_output_window($static_output);
741
			}
742
			$static_output .= "done.\n";
743
			update_output_window($static_output);
744
		}
745
		/*   if a require exists, include it.  this will
746
		 *   show us where an error exists in a package
747
		 *   instead of making us blindly guess
748
		 */
749
		$missing_include = false;
750
		if($pkg_config['include_file'] <> "") {
751
			$static_output .= "Loading package instructions...\n";
752
			update_output_window($static_output);
753
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
754
			if (file_exists($pkg_config['include_file']))
755
				require_once($pkg_config['include_file']);
756
			else {
757
				$missing_include = true;
758
				$static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n";
759
				update_output_window($static_output);
760
				/* XXX: Should undo the steps before this?! */
761
				return false;
762
			}
763
		}
764

    
765
		/* custom commands */
766
		$static_output .= gettext("Custom commands...") . "\n";
767
		update_output_window($static_output);
768
		if ($missing_include == false) {
769
			if($pkg_config['custom_php_global_functions'] <> "") {
770
				$static_output .= gettext("Executing custom_php_global_functions()...");
771
				update_output_window($static_output);
772
				eval_once($pkg_config['custom_php_global_functions']);
773
				$static_output .= gettext("done.") . "\n";
774
				update_output_window($static_output);
775
			}
776
			if($pkg_config['custom_php_install_command']) {
777
				$static_output .= gettext("Executing custom_php_install_command()...");
778
				update_output_window($static_output);
779
				eval_once($pkg_config['custom_php_install_command']);
780
				$static_output .= gettext("done.") . "\n";
781
				update_output_window($static_output);
782
			}
783
			if($pkg_config['custom_php_resync_config_command'] <> "") {
784
				$static_output .= gettext("Executing custom_php_resync_config_command()...");
785
				update_output_window($static_output);
786
				eval_once($pkg_config['custom_php_resync_config_command']);
787
				$static_output .= gettext("done.") . "\n";
788
				update_output_window($static_output);
789
			}
790
		}
791

    
792
		/* custom commands */
793
		$static_output .= "Custom commands...\n";
794
		update_output_window($static_output);
795
		if ($missing_include == false) {
796
			if($pkg_config['custom_php_global_functions'] <> "") {
797
				$static_output .= "Executing custom_php_global_functions()...";
798
				update_output_window($static_output);
799
				eval_once($pkg_config['custom_php_global_functions']);
800
				$static_output .= "done.\n";
801
				update_output_window($static_output);
802
			}
803
			if($pkg_config['custom_php_install_command']) {
804
				$static_output .= "Executing custom_php_install_command()...";
805
				update_output_window($static_output);
806
				eval_once($pkg_config['custom_php_install_command']);
807
				$static_output .= "done.\n";
808
				update_output_window($static_output);
809
			}
810
			if($pkg_config['custom_php_resync_config_command'] <> "") {
811
				$static_output .= "Executing custom_php_resync_config_command()...";
812
				update_output_window($static_output);
813
				eval_once($pkg_config['custom_php_resync_config_command']);
814
				$static_output .= "done.\n";
815
				update_output_window($static_output);
816
			}
817
		}
818
		/* sidebar items */
819
		if(is_array($pkg_config['menu'])) {
820
			$static_output .= "Menu items... ";
821
			update_output_window($static_output);
822
			foreach($pkg_config['menu'] as $menu) {
823
				if(is_array($config['installedpackages']['menu'])) {
824
					foreach($config['installedpackages']['menu'] as $amenu)
825
						if($amenu['name'] == $menu['name'])
826
							continue 2;
827
				} else
828
					$config['installedpackages']['menu'] = array();
829
				$config['installedpackages']['menu'][] = $menu;
830
			}
831
			$static_output .= "done.\n";
832
			update_output_window($static_output);
833
		}
834
		/* integrated tab items */
835
		if(is_array($pkg_config['tabs']['tab'])) {
836
			$static_output .= "Integrated Tab items... ";
837
			update_output_window($static_output);
838
			foreach($pkg_config['tabs']['tab'] as $tab) {
839
				if(is_array($config['installedpackages']['tab'])) {
840
					foreach($config['installedpackages']['tab'] as $atab)
841
						if($atab['name'] == $tab['name'])
842
							continue 2;
843
				} else
844
					$config['installedpackages']['tab'] = array();
845
				$config['installedpackages']['tab'][] = $tab;
846
			}
847
			$static_output .= "done.\n";
848
			update_output_window($static_output);
849
		}
850
		/* services */
851
		if(is_array($pkg_config['service'])) {
852
			$static_output .= "Services... ";
853
			update_output_window($static_output);
854
			foreach($pkg_config['service'] as $service) {
855
				if(is_array($config['installedpackages']['service'])) {
856
					foreach($config['installedpackages']['service'] as $aservice)
857
						if($aservice['name'] == $service['name'])
858
							continue 2;
859
				} else
860
					$config['installedpackages']['service'] = array();
861
				$config['installedpackages']['service'][] = $service;
862
			}
863
			$static_output .= "done.\n";
864
			update_output_window($static_output);
865
		}
866
	} else {
867
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
868
		update_output_window($static_output);
869
		pkg_debug("Unable to load package configuration. Installation aborted.\n");
870
		if($pkg_interface <> "console") {
871
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
872
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
873
		}
874
		sleep(1);
875
		return false;
876
	}
877

    
878
	/* set up package logging streams */
879
	if($pkg_info['logging']) {
880
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
881
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
882
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
883
		pkg_debug("Adding text to file /etc/syslog.conf\n");
884
		system_syslogd_start();
885
	}
886

    
887
	return true;
888
}
889

    
890
function does_package_depend($pkg) {
891
	// Should not happen, but just in case.
892
	if(!$pkg)
893
		return;
894
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
895
	// If this package has dependency then return true
896
	foreach($pkg_var_db_dir as $pvdd) {
897
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
898
			return true;
899
	}	
900
	// Did not find a record of dependencies, so return false.
901
	return false;
902
}
903

    
904
function delete_package($pkg) {
905
	global $config, $g, $static_output, $vardb;
906

    
907
	if(!$pkg) 
908
		return;
909

    
910
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
911

    
912
	// If package has dependencies then skip it
913
	if(does_package_depend($pkg)) {
914
		$static_output .= "Skipping package deletion for {$pkg} because it is a dependency.\n";
915
		update_output_window($static_output);
916
		return;		
917
	} else {
918
		if($pkg)
919
			$static_output .= "Starting package deletion for {$pkg}...";
920
		update_output_window($static_output);		
921
	}
922

    
923
	$info = "";
924
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
925
	remove_freebsd_package($pkg);
926
	$static_output .= "done.\n";
927
	update_output_window($static_output);
928
	foreach($info as $line) {
929
		$depend = trim(str_replace("@pkgdep ", "", $line), " \n");
930
		// If package has dependencies then skip it
931
		if(!does_package_depend($depend)) 			
932
			delete_package($depend);
933
	}
934

    
935
	/* Rescan directories for what has been left and avoid fooling other programs. */
936
	mwexec("/sbin/ldconfig");
937

    
938
	return;
939
}
940

    
941
function delete_package_xml($pkg) {
942
	global $g, $config, $static_output, $pkg_interface, $rcfileprefix;
943

    
944
	conf_mount_rw();
945

    
946
	$pkgid = get_pkg_id($pkg);
947
	if ($pkgid == -1) {
948
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
949
		update_output_window($static_output);
950
		if($pkg_interface <> "console") {
951
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
952
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
953
		}
954
		ob_flush();
955
		sleep(1);
956
		conf_mount_ro();
957
		return;
958
	}
959
	pkg_debug("Removing {$pkg} package... ");
960
	$static_output .= "Removing {$pkg} components...\n";
961
	update_output_window($static_output);
962
	/* parse package configuration */
963
	$packages = &$config['installedpackages']['package'];
964
	$tabs =& $config['installedpackages']['tab'];
965
	$menus =& $config['installedpackages']['menu'];
966
	$services = &$config['installedpackages']['service'];
967
	$pkg_info =& $packages[$pkgid];
968
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
969
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
970
		/* remove tab items */
971
		if(is_array($pkg_config['tabs'])) {
972
			$static_output .= "Tabs items... ";
973
			update_output_window($static_output);
974
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
975
				foreach($pkg_config['tabs']['tab'] as $tab) {
976
					foreach($tabs as $key => $insttab) {
977
						if($insttab['name'] == $tab['name']) {
978
							unset($tabs[$key]);
979
							break;
980
						}
981
					}
982
				}
983
			}
984
			$static_output .= "done.\n";
985
			update_output_window($static_output);
986
		}
987
		/* remove menu items */
988
		if(is_array($pkg_config['menu'])) {
989
			$static_output .= "Menu items... ";
990
			update_output_window($static_output);
991
			if (is_array($pkg_config['menu']) && is_array($menus)) {
992
				foreach($pkg_config['menu'] as $menu) {
993
					foreach($menus as $key => $instmenu) {
994
						if($instmenu['name'] == $menu['name']) {
995
							unset($menus[$key]);
996
							break;
997
						}
998
					}
999
				}
1000
			}
1001
			$static_output .= "done.\n";
1002
			update_output_window($static_output);
1003
		}
1004
		/* remove services */
1005
		if(is_array($pkg_config['service'])) {
1006
			$static_output .= "Services... ";
1007
			update_output_window($static_output);
1008
			if (is_array($pkg_config['service']) && is_array($services)) {
1009
				foreach($pkg_config['service'] as $service) {
1010
					foreach($services as $key => $instservice) {
1011
						if($instservice['name'] == $service['name']) {
1012
							if($g['booting'] != true)
1013
								stop_service($service['name']);
1014
							if($service['rcfile']) {
1015
								$prefix = $rcfileprefix;
1016
								if (!empty($service['prefix']))
1017
									$prefix = $service['prefix'];
1018
								if (file_exists("{$prefix}{$service['rcfile']}"))
1019
									@unlink("{$prefix}{$service['rcfile']}");
1020
							}
1021
							unset($services[$key]);
1022
						}
1023
					}
1024
				}
1025
			}
1026
			$static_output .= "done.\n";
1027
			update_output_window($static_output);
1028
		}
1029
		/*
1030
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
1031
		 * 	Same is done during installation.
1032
		 */
1033
		write_config("Intermediate config write during package removal for {$pkg}.");
1034
		conf_mount_rw(); //Compensate for write_config() sending to _ro
1035

    
1036
		/*
1037
		 * If a require exists, include it.  this will
1038
		 * show us where an error exists in a package
1039
		 * instead of making us blindly guess
1040
		 */
1041
		$missing_include = false;
1042
		if($pkg_config['include_file'] <> "") {
1043
			$static_output .= "Loading package instructions...\n";
1044
			update_output_window($static_output);
1045
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
1046
			if (file_exists($pkg_config['include_file']))
1047
				require_once($pkg_config['include_file']);
1048
			else {
1049
				$missing_include = true;
1050
				update_output_window($static_output);
1051
				$static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
1052
			}
1053
		}
1054
		/* ermal
1055
		 * NOTE: It is not possible to handle parse errors on eval.
1056
		 * So we prevent it from being run at all to not interrupt all the other code.
1057
		 */
1058
		if ($missing_include == false) {
1059
			/* evalate this package's global functions and pre deinstall commands */
1060
			if($pkg_config['custom_php_global_functions'] <> "")
1061
				eval_once($pkg_config['custom_php_global_functions']);
1062
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
1063
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
1064
		}
1065
		/* system files */
1066
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
1067
			$static_output .= "System files... ";
1068
			update_output_window($static_output);
1069
			foreach($pkg_config['modify_system']['item'] as $ms)
1070
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
1071

    
1072
			$static_output .= "done.\n";
1073
			update_output_window($static_output);
1074
		}
1075
		/* deinstall commands */
1076
		if($pkg_config['custom_php_deinstall_command'] <> "") {
1077
			$static_output .= "Deinstall commands... ";
1078
			update_output_window($static_output);
1079
			if ($missing_include == false) {
1080
				eval_once($pkg_config['custom_php_deinstall_command']);
1081
				$static_output .= "done.\n";
1082
			} else
1083
				$static_output .= "\nNot executing custom deinstall hook because an include is missing.\n";
1084
			update_output_window($static_output);
1085
		}
1086
		if($pkg_config['include_file'] <> "") {
1087
			$static_output .= "Removing package instructions...";
1088
			update_output_window($static_output);
1089
			pkg_debug("Remove '{$pkg_config['include_file']}'\n");
1090
			unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
1091
			$static_output .= "done.\n";
1092
			update_output_window($static_output);
1093
		}
1094
		/* remove all additional files */
1095
		if(is_array($pkg_config['additional_files_needed'])) {
1096
			$static_output .= "Auxiliary files... ";
1097
			update_output_window($static_output);
1098
			foreach($pkg_config['additional_files_needed'] as $afn) {
1099
				$filename = get_filename_from_url($afn['item'][0]);
1100
				if($afn['prefix'] <> "")
1101
					$prefix = $afn['prefix'];
1102
				else
1103
					$prefix = "/usr/local/pkg/";
1104
				unlink_if_exists($prefix . $filename);
1105
			}
1106
			$static_output .= "done.\n";
1107
			update_output_window($static_output);
1108
		}
1109
		/* package XML file */
1110
		$static_output .= "Package XML... ";
1111
		update_output_window($static_output);
1112
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1113
		$static_output .= "done.\n";
1114
		update_output_window($static_output);
1115
	}
1116
	/* syslog */
1117
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
1118
		$static_output .= "Syslog entries... ";
1119
		update_output_window($static_output);
1120
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1121
		system_syslogd_start();
1122
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1123
		$static_output .= "done.\n";
1124
		update_output_window($static_output);
1125
	}
1126
	
1127
	conf_mount_ro();
1128
	/* remove config.xml entries */
1129
	$static_output .= "Configuration... ";
1130
	update_output_window($static_output);
1131
	unset($config['installedpackages']['package'][$pkgid]);
1132
	$static_output .= "done.\n";
1133
	update_output_window($static_output);
1134
	write_config("Removed {$pkg} package.\n");
1135
}
1136

    
1137
function expand_to_bytes($size) {
1138
	$conv = array(
1139
			"G" =>	"3",
1140
			"M" =>  "2",
1141
			"K" =>  "1",
1142
			"B" =>  "0"
1143
		);
1144
	$suffix = substr($size, -1);
1145
	if(!in_array($suffix, array_keys($conv))) return $size;
1146
	$size = substr($size, 0, -1);
1147
	for($i = 0; $i < $conv[$suffix]; $i++) {
1148
		$size *= 1024;
1149
	}
1150
	return $size;
1151
}
1152

    
1153
function get_pkg_db() {
1154
	global $g;
1155
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1156
}
1157

    
1158
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1159
	if(!$pkgdb)
1160
		$pkgdb = get_pkg_db();
1161
	if(!is_array($alreadyseen))
1162
		$alreadyseen = array();
1163
	if (!is_array($depend))
1164
		$depend = array();
1165
	foreach($depend as $adepend) {
1166
		$pkgname = reverse_strrchr($adepend['name'], '.');
1167
		if(in_array($pkgname, $alreadyseen)) {
1168
			continue;
1169
		} elseif(!in_array($pkgname, $pkgdb)) {
1170
			$size += expand_to_bytes($adepend['size']);
1171
			$alreadyseen[] = $pkgname;
1172
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1173
		}
1174
	}
1175
	return $size;
1176
}
1177

    
1178
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1179
	global $config, $g;
1180
	if((!is_array($pkg)) and ($pkg != 'all'))
1181
		$pkg = array($pkg);
1182
	$pkgdb = get_pkg_db();
1183
	if(!$pkg_info)
1184
		$pkg_info = get_pkg_sizes($pkg);
1185
	foreach($pkg as $apkg) {
1186
		if(!$pkg_info[$apkg])
1187
			continue;
1188
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1189
	}
1190
	return $toreturn;
1191
}
1192

    
1193
function squash_from_bytes($size, $round = "") {
1194
	$conv = array(1 => "B", "K", "M", "G");
1195
	foreach($conv as $div => $suffix) {
1196
		$sizeorig = $size;
1197
		if(($size /= 1024) < 1) {
1198
			if($round) {
1199
				$sizeorig = round($sizeorig, $round);
1200
			}
1201
			return $sizeorig . $suffix;
1202
		}
1203
	}
1204
	return;
1205
}
1206

    
1207
function pkg_reinstall_all() {
1208
	global $g, $config;
1209

    
1210
	@unlink('/conf/needs_package_sync');
1211
	$pkg_id = 0;
1212
	$todo = array();
1213
	if (is_array($config['installedpackages']['package'])) {
1214
		foreach($config['installedpackages']['package'] as $package)
1215
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1216

    
1217
		echo "One moment please, reinstalling packages...\n";
1218
		echo " >>> Trying to fetch package info...";
1219
		$pkg_info = get_pkg_info();
1220
		if ($pkg_info) {
1221
			echo " Done.\n";
1222
		} else {
1223
			$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
1224
			echo "\n" . sprintf(gettext(' >>> Unable to communicate with %1$s. Please verify DNS and interface configuration, and that %2$s has functional Internet connectivity.'), $xmlrpc_base_url, $g['product_name']) . "\n";
1225
			return;
1226
		}
1227
		foreach($todo as $pkgtodo) {
1228
			$static_output = "";
1229
			if($pkgtodo['name']) {
1230
				uninstall_package($pkgtodo['name']);
1231
				install_package($pkgtodo['name']);
1232
				$pkg_id++;
1233
			}
1234
		}
1235
	}
1236
}
1237

    
1238
?>
(37-37/62)