Project

General

Profile

Download (42.6 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
		if($pkg_info['after_install_info']) 
603
			update_output_window($pkg_info['after_install_info']);	
604
	}
605
}
606

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

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

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

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

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

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

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

    
758
		/* custom commands */
759
		$static_output .= gettext("Custom commands...") . "\n";
760
		update_output_window($static_output);
761
		if ($missing_include == false) {
762
			if($pkg_config['custom_php_global_functions'] <> "") {
763
				$static_output .= gettext("Executing custom_php_global_functions()...");
764
				update_output_window($static_output);
765
				eval_once($pkg_config['custom_php_global_functions']);
766
				$static_output .= gettext("done.") . "\n";
767
				update_output_window($static_output);
768
			}
769
			if($pkg_config['custom_php_install_command']) {
770
				$static_output .= gettext("Executing custom_php_install_command()...");
771
				update_output_window($static_output);
772
				eval_once($pkg_config['custom_php_install_command']);
773
				$static_output .= gettext("done.") . "\n";
774
				update_output_window($static_output);
775
			}
776
			if($pkg_config['custom_php_resync_config_command'] <> "") {
777
				$static_output .= gettext("Executing custom_php_resync_config_command()...");
778
				update_output_window($static_output);
779
				eval_once($pkg_config['custom_php_resync_config_command']);
780
				$static_output .= gettext("done.") . "\n";
781
				update_output_window($static_output);
782
			}
783
		}
784

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

    
871
	/* set up package logging streams */
872
	if($pkg_info['logging']) {
873
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
874
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
875
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
876
		pkg_debug("Adding text to file /etc/syslog.conf\n");
877
		system_syslogd_start();
878
	}
879

    
880
	return true;
881
}
882

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

    
897
function delete_package($pkg) {
898
	global $config, $g, $static_output, $vardb;
899

    
900
	if(!$pkg) 
901
		return;
902

    
903
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
904

    
905
	// If package has dependencies then skip it
906
	if(does_package_depend($pkg)) {
907
		$static_output .= "Skipping package deletion for {$pkg} because it is a dependency.\n";
908
		update_output_window($static_output);
909
		return;		
910
	} else {
911
		if($pkg)
912
			$static_output .= "Starting package deletion for {$pkg}...";
913
		update_output_window($static_output);		
914
	}
915

    
916
	$info = "";
917
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
918
	remove_freebsd_package($pkg);
919
	$static_output .= "done.\n";
920
	update_output_window($static_output);
921
	foreach($info as $line) {
922
		$depend = trim(str_replace("@pkgdep ", "", $line), " \n");
923
		// If package has dependencies then skip it
924
		if(!does_package_depend($depend)) 			
925
			delete_package($depend);
926
	}
927

    
928
	/* Rescan directories for what has been left and avoid fooling other programs. */
929
	mwexec("/sbin/ldconfig");
930

    
931
	return;
932
}
933

    
934
function delete_package_xml($pkg) {
935
	global $g, $config, $static_output, $pkg_interface, $rcfileprefix;
936

    
937
	conf_mount_rw();
938

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

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

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

    
1129
function expand_to_bytes($size) {
1130
	$conv = array(
1131
			"G" =>	"3",
1132
			"M" =>  "2",
1133
			"K" =>  "1",
1134
			"B" =>  "0"
1135
		);
1136
	$suffix = substr($size, -1);
1137
	if(!in_array($suffix, array_keys($conv))) return $size;
1138
	$size = substr($size, 0, -1);
1139
	for($i = 0; $i < $conv[$suffix]; $i++) {
1140
		$size *= 1024;
1141
	}
1142
	return $size;
1143
}
1144

    
1145
function get_pkg_db() {
1146
	global $g;
1147
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1148
}
1149

    
1150
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1151
	if(!$pkgdb)
1152
		$pkgdb = get_pkg_db();
1153
	if(!is_array($alreadyseen))
1154
		$alreadyseen = array();
1155
	if (!is_array($depend))
1156
		$depend = array();
1157
	foreach($depend as $adepend) {
1158
		$pkgname = reverse_strrchr($adepend['name'], '.');
1159
		if(in_array($pkgname, $alreadyseen)) {
1160
			continue;
1161
		} elseif(!in_array($pkgname, $pkgdb)) {
1162
			$size += expand_to_bytes($adepend['size']);
1163
			$alreadyseen[] = $pkgname;
1164
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1165
		}
1166
	}
1167
	return $size;
1168
}
1169

    
1170
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1171
	global $config, $g;
1172
	if((!is_array($pkg)) and ($pkg != 'all'))
1173
		$pkg = array($pkg);
1174
	$pkgdb = get_pkg_db();
1175
	if(!$pkg_info)
1176
		$pkg_info = get_pkg_sizes($pkg);
1177
	foreach($pkg as $apkg) {
1178
		if(!$pkg_info[$apkg])
1179
			continue;
1180
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1181
	}
1182
	return $toreturn;
1183
}
1184

    
1185
function squash_from_bytes($size, $round = "") {
1186
	$conv = array(1 => "B", "K", "M", "G");
1187
	foreach($conv as $div => $suffix) {
1188
		$sizeorig = $size;
1189
		if(($size /= 1024) < 1) {
1190
			if($round) {
1191
				$sizeorig = round($sizeorig, $round);
1192
			}
1193
			return $sizeorig . $suffix;
1194
		}
1195
	}
1196
	return;
1197
}
1198

    
1199
function pkg_reinstall_all() {
1200
	global $g, $config;
1201

    
1202
	@unlink('/conf/needs_package_sync');
1203
	$pkg_id = 0;
1204
	$todo = array();
1205
	if (is_array($config['installedpackages']['package']))
1206
		foreach($config['installedpackages']['package'] as $package)
1207
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1208
	echo "One moment please, reinstalling packages...\n";
1209
	echo " >>> Trying to fetch package info...";
1210
	$pkg_info = get_pkg_info();
1211
	if ($pkg_info) {
1212
		echo " Done.\n";
1213
	} else {
1214
		$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
1215
		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";
1216
		return;
1217
	}
1218
	if(is_array($todo)) {
1219
		foreach($todo as $pkgtodo) {
1220
			$static_output = "";
1221
			if($pkgtodo['name']) {
1222
				uninstall_package($pkgtodo['name']);
1223
				install_package($pkgtodo['name']);
1224
				$pkg_id++;
1225
			}
1226
		}
1227
	}
1228
}
1229

    
1230
?>
(36-36/61)