Project

General

Profile

Download (46 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 Luci
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
if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
85
	conf_mount_rw();
86
	safe_mkdir("/usr/local/pkg");
87
	safe_mkdir("/usr/local/pkg/pf");	
88
	conf_mount_ro();
89
}
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
	// The packagestring passed in must be the full PBI package name, 
103
	// as displayed by the pbi_info utility. e.g. "package-1.2.3_4-i386" 
104
	// It must NOT have ".pbi" on the end.
105
	exec("/usr/local/sbin/pbi_info {$packagestring} | /usr/bin/awk '/Prefix/ {print $2}'",$pbidir);
106
	$pbidir = $pbidir[0];
107
	if ($pbidir == "") {
108
		log_error("PBI dir for {$packagestring} was not found - cannot cleanup PBI files");
109
	}
110
	else {
111
		$linkdirs = array('bin','sbin');
112
		foreach($linkdirs as $dir) {
113
			$target_dir = $pbidir . "/" . $dir;
114
			if(is_dir($target_dir)) {
115
				$files = scandir($target_dir);
116
				foreach($files as $f) {
117
					if($f != '.' && $f != '..') {
118
						// Only try to unlink the file if it is a link to the expected pbi dir.
119
						$local_name = "/usr/local/{$dir}/{$f}";
120
						if(is_link($local_name)) {
121
							if(substr(readlink($local_name),0,strlen($target_dir)) == $target_dir) {
122
								unlink($local_name);
123
							}
124
						}
125
					}
126
				}
127
			}
128
		}
129

    
130
		exec("/usr/local/sbin/pbi_delete {$packagestring} 2>>/tmp/pbi_delete_errors.txt");
131
	}
132
}
133

    
134
/****f* pkg-utils/is_package_installed
135
 * NAME
136
 *   is_package_installed - Check whether a package is installed.
137
 * INPUTS
138
 *   $packagename	- name of the package to check
139
 * RESULT
140
 *   boolean	- true if the package is installed, false otherwise
141
 * NOTES
142
 *   This function is deprecated - get_pkg_id() can already check for installation.
143
 ******/
144
function is_package_installed($packagename) {
145
	$pkg = get_pkg_id($packagename);
146
	if($pkg == -1)
147
		return false;
148
	return true;
149
}
150

    
151
/****f* pkg-utils/get_pkg_id
152
 * NAME
153
 *   get_pkg_id - Find a package's numeric ID.
154
 * INPUTS
155
 *   $pkg_name	- name of the package to check
156
 * RESULT
157
 *   integer    - -1 if package is not found, >-1 otherwise
158
 ******/
159
function get_pkg_id($pkg_name) {
160
	global $config;
161

    
162
	if (is_array($config['installedpackages']['package'])) {
163
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
164
			if($pkg['name'] == $pkg_name)
165
				return $idx;
166
		}
167
	}
168
	return -1;
169
}
170

    
171
/****f* pkg-utils/get_pkg_info
172
 * NAME
173
 *   get_pkg_info - Retrieve package information from pfsense.com.
174
 * INPUTS
175
 *   $pkgs - 'all' to retrieve all packages, an array containing package names otherwise
176
 *   $info - 'all' to retrieve all information, an array containing keys otherwise
177
 * RESULT
178
 *   $raw_versions - Array containing retrieved information, indexed by package name.
179
 ******/
180
function get_pkg_info($pkgs = 'all', $info = 'all') {
181
	global $g;
182

    
183
	$freebsd_version = php_uname("r");
184
	$freebsd_machine = php_uname("m");
185
	$params = array(
186
		"pkg" => $pkgs, 
187
		"info" => $info, 
188
		"freebsd_version" => $freebsd_version[0],
189
		"freebsd_machine" => $freebsd_machine
190
	);
191
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
192
	return $resp ? $resp : array();
193
}
194

    
195
function get_pkg_sizes($pkgs = 'all') {
196
	global $config, $g;
197

    
198
	$freebsd_version = php_uname("r");
199
	$freebsd_machine = php_uname("m");
200
	$params = array(
201
		"pkg" => $pkgs, 
202
		"freebsd_version" => $freebsd_version,
203
		"freebsd_machine" => $freebsd_machine
204
	);
205
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
206
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
207
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
208
	$resp = $cli->send($msg, 10);
209
	if(!is_object($resp))
210
		log_error("Could not get response from XMLRPC server!");
211
 	else if (!$resp->faultCode()) {
212
		$raw_versions = $resp->value();
213
		return xmlrpc_value_to_php($raw_versions);
214
	}
215

    
216
	return array();
217
}
218

    
219
/*
220
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
221
 * This function may also print output to the terminal indicating progress.
222
 */
