Project

General

Profile

Download (45.9 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
	// 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
			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`");
354
			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`");
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
		exec("/usr/bin/tar xzPfU /tmp/pkg_libs.tgz -C /");
391
		exec("/usr/bin/tar xzPfU /tmp/pkg_bins.tgz -C /");
392
		@unlink("/tmp/pkg_libs.tgz");
393
		@unlink("/tmp/pkg_bins.tgz");
394
	}
395
}
396

    
397
function force_remove_package($pkg_name) {
398
	delete_package_xml($pkg_name);
399
}
400

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

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

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

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

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

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

    
549
		$pkgaddout = "";
550

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

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

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

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

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

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

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

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

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

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

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

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

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

    
920
	return true;
921
}
922

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

    
937
function delete_package($pkg) {
938
	global $config, $g, $static_output, $vardb;
939

    
940
	if(!$pkg) 
941
		return;
942

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

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

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

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

    
957
	return;
958
}
959

    
960
function delete_package_xml($pkg) {
961
	global $g, $config, $static_output, $pkg_interface, $rcfileprefix;
962

    
963
	conf_mount_rw();
964

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

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

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

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

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

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

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

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

    
1225
function pkg_reinstall_all() {
1226
	global $g, $config;
1227

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

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

    
1266
	global $config, $g, $rcfileprefix;
1267

    
1268
	log_error("Stopping all packages.");
1269

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

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

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

    
1296
		pclose($shell);
1297
	}
1298
}
1299

    
1300
?>
(39-39/66)