Project

General

Profile

Download (46.7 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 {$packagestring} | /usr/bin/awk '/Prefix/ {print $2}'",$pbidir);
106
	$pbidir = $pbidir[0];
107
	if ($pbidir == "") {
108
		log_error("PBI dir for {$packagestring} was not found - cannot cleanup PBI files");
109
	}
110
	else {
111
		$linkdirs = array('bin','sbin');
112
		foreach($linkdirs as $dir) {
113
			$target_dir = $pbidir . "/" . $dir;
114
			if(is_dir($target_dir)) {
115
				$files = scandir($target_dir);
116
				foreach($files as $f) {
117
					if($f != '.' && $f != '..') {
118
						// Only try to unlink the file if it is a link to the expected pbi dir.
119
						$local_name = "/usr/local/{$dir}/{$f}";
120
						if(is_link($local_name)) {
121
							if(substr(readlink($local_name),0,strlen($target_dir)) == $target_dir) {
122
								unlink($local_name);
123
							}
124
						}
125
					}
126
				}
127
			}
128
		}
129

    
130
		exec("/usr/local/sbin/pbi_delete {$packagestring} 2>>/tmp/pbi_delete_errors.txt");
131
	}
132
}
133

    
134
/****f* pkg-utils/is_package_installed
135
 * NAME
136
 *   is_package_installed - Check whether a package is installed.
137
 * INPUTS
138
 *   $packagename	- name of the package to check
139
 * RESULT
140
 *   boolean	- true if the package is installed, false otherwise
141
 * NOTES
142
 *   This function is deprecated - get_pkg_id() can already check for installation.
143
 ******/
144
function is_package_installed($packagename) {
145
	$pkg = get_pkg_id($packagename);
146
	if($pkg == -1)
147
		return false;
148
	return true;
149
}
150

    
151
/****f* pkg-utils/get_pkg_id
152
 * NAME
153
 *   get_pkg_id - Find a package's numeric ID.
154
 * INPUTS
155
 *   $pkg_name	- name of the package to check
156
 * RESULT
157
 *   integer    - -1 if package is not found, >-1 otherwise
158
 ******/
159
function get_pkg_id($pkg_name) {
160
	global $config;
161

    
162
	if (is_array($config['installedpackages']['package'])) {
163
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
164
			if($pkg['name'] == $pkg_name)
165
				return $idx;
166
		}
167
	}
168
	return -1;
169
}
170

    
171
/****f* pkg-utils/get_pkg_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 \"{$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
	// Back up /usr/local/lib libraries first if
365
	// not running from the builder code.
366
	// also take into account rrd binaries
367
	if(!$builder_package_install) {
368
		if(!file_exists("/tmp/pkg_libs.tgz")) {
369
			$static_output .= "Backing up libraries... ";
370
			update_output_window($static_output);
371
			mwexec("/usr/bin/tar czPf /tmp/pkg_libs.tgz `/bin/cat /etc/pfSense_md5.txt | /usr/bin/grep 'local/lib' | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1`", true);
372
			mwexec("/usr/bin/tar czPf /tmp/pkg_bins.tgz `/bin/cat /etc/pfSense_md5.txt | /usr/bin/grep 'rrd' | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1`", true);
373
			$static_output .= "\n";
374
		}
375
	}
376

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

    
402
	// Restore libraries that we backed up if not 
403
	// running from the builder code.
404
	if(!$builder_package_install) {
405
		$static_output .= "Cleaning up... ";
406
		update_output_window($static_output);
407
		mwexec("/usr/bin/tar xzPfk /tmp/pkg_libs.tgz -C /", true);
408
		mwexec("/usr/bin/tar xzPfk /tmp/pkg_bins.tgz -C /", true);
409
		@unlink("/tmp/pkg_libs.tgz");
410
		@unlink("/tmp/pkg_bins.tgz");
411
		$static_output .= gettext("done.") . "\n";
412
		update_output_window($static_output);
413
	}
414
}
415

    
416
function force_remove_package($pkg_name) {
417
	delete_package_xml($pkg_name);
418
}
419

    
420
/*
421
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
422
 */
423
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
424
	global $config, $config_parsed;
425
	global $builder_package_install;
426
	
427
	// If this code is being called by pfspkg_installer 
428
	// which the builder system uses then return (ignore).
429
	if($builder_package_install)
430
		return;
431
	
432
	if(empty($config['installedpackages']['package']))
433
		return;
434
	if(!is_numeric($pkg_name)) {
435
		$pkg_id = get_pkg_id($pkg_name);
436
		if($pkg_id == -1)
437
			return -1; // This package doesn't really exist - exit the function.
438
	} else {
439
		$pkg_id = $pkg_name;
440
		if(empty($config['installedpackages']['package'][$pkg_id]))
441
			return;  // No package belongs to the pkg_id passed to this function.
442
	}
443
        if (is_array($config['installedpackages']['package'][$pkg_id]))
444
		$package =& $config['installedpackages']['package'][$pkg_id];
445
        else
