Project

General

Profile

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

    
41
safe_mkdir("/var/db/pkg");
42
$g['platform'] = trim(file_get_contents("/etc/platform"));
43
if($g['platform'] == "pfSense") {
44
	safe_mkdir("/usr/local/pkg");
45
	safe_mkdir("/usr/local/pkg/pf");
46
}
47

    
48
$version = split("-", trim(file_get_contents("/etc/version")));
49
$ver = split("\.", $version[0]);
50
$g['version'] = intval($ver[1]);
51

    
52
/****f* pkg-utils/remove_package
53
 * NAME
54
 *   remove_package - Removes package from FreeBSD if it exists
55
 * INPUTS
56
 *   $packagestring	- name/string to check for
57
 * RESULT
58
 *   none
59
 * NOTES
60
 *   
61
 ******/
62
function remove_freebsd_package($packagestring) {
63
	exec("cd /var/db/pkg && echo y | pkg_delete `ls | grep $packagestring`");
64
}
65

    
66
/****f* pkg-utils/is_package_installed
67
 * NAME
68
 *   is_package_installed - Check whether a package is installed.
69
 * INPUTS
70
 *   $packagename	- name of the package to check
71
 * RESULT
72
 *   boolean	- true if the package is installed, false otherwise
73
 * NOTES
74
 *   This function is deprecated - get_pkg_id() can already check for installation.
75
 ******/
76
function is_package_installed($packagename) {
77
	$pkg = get_pkg_id($packagename);
78
	if($pkg == -1) return false;
79
	return true;
80
}
81

    
82
/****f* pkg-utils/get_pkg_id
83
 * NAME
84
 *   get_pkg_id - Find a package's numeric ID.
85
 * INPUTS
86
 *   $pkg_name	- name of the package to check
87
 * RESULT
88
 *   integer    - -1 if package is not found, >-1 otherwise
89
 ******/
90
function get_pkg_id($pkg_name) {
91
	global $config;
92

    
93
	if(is_array($config['installedpackages']['package'])) {
94
		$i = 0;
95
		foreach($config['installedpackages']['package'] as $pkg) {
96
			if($pkg['name'] == $pkg_name) return $i;
97
			$i++;
98
		}
99
	}
100
	return -1;
101
}
102

    
103
/****f* pkg-utils/get_pkg_info
104
 * NAME
105
 *   get_pkg_info - Retrive package information from pfsense.com.
106
 * INPUTS
107
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
108
 *   $info - 'all' to retrive all information, an array containing keys otherwise
109
 * RESULT
110
 *   $raw_versions - Array containing retrieved information, indexed by package name.
111
 ******/
112
function get_pkg_info($pkgs = 'all', $info = 'all') {
113
	global $g;
114
	$freebsd_version = str_replace("\n", "", `uname -r | cut -d'-' -f1 | cut -d'.' -f1`);
115
	$params = array(
116
		"pkg" => $pkgs, 
117
		"info" => $info, 
118
		"freebsd_version" => $freebsd_version
119
		);
120
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
121
	return $resp ? $resp : array();
122
}
123

    
124
function get_pkg_sizes($pkgs = 'all') {
125
	global $g;
126
	$params = array("pkg" => $pkgs);
127
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
128
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $g['xmlrpcbaseurl']);
129
	$resp = $cli->send($msg, 10);
130
	if($resp and !$resp->faultCode()) {
131
		$raw_versions = $resp->value();
132
		return xmlrpc_value_to_php($raw_versions);
133
	} else {
134
		return array();
135
	}
136
}
137

    
138
/*
139
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
140
 * This function may also print output to the terminal indicating progress.
141
 */
142
function resync_all_package_configs($show_message = false) {
143
	global $config, $restart_sync, $pkg_interface;
144
	$i = 0;
145
	log_error("Resyncing configuration for all packages.");
146
	if(!$config['installedpackages']['package']) return;
147
	if($show_message == true) print "Syncing packages:";
148
	foreach($config['installedpackages']['package'] as $package) {
149
		if($show_message == true) print " " . $package['name'];
150
		get_pkg_depends($package['name'], "all");
151
		stop_service($package['name']);
152
		sync_package($i, true, true);
153
		if($restart_sync == true) {
154
			$restart_sync = false;
155
			if($pkg_interface == "console") 
156
				echo "\nSyncing packages:";
157
		}
158
		$i++;
159
	}
160
	if($show_message == true) print ".\n";
161
}
162

    
163
/*
164
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
165
 *				package is installed.
166
 */
