Project

General

Profile

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

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

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

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

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

    
68
		if (!$debug)
69
			return;
70

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

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

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

    
90
/****f* pkg-utils/remove_package
91
 * NAME
92
 *   remove_package - Removes package from FreeBSD if it exists
93
 * INPUTS
94
 *   $packagestring	- name/string to check for
95
 * RESULT
96
 *   none
97
 * NOTES
98
 *   
99
 ******/
100
function remove_freebsd_package($packagestring) {
101
	exec("/usr/sbin/pkg_delete -x {$packagestring}");
102
}
103

    
104
/****f* pkg-utils/is_package_installed
105
 * NAME
106
 *   is_package_installed - Check whether a package is installed.
107
 * INPUTS
108
 *   $packagename	- name of the package to check
109
 * RESULT
110
 *   boolean	- true if the package is installed, false otherwise
111
 * NOTES
112
 *   This function is deprecated - get_pkg_id() can already check for installation.
113
 ******/
114
function is_package_installed($packagename) {
115
	$pkg = get_pkg_id($packagename);
116
	if($pkg == -1)
117
		return false;
118
	return true;
119
}
120

    
121
/****f* pkg-utils/get_pkg_id
122
 * NAME
123
 *   get_pkg_id - Find a package's numeric ID.
124
 * INPUTS
125
 *   $pkg_name	- name of the package to check
126
 * RESULT
127
 *   integer    - -1 if package is not found, >-1 otherwise
128
 ******/
129
function get_pkg_id($pkg_name) {
130
	global $config;
131

    
132
	if (is_array($config['installedpackages']['package'])) {
133
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
134
			if($pkg['name'] == $pkg_name)
135
				return $idx;
136
		}
137
	}
138
	return -1;
139
}
140

    
141
/****f* pkg-utils/get_pkg_info
142
 * NAME
143
 *   get_pkg_info - Retrive package information from pfsense.com.
144
 * INPUTS
145
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
146
 *   $info - 'all' to retrive all information, an array containing keys otherwise
147
 * RESULT
148
 *   $raw_versions - Array containing retrieved information, indexed by package name.
149
 ******/
150
function get_pkg_info($pkgs = 'all', $info = 'all') {
151
	global $g;
152

    
153
	$freebsd_version = php_uname("r");
154
	$freebsd_machine = php_uname("m");
155
	$params = array(
156
		"pkg" => $pkgs, 
157
		"info" => $info, 
158
		"freebsd_version" => $freebsd_version[0],
159
		"freebsd_machine" => $freebsd_machine
160
	);
161
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
162
	return $resp ? $resp : array();
163
}
164

    
165
function get_pkg_sizes($pkgs = 'all') {
166
	global $config, $g;
167

    
168
	$freebsd_version = php_uname("r");
169
	$freebsd_machine = php_uname("m");
170
	$params = array(
171
		"pkg" => $pkgs, 
172
		"freebsd_version" => $freebsd_version,
173
		"freebsd_machine" => $freebsd_machine
174
	);
175
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
176
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
177
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
178
	$resp = $cli->send($msg, 10);
179
	if(!is_object($resp))
180
		log_error("Could not get response from XMLRPC server!");
181
 	else if (!$resp->faultCode()) {
182
		$raw_versions = $resp->value();
183
		return xmlrpc_value_to_php($raw_versions);
184
	}
185

    
186
	return array();
187
}
188

    
189
/*
190
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
191
 * This function may also print output to the terminal indicating progress.
192
 */
193
function resync_all_package_configs($show_message = false) {
194
	global $config, $pkg_interface;
195

    
196
	log_error("Resyncing configuration for all packages.");
197
	if (!is_array($config['installedpackages']['package']))
198
		return;
199
	if($show_message == true)
200
		echo "Syncing packages:";
201

    
202
	conf_mount_rw();
203
	foreach($config['installedpackages']['package'] as $idx => $package) {
204
		if (empty($package['name']))
205
			continue;
206
		if($show_message == true)
207
			echo " " . $package['name'];
208
		get_pkg_depends($package['name'], "all");
209
		stop_service($package['name']);
210
		sync_package($idx, true, true);
211
		if($pkg_interface == "console") 
212
			echo "\nSyncing packages:";
213
	}
214
	if($show_message == true)
215
		echo " done.\n";
216
	@unlink("/conf/needs_package_sync");
217
	conf_mount_ro();
218
}
219

    
220
/*
221
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
222
 *				package is installed.
223
 */