223
function resync_all_package_configs($show_message = false) {
224
	global $config, $pkg_interface, $g;
225

    
226
	log_error(gettext("Resyncing configuration for all packages."));
227

    
228
	if (!is_array($config['installedpackages']['package']))
229
		return;
230

    
231
	if($show_message == true)
232
		echo "Syncing packages:";
233

    
234
	conf_mount_rw();
235

    
236
	foreach($config['installedpackages']['package'] as $idx => $package) {
237
		if (empty($package['name']))
238
			continue;
239
		if($show_message == true)
240
			echo " " . $package['name'];
241
		get_pkg_depends($package['name'], "all");
242
		if($g['booting'] != true)
243
			stop_service($package['name']);
244
		sync_package($idx, true, true);
245
		if($pkg_interface == "console") 
246
			echo "\n" . gettext("Syncing packages:");
247
	}
248

    
249
	if($show_message == true)
250
		echo " done.\n";
251

    
252
	@unlink("/conf/needs_package_sync");
253
	conf_mount_ro();
254
}
255

    
256
/*
257
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
258
 *				package is installed.
259
 */
260
function is_freebsd_pkg_installed($pkg) {
261
	if(!$pkg) 
262
		return;
263
	$output = "";
264
	exec("/usr/local/sbin/pbi_info \"{$pkg}\"", $output, $retval);
265

    
266
	return (intval($retval) == 0);
267
}
268

    
269
/*
270
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
271
 *
272
 * $filetype = "all" || ".xml", ".tgz", etc.
273
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
274
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
275
 *
276
 */
277
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
278
	global $config;
279

    
280
	$pkg_id = get_pkg_id($pkg_name);
281
	if($pkg_id == -1)
282
		return -1; // This package doesn't really exist - exit the function.
283
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
284
		return; // No package belongs to the pkg_id passed to this function.
285

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

    
342
function uninstall_package($pkg_name) {
343
	global $config, $static_output;
344
	global $builder_package_install;
345

    
346
	// Back up /usr/local/lib libraries first if
347
	// not running from the builder code.
348
	// also take into account rrd binaries
349
	if(!$builder_package_install) {
350
		if(!file_exists("/tmp/pkg_libs.tgz")) {
351
			$static_output .= "Backing up libraries... ";
352
			update_output_window($static_output);
353
			mwexec("/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`", true);
354
			mwexec("/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`", true);
355
			$static_output .= "\n";
356
		}
357
	}
358

    
359
	stop_service($pkg_name);
360

    
361
	$id = get_pkg_id($pkg_name);
362
	if ($id >= 0) {
363
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package_pbi'];
364
		$static_output .= "Removing package...\n";
365
		update_output_window($static_output);
366
		if (is_array($pkg_depends)) {
367
			foreach ($pkg_depends as $pkg_depend)
368
				delete_package($pkg_depend);
369
		} else {
370
			// The packages (1 or more) are all in one long string.
371
			// We need to pass them 1 at a time to delete_package.
372
			// Compress any multiple whitespace (sp, tab, cr, lf...) into a single space char.
373
			$pkg_dep_str = preg_replace("'\s+'", ' ', $pkg_depends);
374
			// Get rid of any leading or trailing space.
375
			$pkg_dep_str = trim($pkg_dep_str);
376
			// Now we have a space-separated string. Make it into an array and process it.
377
			$pkg_dep_array = explode(" ", $pkg_dep_str);
378
			foreach ($pkg_dep_array as $pkg_depend) {
379
				delete_package($pkg_depend);
380
			}
381
		}
382
	}
383
	delete_package_xml($pkg_name);
384

    
385
	// Restore libraries that we backed up if not 
386
	// running from the builder code.
387
	if(!$builder_package_install) {
388
		$static_output .= "Cleaning up... ";
389
		update_output_window($static_output);
390
		mwexec("/usr/bin/tar xzPfk /tmp/pkg_libs.tgz -C /", true);
391
		mwexec("/usr/bin/tar xzPfk /tmp/pkg_bins.tgz -C /", true);
392
		@unlink("/tmp/pkg_libs.tgz");
393
		@unlink("/tmp/pkg_bins.tgz");
394
		$static_output .= gettext("done.") . "\n";
395
		update_output_window($static_output);
396
	}
397
}
398

    
399
function force_remove_package($pkg_name) {
400
	delete_package_xml($pkg_name);
401
}
402

    
403
/*
404
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
405
 */
