Project

General

Profile

Download (35.2 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
	if($pkg_info['after_install_info']) 
440
		update_output_window($pkg_info['after_install_info']);	
441
	start_service($pkg_info['config_file']);
442
	$restart_sync = true;
443
}
444

    
445
function get_after_install_info($package) {
446
	global $pkg_info;
447
	/* fetch package information if needed */
448
	if(!$pkg_info or !is_array($pkg_info[$package])) {
449
		$pkg_info = get_pkg_info(array($package));
450
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
451
	}
452
	if($pkg_info['after_install_info'])
453
		return $pkg_info['after_install_info'];
454
}
455

    
456
function eval_once($toeval) {
457
	global $evaled;
458
	if(!$evaled) $evaled = array();
459
	$evalmd5 = md5($toeval);
460
	if(!in_array($evalmd5, $evaled)) {
461
		eval($toeval);
462
		$evaled[] = $evalmd5;
463
	}
464
	return;
465
}
466

    
467
function install_package_xml($pkg) {
468
	global $g, $config, $fd_log, $static_output, $pkg_interface;
469
	if(($pkgid = get_pkg_id($pkg)) == -1) {
470
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
471
		update_output_window($static_output);
472
		if($pkg_interface <> "console") {
473
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
474
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
475
		}
476
		sleep(1);
477
		return;
478
	} else {
479
		$pkg_info = $config['installedpackages']['package'][$pkgid];
480
	}
481
	/* set up logging if needed */
482
	if(!$fd_log) {
483
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
484
			update_output_window("Warning, could not open log for writing.");
485
		}
486
	}
487

    
488
	/* set up package logging streams */
489
	if($pkg_info['logging']) {
490
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
491
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
492
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
493
		mwexec("killall syslogd");
494
		system_syslogd_start();
495
	}
496

    
497
	/* make 'y' file */
498
	$fd = fopen("{$g['tmp_path']}/y", "w");
499
	for($line = 0; $line < 10; $line++) {
500
		fwrite($fd, "y\n");
501
	}
502
	fclose($fd);
503

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

    
689
function delete_package($pkg, $pkgid) {
690
	global $g, $config, $fd_log, $static_output;
691
	update_status("Removing package...");
692
	$static_output .= "Removing package... ";
693
	update_output_window($static_output);
694
	$pkgid = get_pkg_id($pkgid);
695
	$pkg_info = $config['installedpackages']['package'][$pkgid];
696

    
697
	$configfile = $pkg_info['configurationfile'];
698
	if(file_exists("/usr/local/pkg/" . $configfile)) {
699
		$static_output .= "\nLoading package configuration $configfile... ";
700
		update_output_window($static_output);
701
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
702
		/*   if a require exists, include it.  this will
703
		 *   show us where an error exists in a package
704
		 *   instead of making us blindly guess
705
		 */
706
		if($pkg_config['include_file'] <> "") {
707
			$static_output .= "\nLoading package instructions...\n";
708
			update_output_window($static_output);
709
			require_once($pkg_config['include_file']);
710
		}
711
	}
712
	$static_output .= "\nStarting package deletion for {$pkg_info['name']}...\n";
713
	update_output_window($static_output);
714
	delete_package_recursive($pkg);
715
	remove_freebsd_package($pkg);
716
	$static_output .= "done.\n";
717
	update_output_window($static_output);
718
	return;
719
}
720

    
721
function delete_package_recursive($pkg) {
722
	global $config, $g;
723
	$fd = fopen("{$g['tmp_path']}/y", "w");
724
	for($line = 0; $line < 10; $line++) {
725
		fwrite($fd, "y\n");
726
	}
727
	fclose($fd);
728
	$info = "";
729
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
730
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
731
	remove_freebsd_package($pkg);
732
	$pkgdb = "";
733
	exec("/bin/ls /var/db/pkg", $pkgdb);
734
	foreach($info as $line) {
735
		$depend = trim(array_pop(explode(":", $line)));
736
		if(in_array($depend, $pkgdb)) 
737
			delete_package_recursive($depend);
738
	}
739
	return;
740
}
741

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

    
904
function expand_to_bytes($size) {
905
	$conv = array(
906
			"G" =>	"3",
907
			"M" =>  "2",
908
			"K" =>  "1",
909
			"B" =>  "0"
910
		);
911
	$suffix = substr($size, -1);
912
	if(!in_array($suffix, array_keys($conv))) return $size;
913
	$size = substr($size, 0, -1);
914
	for($i = 0; $i < $conv[$suffix]; $i++) {
915
		$size *= 1024;
916
	}
917
	return $size;
918
}
919

    
920
function get_pkg_db() {
921
	global $g;
922
	return return_dir_as_array($g['vardb_path'] . '/pkg');
923
}
924

    
925
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
926
	if(!$pkgdb) $pkgdb = get_pkg_db();
927
	if(!$alreadyseen) $alreadyseen = array();
928
	foreach($depend as $adepend) {
929
		$pkgname = reverse_strrchr($adepend['name'], '.');
930
		if(in_array($pkgname, $alreadyseen)) {
931
			continue;
932
		} elseif(!in_array($pkgname, $pkgdb)) {
933
			$size += expand_to_bytes($adepend['size']);
934
			$alreadyseen[] = $pkgname;
935
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
936
		} else {
937
			continue;
938
		}
939
	}
940
	return $size;
941
}
942

    
943
function get_package_install_size($pkg = 'all', $pkg_info = "") {
944
	global $config, $g;
945
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
946
	$pkgdb = get_pkg_db();
947
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
948
	foreach($pkg as $apkg) {
949
		if(!$pkg_info[$apkg]) continue;
950
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
951
	}
952
	return $toreturn;
953
}
954

    
955
function squash_from_bytes($size, $round = "") {
956
	$conv = array(1 => "B", "K", "M", "G");
957
	foreach($conv as $div => $suffix) {
958
		$sizeorig = $size;
959
		if(($size /= 1024) < 1) {
960
			if($round) {
961
				$sizeorig = round($sizeorig, $round);
962
			}
963
			return $sizeorig . $suffix;
964
		}
965
	}
966
	return;
967
}
968

    
969
?>
(23-23/40)