224
function is_freebsd_pkg_installed($pkg) {
225
	$output = "";
226
	exec("/usr/sbin/pkg_info -E \"{$pkg}*\"", $output, $retval);
227

    
228
	return (intval($retval) == 0);
229
}
230

    
231
/*
232
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
233
 *
234
 * $filetype = "all" || ".xml", ".tgz", etc.
235
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
236
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
237
 *
238
 */
239
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
240
	global $config;
241

    
242
	$pkg_id = get_pkg_id($pkg_name);
243
	if($pkg_id == -1)
244
		return -1; // This package doesn't really exist - exit the function.
245
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
246
		return; // No package belongs to the pkg_id passed to this function.
247

    
248
	$package =& $config['installedpackages']['package'][$pkg_id];
249
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
250
		log_error("The {$package['name']} package is missing required dependencies and is being reinstalled." . $package['configurationfile']);
251
		uninstall_package($package['name']);
252
		if (install_package($package['name']) < 0) {
253
			log_error("Failed reinstalling package {$package['name']}.");
254
			return false;
255
		}
256
	}
257
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
258
	if (!empty($pkg_xml['additional_files_needed'])) {
259
		foreach($pkg_xml['additional_files_needed'] as $item) {
260
			if ($return_nosync == 0 && isset($item['nosync']))
261
				continue; // Do not return depends with nosync set if not required.
262
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
263
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
264
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file)))
265
					continue;
266
			if ($item['prefix'] != "")
267
				$prefix = $item['prefix'];
268
			else
269
				$prefix = "/usr/local/pkg/";
270
			// Ensure that the prefix exists to avoid installation errors.
271
			if(!is_dir($prefix)) 
272
				exec("/bin/mkdir -p {$prefix}");
273
			if(!file_exists($prefix . $depend_file))
274
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
275
			switch ($format) {
276
			case "files":
277
				$depends[] = $prefix . $depend_file;
278
				break;
279
			case "names":
280
				switch ($filetype) {
281
				case "all":
282
					if(preg_match("/\.xml/i", $depend_file)) {
283
						$depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui");
284
						if (!empty($depend_xml))
285
							$depends[] = $depend_xml['name'];
286
					} else
287
						$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
288
					break;
289
				case ".xml":
290
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
291
					if (!empty($depend_xml))
292
						$depends[] = $depend_xml['name'];
293
					break;
294
				default:
295
					$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
296
					break;
297
				}
298
			}
299
		}
300
		return $depends;
301
	}
302
}
303

    
304
function uninstall_package($pkg_name) {
305
	global $config, $static_output;
306

    
307
	$id = get_pkg_id($pkg_name);
308
	if ($id >= 0) {
309
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
310
		$static_output .= "Removing package...\n";
311
		update_output_window($static_output);
312
		if (is_array($pkg_depends)) {
313
			foreach ($pkg_depends as $pkg_depend)
314
				delete_package($pkg_depend);
315
		}
316
	}
317
	delete_package_xml($pkg_name);
318
}
319

    
320
function force_remove_package($pkg_name) {
321
	delete_package_xml($pkg_name);
322
}
323

    
324
/*
325
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
326
 */
327
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
328
	global $config, $config_parsed;
329
	
330
	if(empty($config['installedpackages']['package']))
331
		return;
332
	if(!is_numeric($pkg_name)) {
333
		$pkg_id = get_pkg_id($pkg_name);
334
		if($pkg_id == -1)
335
			return -1; // This package doesn't really exist - exit the function.
336
	} else {
337
		$pkg_id = $pkg_name;
338
		if(empty($config['installedpackages']['package'][$pkg_id]))
339
			return;  // No package belongs to the pkg_id passed to this function.
340
	}
341
        if (is_array($config['installedpackages']['package'][$pkg_id]))
342
		$package =& $config['installedpackages']['package'][$pkg_id];
343
        else
344
		return; /* empty package tag */
345
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
346
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
347
		force_remove_package($package['name']);
348
		return -1;
349
	}
350
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
351
	if(isset($pkg_config['nosync']))
352
		return;
353
	/* Bring in package include files */
