Project

General

Profile

Download (44.4 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
	// If the ALT PKG Repo has a username/password set, use it.
180
	if($config['system']['altpkgrepo']['username'] && 
181
	   $config['system']['altpkgrepo']['password']) {
182
		$username = $config['system']['altpkgrepo']['username'];
183
		$password = $config['system']['altpkgrepo']['password'];
184
		$cli->setCredentials($username, $password);
185
	}
186
	elseif($g['xmlrpcauthuser'] && $g['xmlrpcauthpass']) {
187
		$username = $g['xmlrpcauthuser'];
188
		$password = $g['xmlrpcauthpass'];
189
		$cli->setCredentials($username, $password);
190
	}
191
	$resp = $cli->send($msg, 10);
192
	if(!is_object($resp))
193
		log_error("Could not get response from XMLRPC server!");
194
 	else if (!$resp->faultCode()) {
195
		$raw_versions = $resp->value();
196
		return xmlrpc_value_to_php($raw_versions);
197
	}
198

    
199
	return array();
200
}
201

    
202
/*
203
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
204
 * This function may also print output to the terminal indicating progress.
205
 */
206
function resync_all_package_configs($show_message = false) {
207
	global $config, $pkg_interface, $g;
208

    
209
	log_error("Resyncing configuration for all packages.");
210

    
211
	if (!is_array($config['installedpackages']['package']))
212
		return;
213

    
214
	if($show_message == true)
215
		echo "Syncing packages:";
216

    
217
	conf_mount_rw();
218

    
219
	foreach($config['installedpackages']['package'] as $idx => $package) {
220
		if (empty($package['name']))
221
			continue;
222
		if($show_message == true)
223
			echo " " . $package['name'];
224
		get_pkg_depends($package['name'], "all");
225
		if($g['booting'] != true)
226
			stop_service($package['name']);
227
		sync_package($idx, true, true);
228
		if($pkg_interface == "console") 
229
			echo "\nSyncing packages:";
230
	}
231

    
232
	if($show_message == true)
233
		echo " done.\n";
234

    
235
	@unlink("/conf/needs_package_sync");
236
	conf_mount_ro();
237
}
238

    
239
/*
240
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
241
 *				package is installed.
242
 */
243
function is_freebsd_pkg_installed($pkg) {
244
	if(!$pkg) 
245
		return;
246
	$output = "";
247
	exec("/usr/sbin/pkg_info -E \"{$pkg}*\"", $output, $retval);
248

    
249
	return (intval($retval) == 0);
250
}
251

    
252
/*
253
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
254
 *
255
 * $filetype = "all" || ".xml", ".tgz", etc.
256
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
257
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
258
 *
259
 */
260
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
261
	global $config;
262

    
263
	$pkg_id = get_pkg_id($pkg_name);
264
	if($pkg_id == -1)
265
		return -1; // This package doesn't really exist - exit the function.
266
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
267
		return; // No package belongs to the pkg_id passed to this function.
268

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

    
325
function uninstall_package($pkg_name) {
326
	global $config, $static_output;
327
	global $builder_package_install;
328

    
329
	// Back up /usr/local/lib libraries first if
330
	// not running from the builder code.
331
	// also take into account rrd binaries
332
	if(!$builder_package_install) {
333
		if(!file_exists("/tmp/pkg_libs.tgz")) {
334
			$static_output .= "Backing up libraries... ";
335
			update_output_window($static_output);
336
			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`");
337
			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`");
338
			$static_output .= "\n";
339
		}
340
	}
341

    
342
	stop_service($pkg_name);
343

    
344
	$id = get_pkg_id($pkg_name);
345
	if ($id >= 0) {
346
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
347
		$static_output .= "Removing package...\n";
348
		update_output_window($static_output);
349
		if (is_array($pkg_depends)) {
350
			foreach ($pkg_depends as $pkg_depend)
351
				delete_package($pkg_depend);
352
		}
353
	}
354
	delete_package_xml($pkg_name);
355

    
356
	// Restore libraries that we backed up if not 
357
	// running from the builder code.
358
	if(!$builder_package_install) {
359
		$static_output .= "Cleaning up... ";
360
		update_output_window($static_output);
361
		exec("/usr/bin/tar xzPfU /tmp/pkg_libs.tgz -C /");
362
		exec("/usr/bin/tar xzPfU /tmp/pkg_bins.tgz -C /");
363
		@unlink("/tmp/pkg_libs.tgz");
364
		@unlink("/tmp/pkg_bins.tgz");
365
	}
366
}
367

    
368
function force_remove_package($pkg_name) {
369
	delete_package_xml($pkg_name);
370
}
371

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

    
423
	if(!empty($pkg_config['custom_php_global_functions']))