446
		return; /* empty package tag */
447
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
448
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
449
		force_remove_package($package['name']);
450
		return -1;
451
	}
452
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
453
	if(isset($pkg_config['nosync']))
454
		return;
455
	/* Bring in package include files */
456
	if (!empty($pkg_config['include_file'])) {
457
		$include_file = $pkg_config['include_file'];
458
		if (file_exists($include_file))
459
			require_once($include_file);
460
		else {
461
			/* XXX: What the heck is this?! */
462
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
463
			uninstall_package($package['name']);
464
			if (install_package($package['name']) < 0) {
465
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
466
				return -1;
467
			}
468
		}
469
	}
470

    
471
	if(!empty($pkg_config['custom_php_global_functions']))
472
		eval($pkg_config['custom_php_global_functions']);
473
	if(!empty($pkg_config['custom_php_resync_config_command']))
474
		eval($pkg_config['custom_php_resync_config_command']);
475
	if($sync_depends == true) {
476
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
477
		if(is_array($depends)) {
478
			foreach($depends as $item) {
479
				if(!file_exists($item)) {
480
					require_once("notices.inc");
481
					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);
482
					log_error("Could not find {$item}. Reinstalling package.");
483
					uninstall_package($pkg_name);
484
					if (install_package($pkg_name) < 0) {
485
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
486
						return -1;
487
					}
488
				} else {
489
					$item_config = parse_xml_config_pkg($item, "packagegui");
490
					if (empty($item_config))
491
						continue;
492
					if(isset($item_config['nosync']))
493
						continue;
494
					if (!empty($item_config['include_file'])) {
495
						if (file_exists($item_config['include_file']))	
496
							require_once($item_config['include_file']);
497
						else {
498
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
499
							continue;
500
						}
501
					}
502
					if($item_config['custom_php_global_functions'] <> "")
503
						eval($item_config['custom_php_global_functions']);
504
					if($item_config['custom_php_resync_config_command'] <> "")
505
						eval($item_config['custom_php_resync_config_command']);
506
					if($show_message == true)
507
						print " " . $item_config['name'];
508
				}
509
			}
510
		}
511
	}
512
}
513

    
514
/*
515
 * pkg_fetch_recursive: Download and install a FreeBSD PBI package. This function provides output to
516
 * 			a progress bar and output window.
517
 */
518
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
519
	global $static_output, $g;
520

    
521
	// Clean up incoming filenames
522
	$filename = str_replace("  ", " ", $filename);
523
	$filename = str_replace("\n", " ", $filename);
524
	$filename = str_replace("  ", " ", $filename);
525

    
526
	$pkgs = explode(" ", $filename);
527
	foreach($pkgs as $filename) {
528
		$filename = trim($filename);
529
		if (($g['platform'] == "nanobsd") || ($g['platform'] == "embedded")) {
530
			$pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ ";
531
			$pkgstagingdir = "/root/tmp";
532
			if (!is_dir($pkgstagingdir))
533
				mkdir($pkgstagingdir);
534
			$pkgstaging = "-o {$pkgstagingdir}/instmp.XXXXXX";
535
			$fetchdir = $pkgstagingdir;
536
		} else {
537
			$fetchdir = $g['tmp_path'];
538
		}
539

    
540
		/* FreeBSD has no PBI's hosted, so fall back to our own URL for now. (Maybe fail to PC-BSD?) */
541
		$arch = php_uname("m");
542
		$arch = ($arch == "i386") ? "" : $arch . '/';
543
		$rel = get_freebsd_version();
544
		$priv_url = "http://files.pfsense.org/packages/{$arch}{$rel}/All/";
545
		if (empty($base_url))
546
			$base_url = $priv_url;
547
		if (substr($base_url, -1) == "/")
548
			$base_url = substr($base_url, 0, -1);
549
		$fetchto = "{$fetchdir}/apkg_{$filename}";
550
		$static_output .= "\n" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... ";
551
		if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
552
			if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
553
				$static_output .= " could not download from there or {$priv_url}/{$filename}.\n";
554
				update_output_window($static_output);
555
				return false;
556
			} else if ($base_url == $priv_url) {
557
				$static_output .= " failed to download.\n";
558
				update_output_window($static_output);
559
				return false;
560
			} else {
561
				$static_output .= " [{$osname} repository]\n";
562
				update_output_window($static_output);
563
			}
564
		}
565
		$static_output .= " (extracting)\n";
566
		update_output_window($static_output);
567

    
568
		$pkgaddout = "";
569

    
570
		exec("/usr/local/sbin/pbi_add {$pkgstaging} -f -v --no-checksig {$fetchto} 2>&1", $pkgaddout);
571
		pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\npbi_add successfully completed.\n");
572
		setup_library_paths();
573
		exec("/usr/local/sbin/pbi_info " . preg_replace('/\.pbi$/','',$filename) . " | /usr/bin/awk '/Prefix/ {print $2}'",$pbidir);
574
		$pbidir = $pbidir[0];
