Project

General

Profile

Download (36.4 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

    
36
/*
37
	pfSense_BUILDER_BINARIES:	/usr/bin/cd	/usr/bin/tar	/bin/cat	/usr/sbin/fifolog_create	/bin/chmod
38
	pfSense_BUILDER_BINARIES:	/usr/bin/killall	/usr/sbin/pkg_info	/usr/sbin/pkg_delete	/bin/rm	/bin/ls
39
	pfSense_BUILDER_BINARIES:	/sbin/pfctl
40
	pfSense_MODULE:	pkg
41
*/
42

    
43
require_once("xmlrpc.inc");
44
if(file_exists("/cf/conf/use_xmlreader"))
45
	require_once("xmlreader.inc");
46
else
47
	require_once("xmlparse.inc");
48
require_once("service-utils.inc");
49
require_once("pfsense-utils.inc");
50
require_once("globals.inc");
51

    
52
if(!function_exists("update_status")) {
53
	function update_status($status) {
54
		echo $status . "\n";
55
	}
56
}
57
if(!function_exists("update_output_window")) {
58
	function update_output_window($status) {
59
		echo $status . "\n";
60
	}
61
}
62

    
63
safe_mkdir("/var/db/pkg");
64

    
65
$g['platform'] = trim(file_get_contents("/etc/platform"));
66
if($g['platform'] == "pfSense") {
67
	safe_mkdir("/usr/local/pkg");
68
	safe_mkdir("/usr/local/pkg/pf");
69
} else {
70
	if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
71
	conf_mount_rw();
72
	safe_mkdir("/usr/local/pkg");
73
	safe_mkdir("/usr/local/pkg/pf");	
74
	conf_mount_ro();
75
	}
76
}
77

    
78
$version = split("-", trim(file_get_contents("/etc/version")));
79
$ver = split("\.", $version[0]);
80
$g['version'] = intval($ver[1]);
81

    
82
/****f* pkg-utils/remove_package
83
 * NAME
84
 *   remove_package - Removes package from FreeBSD if it exists
85
 * INPUTS
86
 *   $packagestring	- name/string to check for
87
 * RESULT
88
 *   none
89
 * NOTES
90
 *   
91
 ******/
92
function remove_freebsd_package($packagestring) {
93
	exec("cd /var/db/pkg && echo y | pkg_delete `ls | grep $packagestring`");
94
}
95

    
96
/****f* pkg-utils/is_package_installed
97
 * NAME
98
 *   is_package_installed - Check whether a package is installed.
99
 * INPUTS
100
 *   $packagename	- name of the package to check
101
 * RESULT
102
 *   boolean	- true if the package is installed, false otherwise
103
 * NOTES
104
 *   This function is deprecated - get_pkg_id() can already check for installation.
105
 ******/
106
function is_package_installed($packagename) {
107
	$pkg = get_pkg_id($packagename);
108
	if($pkg == -1) return false;
109
	return true;
110
}
111

    
112
/****f* pkg-utils/get_pkg_id
113
 * NAME
114
 *   get_pkg_id - Find a package's numeric ID.
115
 * INPUTS
116
 *   $pkg_name	- name of the package to check
117
 * RESULT
118
 *   integer    - -1 if package is not found, >-1 otherwise
119
 ******/
120
function get_pkg_id($pkg_name) {
121
	global $config;
122

    
123
	if(is_array($config['installedpackages']['package'])) {
124
		$i = 0;
125
		foreach($config['installedpackages']['package'] as $pkg) {
126
			if($pkg['name'] == $pkg_name) return $i;
127
			$i++;
128
		}
129
	}
130
	return -1;
131
}
132

    
133
/****f* pkg-utils/get_pkg_info
134
 * NAME
135
 *   get_pkg_info - Retrive package information from pfsense.com.
136
 * INPUTS
137
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
138
 *   $info - 'all' to retrive all information, an array containing keys otherwise
139
 * RESULT
140
 *   $raw_versions - Array containing retrieved information, indexed by package name.
141
 ******/