354
	if (!empty($pkg_config['include_file'])) {
355
		$include_file = $pkg_config['include_file'];
356
		if (file_exists($include_file))
357
			require_once($include_file);
358
		else {
359
			/* XXX: What the heck is this?! */
360
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
361
			uninstall_package($package['name']);
362
			if (install_package($package['name']) < 0) {
363
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
364
				return -1;
365
			}
366
		}
367
	}
368

    
369
	if(!empty($pkg_config['custom_php_global_functions']))
370
		eval($pkg_config['custom_php_global_functions']);
371
	if(!empty($pkg_config['custom_php_resync_config_command']))
372
		eval($pkg_config['custom_php_resync_config_command']);
373
	if($sync_depends == true) {
374
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
375
		if(is_array($depends)) {
376
			foreach($depends as $item) {
377
				if(!file_exists($item)) {
378
					require_once("notices.inc");
379
					file_notice($package['name'], "The {$package['name']} package is missing required dependencies and must be reinstalled.", "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1);
380
					log_error("Could not find {$item}. Reinstalling package.");
381
					uninstall_package($pkg_name);
382
					if (install_package($pkg_name) < 0) {
383
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
384
						return -1;
385
					}
386
				} else {
387
					$item_config = parse_xml_config_pkg($item, "packagegui");
388
					if (empty($item_config))
389
						continue;
390
					if(isset($item_config['nosync']))
391
						continue;
392
					if (!empty($item_config['include_file'])) {
393
						if (file_exists($item_config['include_file']))	
394
							require_once($item_config['include_file']);
395
						else {
396
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
397
							continue;
398
						}
399
					}
400
					if($item_config['custom_php_global_functions'] <> "")
401
						eval($item_config['custom_php_global_functions']);
402
					if($item_config['custom_php_resync_config_command'] <> "")
403
						eval($item_config['custom_php_resync_config_command']);
404
					if($show_message == true)
405
						print " " . $item_config['name'];
406
				}
407
			}
408
		}
409
	}
410
}
411

    
412
/*
413
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
414
 * 			a progress bar and output window.
415
 */
416
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
417
	global $static_output, $g;
418

    
419
	$osname = php_uname("s");
420
	$arch =  php_uname("m");
421
	$rel = php_uname("r");
422
	$rel = substr($rel, 0, strrpos($rel, "-"));
423
	$priv_url = "http://ftp2.{$osname}.org/pub/{$osname}/ports/{$arch}/packages-{$rel}/Latest";
424
	if (empty($base_url))
425
		$base_url = $priv_url;
426
	if (substr($base_url, -1) == "/")
427
		$base_url = substr($base_url, 0, -1);
428
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
429
	$fetchto = "{$g['tmp_path']}/apkg_{$filename}";
430
	if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
431
		if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
432
			$static_output .= " could not download.\n";
433
			update_output_window($static_output);
434
			return false;
435
		} else if ($base_url == $priv_url) {
436
			$static_output .= " failed to download.\n";
437
			update_output_window($static_output);
438
			return false;
439
		} else {
440
			$static_output .= " downloaded from {$osname} repository instead of provided one.\n";
441
			update_output_window($static_output);
442
		}
443
	}
444
	$static_output .= " (extracting)";
445
	update_output_window($static_output);
446
	$slaveout = "";
447
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
448
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
449
	if ($raw_depends_list != "") {
450
		$pkg_extension = ".tbz";
451
		foreach($raw_depends_list as $adepend) {
452
			$working_depend = explode(" ", trim($adepend, "\n"));
453
			if (substr($working_depend[1], -4) != ".tbz")
454
				$depend_filename = $working_depend[1] . $pkg_extension;
455
			else
456
				$depend_filename = $working_depend[1];
457
			if (!is_freebsd_pkg_installed($working_depend[1])) {
458
				if (pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url) == false)
459
					return false;
460
			} else {
461
				//$dependlevel++;
462
				$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " already installed.";
463
				pkg_debug($working_depend[1] . "\n");
464
			}
465
		}
466
	}
467
	$pkgaddout = "";
