Project

General

Profile

Download (47.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 Luci
12
 * Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
13
 * All rights reserved.
14
 * Redistribution and use in source and binary forms, with or without
15
 * modification, are permitted provided that the following conditions are met:
16
 *
17
 * 1. Redistributions of source code must retain the above copyright notice,
18
 * this list of conditions and the following disclaimer.
19
 *
20
 * 2. Redistributions in binary form must reproduce the above copyright
21
 * notice, this list of conditions and the following disclaimer in the
22
 * documentation and/or other materials provided with the distribution.
23
 *
24
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
25
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
26
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
28
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33
 * POSSIBILITY OF SUCH DAMAGE.
34
 *
35
 */
36

    
37
/*
38
	pfSense_BUILDER_BINARIES:	/usr/bin/cd	/usr/bin/tar	/usr/sbin/fifolog_create	/bin/chmod
39
	pfSense_BUILDER_BINARIES:	/usr/sbin/pkg_add	/usr/sbin/pkg_info	/usr/sbin/pkg_delete	/bin/rm
40
	pfSense_MODULE:	pkg
41
*/
42

    
43
require_once("globals.inc");
44
require_once("xmlrpc.inc");
45
require_once("service-utils.inc");
46
if(file_exists("/cf/conf/use_xmlreader"))
47
	require_once("xmlreader.inc");
48
else
49
	require_once("xmlparse.inc");
50
require_once("service-utils.inc");
51
require_once("pfsense-utils.inc");
52

    
53
if(!function_exists("update_status")) {
54
	function update_status($status) {
55
		echo $status . "\n";
56
	}
57
}
58
if(!function_exists("update_output_window")) {
59
	function update_output_window($status) {
60
		echo htmlspecialchars($status) . "\n";
61
	}
62
}
63

    
64
if (!function_exists("pkg_debug")) {
65
	/* set up logging if needed */
66
	function pkg_debug($msg) {
67
		global $g, $debug, $fd_log;
68

    
69
		if (!$debug)
70
			return;
71

    
72
		if (!$fd_log) {
73
			if (!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$package}.log", "w"))
74
				update_output_window("Warning, could not open log for writing.");
75
		}
76
		@fwrite($fd_log, $msg);
77
	}
78
}
79

    
80
$vardb = "/var/db/pkg";
81
safe_mkdir($vardb);
82
$g['platform'] = trim(file_get_contents("/etc/platform"));
83

    
84
if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
85
	conf_mount_rw();
86
	safe_mkdir("/usr/local/pkg");
87
	safe_mkdir("/usr/local/pkg/pf");	
88
	conf_mount_ro();
89
}
90

    
91
/****f* pkg-utils/remove_package
92
 * NAME
93
 *   remove_package - Removes package from FreeBSD if it exists
94
 * INPUTS
95
 *   $packagestring	- name/string to check for
96
 * RESULT
97
 *   none
98
 * NOTES
99
 *   
100
 ******/