142
function get_pkg_info($pkgs = 'all', $info = 'all') {
143
	global $g;
144
	$freebsd_version = str_replace("\n", "", `uname -r | cut -d'-' -f1 | cut -d'.' -f1`);
145
	$freebsd_machine = str_replace("\n", "", `uname -m`);
146
	$params = array(
147
		"pkg" => $pkgs, 
148
		"info" => $info, 
149
		"freebsd_version" => $freebsd_version,
150
		"freebsd_machine" => $freebsd_machine
151
	);
152
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
153
	return $resp ? $resp : array();
154
}
155

    
156
function get_pkg_sizes($pkgs = 'all') {
157
	global $g;
158
	$params = array("pkg" => $pkgs);
159
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
160
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
161
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
162
	$resp = $cli->send($msg, 10);
163
	if($resp and !$resp->faultCode()) {
164
		$raw_versions = $resp->value();
165
		return xmlrpc_value_to_php($raw_versions);
166
	} else {
167
		return array();
168
	}
169
}
170

    
171
/*
172
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
173
 * This function may also print output to the terminal indicating progress.
174
 */
175
function resync_all_package_configs($show_message = false) {
176
	global $config, $restart_sync, $pkg_interface;
177
	$i = 0;
178
	log_error("Resyncing configuration for all packages.");
179
	if(!$config['installedpackages']['package']) return;
180
	if($show_message == true) print "Syncing packages:";
181
	foreach($config['installedpackages']['package'] as $package) {
182
		if (empty($package['name']))
183
			continue;
184
		if($show_message == true) print " " . $package['name'];
185
		get_pkg_depends($package['name'], "all");
186
		stop_service($package['name']);
187
		sync_package($i, true, true);
188
		if($restart_sync == true) {
189
			$restart_sync = false;
190
			if($pkg_interface == "console") 
191
				echo "\nSyncing packages:";
192
		}
193
		$i++;
194
	}
195
	if($show_message == true) print ".\n";
196
}
197

    
198
/*
199
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
200
 *				package is installed.
201
 */
202
function is_freebsd_pkg_installed($pkg) {
203
	global $g;
204
	if(in_array($pkg, return_dir_as_array("{$g['vardb_path']}/pkg"))) return true;
205
	return false;
206
}
207

    
208
/*
209
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
210
 *
211
 * $filetype = "all" || ".xml", ".tgz", etc.
212
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
213
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
214
 *
215
 */
216
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
217
	global $config;
218
	require_once("notices.inc");
219
	$pkg_id = get_pkg_id($pkg_name);
220
	if(!is_numeric($pkg_name)) {
221
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
222
	} else {
223
		if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
224
	}
225
	$package = $config['installedpackages']['package'][$pkg_id];
226
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
227
		log_error("The {$package['name']} package is missing required dependencies and must be reinstalled." . $package['configurationfile']);
228
		install_package($package['name']);
229
		uninstall_package_from_name($package['name']);
230
		install_package($package['name']);
231
		return;
232
	}
233
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
234
	if($pkg_xml['additional_files_needed'] != "") {
235
		foreach($pkg_xml['additional_files_needed'] as $item) {
236
			if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
237
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
238
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
239
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file))) continue;
240
			if ($item['prefix'] != "") {
241
				$prefix = $item['prefix'];
242
			} else {
243
				$prefix = "/usr/local/pkg/";
244
			}
245
			if(!file_exists($prefix . $depend_file))
246
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
247
			switch ($format) {
248
				case "files":
249
				$depends[] = $depend_file;
250
			break;
251
            			case "names":
252
                		switch ($filetype) {
253

    
254
				case "all":
255
				if(preg_match("/\.xml/i", $depend_file)) {
256
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
257
					$depends[] = $depend_xml['name'];
258
					break;
259
				} else {
260
					$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
261
				break;
262
				}
263
				case ".xml":
264
				$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
265
				$depends[] = $depend_xml['name'];
266
				break;
267
				default:
268
				$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
269
				break;
270
				}
271
			}
272
		}
273
		return $depends;
274
	}
