Project

General

Profile

Download (41.3 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
	if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
485
		if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
486
			$static_output .= " could not download from there or {$priv_url}/{$filename}.\n";
487
			update_output_window($static_output);
488
			return false;
489
		} else if ($base_url == $priv_url) {
490
			$static_output .= " failed to download.\n";
491
			update_output_window($static_output);
492
			return false;
493
		} else {
494
			$static_output .= " [{$osname} repository]\n";
495
			update_output_window($static_output);
496
		}
497
	}
498
	$static_output .= " (extracting)\n";
499
	update_output_window($static_output);
500
	$slaveout = "";
501
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
502
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
503
	if ($raw_depends_list != "") {
504
		$pkg_extension = ".tbz";
505
		foreach($raw_depends_list as $adepend) {
506
			$working_depend = explode(" ", trim($adepend, "\n"));
507
			if (substr($working_depend[1], -4) != ".tbz")
508
				$depend_filename = $working_depend[1] . $pkg_extension;
509
			else
510
				$depend_filename = $working_depend[1];
511
			if (!is_freebsd_pkg_installed($working_depend[1])) {
512
				if (pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url) == false)
513
					return false;
514
			} else {
515
				pkg_debug($working_depend[1] . "\n");
516
			}
517
		}
518
	}
519

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

    
524
	return true;
525
}
526

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

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

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

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

    
619
function eval_once($toeval) {
620
	global $evaled;
621
	if(!$evaled) $evaled = array();
622
	$evalmd5 = md5($toeval);
623
	if(!in_array($evalmd5, $evaled)) {
624
		@eval($toeval);
625
		$evaled[] = $evalmd5;
626
	}
627
	return;
628
}
629

    
630
function install_package_xml($pkg) {
631
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
632

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

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

    
708
				if($afn['prefix'] <> "")
709
					$prefix = $afn['prefix'];
710
				else
711
					$prefix = "/usr/local/pkg/";
712

    
713
				if(!is_dir($prefix)) 
714
					safe_mkdir($prefix);
715
 				$static_output .= $filename . " ";
716
				update_output_window($static_output);
717
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
718
					$static_output .= "failed.\n";
719
					update_output_window($static_output);
720
					return false;
721
				}
722
				if(stristr($filename, ".tgz") <> "") {
723
					pkg_debug("Extracting tarball to -C for " . $filename . "...\n");
724
					$tarout = "";
725
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
726
					pkg_debug(print_r($tarout, true) . "\n");
727
				}
728
				if($pkg_chmod <> "") {
729
					pkg_debug("Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
730
					@chmod($prefix . $filename, $pkg_chmod);
731
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
732
				}
733
				$static_output = $static_orig;
734
                                update_output_window($static_output);
735
			}
736
			$static_output .= "done.\n";
737
			update_output_window($static_output);
738
		}
739
		/*   if a require exists, include it.  this will
740
		 *   show us where an error exists in a package
741
		 *   instead of making us blindly guess
742
		 */
743
		$missing_include = false;
744
		if($pkg_config['include_file'] <> "") {
745
			$static_output .= "Loading package instructions...\n";
746
			update_output_window($static_output);
747
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
748
			if (file_exists($pkg_config['include_file']))
749
				require_once($pkg_config['include_file']);
750
			else {
751
				$missing_include = true;
752
				$static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n";
753
				update_output_window($static_output);
754
				/* XXX: Should undo the steps before this?! */
755
				return false;
756
			}
757
		}
758
		/* sidebar items */
759
		if(is_array($pkg_config['menu'])) {
760
			$static_output .= "Menu items... ";
761
			update_output_window($static_output);
762
			foreach($pkg_config['menu'] as $menu) {
763
				if(is_array($config['installedpackages']['menu']))
764
					foreach($config['installedpackages']['menu'] as $amenu)
765
						if($amenu['name'] == $menu['name'])
766
							continue 2;
767
				$config['installedpackages']['menu'][] = $menu;
768
			}
769
			$static_output .= "done.\n";
770
			update_output_window($static_output);
771
		}
772
		/* integrated tab items */
773
		if(is_array($pkg_config['tabs']['tab'])) {
774
			$static_output .= "Integrated Tab items... ";
775
			update_output_window($static_output);
776
			foreach($pkg_config['tabs']['tab'] as $tab) {
777
				if(is_array($config['installedpackages']['tab']))
778
					foreach($config['installedpackages']['tab'] as $atab)
779
						if($atab['name'] == $tab['name'])
780
							continue 2;
781
				$config['installedpackages']['tab'][] = $tab;
782
			}
783
			$static_output .= "done.\n";
784
			update_output_window($static_output);
785
		}
786
		/* services */
