Project

General

Profile

Download (41 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 - Retrive package information from pfsense.com.
145
 * INPUTS
146
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
147
 *   $info - 'all' to retrive 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
	if(!$builder_package_install) {
320
		if(!file_exists("/tmp/pkg_libs.tgz")) {
321
			$static_output .= "Backing up libraries... ";
322
			update_output_window($static_output);
323
			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`");
324
			$static_output .= "\n";
325
		}
326
	}
327

    
328
	stop_service($pkg_name);
329

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

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

    
352
function force_remove_package($pkg_name) {
353
	delete_package_xml($pkg_name);
354
}
355

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

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

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

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

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

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

    
520
	return true;
521
}
522

    
523
function install_package($package, $pkg_info = "") {
524
	global $g, $config, $static_output, $pkg_interface;
525

    
526
	/* safe side. Write config below will send to ro again. */
527
	conf_mount_rw();
528

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

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

    
615
function eval_once($toeval) {
616
	global $evaled;
617
	if(!$evaled) $evaled = array();
618
	$evalmd5 = md5($toeval);
619
	if(!in_array($evalmd5, $evaled)) {
620
		@eval($toeval);
621
		$evaled[] = $evalmd5;
622
	}
623
	return;
624
}
625

    
626
function install_package_xml($pkg) {
627
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
628

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

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

    
704
				if($afn['prefix'] <> "")
705
					$prefix = $afn['prefix'];
706
				else
707
					$prefix = "/usr/local/pkg/";
708

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

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

    
843
	return true;
844
}
845

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

    
860
function delete_package($pkg) {
861
	global $config, $g, $static_output, $vardb;
862

    
863
	if(!$pkg) 
864
		return;
865

    
866
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
867

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

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

    
891
	/* Rescan directories for what has been left and avoid fooling other programs. */
892
	mwexec("/sbin/ldconfig");
893

    
894
	return;
895
}
896

    
897
function delete_package_xml($pkg) {
898
	global $g, $config, $static_output, $pkg_interface, $rcfileprefix;
899

    
900
	conf_mount_rw();
901

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

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

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

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

    
1108
function get_pkg_db() {
1109
	global $g;
1110
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1111
}
1112

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

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

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

    
1162
function pkg_reinstall_all() {
1163
	global $g, $config;
1164

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

    
1193
?>
(36-36/61)