468
	exec("/usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
469
	pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\npkg_add successfully completed.\n");
470

    
471
	return true;
472
}
473

    
474
function install_package($package, $pkg_info = "") {
475
	global $g, $config, $static_output, $pkg_interface;
476

    
477
	/* safe side. Write config below will send to ro again. */
478
	conf_mount_rw();
479

    
480
	if($pkg_interface == "console") 	
481
		echo "\n";
482
	/* fetch package information if needed */
483
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
484
		$pkg_info = get_pkg_info(array($package));
485
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
486
		if (empty($pkg_info)) {
487
			conf_mount_ro();
488
			return -1;
489
		}
490
	}
491
	pkg_debug("Beginning package installation.\n");
492
	log_error('Beginning package installation for ' . $pkg_info['name'] . '.');
493
	$static_output .= "Beginning package installation for " . $pkg_info['name'] . "...";
494
	update_status($static_output);
495
	/* fetch the package's configuration file */
496
	if($pkg_info['config_file'] != "") {
497
		$static_output .= "\nDownloading package configuration file... ";
498
		update_output_window($static_output);
499
		pkg_debug("Downloading package configuration file...\n");
500
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
501
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
502
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
503
			pkg_debug("ERROR! Unable to fetch package configuration file. Aborting installation.\n");
504
			if($pkg_interface == "console")
505
				print "\nERROR! Unable to fetch package configuration file. Aborting package installation.\n";
506
			else {
507
				$static_output .= "failed!\n\nInstallation aborted.";
508
				update_output_window($static_output);
509
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
510
			}
511
			conf_mount_ro();
512
			return -1;
513
		}
514
		$static_output .= "done.\n";
515
		update_output_window($static_output);
516
	}
517
	/* add package information to config.xml */
518
	$pkgid = get_pkg_id($pkg_info['name']);
519
	$static_output .= "Saving updated package information... ";
520
	update_output_window($static_output);
521
	if($pkgid == -1) {
522
		$config['installedpackages']['package'][] = $pkg_info;
523
		$changedesc = "Installed {$pkg_info['name']} package.";
524
		$to_output = "done.\n";
525
	} else {
526
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
527
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
528
		$to_output = "overwrite!\n";
529
	}
530
	/* XXX: Fix inclusion of config.inc that causes data loss! */
531
	conf_mount_ro();
532
	write_config();
533
	$static_output .= $to_output;
534
	update_output_window($static_output);
535
	/* install other package components */
536
	if (!install_package_xml($package)) {
537
		uninstall_package($package);
538
		write_config($changedesc);
539
		$static_output .= "Failed to install package.\n";
540
		update_output_window($static_output);
541
		return -1;
542
	} else {
543
		$static_output .= "Writing configuration... ";
544
		update_output_window($static_output);
545
		write_config($changedesc);
546
		$static_output .= "done.\n";
547
		update_output_window($static_output);
548
		$static_output .= "Starting service.\n";
549
		update_output_window($static_output);
550
		if($pkg_info['after_install_info']) 
551
			update_output_window($pkg_info['after_install_info']);	
552
		start_service($pkg_info['name']);
553
	}
554
}
555

    
556
function get_after_install_info($package) {
557
	global $pkg_info;
558
	/* fetch package information if needed */
559
	if(!$pkg_info or !is_array($pkg_info[$package])) {
560
		$pkg_info = get_pkg_info(array($package));
561
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
562
	}
563
	if($pkg_info['after_install_info'])
564
		return $pkg_info['after_install_info'];
565
}
566

    
567
function eval_once($toeval) {
568
	global $evaled;
569
	if(!$evaled) $evaled = array();
570
	$evalmd5 = md5($toeval);
571
	if(!in_array($evalmd5, $evaled)) {
572
		@eval($toeval);
573
		$evaled[] = $evalmd5;
574
	}
575
	return;
576
}
577

    
578
function install_package_xml($pkg) {
579
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
580

    
581
	if(($pkgid = get_pkg_id($pkg)) == -1) {
582
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
583
		update_output_window($static_output);
584
		if($pkg_interface <> "console") {
585
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
586
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
587
		}
588
		sleep(1);
589
		return false;
590
	} else
591
		$pkg_info = $config['installedpackages']['package'][$pkgid];
592

    
593
	/* pkg_add the package and its dependencies */
594
	if($pkg_info['depends_on_package_base_url'] != "") {
595
		if($pkg_interface == "console") 
596
			echo "\n";
597
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
598
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
599
		$static_orig = $static_output;
600
		$static_output .= "\n";
601
		update_output_window($static_output);
602
		foreach((array) $pkg_info['depends_on_package'] as $pkgdep) {
603
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
604
			$static_output = $static_orig . "\nChecking for package installation... ";
605
			update_output_window($static_output);
606
			if (!is_freebsd_pkg_installed($pkg_name)) {
607
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
608
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
609
					update_output_window($static_output);
610
					pkg_debug("Package WAS NOT installed properly.\n");
611
					if($pkg_interface <> "console") {
612
						echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
613
						echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
614
					}
615
					sleep(1);
616
					return false;
617
				}
618
			}
619
		}
620
	}