275
}
276

    
277
function uninstall_package_from_name($pkg_name) {
278
	global $config;
279
	$id = get_pkg_id($pkg_name);
280
	$todel = substr(reverse_strrchr($config['installedpackages']['package'][$id]['depends_on_package'], "."), 0, -1);
281
	delete_package($todel, $pkg_name);
282
	delete_package_xml($pkg_name);
283
	remove_freebsd_package($pkg_name);
284
}
285

    
286
function force_remove_package($pkg_name) {
287
	global $config;
288
	delete_package_xml($pkg_name);
289
}
290

    
291
/*
292
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
293
 */
294
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
295
	global $config;
296
	require_once("notices.inc");
297
	if(!$config['installedpackages']['package']) return;
298
	if(!is_numeric($pkg_name)) {
299
		$pkg_id = get_pkg_id($pkg_name);
300
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
301
	} else {
302
		$pkg_id = $pkg_name;
303
		if(!isset($config['installedpackages']['package'][$pkg_id]))
304
		return;  // No package belongs to the pkg_id passed to this function.
305
	}
306
        if (is_array($config['installedpackages']['package'][$pkg_id]))
307
			$package = $config['installedpackages']['package'][$pkg_id];
308
        else
309
			return; /* empty package tag */
310
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
311
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
312
		force_remove_package($package['name']);
313
	} else {
314
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
315

    
316
		/* Bring in package include files */
317
		if (!empty($pkg_config['include_file'])) {
318
			$include_file = $pkg_config['include_file'];
319
			if (file_exists($include_file))
320
				require_once($include_file);
321
			else {
322
				/* XXX: What the heck is this?! */
323
				log_error("Could not locate {$include_file}.");
324
				install_package($package['name']);
325
				uninstall_package_from_name($package['name']);
326
				remove_freebsd_package($package['name']);
327
				install_package($package['name']);
328
			}
329
		}
330

    
331
		/* XXX: Zend complains about the next line "Wrong break depth"
332
		 * The code is obviously wrong, but I'm not sure what it's supposed to do?
333
		 */
334
		if(isset($pkg_config['nosync'])) continue;
335
		if(!empty($pkg_config['custom_php_global_functions']))
336
			eval($pkg_config['custom_php_global_functions']);
337
		if(!empty($pkg_config['custom_php_resync_config_command']))
338
			eval($pkg_config['custom_php_resync_config_command']);
339
		if($sync_depends == true) {
340
			$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
341
			if(is_array($depends)) {
342
				foreach($depends as $item) {
343
					if(!file_exists("/usr/local/pkg/" . $item)) {
344
						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);
345
						log_error("Could not find {$item}. Reinstalling package.");
346
						install_package($pkg_name);
347
						uninstall_package_from_name($pkg_name);
348
						remove_freebsd_package($pkg_name);						
349
						install_package($pkg_name);
350
					} else {
351
						$item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
352
						if(isset($item_config['nosync'])) continue;
353
						if($item_config['custom_php_command_before_form'] <> "") {
354
							eval($item_config['custom_php_command_before_form']);
355
						}
356
						if($item_config['custom_php_resync_config_command'] <> "") {
357
							eval($item_config['custom_php_resync_config_command']);
358
						}
359
						if($show_message == true) print " " . $item_config['name'];
360
					}
361
				}
362
			}
363
		}
364
	}
365
}
366

    
367
/*
368
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
369
 * 			a progress bar and output window.
370
 *
371
 * XXX: This function needs to return where a pkg_add fails. Our current error messages aren't very descriptive.
372
 */
373
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = 'http://ftp2.freebsd.org/pub/FreeBSD/ports/i386/packages-5.4-release/Latest') {
374
	global $pkgent, $static_output, $g, $fd_log;
375
	$pkg_extension = strrchr($filename, '.');
376
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
377
	$fetchto = "{$g['tmp_path']}/apkg_" . $pkgname . $pkg_extension;
378
	download_file_with_progress_bar($base_url . '/' . $filename, $fetchto);
379
	$static_output .= " (extracting)";
380
	update_output_window($static_output);
381
		$slaveout = "";
382
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
383
	$workingdir = preg_grep("/instmp/", $slaveout);
384
	$workingdir = $workingdir[0];
385
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
386
	if($raw_depends_list != "") {
387
		if($pkgent['exclude_dependency'] != "")
388
			$raw_depends_list = array_values(preg_grep($pkgent['exclude_dependency'], PREG_GREP_INVERT));
389
		foreach($raw_depends_list as $adepend) {
390
			$working_depend = explode(" ", $adepend);
391
			//$working_depend = explode("-", $working_depend[1]);
392
			$depend_filename = $working_depend[1] . $pkg_extension;
393
			if(is_freebsd_pkg_installed($working_depend[1]) === false) {
394
				pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url);
395
			} else {
396
//				$dependlevel++;
397
				$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " ";
398
				@fwrite($fd_log, $working_depend[1] . "\n");
399
			}
400
		}
401
	}