167
function is_freebsd_pkg_installed($pkg) {
168
	global $g;
169
	if(in_array($pkg, return_dir_as_array("{$g['vardb_path']}/pkg"))) return true;
170
	return false;
171
}
172

    
173
/*
174
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
175
 *
176
 * $filetype = "all" || ".xml", ".tgz", etc.
177
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
178
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
179
 *
180
 */
181
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
182
	global $config;
183
	require_once("notices.inc");
184
	$pkg_id = get_pkg_id($pkg_name);
185
	if(!is_numeric($pkg_name)) {
186
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
187
	} else {
188
		if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
189
	}
190
	$package = $config['installedpackages']['package'][$pkg_id];
191
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
192
		log_error("The {$package['name']} package is missing required dependencies and must be reinstalled." . $package['configurationfile']);
193
		install_package($package['name']);
194
		uninstall_package_from_name($package['name']);
195
		install_package($package['name']);
196
		return;
197
	}
198
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
199
	if($pkg_xml['additional_files_needed'] != "") {
200
		foreach($pkg_xml['additional_files_needed'] as $item) {
201
			if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
202
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
203
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
204
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file))) continue;
205
			if ($item['prefix'] != "") {
206
				$prefix = $item['prefix'];
207
			} else {
208
				$prefix = "/usr/local/pkg/";
209
			}
210
			if(!file_exists($prefix . $depend_file))
211
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
212
			switch ($format) {
213
				case "files":
214
				$depends[] = $depend_file;
215
			break;
216
            			case "names":
217
                		switch ($filetype) {
218

    
219
				case "all":
220
				if(preg_match("/\.xml/i", $depend_file)) {
221
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
222
					$depends[] = $depend_xml['name'];
223
					break;
224
				} else {
225
					$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
226
				break;
227
				}
228
				case ".xml":
229
				$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
230
				$depends[] = $depend_xml['name'];
231
				break;
232
				default:
233
				$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
234
				break;
235
				}
236
			}
237
		}
238
		return $depends;
239
	}
240
}
241

    
242
function uninstall_package_from_name($pkg_name) {
243
	global $config;
244
	$id = get_pkg_id($pkg_name);
245
	$todel = substr(reverse_strrchr($config['installedpackages']['package'][$id]['depends_on_package'], "."), 0, -1);
246
	delete_package($todel, $pkg_name);
247
	delete_package_xml($pkg_name);
248
	remove_freebsd_package($pkg_name);
249
}
250

    
251
function force_remove_package($pkg_name) {
252
	global $config;
253
	delete_package_xml($pkg_name);
254
}
255

    
256
/*
257
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
258
 */
259
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
260
	global $config;
261
	require_once("notices.inc");
262
	if(!$config['installedpackages']['package']) return;
263
	if(!is_numeric($pkg_name)) {
264
		$pkg_id = get_pkg_id($pkg_name);
265
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
266
	} else {
267
		$pkg_id = $pkg_name;
268
		if(!isset($config['installedpackages']['package'][$pkg_id]))
269
		return;  // No package belongs to the pkg_id passed to this function.
270
	}
271
        if (is_array($config['installedpackages']['package'][$pkg_id]))
272
			$package = $config['installedpackages']['package'][$pkg_id];
273
        else
274
			return; /* empty package tag */
275
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
276
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
277
		force_remove_package($package['name']);