621
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
622
	if(file_exists("/usr/local/pkg/" . $configfile)) {
623
		$static_output .= "\nLoading package configuration... ";
624
		update_output_window($static_output);
625
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
626
		$static_output .= "done.\n";
627
		update_output_window($static_output);
628
		$static_output .= "\tConfiguring package components...\n";
629
		if (!empty($pkg_config['filter_rules_needed']))
630
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
631
		update_output_window($static_output);
632
		/* modify system files */
633
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
634
			$static_output .= "\tSystem files... ";
635
			update_output_window($static_output);
636
			foreach($pkg_config['modify_system']['item'] as $ms) {
637
				if($ms['textneeded']) {
638
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
639
				}
640
			}
641
			$static_output .= "done.\n";
642
			update_output_window($static_output);
643
		}
644
		/* download additional files */
645
		if(is_array($pkg_config['additional_files_needed'])) {
646
			$static_output .= "\tAdditional files... ";
647
			$static_orig = $static_output;
648
			update_output_window($static_output);
649
			foreach($pkg_config['additional_files_needed'] as $afn) {
650
				$filename = get_filename_from_url($afn['item'][0]);
651
				if($afn['chmod'] <> "")
652
					$pkg_chmod = $afn['chmod'];
653
				else
654
					$pkg_chmod = "";
655

    
656
				if($afn['prefix'] <> "")
657
					$prefix = $afn['prefix'];
658
				else
659
					$prefix = "/usr/local/pkg/";
660

    
661
				if(!is_dir($prefix)) 
662
					safe_mkdir($prefix);
663
 				$static_output .= $filename . " ";
664
                                update_output_window($static_output);
665
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
666
					$static_output .= "failed.\n";
667
					update_output_window($static_output);
668
					return false;
669
				}
670
				if(stristr($filename, ".tgz") <> "") {
671
					pkg_debug("Extracting tarball to -C for " . $filename . "...\n");
672
					$tarout = "";
673
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
674
					pkg_debug(print_r($tarout, true) . "\n");
675
				}
676
				if($pkg_chmod <> "") {
677
					pkg_debug("Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
678
					@chmod($prefix . $filename, $pkg_chmod);
679
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
680
				}
681
				$static_output = $static_orig;
682
                                update_output_window($static_output);
683
			}
684
			$static_output .= "done.\n";
685
			update_output_window($static_output);
686
		}
687
		/*   if a require exists, include it.  this will
688
		 *   show us where an error exists in a package
689
		 *   instead of making us blindly guess
690
		 */
691
		$missing_include = false;
692
		if($pkg_config['include_file'] <> "") {
693
			$static_output .= "Loading package instructions...\n";
694
			update_output_window($static_output);
695
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
696
			if (file_exists($pkg_config['include_file']))
697
				require_once($pkg_config['include_file']);
698
			else {
699
				$missing_include = true;
700
				$static_output .= "\tInclude " . basename($pkg_config['include_file']) . " is missing!\n";
701
				update_output_window($static_output);
702
				/* XXX: Should undo the steps before this?! */
703
				return false;
704
			}
705
		}
706
		/* sidebar items */
707
		if(is_array($pkg_config['menu'])) {
708
			$static_output .= "\tMenu items... ";
709
			update_output_window($static_output);
710
			foreach($pkg_config['menu'] as $menu) {
711
				if(is_array($config['installedpackages']['menu']))
712
					foreach($config['installedpackages']['menu'] as $amenu)
713
						if($amenu['name'] == $menu['name'])
714
							continue 2;
715
				$config['installedpackages']['menu'][] = $menu;
716
			}
717
			$static_output .= "done.\n";
718
			update_output_window($static_output);
719
		}