402
	$pkgaddout = "";
403
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
404
	@fwrite($fd_log, $pkgname . " " . print_r($pkgaddout, true) . "\n");
405
	return true;
406
}
407

    
408
function install_package($package, $pkg_info = "") {
409
	global $g, $config, $pkg_interface, $fd_log, $static_output, $pkg_interface, $restart_sync;
410
	if($pkg_interface == "console") 	
411
		echo "\n";
412
	/* open logfiles and begin installation */
413
	if(!$fd_log) {
414
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$package}.log", "w")) {
415
			update_output_window("Warning, could not open log for writing.");
416
		}
417
	}
418
	/* fetch package information if needed */
419
	if(!$pkg_info or !is_array($pkg_info[$package])) {
420
		$pkg_info = get_pkg_info(array($package));
421
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
422
	}
423
	@fwrite($fd_log, "Beginning package installation.\n");
424
	log_error('Beginning package installation for ' . $pkg_info['name'] . '.');
425
	update_status("Beginning package installation for " . $pkg_info['name'] . "...");	
426
	/* fetch the package's configuration file */
427
	if($pkg_info['config_file'] != "") {
428
		$static_output .= "Downloading package configuration file... ";
429
		update_output_window($static_output);
430
		@fwrite($fd_log, "Downloading package configuration file...\n");
431
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
432
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
433
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
434
			@fwrite($fd_log, "ERROR! Unable to fetch package configuration file. Aborting installation.\n");
435
			if($pkg_interface == "console") {
436
				print "\nERROR! Unable to fetch package configuration file. Aborting package installation.\n";
437
				return;
438
			} else {
439
				$static_output .= "failed!\n\nInstallation aborted.";
440
				update_output_window($static_output);
441
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
442
			 	return -1;
443
			}
444
		}
445
		$static_output .= "done.\n";
446
		update_output_window($static_output);
447
	}
448
	/* add package information to config.xml */
449
	$pkgid = get_pkg_id($pkg_info['name']);
450
	$static_output .= "Saving updated package information... ";
451
	update_output_window($static_output);
452
	if($pkgid == -1) {
453
		$config['installedpackages']['package'][] = $pkg_info;
454
		$changedesc = "Installed {$pkg_info['name']} package.";
455
		$to_output = "done.\n";
456
	} else {
457
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
458
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
459
		$to_output = "overwrite!\n";
460
	}
461
	$static_output .= $to_output;
462
	update_output_window($static_output);
463
	/* install other package components */
464
	install_package_xml($package);
465
	$static_output .= "Writing configuration... ";
466
	update_output_window($static_output);
467
	write_config($changedesc);
468
	$static_output .= "done.\n";
469
	update_output_window($static_output);
470
	$static_output .= "Starting service.\n";
471
	update_output_window($static_output);
472
	if($pkg_info['after_install_info']) 
473
		update_output_window($pkg_info['after_install_info']);	
474
	start_service($pkg_info['config_file']);
475
	$restart_sync = true;