406
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
407
	global $config, $config_parsed;
408
	global $builder_package_install;
409
	
410
	// If this code is being called by pfspkg_installer 
411
	// which the builder system uses then return (ignore).
412
	if($builder_package_install)
413
		return;
414
	
415
	if(empty($config['installedpackages']['package']))
416
		return;
417
	if(!is_numeric($pkg_name)) {
418
		$pkg_id = get_pkg_id($pkg_name);
419
		if($pkg_id == -1)
420
			return -1; // This package doesn't really exist - exit the function.
421
	} else {
422
		$pkg_id = $pkg_name;
423
		if(empty($config['installedpackages']['package'][$pkg_id]))
424
			return;  // No package belongs to the pkg_id passed to this function.
425
	}
426
        if (is_array($config['installedpackages']['package'][$pkg_id]))
427
		$package =& $config['installedpackages']['package'][$pkg_id];
428
        else
429
		return; /* empty package tag */
430
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
431
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
432
		force_remove_package($package['name']);
433
		return -1;
434
	}
435
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
436
	if(isset($pkg_config['nosync']))
437
		return;
438
	/* Bring in package include files */
439
	if (!empty($pkg_config['include_file'])) {
440
		$include_file = $pkg_config['include_file'];
441
		if (file_exists($include_file))
442
			require_once($include_file);
443
		else {
444
			/* XXX: What the heck is this?! */
445
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
446
			uninstall_package($package['name']);
447
			if (install_package($package['name']) < 0) {
448
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
449
				return -1;
450
			}
451
		}
452
	}
453

    
454
	if(!empty($pkg_config['custom_php_global_functions']))
455
		eval($pkg_config['custom_php_global_functions']);
456
	if(!empty($pkg_config['custom_php_resync_config_command']))
457
		eval($pkg_config['custom_php_resync_config_command']);
458
	if($sync_depends == true) {
459
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
460
		if(is_array($depends)) {
461
			foreach($depends as $item) {
462
				if(!file_exists($item)) {
463
					require_once("notices.inc");
464
					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);
465
					log_error("Could not find {$item}. Reinstalling package.");
466
					uninstall_package($pkg_name);
467
					if (install_package($pkg_name) < 0) {
468
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
469
						return -1;
470
					}
471
				} else {
472
					$item_config = parse_xml_config_pkg($item, "packagegui");
473
					if (empty($item_config))
474
						continue;
475
					if(isset($item_config['nosync']))
476
						continue;
477
					if (!empty($item_config['include_file'])) {
478
						if (file_exists($item_config['include_file']))	
479
							require_once($item_config['include_file']);
480
						else {
481
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
482
							continue;
483
						}
484
					}
485
					if($item_config['custom_php_global_functions'] <> "")
486
						eval($item_config['custom_php_global_functions']);
487
					if($item_config['custom_php_resync_config_command'] <> "")
488
						eval($item_config['custom_php_resync_config_command']);
489
					if($show_message == true)
490
						print " " . $item_config['name'];
491
				}
492
			}
493
		}
494
	}
495
}
496

    
497
/*
498
 * pkg_fetch_recursive: Download and install a FreeBSD PBI package. This function provides output to
499
 * 			a progress bar and output window.
500
 */
501
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
502
	global $static_output, $g;
503

    
504
	// Clean up incoming filenames
505
	$filename = str_replace("  ", " ", $filename);
506
	$filename = str_replace("\n", " ", $filename);
507
	$filename = str_replace("  ", " ", $filename);
508

    
509
	$pkgs = explode(" ", $filename);