720
		/* integrated tab items */
721
		if(is_array($pkg_config['tabs']['tab'])) {
722
			$static_output .= "\tIntegrated Tab items... ";
723
			update_output_window($static_output);
724
			foreach($pkg_config['tabs']['tab'] as $tab) {
725
				if(is_array($config['installedpackages']['tab']))
726
					foreach($config['installedpackages']['tab'] as $atab)
727
						if($atab['name'] == $tab['name'])
728
							continue 2;
729
				$config['installedpackages']['tab'][] = $tab;
730
			}
731
			$static_output .= "done.\n";
732
			update_output_window($static_output);
733
		}
734
		/* services */
735
		if(is_array($pkg_config['service'])) {
736
			$static_output .= "\tServices... ";
737
			update_output_window($static_output);
738
			foreach($pkg_config['service'] as $service) {
739
				if(is_array($config['installedpackages']['service']))
740
					foreach($config['installedpackages']['service'] as $aservice)
741
						if($aservice['name'] == $service['name'])
742
							continue 2;
743
				$config['installedpackages']['service'][] = $service;
744
			}
745
			$static_output .= "done.\n";
746
			update_output_window($static_output);
747
		}
748
		/* custom commands */
749
		$static_output .= "Custom commands...\n";
750
		update_output_window($static_output);
751
		if ($missing_include == false) {
752
			if($pkg_config['custom_php_global_functions'] <> "") {
753
				$static_output .= "\tExecuting custom_php_global_functions()...";
754
				update_output_window($static_output);
755
				eval_once($pkg_config['custom_php_global_functions']);
756
				$static_output .= "done.\n";
757
				update_output_window($static_output);
758
			}
759
			if($pkg_config['custom_php_install_command']) {
760
				$static_output .= "\tExecuting custom_php_install_command()...";
761
				update_output_window($static_output);
762
				eval_once($pkg_config['custom_php_install_command']);
763
				$static_output .= "done.\n";
764
				update_output_window($static_output);
765
			}
766
			if($pkg_config['custom_php_resync_config_command'] <> "") {
767
				$static_output .= "\tExecuting custom_php_resync_config_command()...";
768
				update_output_window($static_output);
769
				eval_once($pkg_config['custom_php_resync_config_command']);
770
				$static_output .= "done.\n";
771
				update_output_window($static_output);
772
			}
773
		}
774
	} else {
775
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
776
		update_output_window($static_output);
777
		pkg_debug("Unable to load package configuration. Installation aborted.\n");
778
		if($pkg_interface <> "console") {
779
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
780
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
781
		}
782
		sleep(1);
783
		return false;
784
	}
785

    
786
	/* set up package logging streams */
787
	if($pkg_info['logging']) {
788
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
789
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
790
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
791
		pkg_debug("Adding text to file /etc/syslog.conf\n");
792
		system_syslogd_start();
793
	}
794

    
795
	return true;
796
}
797

    
798
function delete_package($pkg) {
799
	global $config, $g, $static_output, $vardb;
800

    
801
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
802

    
803

    
804
	if (file_exists("{$vardb}/{$pkg}/+REQUIRED_BY") && count(file("{$vardb}/{$pkg}/+REQUIRED_BY")) > 0) {
805
		$static_output .= "\tSkipping package deletion for {$pkg} because it is required by other packages.\n";
806
		update_output_window($static_output);
807
		return;
808
	} else {
809
		if($pkg)
810
			$static_output .= "\tStarting package deletion for {$pkg}...";
811
		update_output_window($static_output);
812
	}
813
	$info = "";
814
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
815
	remove_freebsd_package($pkg);
816
	$static_output .= "done.\n";
817
	update_output_window($static_output);
818
	foreach($info as $line) {
819
		$depend = trim(str_replace("@pkgdep", "", $line), " \n");
820
		delete_package($depend);
821
	}
822

    
823
	return;
824
}
825

    
826
function delete_package_xml($pkg) {
827
	global $g, $config, $static_output, $pkg_interface;
828

    
829
	conf_mount_rw();
830

    
831
	$pkgid = get_pkg_id($pkg);
832
	if ($pkgid == -1) {
833
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
834
		update_output_window($static_output);
835
		if($pkg_interface <> "console") {
836
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
837
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
838
		}
839
		ob_flush();
840
		sleep(1);
841
		conf_mount_ro();
842
		return;
843
	}
844
	pkg_debug("Removing {$pkg} package... ");
845
	$static_output .= "Removing {$pkg} components...\n";
846
	update_output_window($static_output);
847
	/* parse package configuration */
848
	$packages = &$config['installedpackages']['package'];
849
	$tabs =& $config['installedpackages']['tab'];
850
	$menus =& $config['installedpackages']['menu'];
851
	$services = &$config['installedpackages']['service'];
852
	$pkg_info =& $packages[$pkgid];
853
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
854
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
855
		/* remove tab items */
856
		if(is_array($pkg_config['tabs'])) {
857
			$static_output .= "\tTabs items... ";
858
			update_output_window($static_output);
859
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
860
				foreach($pkg_config['tabs']['tab'] as $tab) {
861
					foreach($tabs as $key => $insttab) {
862
						if($insttab['name'] == $tab['name']) {
863
							unset($tabs[$key]);
864
							break;
865
						}
866
					}
867
				}
868
			}
869
			$static_output .= "done.\n";
870
			update_output_window($static_output);
871
		}
