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
		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
	require_once("notices.inc");
154
	$pkg_id = get_pkg_id($pkg_name);
155
	if(!is_numeric($pkg_name)) {
156
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
157
	} else {
158
		if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
159
	}
160
	$package = $config['installedpackages']['package'][$pkg_id];
161
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
162
		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);
163
		return;
164
	}
165
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
166
	if($pkg_xml['additional_files_needed'] != "") {
167
		foreach($pkg_xml['additional_files_needed'] as $item) {
168
			if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
169
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
170
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
171
			if (($filetype != "all") && (!preg_match("/${filetype}/i", $depend_file))) continue;
172
			if ($item['prefix'] != "") {
173
				$prefix = $item['prefix'];
174
			} else {
175
				$prefix = "/usr/local/pkg/";
176
			}
177
			if(!file_exists($prefix . $pkg_name)) {
178
				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);
179
			}
180
			switch ($format) {
181
				case "files":
182
				$depends[] = $depend_file;
183
			break;
184
            			case "names":
185
                		switch ($filetype) {
186

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

    
210
/*
211
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
212
 */
213
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
214
	global $config;
215
	require_once("notices.inc");
216
	if(!$config['installedpackages']['package']) return;
217
	if(!is_numeric($pkg_name)) {
218
		$pkg_id = get_pkg_id($pkg_name);
219
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
220
	} else {
221
		$pkg_id = $pkg_name;
222
		if(!isset($config['installedpackages']['package'][$pkg_id]))
223
		return;  // No package belongs to the pkg_id passed to this function.
224
	}
225
        if (is_array($config['installedpackages']['package'][$pkg_id]))
226
                $package = $config['installedpackages']['package'][$pkg_id];
227
        else
228
                return; /* empty package tag */
229
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
230
		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);
231
	} else {
232
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
233

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
858
function get_pkg_db() {
859
	global $g;
860
	return return_dir_as_array($g['vardb_path'] . '/pkg');
861
}
862

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

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

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