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(gettext("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 "\n" . gettext("Syncing 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(sprintf(gettext('The %1$s package is missing required dependencies and must be reinstalled. %2$s'), $package['name'], $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(sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name']));
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(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
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'], sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name']), "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(gettext("Beginning package installation.") . "\n");
545
	log_error(sprintf(gettext('Beginning package installation for %s .'), $pkg_info['name']));
546
	$static_output .= sprintf(gettext("Beginning package installation for %s ."), $pkg_info['name']);
547
	update_status($static_output);
548
	/* fetch the package's configuration file */
549
	if($pkg_info['config_file'] != "") {
550
		$static_output .= "\n" . gettext("Downloading package configuration file... ");
551
		update_output_window($static_output);
552
		pkg_debug(gettext("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(gettext("ERROR! Unable to fetch package configuration file. Aborting installation.") . "\n");
557
			if($pkg_interface == "console")
558
				print "\n" . gettext("ERROR! Unable to fetch package configuration file. Aborting package installation.") . "\n";
559
			else {
560
				$static_output .= gettext("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 .= gettext("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 .= gettext("Saving updated package information...") . " ";
573
	update_output_window($static_output);
574
	if($pkgid == -1) {
575
		$config['installedpackages']['package'][] = $pkg_info;
576
		$changedesc = sprintf(gettext("Installed %s package."),$pkg_info['name']);
577
		$to_output = gettext("done.") . "\n";
578
	} else {
579
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
580
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
581
		$to_output = gettext("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 .= gettext("Failed to install package.") . "\n";
594
		update_output_window($static_output);
595
		return -1;
596
	} else {
597
		$static_output .= gettext("Writing configuration... ");
598
		update_output_window($static_output);
599
		write_config($changedesc);
600
		$static_output .= gettext("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 .= sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $pkg, "\n\n");
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(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies."));
649
		$static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("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(gettext("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 .= gettext("Loading package configuration... ");
675
		update_output_window($static_output);
676
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
677
		$static_output .= gettext("done.") . "\n";
678
		update_output_window($static_output);
679
		$static_output .= gettext("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 .= gettext("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 .= gettext("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 .= gettext("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(gettext("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(sprintf(gettext('Changing file mode to %1$s for %2$s%3$s%4$s'), $pkg_chmod, $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 .= gettext("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 = gettext("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
		/* sidebar items */
785
		if(is_array($pkg_config['menu'])) {
786
			$static_output .= gettext("Menu items... ");
787
			update_output_window($static_output);
788
			foreach($pkg_config['menu'] as $menu) {
789
				if(is_array($config['installedpackages']['menu'])) {
790
					foreach($config['installedpackages']['menu'] as $amenu)
791
						if($amenu['name'] == $menu['name'])
792
							continue 2;
793
				} else
794
					$config['installedpackages']['menu'] = array();
795
				$config['installedpackages']['menu'][] = $menu;
796
			}
797
			$static_output .= gettext("done.") . "\n";
798
			update_output_window($static_output);
799
		}
800
		/* integrated tab items */
801
		if(is_array($pkg_config['tabs']['tab'])) {
802
			$static_output .= gettext("Integrated Tab items... ");
803
			update_output_window($static_output);
804
			foreach($pkg_config['tabs']['tab'] as $tab) {
805
				if(is_array($config['installedpackages']['tab'])) {
806
					foreach($config['installedpackages']['tab'] as $atab)
807
						if($atab['name'] == $tab['name'])
808
							continue 2;
809
				} else
810
					$config['installedpackages']['tab'] = array();
811
				$config['installedpackages']['tab'][] = $tab;
812
			}
813
			$static_output .= gettext("done.") . "\n";
814
			update_output_window($static_output);
815
		}
816
		/* services */
817
		if(is_array($pkg_config['service'])) {
818
			$static_output .= gettext("Services... ");
819
			update_output_window($static_output);
820
			foreach($pkg_config['service'] as $service) {
821
				if(is_array($config['installedpackages']['service'])) {
822
					foreach($config['installedpackages']['service'] as $aservice)
823
						if($aservice['name'] == $service['name'])
824
							continue 2;
825
				} else
826
					$config['installedpackages']['service'] = array();
827
				$config['installedpackages']['service'][] = $service;
828
			}
829
			$static_output .= gettext("done.") . "\n";
830
			update_output_window($static_output);
831
		}
832
	} else {
833
		$static_output .= gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted.");
834
		update_output_window($static_output);
835
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
836
		if($pkg_interface <> "console") {
837
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
838
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
839
		}
840
		sleep(1);
841
		return false;
842
	}
843

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

    
853
	return true;
854
}
855

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

    
870
function delete_package($pkg) {
871
	global $config, $g, $static_output, $vardb;
872

    
873
	if(!$pkg) 
874
		return;
875

    
876
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
877

    
878
	// If package has dependencies then skip it
879
	if(does_package_depend($pkg)) {
880
		$static_output .= sprintf(gettext("Skipping package deletion for %s because it is a dependency."),$pkg) . "\n";
881
		update_output_window($static_output);
882
		return;		
883
	} else {
884
		if($pkg)
885
			$static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg);
886
		update_output_window($static_output);		
887
	}
888

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

    
901
	/* Rescan directories for what has been left and avoid fooling other programs. */
902
	mwexec("/sbin/ldconfig");
903

    
904
	return;
905
}
906

    
907
function delete_package_xml($pkg) {
908
	global $g, $config, $static_output, $pkg_interface, $rcfileprefix;
909

    
910
	conf_mount_rw();
911

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

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

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

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

    
1118
function get_pkg_db() {
1119
	global $g;
1120
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1121
}
1122

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

    
1143
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1144
	global $config, $g;
1145
	if((!is_array($pkg)) and ($pkg != 'all'))
1146
		$pkg = array($pkg);
1147
	$pkgdb = get_pkg_db();
1148
	if(!$pkg_info)
1149
		$pkg_info = get_pkg_sizes($pkg);
1150
	foreach($pkg as $apkg) {
1151
		if(!$pkg_info[$apkg])
1152
			continue;
1153
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1154
	}
1155
	return $toreturn;
1156
}
1157

    
1158
function squash_from_bytes($size, $round = "") {
1159
	$conv = array(1 => "B", "K", "M", "G");
1160
	foreach($conv as $div => $suffix) {
1161
		$sizeorig = $size;
1162
		if(($size /= 1024) < 1) {
1163
			if($round) {
1164
				$sizeorig = round($sizeorig, $round);
1165
			}
1166
			return $sizeorig . $suffix;
1167
		}
1168
	}
1169
	return;
1170
}
1171

    
1172
function pkg_reinstall_all() {
1173
	global $g, $config;
1174

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

    
1203
?>
(36-36/61)