Project

General

Profile

Download (32.8 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 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
/****f* pkg-utils/is_package_installed
49
 * NAME
50
 *   is_package_installed - Check whether a package is installed.
51
 * INPUTS
52
 *   $packagename	- name of the package to check
53
 * RESULT
54
 *   boolean	- true if the package is installed, false otherwise
55
 * NOTES
56
 *   This function is deprecated - get_pkg_id() can already check for installation.
57
 ******/
58
function is_package_installed($packagename) {
59
	$pkg = get_pkg_id($packagename);
60
	if($pkg == -1) return false;
61
	return true;
62
}
63
            
64
/****f* pkg-utils/get_pkg_id
65
 * NAME
66
 *   get_pkg_id - Find a package's numeric ID.
67
 * INPUTS
68
 *   $pkg_name	- name of the package to check
69
 * RESULT
70
 *   integer    - -1 if package is not found, >-1 otherwise
71
 ******/
72
function get_pkg_id($pkg_name) {
73
	global $config;
74

    
75
	if(is_array($config['installedpackages']['package'])) {
76
		$i = 0;
77
		foreach($config['installedpackages']['package'] as $pkg) {
78
			if($pkg['name'] == $pkg_name) return $i;
79
			$i++;
80
		}
81
	}
82
	return -1;
83
}
84

    
85
/****f* pkg-utils/get_pkg_info
86
 * NAME
87
 *   get_pkg_info - Retrive package information from pfsense.com.
88
 * INPUTS
89
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
90
 *   $info - 'all' to retrive all information, an array containing keys otherwise
91
 * RESULT
92
 *   $raw_versions - Array containing retrieved information, indexed by package name.
93
 ******/
94
function get_pkg_info($pkgs = 'all', $info = 'all') {
95
	global $g;
96
	$params = array("pkg" => $pkgs, "info" => $info);
97
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
98
	return $resp ? $resp : array();
99
}
100

    
101
function get_pkg_sizes($pkgs = 'all') {
102
	global $g;
103
	$params = array("pkg" => $pkgs);
104
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
105
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $g['xmlrpcbaseurl']);
106
	$resp = $cli->send($msg, 10);  
107
	if($resp and !$resp->faultCode()) {
108
		$raw_versions = $resp->value();
109
		return xmlrpc_value_to_php($raw_versions);
110
	} else {
111
		return array();
112
	}
113
}
114

    
115
/*
116
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
117
 * This function may also print output to the terminal indicating progress.
118
 */
119
function resync_all_package_configs($show_message = false) {
120
	global $config;
121
	$i = 0;
122
	log_error("Resyncing configuration for all packages.");
123
	if(!$config['installedpackages']['package']) return;
124
	if($show_message == true) print "Syncing packages:";
125
	foreach($config['installedpackages']['package'] as $package) {
126
		if($show_message == true) print " " . $package['name'];
127
		sync_package($i, true, true);
128
		$i++;
129
	}
130
	if($show_message == true) print ".\n";
131
}
132

    
133
/*
134
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
135
 *				package is installed.
136
 */
137
function is_freebsd_pkg_installed($pkg) {
138
	global $g;
139
	if(in_array($pkg, return_dir_as_array("{$g['vardb_path']}/pkg"))) return true;
140
	return false;
141
}
142

    
143
/*
144
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
145
 *
146
 * $filetype = "all" || ".xml", ".tgz", etc.
147
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
148
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
149
 *
150
 */
151
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
152
	global $config;
153
	$pkg_id = get_pkg_id($pkg_name);
154
	if(!is_numeric($pkg_name)) {
155
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
156
	} else {
157
		if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
158
	}
159
	$package = $config['installedpackages']['package'][$pkg_id];
160
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
161
		file_notice($package['name'], "The {$package['name']} package is missing its configuration file and must be reinstalled.", "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1);
162
		return;
163
	}