278
	} else {
279
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
280

    
281
		/* Bring in package include files */
282
		if (isset($pkg_config['include_file']) && $pkg_config['include_file'] != "") {
283
			$include_file = $pkg_config['include_file'];
284
			if (file_exists($include_file))
285
				require_once($include_file);
286
			else
287
				if (file_exists($include_file)) {
288
					require_once($include_file);
289
				} else {
290
					log_error("Could not locate {$include_file}.");
291
					install_package($package['name']);
292
					uninstall_package_from_name($package['name']);
293
					remove_freebsd_package($package['name']);
294
					install_package($package['name']);
295
				}
296
		}
297

    
298
		/* XXX: Zend complains about the next line "Wrong break depth"
299
		 * The code is obviously wrong, but I'm not sure what it's supposed to do?
300
		 */
301
		if(isset($pkg_config['nosync'])) continue;
302
		if($pkg_config['custom_php_global_functions'] <> "")
303
		eval($pkg_config['custom_php_global_functions']);
304
		if($pkg_config['custom_php_resync_config_command'] <> "")
305
		eval($pkg_config['custom_php_resync_config_command']);
306
		if($sync_depends == true) {
307
			$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
308
			if(is_array($depends)) {
309
				foreach($depends as $item) {
310
					if(!file_exists("/usr/local/pkg/" . $item)) {
311
						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);
312
						log_error("Could not find {$item}. Reinstalling package.");
313
						install_package($pkg_name);
314
						uninstall_package_from_name($pkg_name);
315
						remove_freebsd_package($pkg_name);						
316
						install_package($pkg_name);
317
					} else {
318
						$item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
319
						if(isset($item_config['nosync'])) continue;
320
						if($item_config['custom_php_command_before_form'] <> "") {
321
							eval($item_config['custom_php_command_before_form']);
322
						}
323
						if($item_config['custom_php_resync_config_command'] <> "") {
324
							eval($item_config['custom_php_resync_config_command']);
325
						}
326
						if($show_message == true) print " " . $item_config['name'];
327
					}
328
				}
329
			}
330
		}
331
	}
332
}
333

    
334
/*
335
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
336
 * 			a progress bar and output window.
337
 *
338
 * XXX: This function needs to return where a pkg_add fails. Our current error messages aren't very descriptive.
339
 */
340
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = 'http://ftp2.freebsd.org/pub/FreeBSD/ports/i386/packages-5.4-release/Latest') {
341
	global $pkgent, $static_output, $g, $fd_log;
342
	$pkg_extension = strrchr($filename, '.');
343
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
344
	$fetchto = "/tmp/apkg_" . $pkgname . $pkg_extension;
345
	download_file_with_progress_bar($base_url . '/' . $filename, $fetchto);
346
	$static_output .= " (extracting)";
347
	update_output_window($static_output);
348
		$slaveout = "";
349
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
350
	$workingdir = preg_grep("/instmp/", $slaveout);
351
	$workingdir = $workingdir[0];
352
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
353
	if($raw_depends_list != "") {
354
		if($pkgent['exclude_dependency'] != "")
355
			$raw_depends_list = array_values(preg_grep($pkgent['exclude_dependency'], PREG_GREP_INVERT));
356
		foreach($raw_depends_list as $adepend) {
357
			$working_depend = explode(" ", $adepend);
358
			//$working_depend = explode("-", $working_depend[1]);
359
			$depend_filename = $working_depend[1] . $pkg_extension;
360
			if(is_freebsd_pkg_installed($working_depend[1]) === false) {
361
				pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url);
362
			} else {
363
//				$dependlevel++;
364
				$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " ";
365
				@fwrite($fd_log, $working_depend[1] . "\n");
366
			}
367
		}
368
	}
369
	$pkgaddout = "";
370
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
371
	@fwrite($fd_log, $pkgname . " " . print_r($pkgaddout, true) . "\n");
372
	return true;
373
}
374

    
375
function install_package($package, $pkg_info = "") {
376
	global $g, $config, $pkg_interface, $fd_log, $static_output, $pkg_interface, $restart_sync;
377
	if($pkg_interface == "console") 	
378
		echo "\n";
379
	/* open logfiles and begin installation */
380
	if(!$fd_log) {
381
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$package}.log", "w")) {
382
			update_output_window("Warning, could not open log for writing.");
383
		}
384
	}
385
	/* fetch package information if needed */
386
	if(!$pkg_info or !is_array($pkg_info[$package])) {
387
		$pkg_info = get_pkg_info(array($package));
388
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
389
	}
390
	@fwrite($fd_log, "Beginning package installation.\n");
391
	log_error('Beginning package installation for ' . $pkg_info['name'] . '.');
392
	update_status("Beginning package installation for " . $pkg_info['name'] . "...");	
393
	/* fetch the package's configuration file */