101
function remove_freebsd_package($packagestring) {
102
	// The packagestring passed in must be the full PBI package name, 
103
	// as displayed by the pbi_info utility. e.g. "package-1.2.3_4-i386" 
104
	// It must NOT have ".pbi" on the end.
105
	exec("/usr/local/sbin/pbi_info " . escapeshellarg($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 " . escapeshellarg($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_internal_name
172
 * NAME
173
 *   get_pkg_internal_name - Find a package's internal name (e.g. squid3 internal name is squid)
174
 * INPUTS
175
 *   $package - array of package data from config
176
 * RESULT
177
 *   string - internal name (if defined) or default to package name
178
 ******/
179
function get_pkg_internal_name($package) {
180
	if (isset($package['internal_name']) && ($package['internal_name'] != "")) {
181
		/* e.g. name is Ipguard-dev, internal name is ipguard */
182
		$pkg_internal_name = $package['internal_name'];
183
	} else {
184
		$pkg_internal_name = $package['name'];
185
	}
186
	return $pkg_internal_name;
187
}
188

    
189
/****f* pkg-utils/get_pkg_info
190
 * NAME
191
 *   get_pkg_info - Retrieve package information from pfsense.com.
192
 * INPUTS
193
 *   $pkgs - 'all' to retrieve all packages, an array containing package names otherwise
194
 *   $info - 'all' to retrieve all information, an array containing keys otherwise
195
 * RESULT
196
 *   $raw_versions - Array containing retrieved information, indexed by package name.
197
 ******/
198
function get_pkg_info($pkgs = 'all', $info = 'all') {
199
	global $g;
200

    
201
	$freebsd_version = php_uname("r");
202
	$freebsd_machine = php_uname("m");
203
	$params = array(
204
		"pkg" => $pkgs, 
205
		"info" => $info, 
206
		"freebsd_version" => $freebsd_version[0],
207
		"freebsd_machine" => $freebsd_machine
208
	);
209
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
210
	return $resp ? $resp : array();
211
}
212

    
213
function get_pkg_sizes($pkgs = 'all') {
214
	global $config, $g;
215

    
216
	$freebsd_version = php_uname("r");
217
	$freebsd_machine = php_uname("m");
218
	$params = array(
219
		"pkg" => $pkgs, 
220
		"freebsd_version" => $freebsd_version,
221
		"freebsd_machine" => $freebsd_machine
222
	);
223
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
224
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
225
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
226
	$resp = $cli->send($msg, 10);
227
	if(!is_object($resp))
228
		log_error("Could not get response from XMLRPC server!");
229
 	else if (!$resp->faultCode()) {
230
		$raw_versions = $resp->value();
231
		return xmlrpc_value_to_php($raw_versions);
232
	}
233

    
234
	return array();
235
}
236

    
237
/*
238
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
239
 * This function may also print output to the terminal indicating progress.
240
 */
241
function resync_all_package_configs($show_message = false) {
242
	global $config, $pkg_interface, $g;
243

    
244
	log_error(gettext("Resyncing configuration for all packages."));
245

    
246
	if (!is_array($config['installedpackages']['package']))
247
		return;
248

    
249
	if($show_message == true)
250
		echo "Syncing packages:";
251

    
252
	conf_mount_rw();
253

    
254
	foreach($config['installedpackages']['package'] as $idx => $package) {
255
		if (empty($package['name']))
256
			continue;
257
		if($show_message == true)
258
			echo " " . $package['name'];
259
		get_pkg_depends($package['name'], "all");
260
		if($g['booting'] != true)
261
			stop_service(get_pkg_internal_name($package));
262
		sync_package($idx, true, true);
263
		if($pkg_interface == "console") 
264
			echo "\n" . gettext("Syncing packages:");
265
	}
266

    
267
	if($show_message == true)
268
		echo " done.\n";
269

    
270
	@unlink("/conf/needs_package_sync");
271
	conf_mount_ro();
272
}
273

    
274
/*
275
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
276
 *				package is installed.
277
 */
278
function is_freebsd_pkg_installed($pkg) {
279
	if(!$pkg) 
280
		return;
281
	$output = "";
282
	exec("/usr/local/sbin/pbi_info " . escapeshellarg($pkg), $output, $retval);
283

    
284
	return (intval($retval) == 0);
285
}
286

    
287
/*
288
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
289
 *
290
 * $filetype = "all" || ".xml", ".tgz", etc.
291
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
292
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
293
 *
294
 */
295
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
296
	global $config;
297

    
298
	$pkg_id = get_pkg_id($pkg_name);
299
	if($pkg_id == -1)
300
		return -1; // This package doesn't really exist - exit the function.
301
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
302
		return; // No package belongs to the pkg_id passed to this function.
303

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

    
360
function uninstall_package($pkg_name) {
361
	global $config, $static_output;
362
	global $builder_package_install;
363

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

    
389
	$static_output .= gettext("done.") . "\n";
390
	update_output_window($static_output);
391
}
392

    
393
function force_remove_package($pkg_name) {
394
	delete_package_xml($pkg_name);
395
}
396

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

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

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

    
498
	// Clean up incoming filenames
499
	$filename = str_replace("  ", " ", $filename);
500
	$filename = str_replace("\n", " ", $filename);
501
	$filename = str_replace("  ", " ", $filename);
502

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

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

    
545
		$pkgaddout = "";
546

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

    
570
			update_output_window($static_output);
571
			pkg_debug("pbi_add failed.\n");
572
			return false;
573
		}
574
	}
575
	return true;
576
}
577

    
578
function install_package($package, $pkg_info = "", $force_install = false) {
579
	global $g, $config, $static_output, $pkg_interface;
580

    
581
	/* safe side. Write config below will send to ro again. */
582
	conf_mount_rw();
583

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

    
676
function get_after_install_info($package) {
677
	global $pkg_info;
678
	/* fetch package information if needed */
679
	if(!$pkg_info or !is_array($pkg_info[$package])) {
680
		$pkg_info = get_pkg_info(array($package));
681
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
682
	}
683
	if($pkg_info['after_install_info'])
684
		return $pkg_info['after_install_info'];
685
}
686

    
687
function eval_once($toeval) {
688
	global $evaled;
689
	if(!$evaled) $evaled = array();
690
	$evalmd5 = md5($toeval);
691
	if(!in_array($evalmd5, $evaled)) {
692
		@eval($toeval);
693
		$evaled[] = $evalmd5;
694
	}
695
	return;
696
}
697

    
698
function install_package_xml($pkg) {
699
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
700

    
701
	if(($pkgid = get_pkg_id($pkg)) == -1) {
702
		$static_output .= sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $pkg, "\n\n");
703
		update_output_window($static_output);
704
		if($pkg_interface <> "console") {
705
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
706
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
707
		}
708
		sleep(1);
709
		return false;
710
	} else
711
		$pkg_info = $config['installedpackages']['package'][$pkgid];
712

    
713
	/* pkg_add the package and its dependencies */
714
	if($pkg_info['depends_on_package_base_url'] != "") {
715
		if($pkg_interface == "console") 
716
			echo "\n";
717
		update_status(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies."));
718
		$static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("and its dependencies... ");
719
		$static_orig = $static_output;
720
		$static_output .= "\n";
721
		update_output_window($static_output);
722
		foreach((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) {
723
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
724
			$static_output = $static_orig . "\nChecking for package installation... ";
725
			update_output_window($static_output);
726
			if (!is_freebsd_pkg_installed($pkg_name)) {
727
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
728
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
729
					update_output_window($static_output);
730
					pkg_debug(gettext("Package WAS NOT installed properly.") . "\n");
731
					if($pkg_interface <> "console") {
732
						echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
733
						echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
734
					}
735
					sleep(1);
736
					return false;
737
				}
738
			}
739
		}
740
	}
741
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
742
	if(file_exists("/usr/local/pkg/" . $configfile)) {
743
		$static_output .= gettext("Loading package configuration... ");
744
		update_output_window($static_output);
745
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
746
		$static_output .= gettext("done.") . "\n";
747
		update_output_window($static_output);
748
		$static_output .= gettext("Configuring package components...\n");
749
		if (!empty($pkg_config['filter_rules_needed']))
750
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
751
		update_output_window($static_output);
752
		/* modify system files */
753
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
754
			$static_output .= gettext("System files... ");
755
			update_output_window($static_output);
756
			foreach($pkg_config['modify_system']['item'] as $ms) {
757
				if($ms['textneeded']) {
758
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
759
				}
760
			}
761
			$static_output .= gettext("done.") . "\n";
762
			update_output_window($static_output);
763
		}
764
		/* download additional files */
765
		if(is_array($pkg_config['additional_files_needed'])) {
766
			$static_output .= gettext("Additional files... ");
767
			$static_orig = $static_output;
768
			update_output_window($static_output);
769
			foreach($pkg_config['additional_files_needed'] as $afn) {
770
				$filename = get_filename_from_url($afn['item'][0]);
771
				if($afn['chmod'] <> "")
772
					$pkg_chmod = $afn['chmod'];
773
				else
774
					$pkg_chmod = "";
775

    
776
				if($afn['prefix'] <> "")
777
					$prefix = $afn['prefix'];
778
				else
779
					$prefix = "/usr/local/pkg/";
780

    
781
				if(!is_dir($prefix)) 
782
					safe_mkdir($prefix);
783
 				$static_output .= $filename . " ";
784
				update_output_window($static_output);
785
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
786
					$static_output .= "failed.\n";
787
					@unlink($prefix . $filename);
788
					update_output_window($static_output);
789
					return false;
790
				}
791
				if(stristr($filename, ".tgz") <> "") {
792
					pkg_debug(gettext("Extracting tarball to -C for ") . $filename . "...\n");
793
					$tarout = "";
794
					exec("/usr/bin/tar xvzf " . escapeshellarg($prefix . $filename) . " -C / 2>&1", $tarout);
795
					pkg_debug(print_r($tarout, true) . "\n");
796
				}
797
				if($pkg_chmod <> "") {
798
					pkg_debug(sprintf(gettext('Changing file mode to %1$s for %2$s%3$s%4$s'), $pkg_chmod, $prefix, $filename, "\n"));
799
					@chmod($prefix . $filename, $pkg_chmod);
800
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
801
				}
802
				$static_output = $static_orig;
803
				update_output_window($static_output);
804
			}
805
			$static_output .= gettext("done.") . "\n";
806
			update_output_window($static_output);
807
		}
808
		/*   if a require exists, include it.  this will
809
		 *   show us where an error exists in a package
810
		 *   instead of making us blindly guess
811
		 */
812
		$missing_include = false;
813
		if($pkg_config['include_file'] <> "") {
814
			$static_output = gettext("Loading package instructions...") . "\n";
815
			update_output_window($static_output);
816
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
817
			if (file_exists($pkg_config['include_file']))
818
				require_once($pkg_config['include_file']);
819
			else {
820
				$missing_include = true;
821
				$static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n";
822
				update_output_window($static_output);
823
				/* XXX: Should undo the steps before this?! */
824
				return false;
825
			}
826
		}
827

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

    
936
	/* set up package logging streams */
937
	if($pkg_info['logging']) {
938
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
939
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
940
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
941
		pkg_debug("Adding text to file /etc/syslog.conf\n");
942
		system_syslogd_start();
943
	}
944

    
945
	return true;
946
}
947

    
948
function does_package_depend($pkg) {
949
	// Should not happen, but just in case.
950
	if(!$pkg)
951
		return;
952
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
953
	// If this package has dependency then return true
954
	foreach($pkg_var_db_dir as $pvdd) {
955
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
956
			return true;
957
	}	
958
	// Did not find a record of dependencies, so return false.
959
	return false;
960
}
961

    
962
function delete_package($pkg) {
963
	global $config, $g, $static_output, $vardb;
964

    
965
	if(!$pkg) 
966
		return;
967

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

    
971
	if($pkg)
972
		$static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg);