872
		/* remove menu items */
873
		if(is_array($pkg_config['menu'])) {
874
			$static_output .= "\tMenu items... ";
875
			update_output_window($static_output);
876
			if (is_array($pkg_config['menu']) && is_array($menus)) {
877
				foreach($pkg_config['menu'] as $menu) {
878
					foreach($menus as $key => $instmenu) {
879
						if($instmenu['name'] == $menu['name']) {
880
							unset($menus[$key]);
881
							break;
882
						}
883
					}
884
				}
885
			}
886
			$static_output .= "done.\n";
887
			update_output_window($static_output);
888
		}
889
		/* remove services */
890
		if(is_array($pkg_config['service'])) {
891
			$static_output .= "\tServices... ";
892
			update_output_window($static_output);
893
			if (is_array($pkg_config['service']) && is_array($services)) {
894
				foreach($pkg_config['service'] as $service) {
895
					foreach($services as $key => $instservice) {
896
						if($instservice['name'] == $service['name']) {
897
							stop_service($service['name']);
898
							unset($services[$key]);
899
						}
900
					}
901
				}
902
			}
903
			$static_output .= "done.\n";
904
			update_output_window($static_output);
905
		}
906
		/*
907
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
908
		 * 	Same is done during installation.
909
		 */
910
		write_config();
911

    
912
		/*
913
		 * If a require exists, include it.  this will
914
		 * show us where an error exists in a package
915
		 * instead of making us blindly guess
916
		 */
917
		$missing_include = false;
918
		if($pkg_config['include_file'] <> "") {
919
			$static_output .= "Loading package instructions...\n";
920
			update_output_window($static_output);
921
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
922
			if (file_exists($pkg_config['include_file']))
923
				require_once($pkg_config['include_file']);
924
			else {
925
				$missing_include = true;
926
				update_output_window($static_output);
927
				$static_output .= "\tInclude file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
928
			}
929
		}
930
		/* ermal
931
		 * NOTE: It is not possible to handle parse errors on eval.
932
		 * So we prevent it from being run at all to not interrupt all the other code.
933
		 */
934
		if ($missing_include == false) {
935
			/* evalate this package's global functions and pre deinstall commands */
936
			if($pkg_config['custom_php_global_functions'] <> "")
937
				eval_once($pkg_config['custom_php_global_functions']);
938
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
939
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
940
		}
941
		/* system files */
942
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
943
			$static_output .= "\tSystem files... ";
944
			update_output_window($static_output);
945
			foreach($pkg_config['modify_system']['item'] as $ms)
946
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
947

    
948
			$static_output .= "done.\n";
949
			update_output_window($static_output);
950
		}
951
		/* deinstall commands */
952
		if($pkg_config['custom_php_deinstall_command'] <> "") {
953
			$static_output .= "\tDeinstall commands... ";
954
			update_output_window($static_output);
955
			if ($missing_include == false) {
956
				eval_once($pkg_config['custom_php_deinstall_command']);
957
				$static_output .= "done.\n";
958
			} else
959
				$static_output .= "\n\tNot executing custom deinstall hook because an include is missing.\n";
960
			update_output_window($static_output);
961
		}