394
	if($pkg_info['config_file'] != "") {
395
		$static_output .= "Downloading package configuration file... ";
396
		update_output_window($static_output);
397
		@fwrite($fd_log, "Downloading package configuration file...\n");
398
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
399
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
400
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
401
			@fwrite($fd_log, "ERROR! Unable to fetch package configuration file. Aborting installation.\n");
402
			if($pkg_interface == "console") {
403
				print "\nERROR! Unable to fetch package configuration file. Aborting package installation.\n";
404
				return;
405
			} else {
406
				$static_output .= "failed!\n\nInstallation aborted.";
407
				update_output_window($static_output);
408
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
409
			 	return -1;
410
			}
411
		}
412
		$static_output .= "done.\n";
413
		update_output_window($static_output);
414
	}
415
	/* add package information to config.xml */
416
	$pkgid = get_pkg_id($pkg_info['name']);
417
	$static_output .= "Saving updated package information... ";
418
	update_output_window($static_output);
419
	if($pkgid == -1) {
420
		$config['installedpackages']['package'][] = $pkg_info;
421
		$changedesc = "Installed {$pkg_info['name']} package.";
422
		$to_output = "done.\n";
423
	} else {
424
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
425
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
426
		$to_output = "overwrite!\n";
427
	}
428
	$static_output .= $to_output;
429
	update_output_window($static_output);
430
	/* install other package components */
431
	install_package_xml($package);
432
	$static_output .= "Writing configuration... ";
433
	update_output_window($static_output);
434
	write_config($changedesc);
435
	$static_output .= "done.\n";
436
	update_output_window($static_output);
437
	$static_output .= "Starting service.\n";
438
	update_output_window($static_output);
439
	start_service($pkg_info['config_file']);
440
	$restart_sync = true;
441
}
442

    
443
function eval_once($toeval) {
444
	global $evaled;
445
	if(!$evaled) $evaled = array();
446
	$evalmd5 = md5($toeval);
447
	if(!in_array($evalmd5, $evaled)) {
448
		eval($toeval);
449
		$evaled[] = $evalmd5;
450
	}
451
	return;
452
}
453

    
454
function install_package_xml($pkg) {
455
	global $g, $config, $fd_log, $static_output, $pkg_interface;
456
	if(($pkgid = get_pkg_id($pkg)) == -1) {
457
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
458
		update_output_window($static_output);
459
		if($pkg_interface <> "console") {
460
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
461
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
462
		}
463
		sleep(1);
464
		return;
465
	} else {
466
		$pkg_info = $config['installedpackages']['package'][$pkgid];
467
	}
468
	/* set up logging if needed */
469
	if(!$fd_log) {
470
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
471
			update_output_window("Warning, could not open log for writing.");
472
		}
473
	}
474

    
475
	/* set up package logging streams */
476
	if($pkg_info['logging']) {
477
		mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
478
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
479
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
480
		mwexec("killall syslogd");
481
		system_syslogd_start();
482
	}
483

    
484
	/* make 'y' file */
485
	$fd = fopen("{$g['tmp_path']}/y", "w");
486
	for($line = 0; $line < 10; $line++) {
487
		fwrite($fd, "y\n");
488
	}
489
	fclose($fd);
490

    
491
	/* pkg_add the package and its dependencies */
492
	if($pkg_info['depends_on_package_base_url'] != "") {
493
		if($pkg_interface == "console") 
494
			echo "\n";
495
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
496
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
497
		$static_orig = $static_output;
498
		$static_output .= "\n";
499
		update_output_window($static_output);
500
		foreach((array) $pkg_info['depends_on_package'] as $pkgdep) {
501
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
502
			if(isset($pkg_info['skip_install_checks'])) {
503
				$pkg_installed = true;
504
			} else {
505
				$pkg_installed = is_freebsd_pkg_installed($pkg_name);
506
			}
507
			if($pkg_installed == false) pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url']);
508
			$static_output = $static_orig . "done.\nChecking for successful package installation... ";
509
			update_output_window($static_output);
510
			/* make sure our package was successfully installed */
511
			if($pkg_installed == false) $pkg_installed = is_freebsd_pkg_installed($pkg_name);
512
			if($pkg_installed == true) {
513
				$static_output .= "done.\n";
514
				update_output_window($static_output);
515
				fwrite($fd_log, "pkg_add successfully completed.\n");
516
			} else {
517
				$static_output .= "failed!\n\nInstallation aborted.";
518
				update_output_window($static_output);
519
				fwrite($fd_log, "Package WAS NOT installed properly.\n");
520
				fclose($fd_log);
521
				if($pkg_interface <> "console") {
522
					echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
523
					echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
524
				}
525
				sleep(1);
526
				die;
527
			}
528
		}
529
	}