510
	foreach($pkgs as $filename) {
511
		$filename = trim($filename);
512
		if (($g['platform'] == "nanobsd") || ($g['platform'] == "embedded")) {
513
			$pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ ";
514
			$pkgstagingdir = "/root/tmp";
515
			if (!is_dir($pkgstagingdir))
516
				mkdir($pkgstagingdir);
517
			$pkgstaging = "-o {$pkgstagingdir}/instmp.XXXXXX";
518
			$fetchdir = $pkgstagingdir;
519
		} else {
520
			$fetchdir = $g['tmp_path'];
521
		}
522

    
523
		/* FreeBSD has no PBI's hosted, so fall back to our own URL for now. (Maybe fail to PC-BSD?) */
524
		$arch = php_uname("m");
525
		$arch = ($arch == "i386") ? "" : $arch . '/';
526
		$rel = get_freebsd_version();
527
		$priv_url = "http://files.pfsense.org/packages/{$arch}{$rel}/All/";
528
		if (empty($base_url))
529
			$base_url = $priv_url;
530
		if (substr($base_url, -1) == "/")
531
			$base_url = substr($base_url, 0, -1);
532
		$fetchto = "{$fetchdir}/apkg_{$filename}";
533
		$static_output .= "\n" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... ";
534
		if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
535
			if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
536
				$static_output .= " could not download from there or {$priv_url}/{$filename}.\n";
537
				update_output_window($static_output);
538
				return false;
539
			} else if ($base_url == $priv_url) {
540
				$static_output .= " failed to download.\n";
541
				update_output_window($static_output);
542
				return false;
543
			} else {
544
				$static_output .= " [{$osname} repository]\n";
545
				update_output_window($static_output);
546
			}
547
		}
548
		$static_output .= " (extracting)\n";
549
		update_output_window($static_output);
550

    
551
		$pkgaddout = "";
552

    
553
		exec("/usr/local/sbin/pbi_add {$pkgstaging} -f -v --no-checksig {$fetchto} 2>&1", $pkgaddout);
554
		pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\npbi_add successfully completed.\n");
555
		setup_library_paths();
556
		exec("/usr/local/sbin/pbi_info " . preg_replace('/\.pbi$/','',$filename) . " | /usr/bin/awk '/Prefix/ {print $2}'",$pbidir);
557
		$pbidir = $pbidir[0];
558
		$linkdirs = array('bin','sbin');
559
		foreach($linkdirs as $dir) {
560
			if(is_dir("{$pbidir}/{$dir}")) {
561
				$files = scandir("{$pbidir}/{$dir}");
562
				foreach($files as $f) {
563
					if(!file_exists("/usr/local/{$dir}/{$f}")) {
564
						symlink("{$pbidir}/{$dir}/{$f}","/usr/local/{$dir}/{$f}");
565
					}
566
				}
567
			}
568
		}
569
	}
570
	return true;
571
}
572

    
573
function install_package($package, $pkg_info = "") {
574
	global $g, $config, $static_output, $pkg_interface;
575

    
576
	/* safe side. Write config below will send to ro again. */
577
	conf_mount_rw();
578

    
579
	if($pkg_interface == "console") 	
580
		echo "\n";
581
	/* fetch package information if needed */
582
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
583
		$pkg_info = get_pkg_info(array($package));
584
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
585
		if (empty($pkg_info)) {
586
			conf_mount_ro();
587
			return -1;
588
		}
589
	}
590
	pkg_debug(gettext("Beginning package installation.") . "\n");
591
	log_error(sprintf(gettext('Beginning package installation for %s .'), $pkg_info['name']));
592
	$static_output .= sprintf(gettext("Beginning package installation for %s ."), $pkg_info['name']);
593
	update_status($static_output);
594
	/* fetch the package's configuration file */
595
	if($pkg_info['config_file'] != "") {
596
		$static_output .= "\n" . gettext("Downloading package configuration file... ");
597
		update_output_window($static_output);
598
		pkg_debug(gettext("Downloading package configuration file...") . "\n");
599
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
600
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
601
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
602
			pkg_debug(gettext("ERROR! Unable to fetch package configuration file. Aborting installation.") . "\n");
603
			if($pkg_interface == "console")
604
				print "\n" . gettext("ERROR! Unable to fetch package configuration file. Aborting package installation.") . "\n";
605
			else {
606
				$static_output .= gettext("failed!\n\nInstallation aborted.\n");
607
				update_output_window($static_output);
608
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
609
			}
610
			conf_mount_ro();
611
			return -1;
612
		}
613
		$static_output .= gettext("done.") . "\n";
614
		update_output_window($static_output);
615
	}