164
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
165
	if($pkg_xml['additional_files_needed'] != "") {
166
		foreach($pkg_xml['additional_files_needed'] as $item) {
167
			if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
168
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
169
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
170
			if (($filetype != "all") && (!preg_match("/${filetype}/i", $depend_file))) continue;
171
			if ($item['prefix'] != "") {
172
				$prefix = $item['prefix'];
173
			} else {
174
				$prefix = "/usr/local/pkg/";
175
			}
176
			if(!file_exists($prefix . $pkg_name)) {
177
				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);
178
			}
179
			switch ($format) {
180
				case "files":
181
				$depends[] = $depend_file;
182
			break;
183
            			case "names":
184
                		switch ($filetype) {
185

    
186
				case "all":
187
				if(preg_match("/\.xml/i", $depend_file)) {
188
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
189
					$depends[] = $depend_xml['name'];
190
					break;
191
				} else {
192
					$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
193
				break;
194
				}
195
				case ".xml":
196
				$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
197
				$depends[] = $depend_xml['name'];
198
				break;
199
				default:
200
				$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
201
				break;
202
				}
203
			}
204
		}
205
		return $depends;
206
	}
207
}
208

    
209
/*
210
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
211
 */
212
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
213
	global $config;
214

    
215
	if(!$config['installedpackages']['package']) return;
216
	if(!is_numeric($pkg_name)) {
217
		$pkg_id = get_pkg_id($pkg_name);
218
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
219
	} else {
220
		$pkg_id = $pkg_name;
221
		if(!isset($config['installedpackages']['package'][$pkg_id]))
222
		return;  // No package belongs to the pkg_id passed to this function.
223
	}
224
	$package = $config['installedpackages']['package'][$pkg_id];
225
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
226
		file_notice($package['name'], "The {$package['name']} package is missing its configuration file and must be reinstalled.", "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1);
227
	} else {
228
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
229
		/* XXX: Zend complains about the next line "Wrong break depth"
230
		 * The code is obviously wrong, but I'm not sure what it's supposed to do?
231
		 */
232
		if(isset($pkg_config['nosync'])) continue;
233
		if($pkg_config['custom_php_global_functions'] <> "")
234
		eval($pkg_config['custom_php_global_functions']);
235
		if($pkg_config['custom_php_resync_config_command'] <> "")
236
		eval($pkg_config['custom_php_resync_config_command']);
237
		if($sync_depends == true) {
238
			$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
239
			if(is_array($depends)) {
240
				foreach($depends as $item) {
241
					if(!file_exists("/usr/local/pkg" . $item)) {
242
						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);
243
					} else {
244
						$item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
245
						if(isset($item_config['nosync'])) continue;
246
						if($item_config['custom_php_command_before_form'] <> "") {
247
							eval($item_config['custom_php_command_before_form']);
248
						}
249
						if($item_config['custom_php_resync_config_command'] <> "") {
250
							eval($item_config['custom_php_resync_config_command']);
251
						}
252
						if($show_message == true) print " " . $item_config['name'];
253
					}
254
				}
255
			}
256
		}
257
	}
258
}
259

    
260
/*
261
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
262
 * 			a progress bar and output window.
263
 *
264
 * XXX: This function needs to return where a pkg_add fails. Our current error messages aren't very descriptive.
265
 */
266
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = 'http://ftp2.freebsd.org/pub/FreeBSD/ports/i386/packages-5.4-release/Latest') {
267
	global $pkgent, $static_output, $g, $fd_log;
268
	$pkg_extension = strrchr($filename, '.');
269
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
270
	$fetchto = "/tmp/apkg_" . $pkgname . $pkg_extension;
271
	download_file_with_progress_bar($base_url . '/' . $filename, $fetchto);
272
	$static_output .= " (extracting)";
273
	update_output_window($static_output);	
274
		$slaveout = "";
275
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
276
	$workingdir = preg_grep("/instmp/", $slaveout);
277
	$workingdir = $workingdir[0];
278
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
279
	if($raw_depends_list != "") {
280
		if($pkgent['exclude_dependency'] != "")
281
			$raw_depends_list = array_values(preg_grep($pkgent['exclude_dependency'], PREG_GREP_INVERT));
282
		foreach($raw_depends_list as $adepend) {
283
			$working_depend = explode(" ", $adepend);
284
			//$working_depend = explode("-", $working_depend[1]);
285
			$depend_filename = $working_depend[1] . $pkg_extension;
286
			if(is_freebsd_pkg_installed($working_depend[1]) === false) {
287
				pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url);
288
			} else {
289
//				$dependlevel++;
290
				$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " ";
291
				@fwrite($fd_log, $working_depend[1] . "\n");
292
			}
293
		}
294
	}
295
	$pkgaddout = "";
296
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
297
	@fwrite($fd_log, $pkgname . " " . print_r($pkgaddout, true) . "\n");
298
	return true;