530
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
531
	if(file_exists("/usr/local/pkg/" . $configfile)) {
532
		$static_output .= "Loading package configuration... ";
533
		update_output_window($static_output);
534
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
535
		$static_output .= "done.\n";
536
		update_output_window($static_output);
537
		$static_output .= "Configuring package components...\n";
538
		update_output_window($static_output);
539
		/* modify system files */
540
		if($pkg_config['modify_system']['item'] <> "") {
541
			$static_output .= "\tSystem files... ";
542
			update_output_window($static_output);
543
			foreach($pkg_config['modify_system']['item'] as $ms) {
544
				if($ms['textneeded']) {
545
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
546
				}
547
			}
548
			$static_output .= "done.\n";
549
			update_output_window($static_output);
550
		}
551
		/* download additional files */
552
		if($pkg_config['additional_files_needed'] <> "") {
553
			$static_output .= "\tAdditional files... ";
554
			$static_orig = $static_output;
555
			update_output_window($static_output);
556
			foreach($pkg_config['additional_files_needed'] as $afn) {
557
				$filename = get_filename_from_url($afn['item'][0]);
558
				if($afn['chmod'] <> "") {
559
					$pkg_chmod = $afn['chmod'];
560
				} else {
561
					$pkg_chmod = "";
562
				}
563
				if($afn['prefix'] <> "") {
564
					$prefix = $afn['prefix'];
565
				} else {
566
					$prefix = "/usr/local/pkg/";
567
				}
568
				if(!is_dir($prefix)) 
569
					safe_mkdir($prefix);
570
 				$static_output .= $filename . " ";
571
                                update_output_window($static_output);
572
				download_file_with_progress_bar($afn['item'][0], $prefix . $filename);
573
				if(stristr($filename, ".tgz") <> "") {
574
					fwrite($fd_log, "Extracting tarball to -C for " . $filename . "...\n");
575
					$tarout = "";
576
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
577
					fwrite($fd_log, print_r($tarout, true) . "\n");
578
				}
579
				if($pkg_chmod <> "") {
580
					fwrite($fd_log, "Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
581
					chmod($prefix . $filename, $pkg_chmod);
582
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
583
				}
584
				$static_output = $static_orig;
585
                                update_output_window($static_output);
586
			}
587
			$static_output .= "done.\n";
588
			update_output_window($static_output);
589
		}
590
		/*   if a require exists, include it.  this will
591
		 *   show us where an error exists in a package
592
		 *   instead of making us blindly guess
593
		 */
594
		if($pkg_config['include_file'] <> "") {
595
			$static_output = "Loading package instructions...";
596
			update_output_window($static_output);
597
			fwrite($fd_log, "require_once('include_file')\n");
598
			require_once($pkg_config['include_file']);
599
		}
600
		/* sidebar items */
601
		if($pkg_config['menu'] != "") {
602
			$static_output .= "\tMenu items... ";
603
			update_output_window($static_output);
604
			if(is_array($pkg_config['menu'])) {
605
				foreach($pkg_config['menu'] as $menu) {
606
					if(is_array($config['installedpackages']['menu']))
607
						foreach($config['installedpackages']['menu'] as $amenu)
608
							if($amenu['name'] == $menu['name'])
609
								continue 2;
610
					$config['installedpackages']['menu'][] = $menu;
611
				}
612
			}
613
			$static_output .= "done.\n";
614
			update_output_window($static_output);
615
		}
616
		/* integrated tab items */
617
		if($pkg_config['tabs'] != "") {
618
			$static_output .= "\tIntegrated Tab items... ";
619
			update_output_window($static_output);
620
			if(is_array($pkg_config['tabs']['tab'])) {
621
				foreach($pkg_config['tabs']['tab'] as $tab) {
622
					if(is_array($config['installedpackages']['tab']))
623
						foreach($config['installedpackages']['tab'] as $atab)
624
							if($atab['name'] == $tab['name'])
625
								continue 2;
626
					$config['installedpackages']['tab'][] = $tab;
627
				}
628
			}
629
			$static_output .= "done.\n";
630
			update_output_window($static_output);
631
		}
632
		/* services */
633
		if($pkg_config['service'] != "") {
634
			$static_output .= "\tServices... ";
635
			update_output_window($static_output);
636
			foreach($pkg_config['service'] as $service) {
637
				$config['installedpackages']['service'][] = $service;
638
			}
639
			$static_output .= "done.\n";
640
			update_output_window($static_output);
641
		}
642
		/* custom commands */
643
		$static_output .= "\tCustom commands... ";
644
		update_output_window($static_output);
645
		if($pkg_config['custom_php_global_functions'] <> "") {
646
			$static_output = "Executing custom_php_global_functions()...";
647
			update_output_window($static_output);
648
			eval_once($pkg_config['custom_php_global_functions']);
649
		}
650
		if($pkg_config['custom_php_install_command']) {
651
			$static_output = "Executing custom_php_install_command()...";
652
			update_output_window($static_output);
653
			eval_once($pkg_config['custom_php_install_command']);
654
		}
655
		if($pkg_config['custom_php_resync_config_command'] <> "") {
656
			$static_output = "Executing custom_php_resync_config_command()...";
657
			update_output_window($static_output);
658
			eval_once($pkg_config['custom_php_resync_config_command']);
659
		}
660
		$static_output .= "done.\n";
661
		update_output_window($static_output);
662
	} else {
663
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
664
		update_output_window($static_output);
665
		fwrite($fd_log, "Unable to load package configuration. Installation aborted.\n");
666
		fclose($fd_log);
667
		if($pkg_interface <> "console") {
668
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
669
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
670
		}
671
		sleep(1);
672
		return;
673
	}
674
}
675

    
676
function delete_package($pkg, $pkgid) {
677
	global $g, $config, $fd_log, $static_output;
678
	update_status("Removing package...");
679
	$static_output .= "Removing package... ";
680
	update_output_window($static_output);
681
	$pkgid = get_pkg_id($pkgid);
682
	$pkg_info = $config['installedpackages']['package'][$pkgid];
683

    
684
	$configfile = $pkg_info['configurationfile'];
685
	if(file_exists("/usr/local/pkg/" . $configfile)) {
686
		$static_output .= "\nLoading package configuration $configfile... ";
687
		update_output_window($static_output);
688
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
689
		/*   if a require exists, include it.  this will
690
		 *   show us where an error exists in a package
691
		 *   instead of making us blindly guess
692
		 */
693
		if($pkg_config['include_file'] <> "") {
694
			$static_output .= "\nLoading package instructions...\n";
695
			update_output_window($static_output);
696
			require_once($pkg_config['include_file']);
697
		}
698
	}
699
	$static_output .= "\nStarting package deletion for {$pkg_info['name']}...\n";
700
	update_output_window($static_output);
701
	delete_package_recursive($pkg);
702
	remove_freebsd_package($pkg);
703
	$static_output .= "done.\n";
704
	update_output_window($static_output);
705
	return;
706
}
707

    
708
function delete_package_recursive($pkg) {
709
	global $config, $g;
710
	$fd = fopen("{$g['tmp_path']}/y", "w");
711
	for($line = 0; $line < 10; $line++) {
712
		fwrite($fd, "y\n");
713
	}
714
	fclose($fd);
715
	$info = "";
716
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
717
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
718
	remove_freebsd_package($pkg);
719
	$pkgdb = "";
720
	exec("/bin/ls /var/db/pkg", $pkgdb);
721
	foreach($info as $line) {
722
		$depend = trim(array_pop(explode(":", $line)));
723
		if(in_array($depend, $pkgdb)) 
724
			delete_package_recursive($depend);
725
	}
726
	return;
727
}
728

    
729
function delete_package_xml($pkg) {
730
	global $g, $config, $fd_log, $static_output, $pkg_interface;
731
	if(($pkgid = get_pkg_id($pkg)) == -1) {
732
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
733
		update_output_window($static_output);
734
		if($pkg_interface <> "console") {
735
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
736
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
737
		}
738
		ob_flush();
739
		sleep(1);
740
		return;
741
	}
742
	/* set up logging if needed */
743
	if(!$fd_log) {
744
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
745
			update_output_window("Warning, could not open log for writing.");
746
		}
747
	}
