Project

General

Profile

Download (33.3 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
		get_pkg_depends($package['name'], "all");
128
		sync_package($i, true, true);
129
		$i++;
130
	}
131
	if($show_message == true) print ".\n";
132
}
133

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

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

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

    
211
function force_remove_package($pkg_name) {
212
	global $config;
213
	delete_package_xml($pkg_name);
214
}
215

    
216
/*
217
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
218
 */
219
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
220
	global $config;
221
	require_once("notices.inc");
222
	if(!$config['installedpackages']['package']) return;
223
	if(!is_numeric($pkg_name)) {
224
		$pkg_id = get_pkg_id($pkg_name);
225
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
226
	} else {
227
		$pkg_id = $pkg_name;
228
		if(!isset($config['installedpackages']['package'][$pkg_id]))
229
		return;  // No package belongs to the pkg_id passed to this function.
230
	}
231
        if (is_array($config['installedpackages']['package'][$pkg_id]))
232
			$package = $config['installedpackages']['package'][$pkg_id];
233
        else
234
			return; /* empty package tag */
235
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
236
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
237
		force_remove_package($package['name']);
238
	} else {
239
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
240

    
241
		/* Bring in package include files */
242
		if (isset($pkg_config['include_file']) && $pkg_config['include_file'] != "") {
243
			$include_file = $pkg_config['include_file'];
244
			if (file_exists($include_file))
245
				require_once($include_file);
246
			else
247
				if (file_exists($include_file)) {
248
					require_once($include_file);
249
				} else {
250
					log_error("Could not locate {$include_file}.");
251
					install_package($package['name']);
252
				}
253
		}
254

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

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

    
328
function download_file_with_progress_bar($url_file, $destination_file) {
329
	global $ch, $fout, $file_size, $downloaded, $pkg_interface;
330
	$file_size  = 1;
331
	$downloaded = 1;
332
	/* open destination file */
333
	$fout = fopen($destination_file, "wb");
334

    
335
	/*
336
	 *	Originally by Author: Keyvan Minoukadeh
337
	 *	Modified by Scott Ullrich to return Content-Length size
338
         */
339

    
340
	$ch = curl_init();
341
	curl_setopt($ch, CURLOPT_URL, $url_file);
342
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
343
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
344
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
345

    
346
	curl_exec($ch);
347
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
348
	fclose($fout);
349
	curl_close($ch);
350
	return ($http_code == 200) ? true : $http_code;
351
}
352

    
353
function read_header($ch, $string) {
354
	global $file_size, $fout;
355
	$length = strlen($string);
356
	$regs = "";
357
	ereg("(Content-Length:) (.*)", $string, $regs);
358
	if($regs[2] <> "") {
359
	$file_size = intval($regs[2]);
360
	}
361
	ob_flush();
362
	return $length;
363
}
364

    
365
function read_body($ch, $string) {
366
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $pkg_interface;
367
	$length = strlen($string);
368
	$downloaded += intval($length);
369
	$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
370
	$downloadProgress = 100 - $downloadProgress;
371
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
372
		if($sendto == "status") {
373
			$tostatus = $static_status . $downloadProgress . "%";
374
			update_status($tostatus);
375
		} else {
376
			$tooutput = $static_output . $downloadProgress . "%";
377
			update_output_window($tooutput);
378
		}
379
		update_progress_bar($downloadProgress);
380
		$lastseen = $downloadProgress;
381
	}
382
	fwrite($fout, $string);
383
	ob_flush();
384
	return $length;
385
}
386

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

    
452
function eval_once($toeval) {
453
	global $evaled;
454
	if(!$evaled) $evaled = array();
455
	$evalmd5 = md5($toeval);
456
	if(!in_array($evalmd5, $evaled)) {
457
		eval($toeval);
458
		$evaled[] = $evalmd5;
459
	}
460
	return;
461
}
462

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

    
482
	/* set up package logging streams */
483
	if($pkg_info['logging']) {
484
		mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
485
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
486
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
487
		mwexec("killall syslogd");
488
		system_syslogd_start();
489
	}
490

    
491
	/* make 'y' file */
492
	$fd = fopen("{$g['tmp_path']}/y", "w");