299
}
300

    
301
function download_file_with_progress_bar($url_file, $destination_file) {
302
	global $ch, $fout, $file_size, $downloaded, $pkg_interface;
303
	$file_size  = 1;
304
	$downloaded = 1;
305
	/* open destination file */
306
	$fout = fopen($destination_file, "wb");
307

    
308
	/*
309
	 *	Originally by Author: Keyvan Minoukadeh
310
	 *	Modified by Scott Ullrich to return Content-Length size
311
         */
312

    
313
	$ch = curl_init();
314
	curl_setopt($ch, CURLOPT_URL, $url_file);
315
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
316
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
317
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
318

    
319
	curl_exec($ch);
320
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
321
	fclose($fout);
322
	curl_close($ch);
323
	return ($http_code == 200) ? true : $http_code;
324
}
325

    
326
function read_header($ch, $string) {
327
	global $file_size, $fout;
328
	$length = strlen($string);
329
	$regs = "";
330
	ereg("(Content-Length:) (.*)", $string, $regs);
331
	if($regs[2] <> "") {
332
	$file_size = intval($regs[2]);
333
	}
334
	return $length;
335
}
336

    
337
function read_body($ch, $string) {
338
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $pkg_interface;
339
	$length = strlen($string);
340
	$downloaded += intval($length);
341
	$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
342
	$downloadProgress = 100 - $downloadProgress;
343
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
344
		if($sendto == "status") {
345
			$tostatus = $static_status . $downloadProgress . "%";
346
			update_status($tostatus);
347
		} else {
348
			$tooutput = $static_output . $downloadProgress . "%";
349
			update_output_window($tooutput);
350
		}
351
		update_progress_bar($downloadProgress);
352
		$lastseen = $downloadProgress;
353
	}
354
	fwrite($fout, $string);
355
	return $length;
356
}
357

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

    
423
function eval_once($toeval) {
424
	global $evaled;
425
	if(!$evaled) $evaled = array();
426
	$evalmd5 = md5($toeval);
427
	if(!in_array($evalmd5, $evaled)) {
428
		eval($toeval);
429
		$evaled[] = $evalmd5;
430
	}
431
	return;
432
}
433

    
434
function install_package_xml($pkg) {
435
	global $g, $config, $fd_log, $static_output;
436
	if(($pkgid = get_pkg_id($pkg)) == -1) {
437
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
438
		update_output_window($static_output);
439
		echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
440
		echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
441
		sleep(1);
442
		return;
443
	} else {
444
		$pkg_info = $config['installedpackages']['package'][$pkgid];
445
	}
446
	/* set up logging if needed */
447
	if(!$fd_log) {
448
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
449
			update_output_window("Warning, could not open log for writing.");
450
		}
451
	}
452

    
453
	/* set up package logging streams */
454
	if($pkg_info['logging']) {
455
		mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
456
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
457
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
458
		mwexec("killall syslogd");
459
		system_syslogd_start();
460
	}
461

    
462
	/* make 'y' file */
463
	$fd = fopen("{$g['tmp_path']}/y", "w");
464
	for($line = 0; $line < 10; $line++) {
465
		fwrite($fd, "y\n");
466
	}
467
	fclose($fd);