748
	update_status("Removing {$pkg} components...");
749
	fwrite($fd_log, "Removing {$pkg} package... ");
750
	$static_output .= "Removing {$pkg} components...\n";
751
	update_output_window($static_output);
752
	/* parse package configuration */
753
	$packages = &$config['installedpackages']['package'];
754
	$tabs =& $config['installedpackages']['tab'];
755
	$menus =& $config['installedpackages']['menu'];
756
	$services = &$config['installedpackages']['service'];
757
	if(file_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'])) {
758
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
759
		/* remove tab items */
760
		if(is_array($pkg_config['tabs'])) {
761
			$static_output .= "\tMenu items... ";
762
			update_output_window($static_output);
763
			foreach($tabs as $tab)
764
				$insttabs[] = $tab['name'];
765
			foreach($pkg_config['tabs']['tab'] as $tab)
766
				foreach($insttabs as $key => $insttab)
767
					if($insttab == $tab['name'])
768
						unset($tabs[$key]);
769
			$static_output .= "done.\n";
770
			update_output_window($static_output);
771
		}
772
		/* remove menu items */
773
		if(is_array($pkg_config['menu'])) {
774
			$static_output .= "\tMenu items... ";
775
			update_output_window($static_output);
776
			foreach($menus as $menu)
777
				$instmenus[] = $menu['name'];
778
			foreach($pkg_config['menu'] as $menu)
779
				foreach($instmenus as $key => $instmenu)
780
					if($instmenu == $menu['name'])
781
						unset($menus[$key]);
782
			$static_output .= "done.\n";
783
			update_output_window($static_output);
784
		}
785
		/* remove services */
786
		if(is_array($pkg_config['service'])) {
787
			$static_output .= "\tServices... ";
788
			update_output_window($static_output);
789
			foreach($services as $service) $instservices[] = $service['name'];
790
			foreach($pkg_config['service'] as $service) {
791
				foreach($instservices as $key => $instservice) {
792
					if($instservice == $service['name']) {
793
						stop_service($service['name']);
794
						unset($services[$key]);
795
					}
796
				}
797
			}
798
			$static_output .= "done.\n";
799
			update_output_window($static_output);
800
		}
801
		/*   if a require exists, include it.  this will
802
		 *   show us where an error exists in a package
803
		 *   instead of making us blindly guess
804
		 */
805
		if($pkg_config['include_file'] <> "") {
806
			$static_output = "Loading package instructions...";
807
			update_output_window($static_output);
808
			fwrite($fd_log, "require_once('include_file')\n");
809
			if(file_exists($pkg_config['include_file']))
810
				require_once($pkg_config['include_file']);
811
			fwrite($fd_log, "require_once('include_file') included\n");
812
		}
813
		/* evalate this package's global functions and pre deinstall commands */
814
		if($pkg_config['custom_php_global_functions'] <> "")
815
			eval_once($pkg_config['custom_php_global_functions']);
816
		if($pkg_config['custom_php_pre_deinstall_command'] <> "")
817
			eval_once($pkg_config['custom_php_pre_deinstall_command']);
818
		/* remove all additional files */
819
		if($pkg_config['additional_files_needed'] <> "") {
820
			$static_output .= "\tAuxiliary files... ";
821
			update_output_window($static_output);
822
			foreach($pkg_config['additional_files_needed'] as $afn) {
823
				$filename = get_filename_from_url($afn['item'][0]);
824
				if($afn['prefix'] <> "") {
825
					$prefix = $afn['prefix'];
826
				} else {
827
					$prefix = "/usr/local/pkg/";
828
				}
829
				unlink_if_exists($prefix . $filename);
830
				if(file_exists($prefix . $filename))
831
				    mwexec("rm -rf {$prefix}{$filename}");
832
			}
833
			$static_output .= "done.\n";
834
			update_output_window($static_output);
835
		}
836
		/* system files */
837
		if($pkg_config['modify_system']['item'] <> "") {
838
			$static_output .= "\tSystem files... ";
839
			update_output_window($static_output);
840
			foreach($pkg_config['modify_system']['item'] as $ms) {
841
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
842
			}
843
			$static_output .= "done.\n";
844
			update_output_window($static_output);
845
		}
846
		/* syslog */
847
		if($pkg_config['logging']['logfile_name'] <> "") {
848
			$static_output .= "\tSyslog entries... ";
849
			update_output_window($static_output);
850
			remove_text_from_file("/etc/syslog.conf", $pkg_config['logging']['facilityname'] . "\t\t\t\t" . $pkg_config['logging']['logfilename']);
851
			$static_output .= "done.\n";
852
			update_output_window($static_output);
853
		}
854
		/* deinstall commands */
855
		if($pkg_config['custom_php_deinstall_command'] <> "") {
856
			$static_output .= "\tDeinstall commands... ";
857
			update_output_window($static_output);
858
			eval_once($pkg_config['custom_php_deinstall_command']);
859
			$static_output .= "done.\n";
860
			update_output_window($static_output);
861
		}
862
		/* package XML file */
863
		$static_output .= "\tPackage XML... ";
864
		update_output_window($static_output);
865
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
866
		$static_output .= "done.\n";
867
		update_output_window($static_output);
868
	}