962
		if($pkg_config['include_file'] <> "") {
963
                        $static_output .= "\tRemoving package instructions...";
964
                        update_output_window($static_output);
965
                        pkg_debug("Remove '{$pkg_config['include_file']}'\n");
966
                        unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
967
			$static_output .= "done.\n";
968
                        update_output_window($static_output);
969
			
970
                }
971
		/* remove all additional files */
972
		if(is_array($pkg_config['additional_files_needed'])) {
973
			$static_output .= "\tAuxiliary files... ";
974
			update_output_window($static_output);
975
			foreach($pkg_config['additional_files_needed'] as $afn) {
976
				$filename = get_filename_from_url($afn['item'][0]);
977
				if($afn['prefix'] <> "")
978
					$prefix = $afn['prefix'];
979
				else
980
					$prefix = "/usr/local/pkg/";
981

    
982
				unlink_if_exists($prefix . $filename);
983
			}
984
			$static_output .= "done.\n";
985
			update_output_window($static_output);
986
		}
987
		/* package XML file */
988
		$static_output .= "\tPackage XML... ";
989
		update_output_window($static_output);
990
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
991
		$static_output .= "done.\n";
992
		update_output_window($static_output);
993
	}
994
	/* syslog */
995
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
996
		$static_output .= "\tSyslog entries... ";
997
		update_output_window($static_output);
998
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
999
		system_syslogd_start();
1000
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1001
		$static_output .= "done.\n";
1002
		update_output_window($static_output);
1003
	}
1004
	conf_mount_ro();
1005
	/* remove config.xml entries */
1006
	$static_output .= "\tConfiguration... ";
1007
	update_output_window($static_output);
1008
	unset($config['installedpackages']['package'][$pkgid]);
1009
	$static_output .= "done.\n";
1010
	update_output_window($static_output);
1011
	write_config("Removed {$pkg} package.\n");
1012
}
1013

    
1014
function expand_to_bytes($size) {
1015
	$conv = array(
1016
			"G" =>	"3",
1017
			"M" =>  "2",
1018
			"K" =>  "1",
1019
			"B" =>  "0"
1020
		);
1021
	$suffix = substr($size, -1);
1022
	if(!in_array($suffix, array_keys($conv))) return $size;
1023
	$size = substr($size, 0, -1);
1024
	for($i = 0; $i < $conv[$suffix]; $i++) {
1025
		$size *= 1024;
1026
	}
1027
	return $size;
1028
}
1029

    
1030
function get_pkg_db() {
1031
	global $g;
1032
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1033
}
1034

    
1035
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1036
	if(!$pkgdb)
1037
		$pkgdb = get_pkg_db();
1038
	if(!is_array($alreadyseen))
1039
		$alreadyseen = array();
1040
	if (!is_array($depend))
1041
		$depend = array();
1042
	foreach($depend as $adepend) {
1043
		$pkgname = reverse_strrchr($adepend['name'], '.');
1044
		if(in_array($pkgname, $alreadyseen)) {
1045
			continue;
1046
		} elseif(!in_array($pkgname, $pkgdb)) {
1047
			$size += expand_to_bytes($adepend['size']);
1048
			$alreadyseen[] = $pkgname;
1049
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1050
		}
1051
	}
1052
	return $size;
1053
}
1054

    
1055
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1056
	global $config, $g;
1057
	if((!is_array($pkg)) and ($pkg != 'all'))
1058
		$pkg = array($pkg);
1059
	$pkgdb = get_pkg_db();
1060
	if(!$pkg_info)
1061
		$pkg_info = get_pkg_sizes($pkg);
1062
	foreach($pkg as $apkg) {
1063
		if(!$pkg_info[$apkg])
1064
			continue;
1065
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1066
	}
1067
	return $toreturn;
1068
}
1069

    
1070
function squash_from_bytes($size, $round = "") {
1071
	$conv = array(1 => "B", "K", "M", "G");
1072
	foreach($conv as $div => $suffix) {
1073
		$sizeorig = $size;
1074
		if(($size /= 1024) < 1) {
1075
			if($round) {
1076
				$sizeorig = round($sizeorig, $round);
1077
			}
1078
			return $sizeorig . $suffix;
1079
		}
1080
	}
1081
	return;
1082
}
1083

    
1084
?>
(31-31/54)