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
	if (is_package_installed($pkg_name))
388
		delete_package_xml($pkg_name);
389

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

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

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

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

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

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

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

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

    
546
		$pkgaddout = "";
547

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

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

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

    
582
	/* safe side. */
583
	conf_mount_rw();
584

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

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

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

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

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

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

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

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

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

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

    
946
	return true;
947
}
948

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

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

    
966
	if(!$pkg) 
967
		return;
968

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

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

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

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

    
983
	return;
984
}
985

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

    
989
	conf_mount_rw();
990

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

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

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

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

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

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

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

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

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

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

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

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

    
1305
	global $config, $g;
1306

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

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

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

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

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