787
		if(is_array($pkg_config['service'])) {
788
			$static_output .= "Services... ";
789
			update_output_window($static_output);
790
			foreach($pkg_config['service'] as $service) {
791
				if(is_array($config['installedpackages']['service']))
792
					foreach($config['installedpackages']['service'] as $aservice)
793
						if($aservice['name'] == $service['name'])
794
							continue 2;
795
				$config['installedpackages']['service'][] = $service;
796
			}
797
			$static_output .= "done.\n";
798
			update_output_window($static_output);
799
		}
800
		/* custom commands */
801
		$static_output .= "Custom commands...\n";
802
		update_output_window($static_output);
803
		if ($missing_include == false) {
804
			if($pkg_config['custom_php_global_functions'] <> "") {
805
				$static_output .= "Executing custom_php_global_functions()...";
806
				update_output_window($static_output);
807
				eval_once($pkg_config['custom_php_global_functions']);
808
				$static_output .= "done.\n";
809
				update_output_window($static_output);
810
			}
811
			if($pkg_config['custom_php_install_command']) {
812
				$static_output .= "Executing custom_php_install_command()...";
813
				update_output_window($static_output);
814
				eval_once($pkg_config['custom_php_install_command']);
815
				$static_output .= "done.\n";
816
				update_output_window($static_output);
817
			}
818
			if($pkg_config['custom_php_resync_config_command'] <> "") {
819
				$static_output .= "Executing custom_php_resync_config_command()...";
820
				update_output_window($static_output);
821
				eval_once($pkg_config['custom_php_resync_config_command']);
822
				$static_output .= "done.\n";
823
				update_output_window($static_output);
824
			}
825
		}
826
	} else {
827
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
828
		update_output_window($static_output);
829
		pkg_debug("Unable to load package configuration. Installation aborted.\n");
830
		if($pkg_interface <> "console") {
831
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
832
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
833
		}
834
		sleep(1);
835
		return false;
836
	}
837

    
838
	/* set up package logging streams */
839
	if($pkg_info['logging']) {
840
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
841
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
842
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
843
		pkg_debug("Adding text to file /etc/syslog.conf\n");
844
		system_syslogd_start();
845
	}
846

    
847
	return true;
848
}
849

    
850
function does_package_depend($pkg) {
851
	// Should not happen, but just in case.
852
	if(!$pkg)
853
		return;
854
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
855
	// If this package has dependency then return true
856
	foreach($pkg_var_db_dir as $pvdd) {
857
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
858
			return true;
859
	}	
860
	// Did not find a record of dependencies, so return false.
861
	return false;
862
}
863

    
864
function delete_package($pkg) {
865
	global $config, $g, $static_output, $vardb;
866

    
867
	if(!$pkg) 
868
		return;
869

    
870
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
871

    
872
	// If package has dependencies then skip it
873
	if(does_package_depend($pkg)) {
874
		$static_output .= "Skipping package deletion for {$pkg} because it is a dependency.\n";
875
		update_output_window($static_output);
876
		return;		
877
	} else {
878
		if($pkg)
879
			$static_output .= "Starting package deletion for {$pkg}...";
880
		update_output_window($static_output);		
881
	}
882

    
883
	$info = "";
884
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
885
	remove_freebsd_package($pkg);
886
	$static_output .= "done.\n";
887
	update_output_window($static_output);
888
	foreach($info as $line) {
889
		$depend = trim(str_replace("@pkgdep ", "", $line), " \n");
890
		// If package has dependencies then skip it
891
		if(!does_package_depend($depend)) 			
892
			delete_package($depend);
893
	}
894

    
895
	/* Rescan directories for what has been left and avoid fooling other programs. */
896
	mwexec("/sbin/ldconfig");
897

    
898
	return;
899
}
900

    
901
function delete_package_xml($pkg) {
902
	global $g, $config, $static_output, $pkg_interface, $rcfileprefix;
903

    
904
	conf_mount_rw();
905

    
906
	$pkgid = get_pkg_id($pkg);
907
	if ($pkgid == -1) {
908
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
909
		update_output_window($static_output);
910
		if($pkg_interface <> "console") {
911
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
912
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
913
		}
914
		ob_flush();
915
		sleep(1);
916
		conf_mount_ro();
917
		return;
918
	}
919
	pkg_debug("Removing {$pkg} package... ");
920
	$static_output .= "Removing {$pkg} components...\n";
921
	update_output_window($static_output);
922
	/* parse package configuration */
923
	$packages = &$config['installedpackages']['package'];
924
	$tabs =& $config['installedpackages']['tab'];
925
	$menus =& $config['installedpackages']['menu'];
926
	$services = &$config['installedpackages']['service'];
927
	$pkg_info =& $packages[$pkgid];
928
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
929
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
930
		/* remove tab items */
931
		if(is_array($pkg_config['tabs'])) {
932
			$static_output .= "Tabs items... ";
933
			update_output_window($static_output);
934
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
935
				foreach($pkg_config['tabs']['tab'] as $tab) {
936
					foreach($tabs as $key => $insttab) {
937
						if($insttab['name'] == $tab['name']) {
938
							unset($tabs[$key]);
939
							break;
940
						}
941
					}
942
				}
943
			}
944
			$static_output .= "done.\n";
945
			update_output_window($static_output);
946
		}