476
}
477

    
478
function get_after_install_info($package) {
479
	global $pkg_info;
480
	/* fetch package information if needed */
481
	if(!$pkg_info or !is_array($pkg_info[$package])) {
482
		$pkg_info = get_pkg_info(array($package));
483
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
484
	}
485
	if($pkg_info['after_install_info'])
486
		return $pkg_info['after_install_info'];
487
}
488

    
489
function eval_once($toeval) {
490
	global $evaled;
491
	if(!$evaled) $evaled = array();
492
	$evalmd5 = md5($toeval);
493
	if(!in_array($evalmd5, $evaled)) {
494
		eval($toeval);
495
		$evaled[] = $evalmd5;
496
	}
497
	return;
498
}
499

    
500
function install_package_xml($pkg) {
501
	global $g, $config, $fd_log, $static_output, $pkg_interface;
502
	if(($pkgid = get_pkg_id($pkg)) == -1) {
503
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
504
		update_output_window($static_output);
505
		if($pkg_interface <> "console") {
506
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
507
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
508
		}
509
		sleep(1);
510
		return;
511
	} else {
512
		$pkg_info = $config['installedpackages']['package'][$pkgid];
513
	}
514
	/* set up logging if needed */
515
	if(!$fd_log) {
516
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
517
			update_output_window("Warning, could not open log for writing.");
518
		}
519
	}
520

    
521
	/* set up package logging streams */
522
	if($pkg_info['logging']) {
523
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
524
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
525
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
526
		if(is_process_running("syslogd"))
527
			mwexec("killall syslogd");
528
		system_syslogd_start();
529
	}
530

    
531
	/* make 'y' file */
532
	$fd = fopen("{$g['tmp_path']}/y", "w");
533
	for($line = 0; $line < 10; $line++) {
534
		fwrite($fd, "y\n");
535
	}
536
	fclose($fd);
537

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

    
725
function delete_package($pkg, $pkgid) {
726
	global $g, $config, $fd_log, $static_output;
727
	update_status("Removing package...");
728
	$static_output .= "Removing package... ";
729
	update_output_window($static_output);
730
	$pkgid = get_pkg_id($pkgid);
731
	$pkg_info = $config['installedpackages']['package'][$pkgid];
732

    
733
	$configfile = $pkg_info['configurationfile'];
734
	if(file_exists("/usr/local/pkg/" . $configfile)) {
735
		$static_output .= "\nLoading package configuration $configfile... ";
736
		update_output_window($static_output);
737
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
738
		/*   if a require exists, include it.  this will
739
		 *   show us where an error exists in a package
740
		 *   instead of making us blindly guess
741
		 */
742
		if($pkg_config['include_file'] <> "") {
743
			$static_output .= "\nLoading package instructions...\n";
744
			update_output_window($static_output);
745
			require_once($pkg_config['include_file']);
746
		}
747
	}
748
	$static_output .= "\nStarting package deletion for {$pkg_info['name']}...\n";
749
	update_output_window($static_output);
750
	delete_package_recursive($pkg);
751
	remove_freebsd_package($pkg);
752
	$static_output .= "done.\n";
753
	update_output_window($static_output);
754
	return;
755
}
756

    
757
function delete_package_recursive($pkg) {
758
	global $config, $g;
759
	$fd = fopen("{$g['tmp_path']}/y", "w");
760
	for($line = 0; $line < 10; $line++) {
761
		fwrite($fd, "y\n");
762
	}
763
	fclose($fd);
764
	$info = "";
765
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
766
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
767
	remove_freebsd_package($pkg);
768
	$pkgdb = "";
769
	exec("/bin/ls /var/db/pkg", $pkgdb);
770
	foreach($info as $line) {
771
		$depend = trim(array_pop(explode(":", $line)));
772
		if(in_array($depend, $pkgdb)) 
773
			delete_package_recursive($depend);
774
	}
775
	return;
776
}
777

    
778
function delete_package_xml($pkg) {
779
	global $g, $config, $fd_log, $static_output, $pkg_interface;
780
	conf_mount_rw();
781

    
782
	if(($pkgid = get_pkg_id($pkg)) == -1) {
783
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
784
		update_output_window($static_output);
785
		if($pkg_interface <> "console") {
786
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
787
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
788
		}
789
		ob_flush();
790
		sleep(1);
791
		return;
792
	}
793
	/* set up logging if needed */
794
	if(!$fd_log) {
795
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
796
			update_output_window("Warning, could not open log for writing.");
797
		}
798
	}
799
	update_status("Removing {$pkg} components...");
800
	fwrite($fd_log, "Removing {$pkg} package... ");