616
	/* add package information to config.xml */
617
	$pkgid = get_pkg_id($pkg_info['name']);
618
	$static_output .= gettext("Saving updated package information...") . " ";
619
	update_output_window($static_output);
620
	if($pkgid == -1) {
621
		$config['installedpackages']['package'][] = $pkg_info;
622
		$changedesc = sprintf(gettext("Installed %s package."),$pkg_info['name']);
623
		$to_output = gettext("done.") . "\n";
624
	} else {
625
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
626
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
627
		$to_output = gettext("overwrite!") . "\n";
628
	}
629
	if(file_exists('/conf/needs_package_sync'))
630
		@unlink('/conf/needs_package_sync');
631
	conf_mount_ro();
632
	write_config("Intermediate config write during package install for {$pkg_info['name']}.");
633
	$static_output .= $to_output;
634
	update_output_window($static_output);
635
	/* install other package components */
636
	if (!install_package_xml($package)) {
637
		uninstall_package($package);
638
		write_config($changedesc);
639
		$static_output .= gettext("Failed to install package.") . "\n";
640
		update_output_window($static_output);
641
		return -1;
642
	} else {
643
		$static_output .= gettext("Writing configuration... ");
644
		update_output_window($static_output);
645
		write_config($changedesc);
646
		$static_output .= gettext("done.") . "\n";
647
		update_output_window($static_output);
648
		if($pkg_info['after_install_info']) 
649
			update_output_window($pkg_info['after_install_info']);	
650
	}
651
}
652

    
653
function get_after_install_info($package) {
654
	global $pkg_info;
655
	/* fetch package information if needed */
656
	if(!$pkg_info or !is_array($pkg_info[$package])) {
657
		$pkg_info = get_pkg_info(array($package));
658
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
659
	}
660
	if($pkg_info['after_install_info'])
661
		return $pkg_info['after_install_info'];
662
}
663

    
664
function eval_once($toeval) {
665
	global $evaled;
666
	if(!$evaled) $evaled = array();
667
	$evalmd5 = md5($toeval);
668
	if(!in_array($evalmd5, $evaled)) {
669
		@eval($toeval);
670
		$evaled[] = $evalmd5;
671
	}
672
	return;
673
}
674

    
675
function install_package_xml($pkg) {
676
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
677

    
678
	if(($pkgid = get_pkg_id($pkg)) == -1) {
679
		$static_output .= sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $pkg, "\n\n");
680
		update_output_window($static_output);
681
		if($pkg_interface <> "console") {
682
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
683
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
684
		}
685
		sleep(1);
686
		return false;
687
	} else
688
		$pkg_info = $config['installedpackages']['package'][$pkgid];
689

    
690
	/* pkg_add the package and its dependencies */