869
	/* remove config.xml entries */
870
	$static_output .= "\tConfiguration... ";
871
	update_output_window($static_output);
872
	unset($config['installedpackages']['package'][$pkgid]);
873
	$static_output .= "done.\n";
874
	update_output_window($static_output);
875
	write_config("Removed {$pkg} package.");
876
	/* file cleanup */
877
	$ctag = file("/etc/crontab");
878
	foreach($ctag as $line) {
879
		if(trim($line) != "") $towrite[] = $line;
880
	}
881
	$tmptab = fopen("/tmp/crontab", "w");
882
	foreach($towrite as $line) {
883
		fwrite($tmptab, $line);
884
	}
885
	fclose($tmptab);
886
	rename("/tmp/crontab", "/etc/crontab");
887
}
888

    
889
function expand_to_bytes($size) {
890
	$conv = array(
891
			"G" =>	"3",
892
			"M" =>  "2",
893
			"K" =>  "1",
894
			"B" =>  "0"
895
		);
896
	$suffix = substr($size, -1);
897
	if(!in_array($suffix, array_keys($conv))) return $size;
898
	$size = substr($size, 0, -1);
899
	for($i = 0; $i < $conv[$suffix]; $i++) {
900
		$size *= 1024;
901
	}
902
	return $size;
903
}
904

    
905
function get_pkg_db() {
906
	global $g;
907
	return return_dir_as_array($g['vardb_path'] . '/pkg');
908
}
909

    
910
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
911
	if(!$pkgdb) $pkgdb = get_pkg_db();