468

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

    
631
function delete_package($pkg, $pkgid) {
632
	global $g, $config, $fd_log, $static_output;
633
	update_status("Removing package...");
634
	$static_output .= "Removing package... ";
635
	update_output_window($static_output);
636
	$pkgid = get_pkg_id($pkgid);
637
	$pkg_info = $config['installedpackages']['package'][$pkgid];
638
	echo $id . "<p>";
639
	echo $pkg_config . "<p>";
640
	$configfile = $pkg_info['configurationfile'];
641
	echo $configfile . "<p>";
642
	if(file_exists("/usr/local/pkg/" . $configfile)) {
643
		$static_output .= "\nLoading package configuration $configfile... ";
644
		update_output_window($static_output);
645
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
646
		/*   if a require exists, include it.  this will
647
		 *   show us where an error exists in a package
648
		 *   instead of making us blindly guess
649
		 */
650
		if($pkg_config['include_file'] <> "") {
651
			$static_output .= "\nLoading package instructions...\n";
652
			update_output_window($static_output);
653
			require_once($pkg_config['include_file']);
654
		}
655
	}
656
	$static_output .= "\Starting package deletetion...\n";
657
	update_output_window($static_output);	
658
	delete_package_recursive($pkg);
659
	$static_output .= "done.\n";
660
	update_output_window($static_output);
661
	return;
662
}
663

    
664
function delete_package_recursive($pkg) {
665
	$info = "";
666
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
667
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
668
	$pkgdb = "";
669
	exec("/bin/ls /var/db/pkg", $pkgdb);
670
	if(stristr($info[0], "can't find package") != false) return;
671
	foreach($info as $line) {
672
		$depend = trim(array_pop(explode(":", $line)));
673
		if(in_array($depend, $pkgdb)) delete_package_recursive($depend);
674
	}
675
	$fd = fopen("{$g['tmp_path']}/y", "w");
676
	for($line = 0; $line < 10; $line++) {
677
		fwrite($fd, "y\n");
678
	}
679
	fclose($fd);
680
	return;
681
}
682

    
683
function delete_package_xml($pkg) {
684
	global $g, $config, $fd_log, $static_output;
685
	if(($pkgid = get_pkg_id($pkg)) == -1) {
686
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
687
		update_output_window($static_output);
688
		echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
689
		echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
690
		ob_flush();
691
		sleep(1);
692
		return;
693
	}
694
	/* set up logging if needed */
695
	if(!$fd_log) {
696
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
697
			update_output_window("Warning, could not open log for writing.");
698
		}
699
	}
700
	update_status("Removing {$pkg} components...");
701
	fwrite($fd_log, "Removing {$pkg} package... ");
702
	$static_output .= "Removing {$pkg} components...\n";
703
	update_output_window($static_output);
704
	/* parse package configuration */
705
	$packages = &$config['installedpackages']['package'];
706
	$menus = &$config['installedpackages']['menu'];
707
	$services = &$config['installedpackages']['service'];
708
	if(file_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'])) {
709
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
710
		/* remove menu items */
711
		if(is_array($pkg_config['menu'])) {
712
			$static_output .= "\tMenu items... ";
713
			update_output_window($static_output);
714
			foreach($menus as $menu) $instmenus[] = $menu['name'];
715
			foreach($pkg_config['menu'] as $menu) {
716
				foreach($instmenus as $key => $instmenu) {
717
					if($instmenu == $menu['name']) unset($menus[$key]);
718
				}
719
			}
720
			$static_output .= "done.\n";
721
			update_output_window($static_output);
722
		}
723
		/* remove services */
724
		if(is_array($pkg_config['service'])) {
725
			$static_output .= "\tServices... ";
726
			update_output_window($static_output);
727
			foreach($services as $service) $instservices[] = $service['name'];
728
			foreach($pkg_config['service'] as $service) {
729
				foreach($instservices as $key => $instservice) {
730
					if($instservice == $service['name']) {
731
						stop_service($service['name']);
732
						unset($services[$key]);
733
					}
734
				}
735
			}
736
			$static_output .= "done.\n";
737
			update_output_window($static_output);
738
		}
739
		/*   if a require exists, include it.  this will
740
		 *   show us where an error exists in a package
741
		 *   instead of making us blindly guess
742
		 */
743
		if($pkg_config['include_file'] <> "") {
744
			$static_output = "Loading package instructions...";
745
			update_output_window($static_output);
746
			fwrite($fd_log, "require_once('include_file')\n");
747
			if(file_exists($pkg_config['include_file']))
748
				require_once($pkg_config['include_file']);
749
			fwrite($fd_log, "require_once('include_file') included\n");
750
		}		
751
		/* evalate this package's global functions and pre deinstall commands */
752
		if($pkg_config['custom_php_global_functions'] <> "")
753
			eval_once($pkg_config['custom_php_global_functions']);
754
		if($pkg_config['custom_php_pre_deinstall_command'] <> "") 
755
			eval_once($pkg_config['custom_php_pre_deinstall_command']);
756
		/* remove all additional files */
757
		if($pkg_config['additional_files_needed'] <> "") {
758
			$static_output .= "\tAuxiliary files... ";
759
			update_output_window($static_output);
760
			foreach($pkg_config['additional_files_needed'] as $afn) {
761
				$filename = get_filename_from_url($afn['item'][0]);
762
				if($afn['prefix'] <> "") {
763
					$prefix = $afn['prefix'];
764
				} else {
765
					$prefix = "/usr/local/pkg/";
766
				}
767
				unlink_if_exists($prefix . $filename);
768
				if(file_exists($prefix . $filename))
769
				    mwexec("rm -rf {$prefix}{$filename}");
770
			}
771
			$static_output .= "done.\n";
772
			update_output_window($static_output);
773
		}
774
		/* system files */
775
		if($pkg_config['modify_system']['item'] <> "") {
776
			$static_output .= "\tSystem files... ";
777
			update_output_window($static_output);
778
			foreach($pkg_config['modify_system']['item'] as $ms) {
779
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
780
			}
781
			$static_output .= "done.\n";
782
			update_output_window($static_output);
783
		}
784
		/* syslog */
785
		if($pkg_config['logging']['logfile_name'] <> "") {
786
			$static_output .= "\tSyslog entries... ";
787
			update_output_window($static_output);
788
			remove_text_from_file("/etc/syslog.conf", $pkg_config['logging']['facilityname'] . "\t\t\t\t" . $pkg_config['logging']['logfilename']);
789
			$static_output .= "done.\n";
790
			update_output_window($static_output);
791
		}
792
		/* deinstall commands */
793
		if($pkg_config['custom_php_deinstall_command'] <> "") {
794
			$static_output .= "\tDeinstall commands... ";
795
			update_output_window($static_output);
796
			eval_once($pkg_config['custom_php_deinstall_command']);
797
			$static_output .= "done.\n";
798
			update_output_window($static_output);
799
		}
800
		/* package XML file */
801
		$static_output .= "\tPackage XML... ";
802
		update_output_window($static_output);
803
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
804
		$static_output .= "done.\n";
805
		update_output_window($static_output);
806
	}