691
	if($pkg_info['depends_on_package_base_url'] != "") {
692
		if($pkg_interface == "console") 
693
			echo "\n";
694
		update_status(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies."));
695
		$static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("and its dependencies... ");
696
		$static_orig = $static_output;
697
		$static_output .= "\n";
698
		update_output_window($static_output);
699
		foreach((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) {
700
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
701
			$static_output = $static_orig . "\nChecking for package installation... ";
702
			update_output_window($static_output);
703
			if (!is_freebsd_pkg_installed($pkg_name)) {
704
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
705
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
706
					update_output_window($static_output);
707
					pkg_debug(gettext("Package WAS NOT installed properly.") . "\n");
708
					if($pkg_interface <> "console") {
709
						echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
710
						echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
711
					}
712
					sleep(1);
713
					return false;
714
				}
715
			}
716
		}
717
	}
718
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
719
	if(file_exists("/usr/local/pkg/" . $configfile)) {
720
		$static_output .= gettext("Loading package configuration... ");
721
		update_output_window($static_output);
722
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
723
		$static_output .= gettext("done.") . "\n";
724
		update_output_window($static_output);
725
		$static_output .= gettext("Configuring package components...\n");
726
		if (!empty($pkg_config['filter_rules_needed']))
727
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
728
		update_output_window($static_output);
729
		/* modify system files */
730
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
731
			$static_output .= gettext("System files... ");
732
			update_output_window($static_output);
733
			foreach($pkg_config['modify_system']['item'] as $ms) {
734
				if($ms['textneeded']) {
735
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
736
				}
737
			}
738
			$static_output .= gettext("done.") . "\n";
739
			update_output_window($static_output);
740
		}
741
		/* download additional files */
742
		if(is_array($pkg_config['additional_files_needed'])) {
743
			$static_output .= gettext("Additional files... ");
744
			$static_orig = $static_output;
745
			update_output_window($static_output);
746
			foreach($pkg_config['additional_files_needed'] as $afn) {
747
				$filename = get_filename_from_url($afn['item'][0]);
748
				if($afn['chmod'] <> "")
749
					$pkg_chmod = $afn['chmod'];
750
				else
751
					$pkg_chmod = "";
752

    
753
				if($afn['prefix'] <> "")
754
					$prefix = $afn['prefix'];
755
				else
756
					$prefix = "/usr/local/pkg/";
757

    
758
				if(!is_dir($prefix)) 
759
					safe_mkdir($prefix);
760
 				$static_output .= $filename . " ";
761
				update_output_window($static_output);
762
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
763
					$static_output .= "failed.\n";
764
					@unlink($prefix . $filename);
765
					update_output_window($static_output);
766
					return false;
767
				}
768
				if(stristr($filename, ".tgz") <> "") {
769
					pkg_debug(gettext("Extracting tarball to -C for ") . $filename . "...\n");
770
					$tarout = "";
771
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
772
					pkg_debug(print_r($tarout, true) . "\n");
773
				}
774
				if($pkg_chmod <> "") {
775
					pkg_debug(sprintf(gettext('Changing file mode to %1$s for %2$s%3$s%4$s'), $pkg_chmod, $prefix, $filename, "\n"));
776
					@chmod($prefix . $filename, $pkg_chmod);
777
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
778
				}
779
				$static_output = $static_orig;
780
                                update_output_window($static_output);
781
			}
782
			$static_output .= gettext("done.") . "\n";
783
			update_output_window($static_output);
784
		}
785
		/*   if a require exists, include it.  this will
786
		 *   show us where an error exists in a package
787
		 *   instead of making us blindly guess
788
		 */
789
		$missing_include = false;
790
		if($pkg_config['include_file'] <> "") {
791
			$static_output = gettext("Loading package instructions...") . "\n";
792
			update_output_window($static_output);
793
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
794
			if (file_exists($pkg_config['include_file']))
795
				require_once($pkg_config['include_file']);
796
			else {
797
				$missing_include = true;
798
				$static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n";
799
				update_output_window($static_output);
800
				/* XXX: Should undo the steps before this?! */
801
				return false;
802
			}
803
		}
804

    
805
		/* custom commands */
806
		$static_output .= gettext("Custom commands...") . "\n";
807
		update_output_window($static_output);
808
		if ($missing_include == false) {
809
			if($pkg_config['custom_php_global_functions'] <> "") {
810
				$static_output .= gettext("Executing custom_php_global_functions()...");
811
				update_output_window($static_output);
812
				eval_once($pkg_config['custom_php_global_functions']);
813
				$static_output .= gettext("done.") . "\n";
814
				update_output_window($static_output);
815
			}
816
			if($pkg_config['custom_php_install_command']) {
817
				$static_output .= gettext("Executing custom_php_install_command()...");
818
				update_output_window($static_output);
819
				/* XXX: create symlinks for conf files into the PBI directories.
820
				 *	change packages to store configs at /usr/pbi/pkg/etc and remove this
821
				 */
822
				eval_once($pkg_config['custom_php_install_command']);
823
				// Note: pkg may be mixed-case, e.g. "squidGuard" but the PBI names are lowercase.
824
				// e.g. "squidguard-1.4_4-i386" so feed lowercase to pbi_info below.
825
				// Also add the "-" so that examples like "squid-" do not match "squidguard-".
826
				$pkg_name_for_pbi_match = strtolower($pkg) . "-";
827
				exec("/usr/local/sbin/pbi_info | grep '^{$pkg_name_for_pbi_match}' | xargs /usr/local/sbin/pbi_info | awk '/Prefix/ {print $2}'",$pbidirarray);
828
				$pbidir0 = $pbidirarray[0];
829
				exec("find /usr/local/etc/ -name *.conf | grep \"{$pkg}\"",$files);
830
				foreach($files as $f) {
831
					$pbiconf = str_replace('/usr/local',$pbidir0,$f);
832
					if(is_file($pbiconf) || is_link($pbiconf)) {
833
						unlink($pbiconf);
834
					}
835
					if(is_dir(dirname($pbiconf))) {
836
						symlink($f,$pbiconf);
837
					} else {
838
						log_error("The dir for {$pbiconf} does not exist. Cannot add symlink to {$f}.");
839
					}
840
				}
841
				eval_once($pkg_config['custom_php_install_command']);
842
				$static_output .= gettext("done.") . "\n";
843
				update_output_window($static_output);
844
			}
845
			if($pkg_config['custom_php_resync_config_command'] <> "") {
846
				$static_output .= gettext("Executing custom_php_resync_config_command()...");
847
				update_output_window($static_output);
848
				eval_once($pkg_config['custom_php_resync_config_command']);
849
				$static_output .= gettext("done.") . "\n";
850
				update_output_window($static_output);
851
			}
852
		}