973
	update_output_window($static_output);
974

    
975
	remove_freebsd_package($pkg);
976
	$static_output .= "done.\n";
977
	update_output_window($static_output);
978

    
979
	/* Rescan directories for what has been left and avoid fooling other programs. */
980
	mwexec("/sbin/ldconfig");
981

    
982
	return;
983
}
984

    
985
function delete_package_xml($pkg) {
986
	global $g, $config, $static_output, $pkg_interface;
987

    
988
	conf_mount_rw();
989

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

    
1079
		/*
1080
		 * If a require exists, include it.  this will
1081
		 * show us where an error exists in a package
1082
		 * instead of making us blindly guess
1083
		 */
1084
		$missing_include = false;
1085
		if($pkg_config['include_file'] <> "") {
1086
			$static_output .= gettext("Loading package instructions...") . "\n";
1087
			update_output_window($static_output);
1088
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
1089
			if (file_exists($pkg_config['include_file']))
1090
				require_once($pkg_config['include_file']);
1091
			else {
1092
				$missing_include = true;
1093
				update_output_window($static_output);
1094
				$static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
1095
			}
1096
		}
1097
		/* ermal
1098
		 * NOTE: It is not possible to handle parse errors on eval.
1099
		 * So we prevent it from being run at all to not interrupt all the other code.
1100
		 */
1101
		if ($missing_include == false) {
1102
			/* evalate this package's global functions and pre deinstall commands */
1103
			if($pkg_config['custom_php_global_functions'] <> "")
1104
				eval_once($pkg_config['custom_php_global_functions']);
1105
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
1106
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
1107
		}
1108
		/* system files */
1109
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
1110
			$static_output .= gettext("System files... ");
1111
			update_output_window($static_output);
1112
			foreach($pkg_config['modify_system']['item'] as $ms)
1113
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
1114

    
1115
			$static_output .= gettext("done.") . "\n";
1116
			update_output_window($static_output);
1117
		}