493
	for($line = 0; $line < 10; $line++) {
494
		fwrite($fd, "y\n");
495
	}
496
	fclose($fd);
497

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

    
660
function delete_package($pkg, $pkgid) {
661
	global $g, $config, $fd_log, $static_output;
662
	update_status("Removing package...");
663
	$static_output .= "Removing package... ";
664
	update_output_window($static_output);
665
	$pkgid = get_pkg_id($pkgid);
666
	$pkg_info = $config['installedpackages']['package'][$pkgid];
667

    
668
	$configfile = $pkg_info['configurationfile'];
669
	if(file_exists("/usr/local/pkg/" . $configfile)) {
670
		$static_output .= "\nLoading package configuration $configfile... ";
671
		update_output_window($static_output);
672
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
673
		/*   if a require exists, include it.  this will
674
		 *   show us where an error exists in a package
675
		 *   instead of making us blindly guess
676
		 */
677
		if($pkg_config['include_file'] <> "") {
678
			$static_output .= "\nLoading package instructions...\n";
679
			update_output_window($static_output);
680
			require_once($pkg_config['include_file']);
681
		}
682
	}
683
	$static_output .= "\Starting package deletion...\n";
684
	update_output_window($static_output);
685
	delete_package_recursive($pkg);
686
	$static_output .= "done.\n";
687
	update_output_window($static_output);
688
	return;
689
}
690

    
691
function delete_package_recursive($pkg) {
692
	$info = "";
693
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
694
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
695
	$pkgdb = "";
696
	exec("/bin/ls /var/db/pkg", $pkgdb);
697
	if(stristr($info[0], "can't find package") != false) return;
698
	foreach($info as $line) {
699
		$depend = trim(array_pop(explode(":", $line)));
700
		if(in_array($depend, $pkgdb)) delete_package_recursive($depend);
701
	}
702
	$fd = fopen("{$g['tmp_path']}/y", "w");
703
	for($line = 0; $line < 10; $line++) {
704
		fwrite($fd, "y\n");
705
	}
706
	fclose($fd);
707
	return;
708
}
709

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

    
854
function expand_to_bytes($size) {
855
	$conv = array(
856
			"G" =>	"3",
857
			"M" =>  "2",
858
			"K" =>  "1",
859
			"B" =>  "0"
860
		);
861
	$suffix = substr($size, -1);
862
	if(!in_array($suffix, array_keys($conv))) return $size;
863
	$size = substr($size, 0, -1);
864
	for($i = 0; $i < $conv[$suffix]; $i++) {
865
		$size *= 1024;
866
	}
867
	return $size;
868
}
869

    
870
function get_pkg_db() {
871
	global $g;
872
	return return_dir_as_array($g['vardb_path'] . '/pkg');
873
}
874

    
875
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
876
	if(!$pkgdb) $pkgdb = get_pkg_db();
877
	if(!$alreadyseen) $alreadyseen = array();
878
	foreach($depend as $adepend) {
879
		$pkgname = reverse_strrchr($adepend['name'], '.');
880
		if(in_array($pkgname, $alreadyseen)) {
881
			continue;
882
		} elseif(!in_array($pkgname, $pkgdb)) {
883
			$size += expand_to_bytes($adepend['size']);
884
			$alreadyseen[] = $pkgname;
885
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
886
		} else {
887
			continue;
888
		}
889
	}
890
	return $size;
891
}
892

    
893
function get_package_install_size($pkg = 'all', $pkg_info = "") {
894
	global $config, $g;
895
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
896
	$pkgdb = get_pkg_db();
897
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
898
	foreach($pkg as $apkg) {
899
		if(!$pkg_info[$apkg]) continue;
900
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
901
	}
902
	return $toreturn;
903
}
904

    
905
function squash_from_bytes($size, $round = "") {
906
	$conv = array(1 => "B", "K", "M", "G");
907
	foreach($conv as $div => $suffix) {
908
		$sizeorig = $size;
909
		if(($size /= 1024) < 1) {
910
			if($round) {
911
				$sizeorig = round($sizeorig, $round);
912
			}
913
			return $sizeorig . $suffix;
914
		}
915
	}
916
	return;
917
}
918
?>
(15-15/27)