Project

General

Profile

Download (49.1 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6
 *   This file contains various functions used by the pfSense package system.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11
 * Copyright (C) 2010 Ermal Luci
12
 * Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
13
 * All rights reserved.
14
 * Redistribution and use in source and binary forms, with or without
15
 * modification, are permitted provided that the following conditions are met:
16
 *
17
 * 1. Redistributions of source code must retain the above copyright notice,
18
 * this list of conditions and the following disclaimer.
19
 *
20
 * 2. Redistributions in binary form must reproduce the above copyright
21
 * notice, this list of conditions and the following disclaimer in the
22
 * documentation and/or other materials provided with the distribution.
23
 *
24
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
25
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
26
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
28
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33
 * POSSIBILITY OF SUCH DAMAGE.
34
 *
35
 */
36

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

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

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

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

    
69
		if (!$debug)
70
			return;
71

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

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

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

    
91
/****f* pkg-utils/remove_package
92
 * NAME
93
 *   remove_package - Removes package from FreeBSD if it exists
94
 * INPUTS
95
 *   $packagestring	- name/string to check for
96
 * RESULT
97
 *   none
98
 * NOTES
99
 *   
100
 ******/
101
function remove_freebsd_package($packagestring) {
102
	// The packagestring passed in must be the full PBI package name, 
103
	// as displayed by the pbi_info utility. e.g. "package-1.2.3_4-i386" 
104
	// It must NOT have ".pbi" on the end.
105
	exec("/usr/local/sbin/pbi_info " . 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 package server.
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_machine = php_uname("m");
202
	$params = array(
203
		"pkg" => $pkgs, 
204
		"info" => $info, 
205
		"freebsd_version" => get_freebsd_version(),
206
		"freebsd_machine" => $freebsd_machine
207
	);
208
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
209
	return $resp ? $resp : array();
210
}
211

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

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

    
232
	return array();
233
}
234

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

    
242
	log_error(gettext("Resyncing configuration for all packages."));
243

    
244
	if (!is_array($config['installedpackages']['package']))
245
		return;
246

    
247
	if($show_message == true)
248
		echo "Syncing packages:";
249

    
250
	conf_mount_rw();
251

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

    
265
	if($show_message == true)
266
		echo " done.\n";
267

    
268
	@unlink("/conf/needs_package_sync");
269
	conf_mount_ro();
270
}
271

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

    
282
	return (intval($retval) == 0);
283
}
284

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

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

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

    
358
function uninstall_package($pkg_name) {
359
	global $config, $static_output;
360
	global $builder_package_install;
361

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

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

    
391
function force_remove_package($pkg_name) {
392
	delete_package_xml($pkg_name);
393
}
394

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

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

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

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

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

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

    
541
		$pkgaddout = "";
542

    
543
		$no_checksig = "";
544
		if (isset($config['system']['pkg_nochecksig']))
545
			$no_checksig = "--no-checksig";
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
			foreach(array('bin', 'sbin') as $dir) {
554
				if(!is_dir("{$pbidir}/{$dir}"))
555
					continue;
556

    
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
			pkg_debug("pbi_add successfully completed.\n");
563
		} else {
564
			if (is_array($pkgaddout))
565
				foreach ($pkgaddout as $line)
566
					$static_output .= " " . $line .= "\n";
567

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

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

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

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

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

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

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

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

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

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

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

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

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

    
943
	return true;
944
}
945

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

    
960
function delete_package($pkg) {
961
	global $config, $g, $static_output, $vardb;
962

    
963
	if(!$pkg) 
964
		return;
965

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

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

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

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

    
980
	return;
981
}
982

    
983
function delete_package_xml($pkg) {
984
	global $g, $config, $static_output, $pkg_interface;
985

    
986
	conf_mount_rw();
987

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

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

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

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

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

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

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

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

    
1248
function pkg_reinstall_all() {
1249
	global $g, $config;
1250

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

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

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

    
1302
	global $config, $g;
1303

    
1304
	log_error("Stopping all packages.");
1305

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

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

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

    
1340
function package_skip_tests($index,$requested_version){
1341
	global $config, $g;
1342

    
1343
	/* Get pfsense version*/
1344
	$version = rtrim(file_get_contents("/etc/version"));
1345
	
1346
	if($g['platform'] == "nanobsd")
1347
		if($index['noembedded']) 
1348
			return true;
1349
						
1350
	/* If we are on not on HEAD, and the package wants it, skip */
1351
	if ($version <> "HEAD" && $index['required_version'] == "HEAD" && $requested_version <> "other")
1352
		return true;
1353
							
1354
	/* If there is no required version, and the requested package version is not 'none', then skip */
1355
	if (empty($index['required_version']) && $requested_version <> "none")
1356
		return true;
1357
							
1358
	/* If the requested version is not 'other', and the required version is newer than what we have, skip. */
1359
	if($requested_version <> "other" && (pfs_version_compare("", $version, $index['required_version']) < 0))
1360
		return true;
1361
							
1362
	/* If the requestion version is 'other' and we are on the version requested, skip. */
1363
	if($requested_version == "other" && (pfs_version_compare("", $version, $index['required_version']) == 0))
1364
		return true;
1365
							
1366
	/* Package is only for an older version, lets skip */
1367
	if($index['maximum_version'] && (pfs_version_compare("", $version, $index['maximum_version']) > 0))
1368
		return true;
1369
		
1370
	/* Do not skip package list */	
1371
	return false;
1372
}
1373

    
1374
function get_pkg_interfaces_select_source($include_localhost=false) {
1375
	$interfaces = get_configured_interface_with_descr();
1376
	$ssifs = array();
1377
	foreach ($interfaces as $iface => $ifacename) {
1378
		$tmp["name"]  = $ifacename;
1379
		$tmp["value"] = $iface;
1380
		$ssifs[] = $tmp;
1381
	}
1382
	if ($include_localhost) {
1383
		$tmp["name"]  = "Localhost";
1384
		$tmp["value"] = "lo0";
1385
		$ssifs[] = $tmp;
1386
	}
1387
	return $ssifs;
1388
}
1389
?>
(40-40/67)