Project

General

Profile

Download (33.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
/****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
        if (is_array($config['installedpackages']['package'][$pkg_id]))
225
                $package = $config['installedpackages']['package'][$pkg_id];
226
        else
227
                return; /* empty package tag */
228
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
229
		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);
230
	} else {
231
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
232

    
233
		/* Bring in package include files */
234
		if (isset($pkg_config['include_file']) && $pkg_config['include_file'] != ""
235
) {
236
			$include_file = $pkg_config['include_file'];
237
			if (file_exists('/usr/local/pkg/' . $include_file))
238
				require_once('/usr/local/pkg/' . $include_file);
239
			else
240
				require_once($include_file);
241
		}
242

    
243
		/* XXX: Zend complains about the next line "Wrong break depth"
244
		 * The code is obviously wrong, but I'm not sure what it's supposed to do?
245
		 */
246
		if(isset($pkg_config['nosync'])) continue;
247
		if($pkg_config['custom_php_global_functions'] <> "")
248
		eval($pkg_config['custom_php_global_functions']);
249
		if($pkg_config['custom_php_resync_config_command'] <> "")
250
		eval($pkg_config['custom_php_resync_config_command']);
251
		if($sync_depends == true) {
252
			$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
253
			if(is_array($depends)) {
254
				foreach($depends as $item) {
255
					if(!file_exists("/usr/local/pkg" . $item)) {
256
						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);
257
					} else {
258
						$item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
259
						if(isset($item_config['nosync'])) continue;
260
						if($item_config['custom_php_command_before_form'] <> "") {
261
							eval($item_config['custom_php_command_before_form']);
262
						}
263
						if($item_config['custom_php_resync_config_command'] <> "") {
264
							eval($item_config['custom_php_resync_config_command']);
265
						}
266
						if($show_message == true) print " " . $item_config['name'];
267
					}
268
				}
269
			}
270
		}
271
	}
272
}
273

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

    
315
function download_file_with_progress_bar($url_file, $destination_file) {
316
	global $ch, $fout, $file_size, $downloaded, $pkg_interface;
317
	$file_size  = 1;
318
	$downloaded = 1;
319
	/* open destination file */
320
	$fout = fopen($destination_file, "wb");
321

    
322
	/*
323
	 *	Originally by Author: Keyvan Minoukadeh
324
	 *	Modified by Scott Ullrich to return Content-Length size
325
         */
326

    
327
	$ch = curl_init();
328
	curl_setopt($ch, CURLOPT_URL, $url_file);
329
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
330
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
331
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
332

    
333
	curl_exec($ch);
334
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
335
	fclose($fout);
336
	curl_close($ch);
337
	return ($http_code == 200) ? true : $http_code;
338
}
339

    
340
function read_header($ch, $string) {
341
	global $file_size, $fout;
342
	$length = strlen($string);
343
	$regs = "";
344
	ereg("(Content-Length:) (.*)", $string, $regs);
345
	if($regs[2] <> "") {
346
	$file_size = intval($regs[2]);
347
	}
348
	return $length;
349
}
350

    
351
function read_body($ch, $string) {
352
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $pkg_interface;
353
	$length = strlen($string);
354
	$downloaded += intval($length);
355
	$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
356
	$downloadProgress = 100 - $downloadProgress;
357
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
358
		if($sendto == "status") {
359
			$tostatus = $static_status . $downloadProgress . "%";
360
			update_status($tostatus);
361
		} else {
362
			$tooutput = $static_output . $downloadProgress . "%";
363
			update_output_window($tooutput);
364
		}
365
		update_progress_bar($downloadProgress);
366
		$lastseen = $downloadProgress;
367
	}
368
	fwrite($fout, $string);
369
	return $length;
370
}
371

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

    
437
function eval_once($toeval) {
438
	global $evaled;
439
	if(!$evaled) $evaled = array();
440
	$evalmd5 = md5($toeval);
441
	if(!in_array($evalmd5, $evaled)) {
442
		eval($toeval);
443
		$evaled[] = $evalmd5;
444
	}
445
	return;
446
}
447

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

    
467
	/* set up package logging streams */
468
	if($pkg_info['logging']) {
469
		mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
470
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
471
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
472
		mwexec("killall syslogd");
473
		system_syslogd_start();
474
	}