1118
		/* deinstall commands */
1119
		if($pkg_config['custom_php_deinstall_command'] <> "") {
1120
			$static_output .= gettext("Deinstall commands... ");
1121
			update_output_window($static_output);
1122
			if ($missing_include == false) {
1123
				eval_once($pkg_config['custom_php_deinstall_command']);
1124
				$static_output .= gettext("done.") . "\n";
1125
			} else
1126
				$static_output .= "\nNot executing custom deinstall hook because an include is missing.\n";
1127
			update_output_window($static_output);
1128
		}
1129
		if($pkg_config['include_file'] <> "") {
1130
			$static_output .= gettext("Removing package instructions...");
1131
			update_output_window($static_output);
1132
			pkg_debug(sprintf(gettext("Remove '%s'"), $pkg_config['include_file']) . "\n");
1133
			unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
1134
			$static_output .= gettext("done.") . "\n";
1135
			update_output_window($static_output);
1136
		}
1137
		/* remove all additional files */
1138
		if(is_array($pkg_config['additional_files_needed'])) {
1139
			$static_output .= gettext("Auxiliary files... ");
1140
			update_output_window($static_output);
1141
			foreach($pkg_config['additional_files_needed'] as $afn) {
1142
				$filename = get_filename_from_url($afn['item'][0]);
1143
				if($afn['prefix'] <> "")
1144
					$prefix = $afn['prefix'];
1145
				else
1146
					$prefix = "/usr/local/pkg/";
1147
				unlink_if_exists($prefix . $filename);
1148
			}
1149
			$static_output .= gettext("done.") . "\n";
1150
			update_output_window($static_output);
1151
		}