947
		/* remove menu items */
948
		if(is_array($pkg_config['menu'])) {
949
			$static_output .= "Menu items... ";
950
			update_output_window($static_output);
951
			if (is_array($pkg_config['menu']) && is_array($menus)) {
952
				foreach($pkg_config['menu'] as $menu) {
953
					foreach($menus as $key => $instmenu) {
954
						if($instmenu['name'] == $menu['name']) {
955
							unset($menus[$key]);
956
							break;
957
						}
958
					}
959
				}
960
			}
961
			$static_output .= "done.\n";
962
			update_output_window($static_output);
963
		}
964
		/* remove services */
965
		if(is_array($pkg_config['service'])) {
966
			$static_output .= "Services... ";
967
			update_output_window($static_output);
968
			if (is_array($pkg_config['service']) && is_array($services)) {
969
				foreach($pkg_config['service'] as $service) {
970
					foreach($services as $key => $instservice) {
971
						if($instservice['name'] == $service['name']) {
972
							if($g['booting'] != true)
973
								stop_service($service['name']);
974
							if($service['rcfile']) {
975
								$prefix = $rcfileprefix;
976
								if (!empty($service['prefix']))
977
									$prefix = $service['prefix'];
978
								if (file_exists("{$prefix}{$service['rcfile']}"))
979
									@unlink("{$prefix}{$service['rcfile']}");
980
							}
981
							unset($services[$key]);
982
						}
983
					}
984
				}
985
			}
986
			$static_output .= "done.\n";
987
			update_output_window($static_output);
988
		}
989
		/*
990
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
991
		 * 	Same is done during installation.
992
		 */
993
		write_config("Intermediate config write during package removal for {$pkg}.");
994

    
995
		/*
996
		 * If a require exists, include it.  this will
997
		 * show us where an error exists in a package
998
		 * instead of making us blindly guess
999
		 */
1000
		$missing_include = false;
1001
		if($pkg_config['include_file'] <> "") {
1002
			$static_output .= "Loading package instructions...\n";
1003
			update_output_window($static_output);
1004
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
1005
			if (file_exists($pkg_config['include_file']))
1006
				require_once($pkg_config['include_file']);
1007
			else {
1008
				$missing_include = true;
1009
				update_output_window($static_output);
1010
				$static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
1011
			}
1012
		}
1013
		/* ermal
1014
		 * NOTE: It is not possible to handle parse errors on eval.
1015
		 * So we prevent it from being run at all to not interrupt all the other code.
1016
		 */
1017
		if ($missing_include == false) {
1018
			/* evalate this package's global functions and pre deinstall commands */
1019
			if($pkg_config['custom_php_global_functions'] <> "")
1020
				eval_once($pkg_config['custom_php_global_functions']);
1021
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
1022
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
1023
		}
1024
		/* system files */
1025
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
1026
			$static_output .= "System files... ";
1027
			update_output_window($static_output);
1028
			foreach($pkg_config['modify_system']['item'] as $ms)
1029
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
1030

    
1031
			$static_output .= "done.\n";
1032
			update_output_window($static_output);
1033
		}
1034
		/* deinstall commands */
1035
		if($pkg_config['custom_php_deinstall_command'] <> "") {
1036
			$static_output .= "Deinstall commands... ";
1037
			update_output_window($static_output);
1038
			if ($missing_include == false) {
1039
				eval_once($pkg_config['custom_php_deinstall_command']);
1040
				$static_output .= "done.\n";
1041
			} else
1042
				$static_output .= "\nNot executing custom deinstall hook because an include is missing.\n";
1043
			update_output_window($static_output);
1044
		}
1045
		if($pkg_config['include_file'] <> "") {
1046
			$static_output .= "Removing package instructions...";
1047
			update_output_window($static_output);
1048
			pkg_debug("Remove '{$pkg_config['include_file']}'\n");
1049
			unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
1050
			$static_output .= "done.\n";
1051
			update_output_window($static_output);
1052
		}
1053
		/* remove all additional files */