853
		/* sidebar items */
854
		if(is_array($pkg_config['menu'])) {
855
			$static_output .= gettext("Menu items... ");
856
			update_output_window($static_output);
857
			foreach($pkg_config['menu'] as $menu) {
858
				if(is_array($config['installedpackages']['menu'])) {
859
					foreach($config['installedpackages']['menu'] as $amenu)
860
						if($amenu['name'] == $menu['name'])
861
							continue 2;
862
				} else
863
					$config['installedpackages']['menu'] = array();
864
				$config['installedpackages']['menu'][] = $menu;
865
			}
866
			$static_output .= gettext("done.") . "\n";
867
			update_output_window($static_output);
868
		}
869
		/* integrated tab items */
870
		if(is_array($pkg_config['tabs']['tab'])) {
871
			$static_output .= gettext("Integrated Tab items... ");
872
			update_output_window($static_output);
873
			foreach($pkg_config['tabs']['tab'] as $tab) {
874
				if(is_array($config['installedpackages']['tab'])) {
875
					foreach($config['installedpackages']['tab'] as $atab)
876
						if($atab['name'] == $tab['name'])
877
							continue 2;
878
				} else
879
					$config['installedpackages']['tab'] = array();
880
				$config['installedpackages']['tab'][] = $tab;
881
			}
882
			$static_output .= gettext("done.") . "\n";
883
			update_output_window($static_output);
884
		}
885
		/* services */
886
		if(is_array($pkg_config['service'])) {
887
			$static_output .= gettext("Services... ");
888
			update_output_window($static_output);
889
			foreach($pkg_config['service'] as $service) {
890
				if(is_array($config['installedpackages']['service'])) {
891
					foreach($config['installedpackages']['service'] as $aservice)
892
						if($aservice['name'] == $service['name'])
893
							continue 2;
894
				} else
895
					$config['installedpackages']['service'] = array();
896
				$config['installedpackages']['service'][] = $service;
897
			}
898
			$static_output .= gettext("done.") . "\n";
899
			update_output_window($static_output);
900
		}
901
	} else {
902
		$static_output .= gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted.");
903
		update_output_window($static_output);
904
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
905
		if($pkg_interface <> "console") {
906
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
907
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
908
		}
909
		sleep(1);
910
		return false;
911
	}
912

    
913
	/* set up package logging streams */
914
	if($pkg_info['logging']) {
915
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
916
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
917
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
918
		pkg_debug("Adding text to file /etc/syslog.conf\n");
919
		system_syslogd_start();
920
	}
921

    
922
	return true;
923
}
924

    
925
function does_package_depend($pkg) {
926
	// Should not happen, but just in case.
927
	if(!$pkg)
928
		return;
929
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
930
	// If this package has dependency then return true
931
	foreach($pkg_var_db_dir as $pvdd) {
932
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
933
			return true;
934
	}	
935
	// Did not find a record of dependencies, so return false.
936
	return false;
937
}
938

    
939
function delete_package($pkg) {
940
	global $config, $g, $static_output, $vardb;
941

    
942
	if(!$pkg) 
943
		return;
944

    
945
	// Note: $pkg has the full PBI package name followed by ".pbi". Strip off ".pbi".
946
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
947

    
948
	if($pkg)
949
		$static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg);
950
	update_output_window($static_output);
951

    
952
	remove_freebsd_package($pkg);
953
	$static_output .= "done.\n";
954
	update_output_window($static_output);