575
		$linkdirs = array('bin','sbin');
576
		foreach($linkdirs as $dir) {
577
			if(is_dir("{$pbidir}/{$dir}")) {
578
				$files = scandir("{$pbidir}/{$dir}");
579
				foreach($files as $f) {
580
					if(!file_exists("/usr/local/{$dir}/{$f}")) {
581
						symlink("{$pbidir}/{$dir}/{$f}","/usr/local/{$dir}/{$f}");
582
					}
583
				}
584
			}
585
		}
586
	}
587
	return true;
588
}
589

    
590
function install_package($package, $pkg_info = "") {
591
	global $g, $config, $static_output, $pkg_interface;
592

    
593
	/* safe side. Write config below will send to ro again. */
594
	conf_mount_rw();
595

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

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

    
681
function eval_once($toeval) {
682
	global $evaled;
683
	if(!$evaled) $evaled = array();
684
	$evalmd5 = md5($toeval);
685
	if(!in_array($evalmd5, $evaled)) {
686
		@eval($toeval);
687
		$evaled[] = $evalmd5;
688
	}
689
	return;
690
}
691

    
692
function install_package_xml($pkg) {
693
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
694

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

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

    
770
				if($afn['prefix'] <> "")
771
					$prefix = $afn['prefix'];
772
				else
773
					$prefix = "/usr/local/pkg/";
774

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

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

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

    
939
	return true;
940
}
941

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

    
956
function delete_package($pkg) {
957
	global $config, $g, $static_output, $vardb;
958

    
959
	if(!$pkg) 
960
		return;
961

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

    
965
	if($pkg)
966
		$static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg);
967
	update_output_window($static_output);
968

    
969
	remove_freebsd_package($pkg);
970
	$static_output .= "done.\n";
971
	update_output_window($static_output);
972

    
973
	/* Rescan directories for what has been left and avoid fooling other programs. */
974
	mwexec("/sbin/ldconfig");
975

    
976
	return;
977
}
978

    
979
function delete_package_xml($pkg) {
980
	global $g, $config, $static_output, $pkg_interface;
981

    
982
	conf_mount_rw();
983

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

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

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

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

    
1190
function get_pkg_db() {
1191
	global $g;
1192
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1193
}
1194

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

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

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

    
1244
function pkg_reinstall_all() {
1245
	global $g, $config;
1246

    
1247
	@unlink('/conf/needs_package_sync');
1248
	$pkg_id = 0;
1249
	$todo = array();
1250
	if (is_array($config['installedpackages']['package']))
1251
		foreach($config['installedpackages']['package'] as $package)
1252
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1253
	echo "One moment please, reinstalling packages...\n";
1254
	echo " >>> Trying to fetch package info...";
1255
	$pkg_info = get_pkg_info();
1256
	if ($pkg_info) {
1257
		echo " Done.\n";
1258
	} else {
1259
		$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
1260
		echo "\n" . sprintf(gettext(' >>> Unable to communicate with %1$s. Please verify DNS and interface configuration, and that %2$s has functional Internet connectivity.'), $xmlrpc_base_url, $g['product_name']) . "\n";
1261
		return;
1262
	}
1263
	if(is_array($todo)) {
1264
		foreach($todo as $pkgtodo) {
1265
			$static_output = "";
1266
			if($pkgtodo['name']) {
1267
				uninstall_package($pkgtodo['name']);
1268
				install_package($pkgtodo['name']);
1269
				$pkg_id++;
1270
			}
1271
		}
1272
	}
1273
}
1274

    
1275
function stop_packages() {
1276
	require_once("config.inc");
1277
	require_once("functions.inc");
1278
	require_once("filter.inc");
1279
	require_once("shaper.inc");
1280
	require_once("captiveportal.inc");
1281
	require_once("pkg-utils.inc");
1282
	require_once("pfsense-utils.inc");
1283
	require_once("service-utils.inc");
1284

    
1285
	global $config, $g;
1286

    
1287
	log_error("Stopping all packages.");
1288

    
1289
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1290
	if (!$rcfiles)
1291
		$rcfiles = array();
1292
	else {
1293
		$rcfiles = array_flip($rcfiles);
1294
		if (!$rcfiles)
1295
			$rcfiles = array();
1296
	}
1297

    
1298
	if (is_array($config['installedpackages']['package'])) {
1299
		foreach($config['installedpackages']['package'] as $package) {
1300
			echo " Stopping package {$package['name']}...";
1301
			$internal_name = get_pkg_internal_name($package);
1302
			stop_service($internal_name);
1303
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1304
			echo "done.\n";
1305
		}
1306
	}
1307

    
1308
	$shell = @popen("/bin/sh", "w");
1309
	if ($shell) {
1310
		foreach ($rcfiles as $rcfile => $number) {
1311
			echo " Stopping {$rcfile}...";
1312
			fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1");
1313
			echo "done.\n";
1314
		}
1315

    
1316
		pclose($shell);
1317
	}
1318
}
1319

    
1320
?>
(40-40/67)