475

    
476
	/* make 'y' file */
477
	$fd = fopen("{$g['tmp_path']}/y", "w");
478
	for($line = 0; $line < 10; $line++) {
479
		fwrite($fd, "y\n");
480
	}
481
	fclose($fd);
482

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

    
645
function delete_package($pkg, $pkgid) {
646
	global $g, $config, $fd_log, $static_output;
647
	update_status("Removing package...");
648
	$static_output .= "Removing package... ";
649
	update_output_window($static_output);
650
	$pkgid = get_pkg_id($pkgid);
651
	$pkg_info = $config['installedpackages']['package'][$pkgid];
652

    
653
	$configfile = $pkg_info['configurationfile'];
654
	if(file_exists("/usr/local/pkg/" . $configfile)) {
655
		$static_output .= "\nLoading package configuration $configfile... ";
656
		update_output_window($static_output);
657
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
658
		/*   if a require exists, include it.  this will
659
		 *   show us where an error exists in a package
660
		 *   instead of making us blindly guess
661
		 */
662
		if($pkg_config['include_file'] <> "") {
663
			$static_output .= "\nLoading package instructions...\n";
664
			update_output_window($static_output);
665
			require_once($pkg_config['include_file']);
666
		}
667
	}
668
	$static_output .= "\Starting package deletion...\n";
669
	update_output_window($static_output);	
670
	delete_package_recursive($pkg);
671
	$static_output .= "done.\n";
672
	update_output_window($static_output);
673
	return;
674
}
675

    
676
function delete_package_recursive($pkg) {
677
	$info = "";
678
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
679
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
680
	$pkgdb = "";
681
	exec("/bin/ls /var/db/pkg", $pkgdb);
682
	if(stristr($info[0], "can't find package") != false) return;
683
	foreach($info as $line) {
684
		$depend = trim(array_pop(explode(":", $line)));
685
		if(in_array($depend, $pkgdb)) delete_package_recursive($depend);
686
	}
687
	$fd = fopen("{$g['tmp_path']}/y", "w");
688
	for($line = 0; $line < 10; $line++) {
689
		fwrite($fd, "y\n");
690
	}
691
	fclose($fd);
692
	return;
693
}
694

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

    
839
function expand_to_bytes($size) {
840
	$conv = array(
841
			"G" =>	"3",
842
			"M" =>  "2",
843
			"K" =>  "1",
844
			"B" =>  "0"
845
		);
846
	$suffix = substr($size, -1);
847
	if(!in_array($suffix, array_keys($conv))) return $size;
848
	$size = substr($size, 0, -1);
849
	for($i = 0; $i < $conv[$suffix]; $i++) {
850
		$size *= 1024;
851
	}
852
	return $size;
853
}
854

    
855
function get_pkg_db() {
856
	global $g;
857
	return return_dir_as_array($g['vardb_path'] . '/pkg');
858
}
859

    
860
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
861
	if(!$pkgdb) $pkgdb = get_pkg_db();
862
	if(!$alreadyseen) $alreadyseen = array();
863
	foreach($depend as $adepend) {
864
		$pkgname = reverse_strrchr($adepend['name'], '.');
865
		if(in_array($pkgname, $alreadyseen)) {
866
			continue;
867
		} elseif(!in_array($pkgname, $pkgdb)) {
868
			$size += expand_to_bytes($adepend['size']);
869
			$alreadyseen[] = $pkgname;
870
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
871
		} else {
872
			continue;
873
		}
874
	}
875
	return $size;
876
}
877

    
878
function get_package_install_size($pkg = 'all', $pkg_info = "") {
879
	global $config, $g;
880
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
881
	$pkgdb = get_pkg_db();
882
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
883
	foreach($pkg as $apkg) {
884
		if(!$pkg_info[$apkg]) continue;
885
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
886
	}
887
	return $toreturn;
888
}
889

    
890
function squash_from_bytes($size, $round = "") {
891
	$conv = array(1 => "B", "K", "M", "G");
892
	foreach($conv as $div => $suffix) {
893
		$sizeorig = $size;
894
		if(($size /= 1024) < 1) {
895
			if($round) {
896
				$sizeorig = round($sizeorig, $round);
897
			}
898
			return $sizeorig . $suffix;
899
		}
900
	}
901
	return;
902
}
903
?>
(15-15/27)