424
		eval($pkg_config['custom_php_global_functions']);
425
	if(!empty($pkg_config['custom_php_resync_config_command']))
426
		eval($pkg_config['custom_php_resync_config_command']);
427
	if($sync_depends == true) {
428
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
429
		if(is_array($depends)) {
430
			foreach($depends as $item) {
431
				if(!file_exists($item)) {
432
					require_once("notices.inc");
433
					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);
434
					log_error("Could not find {$item}. Reinstalling package.");
435
					uninstall_package($pkg_name);
436
					if (install_package($pkg_name) < 0) {
437
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
438
						return -1;
439
					}
440
				} else {
441
					$item_config = parse_xml_config_pkg($item, "packagegui");
442
					if (empty($item_config))
443
						continue;
444
					if(isset($item_config['nosync']))
445
						continue;
446
					if (!empty($item_config['include_file'])) {
447
						if (file_exists($item_config['include_file']))	
448
							require_once($item_config['include_file']);
449
						else {
450
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
451
							continue;
452
						}
453
					}
454
					if($item_config['custom_php_global_functions'] <> "")
455
						eval($item_config['custom_php_global_functions']);
456
					if($item_config['custom_php_resync_config_command'] <> "")
457
						eval($item_config['custom_php_resync_config_command']);
458
					if($show_message == true)
459
						print " " . $item_config['name'];
460
				}
461
			}
462
		}
463
	}
464
}
465

    
466
/*
467
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
468
 * 			a progress bar and output window.
469
 */
470
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
471
	global $static_output, $g;
472

    
473
	if (($g['platform'] == "nanobsd") || ($g['platform'] == "embedded")) {
474
		$pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ ";
475
		$pkgstagingdir = "/root/tmp";
476
		if (!is_dir($pkgstagingdir))
477
			mkdir($pkgstagingdir);
478
		$pkgstaging = "-t {$pkgstagingdir}/instmp.XXXXXX";
479
		$fetchdir = $pkgstagingdir;
480
	} else {
481
		$fetchdir = $g['tmp_path'];
482
	}
483

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

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

    
537
	return true;
