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
		$osname = php_uname("s");
522
		$arch =  php_uname("m");
523
		$rel = strtolower(php_uname("r"));
524
		if (substr_count($rel, '-') > 1)
525
			$rel = substr($rel, 0, strrpos($rel, "-"));
526
		$priv_url = "http://ftp2.{$osname}.org/pub/{$osname}/ports/{$arch}/packages-{$rel}/All";
527
		if (empty($base_url))
528
			$base_url = $priv_url;
529
		if (substr($base_url, -1) == "/")
530
			$base_url = substr($base_url, 0, -1);
531
		$fetchto = "{$fetchdir}/apkg_{$filename}";
532
		$static_output .= "\n" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... ";
533
		if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
534
			if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
535
				$static_output .= " could not download from there or {$priv_url}/{$filename}.\n";
536
				update_output_window($static_output);
537
				return false;
538
			} else if ($base_url == $priv_url) {
539
				$static_output .= " failed to download.\n";
540
				update_output_window($static_output);
541
				return false;
542
			} else {
543
				$static_output .= " [{$osname} repository]\n";
544
				update_output_window($static_output);
545
			}
546
		}
547
		$static_output .= " (extracting)\n";
548
		update_output_window($static_output);
549

    
550
		$pkgaddout = "";
551

    
552
		exec("/usr/local/sbin/pbi_add {$pkgstaging} -f -v --no-checksig {$fetchto} 2>&1", $pkgaddout);
553
		pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\npbi_add successfully completed.\n");
554

    
555
		exec("/usr/local/sbin/pbi_info " . preg_replace('/\.pbi$/','',$filename) . " | /usr/bin/awk '/Prefix/ {print $2}'",$pbidir);
556
		$pbidir = $pbidir[0];
557
		$linkdirs = array('bin','sbin');
558
		foreach($linkdirs as $dir) {
559
			if(is_dir("{$pbidir}/{$dir}")) {
560
				$files = scandir("{$pbidir}/{$dir}");
561
				foreach($files as $f) {
562
					if(!file_exists("/usr/local/{$dir}/{$f}")) {
563
						symlink("{$pbidir}/{$dir}/{$f}","/usr/local/{$dir}/{$f}");
564
					}
565
				}
566
			}
567
		}
568
	}
569
	return true;
570
}
571

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

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

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

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

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

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

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

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

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

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

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

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

    
921
	return true;
922
}
923

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

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

    
941
	if(!$pkg) 
942
		return;
943

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

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

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

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

    
958
	return;
959
}
960

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

    
964
	conf_mount_rw();
965

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1301
?>
(38-38/65)