955

    
956
	/* Rescan directories for what has been left and avoid fooling other programs. */
957
	mwexec("/sbin/ldconfig");
958

    
959
	return;
960
}
961

    
962
function delete_package_xml($pkg) {
963
	global $g, $config, $static_output, $pkg_interface;
964

    
965
	conf_mount_rw();
966

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

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

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

    
1157
function expand_to_bytes($size) {
1158
	$conv = array(
1159
			"G" =>	"3",
1160
			"M" =>  "2",
1161
			"K" =>  "1",
1162
			"B" =>  "0"
1163
		);
1164
	$suffix = substr($size, -1);
1165
	if(!in_array($suffix, array_keys($conv))) return $size;
1166
	$size = substr($size, 0, -1);
1167
	for($i = 0; $i < $conv[$suffix]; $i++) {
1168
		$size *= 1024;
1169
	}
1170
	return $size;
1171
}
1172

    
1173
function get_pkg_db() {
1174
	global $g;
1175
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1176
}
1177

    
1178
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1179
	if(!$pkgdb)
1180
		$pkgdb = get_pkg_db();
1181
	if(!is_array($alreadyseen))
1182
		$alreadyseen = array();
1183
	if (!is_array($depend))
1184
		$depend = array();
1185
	foreach($depend as $adepend) {
1186
		$pkgname = reverse_strrchr($adepend['name'], '.');
1187
		if(in_array($pkgname, $alreadyseen)) {
1188
			continue;
1189
		} elseif(!in_array($pkgname, $pkgdb)) {
1190
			$size += expand_to_bytes($adepend['size']);
1191
			$alreadyseen[] = $pkgname;
1192
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1193
		}
1194
	}
1195
	return $size;
1196
}
1197

    
1198
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1199
	global $config, $g;
1200
	if((!is_array($pkg)) and ($pkg != 'all'))
1201
		$pkg = array($pkg);
1202
	$pkgdb = get_pkg_db();
1203
	if(!$pkg_info)
1204
		$pkg_info = get_pkg_sizes($pkg);
1205
	foreach($pkg as $apkg) {
1206
		if(!$pkg_info[$apkg])
1207
			continue;
1208
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1209
	}
1210
	return $toreturn;
1211
}
1212

    
1213
function squash_from_bytes($size, $round = "") {
1214
	$conv = array(1 => "B", "K", "M", "G");
1215
	foreach($conv as $div => $suffix) {
1216
		$sizeorig = $size;
1217
		if(($size /= 1024) < 1) {
1218
			if($round) {
1219
				$sizeorig = round($sizeorig, $round);
1220
			}
1221
			return $sizeorig . $suffix;
1222
		}
1223
	}
1224
	return;
1225
}
1226

    
1227
function pkg_reinstall_all() {
1228
	global $g, $config;
1229

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

    
1258
function stop_packages() {
1259
	require_once("config.inc");
1260
	require_once("functions.inc");
1261
	require_once("filter.inc");
1262
	require_once("shaper.inc");
1263
	require_once("captiveportal.inc");
1264
	require_once("pkg-utils.inc");
1265
	require_once("pfsense-utils.inc");
1266
	require_once("service-utils.inc");
1267

    
1268
	global $config, $g;
1269

    
1270
	log_error("Stopping all packages.");
1271

    
1272
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1273
	if (!$rcfiles)
1274
		$rcfiles = array();
1275
	else {
1276
		$rcfiles = array_flip($rcfiles);
1277
		if (!$rcfiles)
1278
			$rcfiles = array();
1279
	}
1280

    
1281
	if (is_array($config['installedpackages']['package'])) {
1282
		foreach($config['installedpackages']['package'] as $package) {
1283
			echo " Stopping package {$package['name']}...";
1284
			stop_service($package['name']);
1285
			unset($rcfiles[RCFILEPREFIX . $package['name'] . ".sh"]);
1286
			echo "done.\n";
1287
		}
1288
	}
1289

    
1290
	$shell = @popen("/bin/sh", "w");
1291
	if ($shell) {
1292
		foreach ($rcfiles as $rcfile => $number) {
1293
			echo " Stopping {$rcfile}...";
1294
			fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1");
1295
			echo "done.\n";
1296
		}
1297

    
1298
		pclose($shell);
1299
	}
1300
}
1301

    
1302
?>
(39-39/66)