538
}
539

    
540
function install_package($package, $pkg_info = "") {
541
	global $g, $config, $static_output, $pkg_interface;
542

    
543
	/* safe side. Write config below will send to ro again. */
544
	conf_mount_rw();
545

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

    
597
	if(file_exists('/conf/needs_package_sync'))
598
		@unlink('/conf/needs_package_sync');
599
	write_config("Intermediate config write during package install for {$pkg_info['name']}.");
600
	conf_mount_rw(); //Compensate write_config() sending to _ro
601

    
602
	$static_output .= $to_output;
603
	update_output_window($static_output);
604
	/* install other package components */
605
	if (!install_package_xml($package)) {
606
		uninstall_package($package);
607
		write_config($changedesc);
608
		conf_mount_rw(); //Compensate write_config() sending to _ro
609
		$static_output .= "Failed to install package.\n";
610
		update_output_window($static_output);
611
		return -1;
612
	} else {
613
		$static_output .= "Writing configuration... ";
614
		update_output_window($static_output);
615
		write_config($changedesc);
616
		conf_mount_rw(); //Compensate write_config() sending to _ro
617
		$static_output .= "done.\n";
618
		update_output_window($static_output);
619
		if($pkg_info['after_install_info']) 
620
			update_output_window($pkg_info['after_install_info']);	
621
	}
622
	conf_mount_ro();
623
}
624

    
625
function get_after_install_info($package) {
626
	global $pkg_info;
627
	/* fetch package information if needed */
628
	if(!$pkg_info or !is_array($pkg_info[$package])) {
629
		$pkg_info = get_pkg_info(array($package));
630
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
631
	}
632
	if($pkg_info['after_install_info'])
633
		return $pkg_info['after_install_info'];
634
}
635

    
636
function eval_once($toeval) {
637
	global $evaled;
638
	if(!$evaled) $evaled = array();
639
	$evalmd5 = md5($toeval);
640
	if(!in_array($evalmd5, $evaled)) {
641
		@eval($toeval);
642
		$evaled[] = $evalmd5;
643
	}
644
	return;
645
}
646

    
647
function install_package_xml($pkg) {
648
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
649

    
650
	if(($pkgid = get_pkg_id($pkg)) == -1) {
651
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
652
		update_output_window($static_output);
653
		if($pkg_interface <> "console") {
654
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
655
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
656
		}
657
		sleep(1);
658
		return false;
659
	} else
660
		$pkg_info = $config['installedpackages']['package'][$pkgid];
661

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

    
725
				if($afn['prefix'] <> "")
726
					$prefix = $afn['prefix'];
727
				else
728
					$prefix = "/usr/local/pkg/";
729

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

    
777
		/* custom commands */
778
		$static_output .= gettext("Custom commands...") . "\n";
779
		update_output_window($static_output);
780
		if ($missing_include == false) {
781
			if($pkg_config['custom_php_global_functions'] <> "") {
782
				$static_output .= gettext("Executing custom_php_global_functions()...");
783
				update_output_window($static_output);
784
				eval_once($pkg_config['custom_php_global_functions']);
785
				$static_output .= gettext("done.") . "\n";
786
				update_output_window($static_output);
787
			}
788
			if($pkg_config['custom_php_install_command']) {
789
				$static_output .= gettext("Executing custom_php_install_command()...");
790
				update_output_window($static_output);
791
				eval_once($pkg_config['custom_php_install_command']);
792
				$static_output .= gettext("done.") . "\n";
793
				update_output_window($static_output);
794
			}
795
			if($pkg_config['custom_php_resync_config_command'] <> "") {
796
				$static_output .= gettext("Executing custom_php_resync_config_command()...");
797
				update_output_window($static_output);
798
				eval_once($pkg_config['custom_php_resync_config_command']);
799
				$static_output .= gettext("done.") . "\n";
800
				update_output_window($static_output);
801
			}
802
		}
803

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

    
890
	/* set up package logging streams */
891
	if($pkg_info['logging']) {
892
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
893
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
894
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
895
		pkg_debug("Adding text to file /etc/syslog.conf\n");
896
		system_syslogd_start();
897
	}
898

    
899
	return true;
900
}
901

    
902
function does_package_depend($pkg) {
903
	// Should not happen, but just in case.
904
	if(!$pkg)
905
		return;
906
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
907
	// If this package has dependency then return true
908
	foreach($pkg_var_db_dir as $pvdd) {
909
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
910
			return true;
911
	}	
912
	// Did not find a record of dependencies, so return false.
913
	return false;
914
}
915

    
916
function delete_package($pkg) {
917
	global $config, $g, $static_output, $vardb;
918

    
919
	if(!$pkg) 
920
		return;
921

    
922
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
923

    
924
	// If package has dependencies then skip it
925
	if(does_package_depend($pkg)) {
926
		$static_output .= "Skipping package deletion for {$pkg} because it is a dependency.\n";
927
		update_output_window($static_output);
928
		return;		
929
	} else {
930
		if($pkg)
931
			$static_output .= "Starting package deletion for {$pkg}...";
932
		update_output_window($static_output);		
933
	}
934

    
935
	$info = "";
936
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
937
	remove_freebsd_package($pkg);
938
	$static_output .= "done.\n";
939
	update_output_window($static_output);
940
	foreach($info as $line) {
941
		$depend = trim(str_replace("@pkgdep ", "", $line), " \n");
942
		// If package has dependencies then skip it
943
		if(!does_package_depend($depend)) 			
944
			delete_package($depend);
945
	}
946

    
947
	/* Rescan directories for what has been left and avoid fooling other programs. */
948
	mwexec("/sbin/ldconfig");
949

    
950
	return;
951
}
952

    
953
function delete_package_xml($pkg) {
954
	global $g, $config, $static_output, $pkg_interface, $rcfileprefix;
955

    
956
	conf_mount_rw();
957

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

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

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

    
1149
function expand_to_bytes($size) {
1150
	$conv = array(
1151
			"G" =>	"3",
1152
			"M" =>  "2",
1153
			"K" =>  "1",
1154
			"B" =>  "0"
1155
		);
1156
	$suffix = substr($size, -1);
1157
	if(!in_array($suffix, array_keys($conv))) return $size;
1158
	$size = substr($size, 0, -1);
1159
	for($i = 0; $i < $conv[$suffix]; $i++) {
1160
		$size *= 1024;
1161
	}
1162
	return $size;
1163
}
1164

    
1165
function get_pkg_db() {
1166
	global $g;
1167
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1168
}
1169

    
1170
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1171
	if(!$pkgdb)
1172
		$pkgdb = get_pkg_db();
1173
	if(!is_array($alreadyseen))
1174
		$alreadyseen = array();
1175
	if (!is_array($depend))
1176
		$depend = array();
1177
	foreach($depend as $adepend) {
1178
		$pkgname = reverse_strrchr($adepend['name'], '.');
1179
		if(in_array($pkgname, $alreadyseen)) {
1180
			continue;
1181
		} elseif(!in_array($pkgname, $pkgdb)) {
1182
			$size += expand_to_bytes($adepend['size']);
1183
			$alreadyseen[] = $pkgname;
1184
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1185
		}
1186
	}
1187
	return $size;
1188
}
1189

    
1190
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1191
	global $config, $g;