801
	$static_output .= "Removing {$pkg} components...\n";
802
	update_output_window($static_output);
803
	/* parse package configuration */
804
	$packages = &$config['installedpackages']['package'];
805
	$tabs =& $config['installedpackages']['tab'];
806
	$menus =& $config['installedpackages']['menu'];
807
	$services = &$config['installedpackages']['service'];
808
	if(file_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'])) {
809
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
810
		/* remove tab items */
811
		if(is_array($pkg_config['tabs'])) {
812
			$static_output .= "\tMenu items... ";
813
			update_output_window($static_output);
814
			if(is_array($tabs))
815
				foreach($tabs as $tab)
816
					$insttabs[] = $tab['name'];
817
			if($pkg_config['tabs']['tab'])
818
				foreach($pkg_config['tabs']['tab'] as $tab)
819
					foreach($insttabs as $key => $insttab)
820
						if($insttab == $tab['name'])
821
							unset($tabs[$key]);
822
			$static_output .= "done.\n";
823
			update_output_window($static_output);
824
		}
825
		/* remove menu items */
826
		if(is_array($pkg_config['menu'])) {
827
			$static_output .= "\tMenu items... ";
828
			update_output_window($static_output);
829
			foreach($menus as $menu)
830
				$instmenus[] = $menu['name'];
831
			foreach($pkg_config['menu'] as $menu)
832
				foreach($instmenus as $key => $instmenu)
833
					if($instmenu == $menu['name'])
834
						unset($menus[$key]);
835
			$static_output .= "done.\n";
836
			update_output_window($static_output);
837
		}
838
		/* remove services */
839
		if(is_array($pkg_config['service'])) {
840
			$static_output .= "\tServices... ";
841
			update_output_window($static_output);
842
			foreach($services as $service) $instservices[] = $service['name'];
843
			foreach($pkg_config['service'] as $service) {
844
				foreach($instservices as $key => $instservice) {
845
					if($instservice == $service['name']) {
846
						stop_service($service['name']);
847
						unset($services[$key]);
848
					}
849
				}
850
			}
851
			$static_output .= "done.\n";
852
			update_output_window($static_output);
853
		}
854
		/*   if a require exists, include it.  this will
855
		 *   show us where an error exists in a package
856
		 *   instead of making us blindly guess
857
		 */
858
		if($pkg_config['include_file'] <> "") {
859
			$static_output = "Loading package instructions...";
860
			update_output_window($static_output);
861
			fwrite($fd_log, "require_once('include_file')\n");
862
			if(file_exists($pkg_config['include_file']))
863
				require_once($pkg_config['include_file']);
864
			fwrite($fd_log, "require_once('include_file') included\n");
865
		}
866
		/* evalate this package's global functions and pre deinstall commands */
867
		if($pkg_config['custom_php_global_functions'] <> "")
868
			eval_once($pkg_config['custom_php_global_functions']);
869
		if($pkg_config['custom_php_pre_deinstall_command'] <> "")
870
			eval_once($pkg_config['custom_php_pre_deinstall_command']);
871
		/* remove all additional files */
872
		if($pkg_config['additional_files_needed'] <> "") {
873
			$static_output .= "\tAuxiliary files... ";
874
			update_output_window($static_output);
875
			foreach($pkg_config['additional_files_needed'] as $afn) {
876
				$filename = get_filename_from_url($afn['item'][0]);
877
				if($afn['prefix'] <> "") {
878
					$prefix = $afn['prefix'];
879
				} else {
880
					$prefix = "/usr/local/pkg/";
881
				}
882
				unlink_if_exists($prefix . $filename);
883
				if(file_exists($prefix . $filename))
884
				    mwexec("rm -rf {$prefix}{$filename}");
885
			}
886
			$static_output .= "done.\n";
887
			update_output_window($static_output);
888
		}
889
		/* system files */
890
		if($pkg_config['modify_system']['item'] <> "") {
891
			$static_output .= "\tSystem files... ";
892
			update_output_window($static_output);
893
			foreach($pkg_config['modify_system']['item'] as $ms) {
894
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
895
			}
896
			$static_output .= "done.\n";
897
			update_output_window($static_output);
898
		}
899
		/* syslog */
900
		if($pkg_config['logging']['logfile_name'] <> "") {
901
			$static_output .= "\tSyslog entries... ";
902
			update_output_window($static_output);
903
			remove_text_from_file("/etc/syslog.conf", $pkg_config['logging']['facilityname'] . "\t\t\t\t" . $pkg_config['logging']['logfilename']);
904
			$static_output .= "done.\n";
905
			update_output_window($static_output);
906
		}
907
		/* deinstall commands */
908
		if($pkg_config['custom_php_deinstall_command'] <> "") {
909
			$static_output .= "\tDeinstall commands... ";
910
			update_output_window($static_output);
911
			eval_once($pkg_config['custom_php_deinstall_command']);
912
			$static_output .= "done.\n";
913
			update_output_window($static_output);
914
		}
915
		/* package XML file */
916
		$static_output .= "\tPackage XML... ";
917
		update_output_window($static_output);
918
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
919
		$static_output .= "done.\n";
920
		update_output_window($static_output);
921
	}