1152
		/* package XML file */
1153
		$static_output .= gettext("Package XML... ");
1154
		update_output_window($static_output);
1155
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1156
		$static_output .= gettext("done.") . "\n";
1157
		update_output_window($static_output);
1158
	}
1159
	/* syslog */
1160
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
1161
		$static_output .= "Syslog entries... ";
1162
		update_output_window($static_output);
1163
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1164
		system_syslogd_start();
1165
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1166
		$static_output .= "done.\n";
1167
		update_output_window($static_output);
1168
	}
1169
	
1170
	conf_mount_ro();
1171
	/* remove config.xml entries */
1172
	$static_output .= gettext("Configuration... ");
1173
	update_output_window($static_output);
1174
	unset($config['installedpackages']['package'][$pkgid]);
1175
	$static_output .= gettext("done.") . "\n";
1176
	update_output_window($static_output);
1177
	write_config("Removed {$pkg} package.\n");
1178
}
1179

    
1180
function expand_to_bytes($size) {
1181
	$conv = array(
1182
			"G" =>	"3",
1183
			"M" =>  "2",
1184
			"K" =>  "1",
1185
			"B" =>  "0"
1186
		);
1187
	$suffix = substr($size, -1);
1188
	if(!in_array($suffix, array_keys($conv))) return $size;
1189
	$size = substr($size, 0, -1);
1190
	for($i = 0; $i < $conv[$suffix]; $i++) {
1191
		$size *= 1024;
1192
	}
1193
	return $size;
1194
}
1195

    
1196
function get_pkg_db() {
1197
	global $g;
1198
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1199
}
1200

    
1201
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1202
	if(!$pkgdb)
1203
		$pkgdb = get_pkg_db();
1204
	if(!is_array($alreadyseen))
1205
		$alreadyseen = array();
1206
	if (!is_array($depend))
1207
		$depend = array();
1208
	foreach($depend as $adepend) {
1209
		$pkgname = reverse_strrchr($adepend['name'], '.');
1210
		if(in_array($pkgname, $alreadyseen)) {
1211
			continue;
1212
		} elseif(!in_array($pkgname, $pkgdb)) {
1213
			$size += expand_to_bytes($adepend['size']);
1214
			$alreadyseen[] = $pkgname;
1215
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1216
		}
1217
	}
1218
	return $size;
1219
}
1220

    
1221
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1222
	global $config, $g;
1223
	if((!is_array($pkg)) and ($pkg != 'all'))
1224
		$pkg = array($pkg);
1225
	$pkgdb = get_pkg_db();
1226
	if(!$pkg_info)
1227
		$pkg_info = get_pkg_sizes($pkg);
1228
	foreach($pkg as $apkg) {
1229
		if(!$pkg_info[$apkg])
1230
			continue;
1231
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1232
	}
1233
	return $toreturn;