1192
	if((!is_array($pkg)) and ($pkg != 'all'))
1193
		$pkg = array($pkg);
1194
	$pkgdb = get_pkg_db();
1195
	if(!$pkg_info)
1196
		$pkg_info = get_pkg_sizes($pkg);
1197
	foreach($pkg as $apkg) {
1198
		if(!$pkg_info[$apkg])
1199
			continue;
1200
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1201
	}
1202
	return $toreturn;
1203
}
1204

    
1205
function squash_from_bytes($size, $round = "") {
1206
	$conv = array(1 => "B", "K", "M", "G");
1207
	foreach($conv as $div => $suffix) {
1208
		$sizeorig = $size;
1209
		if(($size /= 1024) < 1) {
1210
			if($round) {
1211
				$sizeorig = round($sizeorig, $round);
1212
			}
1213
			return $sizeorig . $suffix;
1214
		}
1215
	}
1216
	return;
1217
}
1218

    
1219
function pkg_reinstall_all() {
1220
	global $g, $config;
1221

    
1222
	@unlink('/conf/needs_package_sync');
1223
	$pkg_id = 0;
1224
	$todo = array();
1225
	if (is_array($config['installedpackages']['package'])) {
1226
		foreach($config['installedpackages']['package'] as $package)
1227
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1228

    
1229
		echo "One moment please, reinstalling packages...\n";
1230
		echo " >>> Trying to fetch package info...";
1231
		$pkg_info = get_pkg_info();
1232
		if ($pkg_info) {
1233
			echo " Done.\n";
1234
		} else {
1235
			$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
1236
			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";
1237
			return;
1238
		}
1239
		foreach($todo as $pkgtodo) {
1240
			$static_output = "";
1241
			if($pkgtodo['name']) {
1242
				uninstall_package($pkgtodo['name']);
1243
				install_package($pkgtodo['name']);
1244
				$pkg_id++;
1245
			}
1246
		}
1247
	}
1248
}
1249

    
1250
function stop_packages() {
1251
	require_once("config.inc");
1252
	require_once("functions.inc");
1253
	require_once("filter.inc");
1254
	require_once("shaper.inc");
1255
	require_once("captiveportal.inc");
1256
	require_once("pkg-utils.inc");
1257
	require_once("pfsense-utils.inc");
1258
	require_once("service-utils.inc");
1259

    
1260
	global $config, $g, $rcfileprefix;
1261

    
1262
	log_error("Stopping all packages.");
1263

    
1264
	$rcfiles = glob("{$rcfileprefix}*.sh");
1265
	if (!$rcfiles)
1266
		$rcfiles = array();
1267
	else {
1268
		$rcfiles = array_flip($rcfiles);
1269
		if (!$rcfiles)
1270
			$rcfiles = array();
1271
	}
1272

    
1273
	if (is_array($config['installedpackages']['package'])) {
1274
		foreach($config['installedpackages']['package'] as $package) {
1275
			echo " Stopping package {$package['name']}...";
1276
			stop_service($package['name']);
1277
			unset($rcfiles["{$rcfileprefix}{$package['name']}.sh"]);
1278
			echo "done.\n";
1279
		}
1280
	}
1281

    
1282
	$shell = @popen("/bin/sh", "w");
1283
	if ($shell) {
1284
		foreach ($rcfiles as $rcfile => $number) {
1285
			echo " Stopping {$rcfile}...";
1286
			fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1");
1287
			echo "done.\n";
1288
		}
1289

    
1290
		pclose($shell);
1291
	}
1292
}
1293

    
1294
?>
(37-37/62)