912
	if(!$alreadyseen) $alreadyseen = array();
913
	foreach($depend as $adepend) {
914
		$pkgname = reverse_strrchr($adepend['name'], '.');
915
		if(in_array($pkgname, $alreadyseen)) {
916
			continue;
917
		} elseif(!in_array($pkgname, $pkgdb)) {
918
			$size += expand_to_bytes($adepend['size']);
919
			$alreadyseen[] = $pkgname;
920
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
921
		} else {
922
			continue;
923
		}
924
	}
925
	return $size;
926
}
927

    
928
function get_package_install_size($pkg = 'all', $pkg_info = "") {
929
	global $config, $g;
930
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
931
	$pkgdb = get_pkg_db();
932
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
933
	foreach($pkg as $apkg) {
934
		if(!$pkg_info[$apkg]) continue;
935
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
936
	}
937
	return $toreturn;
938
}
939

    
940
function squash_from_bytes($size, $round = "") {
941
	$conv = array(1 => "B", "K", "M", "G");
942
	foreach($conv as $div => $suffix) {
943
		$sizeorig = $size;
944
		if(($size /= 1024) < 1) {
945
			if($round) {
946
				$sizeorig = round($sizeorig, $round);
947
			}
948
			return $sizeorig . $suffix;
949
		}
950
	}
951
	return;
952
}
953

    
954
?>
(22-22/37)