1234
}
1235

    
1236
function squash_from_bytes($size, $round = "") {
1237
	$conv = array(1 => "B", "K", "M", "G");
1238
	foreach($conv as $div => $suffix) {
1239
		$sizeorig = $size;
1240
		if(($size /= 1024) < 1) {
1241
			if($round) {
1242
				$sizeorig = round($sizeorig, $round);
1243
			}
1244
			return $sizeorig . $suffix;
1245
		}
1246
	}
1247
	return;
1248
}
1249

    
1250
function pkg_reinstall_all() {
1251
	global $g, $config;
1252

    
1253
	@unlink('/conf/needs_package_sync');
1254
	if (is_array($config['installedpackages']['package'])) {
1255
		echo gettext("One moment please, reinstalling packages...\n");
1256
		echo gettext(" >>> Trying to fetch package info...");
1257
		log_error(gettext("Attempting to reinstall all packages"));
1258
		$pkg_info = get_pkg_info();
1259
		if ($pkg_info) {
1260
			echo " Done.\n";
1261
		} else {
1262
			$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
1263
			$error = 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']);
1264
			echo "\n{$error}\n";
1265
			log_error(gettext("Cannot reinstall packages: ") . $error);
1266
			return;
1267
		}
1268
		$todo = array();
1269
		$all_names = array();
1270
		foreach($config['installedpackages']['package'] as $package) {
1271
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1272
			$all_names[] = $package['name'];
1273
		}
1274
		$package_name_list = gettext("List of packages to reinstall: ") . implode(", ", $all_names);
1275
		echo " >>> {$package_name_list}\n";
1276
		log_error($package_name_list);
1277

    
1278
		foreach($todo as $pkgtodo) {
1279
			$static_output = "";
1280
			if($pkgtodo['name']) {
1281
				log_error(gettext("Uninstalling package") . " {$pkgtodo['name']}");
1282
				uninstall_package($pkgtodo['name']);
1283
				log_error(gettext("Finished uninstalling package") . " {$pkgtodo['name']}");
1284
				log_error(gettext("Reinstalling package") . " {$pkgtodo['name']}");
1285
				install_package($pkgtodo['name']);
1286
				log_error(gettext("Finished installing package") . " {$pkgtodo['name']}");
1287
			}
1288
		}
1289
		log_error(gettext("Finished reinstalling all packages."));
1290
	} else
1291
		echo "No packages are installed.";
1292
}
1293

    
1294
function stop_packages() {
1295
	require_once("config.inc");
1296
	require_once("functions.inc");
1297
	require_once("filter.inc");
1298
	require_once("shaper.inc");
1299
	require_once("captiveportal.inc");
1300
	require_once("pkg-utils.inc");
1301
	require_once("pfsense-utils.inc");
1302
	require_once("service-utils.inc");
1303

    
1304
	global $config, $g;
1305

    
1306
	log_error("Stopping all packages.");
1307

    
1308
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1309
	if (!$rcfiles)
1310
		$rcfiles = array();
1311
	else {
1312
		$rcfiles = array_flip($rcfiles);
1313
		if (!$rcfiles)
1314
			$rcfiles = array();
1315
	}
1316

    
1317
	if (is_array($config['installedpackages']['package'])) {
1318
		foreach($config['installedpackages']['package'] as $package) {
1319
			echo " Stopping package {$package['name']}...";
1320
			$internal_name = get_pkg_internal_name($package);
1321
			stop_service($internal_name);
1322
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1323
			echo "done.\n";
1324
		}
1325
	}
1326

    
1327
	foreach ($rcfiles as $rcfile => $number) {
1328
		$shell = @popen("/bin/sh", "w");
1329
		if ($shell) {
1330
			echo " Stopping {$rcfile}...";
1331
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1332
				if ($shell)
1333
					pclose($shell);
1334
				$shell = @popen("/bin/sh", "w");
1335
			}
1336
			echo "done.\n";
1337
			pclose($shell);
1338
		}
1339
	}
1340
}
1341

    
1342
function get_pkg_interfaces_select_source($include_localhost=false) {
1343
	$interfaces = get_configured_interface_with_descr();
1344
	$ssifs = array();
1345
	foreach ($interfaces as $iface => $ifacename) {
1346
		$tmp["name"]  = $ifacename;
1347
		$tmp["value"] = $iface;
1348
		$ssifs[] = $tmp;
1349
	}
1350
	if ($include_localhost) {
1351
		$tmp["name"]  = "Localhost";
1352
		$tmp["value"] = "lo0";
1353
		$ssifs[] = $tmp;
1354
	}
1355
	return $ssifs;
1356
}
1357
?>
(40-40/66)