1054
		if(is_array($pkg_config['additional_files_needed'])) {
1055
			$static_output .= "Auxiliary files... ";
1056
			update_output_window($static_output);
1057
			foreach($pkg_config['additional_files_needed'] as $afn) {
1058
				$filename = get_filename_from_url($afn['item'][0]);
1059
				if($afn['prefix'] <> "")
1060
					$prefix = $afn['prefix'];
1061
				else
1062
					$prefix = "/usr/local/pkg/";
1063
				unlink_if_exists($prefix . $filename);
1064
			}
1065
			$static_output .= "done.\n";
1066
			update_output_window($static_output);
1067
		}
1068
		/* package XML file */
1069
		$static_output .= "Package XML... ";
1070
		update_output_window($static_output);
1071
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1072
		$static_output .= "done.\n";
1073
		update_output_window($static_output);
1074
	}
1075
	/* syslog */
1076
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
1077
		$static_output .= "Syslog entries... ";
1078
		update_output_window($static_output);
1079
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1080
		system_syslogd_start();
1081
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1082
		$static_output .= "done.\n";
1083
		update_output_window($static_output);
1084
	}
1085
	
1086
	conf_mount_ro();
1087
	/* remove config.xml entries */
1088
	$static_output .= "Configuration... ";
1089
	update_output_window($static_output);
1090
	unset($config['installedpackages']['package'][$pkgid]);
1091
	$static_output .= "done.\n";
1092
	update_output_window($static_output);
1093
	write_config("Removed {$pkg} package.\n");
1094
}
1095

    
1096
function expand_to_bytes($size) {
1097
	$conv = array(
1098
			"G" =>	"3",
1099
			"M" =>  "2",
1100
			"K" =>  "1",
1101
			"B" =>  "0"
1102
		);
1103
	$suffix = substr($size, -1);
1104
	if(!in_array($suffix, array_keys($conv))) return $size;
1105
	$size = substr($size, 0, -1);
1106
	for($i = 0; $i < $conv[$suffix]; $i++) {
1107
		$size *= 1024;
1108
	}
1109
	return $size;
1110
}
1111

    
1112
function get_pkg_db() {
1113
	global $g;
1114
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1115
}
1116

    
1117
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1118
	if(!$pkgdb)
1119
		$pkgdb = get_pkg_db();
1120
	if(!is_array($alreadyseen))
1121
		$alreadyseen = array();
1122
	if (!is_array($depend))
1123
		$depend = array();
1124
	foreach($depend as $adepend) {
1125
		$pkgname = reverse_strrchr($adepend['name'], '.');
1126
		if(in_array($pkgname, $alreadyseen)) {
1127
			continue;
1128
		} elseif(!in_array($pkgname, $pkgdb)) {
1129
			$size += expand_to_bytes($adepend['size']);
1130
			$alreadyseen[] = $pkgname;
1131
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1132
		}
1133
	}
1134
	return $size;
1135
}
1136

    
1137
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1138
	global $config, $g;
1139
	if((!is_array($pkg)) and ($pkg != 'all'))
1140
		$pkg = array($pkg);
1141
	$pkgdb = get_pkg_db();
1142
	if(!$pkg_info)
1143
		$pkg_info = get_pkg_sizes($pkg);
1144
	foreach($pkg as $apkg) {
1145
		if(!$pkg_info[$apkg])
1146
			continue;
1147
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1148
	}
1149
	return $toreturn;
1150
}
1151

    
1152
function squash_from_bytes($size, $round = "") {
1153
	$conv = array(1 => "B", "K", "M", "G");
1154
	foreach($conv as $div => $suffix) {
1155
		$sizeorig = $size;
1156
		if(($size /= 1024) < 1) {
1157
			if($round) {
1158
				$sizeorig = round($sizeorig, $round);
1159
			}
1160
			return $sizeorig . $suffix;
1161
		}
1162
	}
1163
	return;
1164
}
1165

    
1166
function pkg_reinstall_all() {
1167
	global $g, $config;
1168

    
1169
	@unlink('/conf/needs_package_sync');
1170
	$pkg_id = 0;
1171
	$todo = array();
1172
	if (is_array($config['installedpackages']['package']))
1173
		foreach($config['installedpackages']['package'] as $package)
1174
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1175
	echo "One moment please, reinstalling packages...\n";
1176
	echo " >>> Trying to fetch package info...";
1177
	$pkg_info = get_pkg_info();
1178
	if ($pkg_info) {
1179
		echo " Done.\n";
1180
	} else {
1181
		$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
1182
		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";
1183
		return;
1184
	}
1185
	if(is_array($todo)) {
1186
		foreach($todo as $pkgtodo) {
1187
			$static_output = "";
1188
			if($pkgtodo['name']) {
1189
				uninstall_package($pkgtodo['name']);
1190
				install_package($pkgtodo['name']);
1191
				$pkg_id++;
1192
			}
1193
		}
1194
	}
1195
}
1196

    
1197
?>
(36-36/61)