807
	/* remove config.xml entries */
808
	$static_output .= "\tConfiguration... ";
809
	update_output_window($static_output);
810
	unset($config['installedpackages']['package'][$pkgid]);
811
	$static_output .= "done.\n";
812
	update_output_window($static_output);
813
	write_config("Removed {$pkg} package.");
814
	/* file cleanup */
815
	$ctag = file("/etc/crontab");
816
	foreach($ctag as $line) {
817
		if(trim($line) != "") $towrite[] = $line;
818
	}
819
	$tmptab = fopen("/tmp/crontab", "w");
820
	foreach($towrite as $line) {
821
		fwrite($tmptab, $line);
822
	}
823
	fclose($tmptab);
824
	rename("/tmp/crontab", "/etc/crontab");
825
}
826

    
827
function expand_to_bytes($size) {
828
	$conv = array(
829
			"G" =>	"3",
830
			"M" =>  "2",
831
			"K" =>  "1",
832
			"B" =>  "0"
833
		);
834
	$suffix = substr($size, -1);
835
	if(!in_array($suffix, array_keys($conv))) return $size;
836
	$size = substr($size, 0, -1);
837
	for($i = 0; $i < $conv[$suffix]; $i++) {
838
		$size *= 1024;
839
	}
840
	return $size;
841
}
842

    
843
function get_pkg_db() {
844
	global $g;
845
	return return_dir_as_array($g['vardb_path'] . '/pkg');
846
}
847

    
848
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
849
	if(!$pkgdb) $pkgdb = get_pkg_db();
850
	if(!$alreadyseen) $alreadyseen = array();
851
	foreach($depend as $adepend) {
852
		$pkgname = reverse_strrchr($adepend['name'], '.');
853
		if(in_array($pkgname, $alreadyseen)) {
854
			continue;
855
		} elseif(!in_array($pkgname, $pkgdb)) {
856
			$size += expand_to_bytes($adepend['size']);
857
			$alreadyseen[] = $pkgname;
858
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
859
		} else {
860
			continue;
861
		}
862
	}
863
	return $size;
864
}
865

    
866
function get_package_install_size($pkg = 'all', $pkg_info = "") {
867
	global $config, $g;
868
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
869
	$pkgdb = get_pkg_db();
870
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
871
	foreach($pkg as $apkg) {
872
		if(!$pkg_info[$apkg]) continue;
873
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
874
	}
875
	return $toreturn;
876
}
877

    
878
function squash_from_bytes($size, $round = "") {
879
	$conv = array(1 => "B", "K", "M", "G");
880
	foreach($conv as $div => $suffix) {
881
		$sizeorig = $size;
882
		if(($size /= 1024) < 1) {
883
			if($round) {
884
				$sizeorig = round($sizeorig, $round);
885
			}
886
			return $sizeorig . $suffix;
887
		}
888
	}
889
	return;
890
}
891
?>
(15-15/27)