922
	/* remove config.xml entries */
923
	$static_output .= "\tConfiguration... ";
924
	update_output_window($static_output);
925
	unset($config['installedpackages']['package'][$pkgid]);
926
	$static_output .= "done.\n";
927
	update_output_window($static_output);
928
	write_config("Removed {$pkg} package.");
929
	/* file cleanup */
930
	$ctag = file("/etc/crontab");
931
	foreach($ctag as $line) {
932
		if(trim($line) != "") $towrite[] = $line;
933
	}
934
	$tmptab = fopen("{$g['tmp_path']}/crontab", "w");
935
	foreach($towrite as $line) {
936
		fwrite($tmptab, $line);
937
	}
938
	fclose($tmptab);
939

    
940
	// Go RW again since the write_config above will put it back to RO
941
	conf_mount_rw();
942
	rename("{$g['tmp_path']}/crontab", "/etc/crontab");
943
	conf_mount_ro();
944
}
945

    
946
function expand_to_bytes($size) {
947
	$conv = array(
948
			"G" =>	"3",
949
			"M" =>  "2",
950
			"K" =>  "1",
951
			"B" =>  "0"
952
		);
953
	$suffix = substr($size, -1);
954
	if(!in_array($suffix, array_keys($conv))) return $size;
955
	$size = substr($size, 0, -1);
956
	for($i = 0; $i < $conv[$suffix]; $i++) {
957
		$size *= 1024;
958
	}
959
	return $size;
960
}
961

    
962
function get_pkg_db() {
963
	global $g;
964
	return return_dir_as_array($g['vardb_path'] . '/pkg');
965
}
966

    
967
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
968
	if(!$pkgdb) $pkgdb = get_pkg_db();
969
	if(!$alreadyseen) $alreadyseen = array();
970
	foreach($depend as $adepend) {
971
		$pkgname = reverse_strrchr($adepend['name'], '.');
972
		if(in_array($pkgname, $alreadyseen)) {
973
			continue;
974
		} elseif(!in_array($pkgname, $pkgdb)) {
975
			$size += expand_to_bytes($adepend['size']);
976
			$alreadyseen[] = $pkgname;
977
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
978
		} else {
979
			continue;
980
		}
981
	}
982
	return $size;
983
}
984

    
985
function get_package_install_size($pkg = 'all', $pkg_info = "") {
986
	global $config, $g;
987
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
988
	$pkgdb = get_pkg_db();
989
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
990
	foreach($pkg as $apkg) {
991
		if(!$pkg_info[$apkg]) continue;
992
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
993
	}
994
	return $toreturn;
995
}
996

    
997
function squash_from_bytes($size, $round = "") {
998
	$conv = array(1 => "B", "K", "M", "G");
999
	foreach($conv as $div => $suffix) {
1000
		$sizeorig = $size;
1001
		if(($size /= 1024) < 1) {
1002
			if($round) {
1003
				$sizeorig = round($sizeorig, $round);
1004
			}
1005
			return $sizeorig . $suffix;
1006
		}
1007
	}
1008
	return;
1009
}
1010

    
1011
?>
(30-30/50)