Project

General

Profile

Download (34.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6
 *   This file contains various functions used by the pfSense package system.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11
 * Copyright (C) 2005-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/remove_package
49
 * NAME
50
 *   remove_package - Removes package from FreeBSD if it exists
51
 * INPUTS
52
 *   $packagestring	- name/string to check for
53
 * RESULT
54
 *   none
55
 * NOTES
56
 *   
57
 ******/
58
function remove_freebsd_package($packagestring) {
59
	exec("cd /var/db/pkg && pkg_delete `ls | grep $packagestring`");
60
}
61

    
62
/****f* pkg-utils/is_package_installed
63
 * NAME
64
 *   is_package_installed - Check whether a package is installed.
65
 * INPUTS
66
 *   $packagename	- name of the package to check
67
 * RESULT
68
 *   boolean	- true if the package is installed, false otherwise
69
 * NOTES
70
 *   This function is deprecated - get_pkg_id() can already check for installation.
71
 ******/
72
function is_package_installed($packagename) {
73
	$pkg = get_pkg_id($packagename);
74
	if($pkg == -1) return false;
75
	return true;
76
}
77

    
78
/****f* pkg-utils/get_pkg_id
79
 * NAME
80
 *   get_pkg_id - Find a package's numeric ID.
81
 * INPUTS
82
 *   $pkg_name	- name of the package to check
83
 * RESULT
84
 *   integer    - -1 if package is not found, >-1 otherwise
85
 ******/
86
function get_pkg_id($pkg_name) {
87
	global $config;
88

    
89
	if(is_array($config['installedpackages']['package'])) {
90
		$i = 0;
91
		foreach($config['installedpackages']['package'] as $pkg) {
92
			if($pkg['name'] == $pkg_name) return $i;
93
			$i++;
94
		}
95
	}
96
	return -1;
97
}
98

    
99
/****f* pkg-utils/get_pkg_info
100
 * NAME
101
 *   get_pkg_info - Retrive package information from pfsense.com.
102
 * INPUTS
103
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
104
 *   $info - 'all' to retrive all information, an array containing keys otherwise
105
 * RESULT
106
 *   $raw_versions - Array containing retrieved information, indexed by package name.
107
 ******/
108
function get_pkg_info($pkgs = 'all', $info = 'all') {
109
	global $g;
110
	$params = array("pkg" => $pkgs, "info" => $info);
111
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
112
	return $resp ? $resp : array();
113
}
114

    
115
function get_pkg_sizes($pkgs = 'all') {
116
	global $g;
117
	$params = array("pkg" => $pkgs);
118
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
119
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $g['xmlrpcbaseurl']);
120
	$resp = $cli->send($msg, 10);
121
	if($resp and !$resp->faultCode()) {
122
		$raw_versions = $resp->value();
123
		return xmlrpc_value_to_php($raw_versions);
124
	} else {
125
		return array();
126
	}
127
}
128

    
129
/*
130
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
131
 * This function may also print output to the terminal indicating progress.
132
 */
133
function resync_all_package_configs($show_message = false) {
134
	global $config, $restart_sync, $pkg_interface;
135
	$i = 0;
136
	log_error("Resyncing configuration for all packages.");
137
	if(!$config['installedpackages']['package']) return;
138
	if($show_message == true) print "Syncing packages:";
139
	foreach($config['installedpackages']['package'] as $package) {
140
		if($show_message == true) print " " . $package['name'];
141
		get_pkg_depends($package['name'], "all");
142
		stop_service($package['name']);
143
		sync_package($i, true, true);
144
		if($restart_sync == true) {
145
			$restart_sync = false;
146
			if($pkg_interface == "console") 
147
				echo "\nSyncing packages:";
148
		}
149
		$i++;
150
	}
151
	if($show_message == true) print ".\n";
152
}
153

    
154
/*
155
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
156
 *				package is installed.
157
 */
158
function is_freebsd_pkg_installed($pkg) {
159
	global $g;
160
	if(in_array($pkg, return_dir_as_array("{$g['vardb_path']}/pkg"))) return true;
161
	return false;
162
}
163

    
164
/*
165
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
166
 *
167
 * $filetype = "all" || ".xml", ".tgz", etc.
168
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
169
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
170
 *
171
 */
172
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
173
	global $config;
174
	require_once("notices.inc");
175
	$pkg_id = get_pkg_id($pkg_name);
176
	if(!is_numeric($pkg_name)) {
177
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
178
	} else {
179
		if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
180
	}
181
	$package = $config['installedpackages']['package'][$pkg_id];
182
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
183
		log_error("The {$package['name']} package is missing required dependencies and must be reinstalled." . $package['configurationfile']);
184
		install_package($package['name']);
185
		uninstall_package_from_name($package['name']);
186
		install_package($package['name']);
187
		return;
188
	}
189
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
190
	if($pkg_xml['additional_files_needed'] != "") {
191
		foreach($pkg_xml['additional_files_needed'] as $item) {
192
			if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
193
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
194
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
195
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file))) continue;
196
			if ($item['prefix'] != "") {
197
				$prefix = $item['prefix'];
198
			} else {
199
				$prefix = "/usr/local/pkg/";
200
			}
201
			if(!file_exists($prefix . $depend_file))
202
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
203
			switch ($format) {
204
				case "files":
205
				$depends[] = $depend_file;
206
			break;
207
            			case "names":
208
                		switch ($filetype) {
209

    
210
				case "all":
211
				if(preg_match("/\.xml/i", $depend_file)) {
212
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
213
					$depends[] = $depend_xml['name'];
214
					break;
215
				} else {
216
					$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
217
				break;
218
				}
219
				case ".xml":
220
				$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
221
				$depends[] = $depend_xml['name'];
222
				break;
223
				default:
224
				$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
225
				break;
226
				}
227
			}
228
		}
229
		return $depends;
230
	}
231
}
232

    
233
function uninstall_package_from_name($pkg_name) {
234
	global $config;
235
	$id = get_pkg_id($pkg_name);
236
	$todel = substr(reverse_strrchr($config['installedpackages']['package'][$id]['depends_on_package'], "."), 0, -1);
237
	delete_package($todel, $pkg_name);
238
	delete_package_xml($pkg_name);
239
}
240

    
241
function force_remove_package($pkg_name) {
242
	global $config;
243
	delete_package_xml($pkg_name);
244
}
245

    
246
/*
247
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
248
 */
249
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
250
	global $config;
251
	require_once("notices.inc");
252
	if(!$config['installedpackages']['package']) return;
253
	if(!is_numeric($pkg_name)) {
254
		$pkg_id = get_pkg_id($pkg_name);
255
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
256
	} else {
257
		$pkg_id = $pkg_name;
258
		if(!isset($config['installedpackages']['package'][$pkg_id]))
259
		return;  // No package belongs to the pkg_id passed to this function.
260
	}
261
        if (is_array($config['installedpackages']['package'][$pkg_id]))
262
			$package = $config['installedpackages']['package'][$pkg_id];
263
        else
264
			return; /* empty package tag */
265
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
266
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
267
		force_remove_package($package['name']);
268
	} else {
269
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
270

    
271
		/* Bring in package include files */
272
		if (isset($pkg_config['include_file']) && $pkg_config['include_file'] != "") {
273
			$include_file = $pkg_config['include_file'];
274
			if (file_exists($include_file))
275
				require_once($include_file);
276
			else
277
				if (file_exists($include_file)) {
278
					require_once($include_file);
279
				} else {
280
					log_error("Could not locate {$include_file}.");
281
					install_package($package['name']);
282
					uninstall_package_from_name($package['name']);
283
					install_package($package['name']);
284
				}
285
		}
286

    
287
		/* XXX: Zend complains about the next line "Wrong break depth"
288
		 * The code is obviously wrong, but I'm not sure what it's supposed to do?
289
		 */
290
		if(isset($pkg_config['nosync'])) continue;
291
		if($pkg_config['custom_php_global_functions'] <> "")
292
		eval($pkg_config['custom_php_global_functions']);
293
		if($pkg_config['custom_php_resync_config_command'] <> "")
294
		eval($pkg_config['custom_php_resync_config_command']);
295
		if($sync_depends == true) {
296
			$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
297
			if(is_array($depends)) {
298
				foreach($depends as $item) {
299
					if(!file_exists("/usr/local/pkg/" . $item)) {
300
						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);
301
						log_error("Could not find {$item}. Reinstalling package.");
302
						install_package($pkg_name);
303
						uninstall_package_from_name($pkg_name);
304
						install_package($pkg_name);
305
					} else {
306
						$item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
307
						if(isset($item_config['nosync'])) continue;
308
						if($item_config['custom_php_command_before_form'] <> "") {
309
							eval($item_config['custom_php_command_before_form']);
310
						}
311
						if($item_config['custom_php_resync_config_command'] <> "") {
312
							eval($item_config['custom_php_resync_config_command']);
313
						}
314
						if($show_message == true) print " " . $item_config['name'];
315
					}
316
				}
317
			}
318
		}
319
	}
320
}
321

    
322
/*
323
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
324
 * 			a progress bar and output window.
325
 *
326
 * XXX: This function needs to return where a pkg_add fails. Our current error messages aren't very descriptive.
327
 */
328
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = 'http://ftp2.freebsd.org/pub/FreeBSD/ports/i386/packages-5.4-release/Latest') {
329
	global $pkgent, $static_output, $g, $fd_log;
330
	$pkg_extension = strrchr($filename, '.');
331
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
332
	$fetchto = "/tmp/apkg_" . $pkgname . $pkg_extension;
333
	download_file_with_progress_bar($base_url . '/' . $filename, $fetchto);
334
	$static_output .= " (extracting)";
335
	update_output_window($static_output);
336
		$slaveout = "";
337
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
338
	$workingdir = preg_grep("/instmp/", $slaveout);
339
	$workingdir = $workingdir[0];
340
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
341
	if($raw_depends_list != "") {
342
		if($pkgent['exclude_dependency'] != "")
343
			$raw_depends_list = array_values(preg_grep($pkgent['exclude_dependency'], PREG_GREP_INVERT));
344
		foreach($raw_depends_list as $adepend) {
345
			$working_depend = explode(" ", $adepend);
346
			//$working_depend = explode("-", $working_depend[1]);
347
			$depend_filename = $working_depend[1] . $pkg_extension;
348
			if(is_freebsd_pkg_installed($working_depend[1]) === false) {
349
				pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url);
350
			} else {
351
//				$dependlevel++;
352
				$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " ";
353
				@fwrite($fd_log, $working_depend[1] . "\n");
354
			}
355
		}
356
	}
357
	$pkgaddout = "";
358
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
359
	@fwrite($fd_log, $pkgname . " " . print_r($pkgaddout, true) . "\n");
360
	return true;
361
}
362

    
363
function download_file_with_progress_bar($url_file, $destination_file) {
364
	global $ch, $fout, $file_size, $downloaded, $pkg_interface;
365
	$file_size  = 1;
366
	$downloaded = 1;
367
	/* open destination file */
368
	$fout = fopen($destination_file, "wb");
369

    
370
	/*
371
	 *	Originally by Author: Keyvan Minoukadeh
372
	 *	Modified by Scott Ullrich to return Content-Length size
373
         */
374

    
375
	$ch = curl_init();
376
	curl_setopt($ch, CURLOPT_URL, $url_file);
377
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
378
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
379
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
380

    
381
	curl_exec($ch);
382
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
383
	if($fout)
384
		fclose($fout);
385
	curl_close($ch);
386
	return ($http_code == 200) ? true : $http_code;
387
}
388

    
389
function read_header($ch, $string) {
390
	global $file_size, $fout;
391
	$length = strlen($string);
392
	$regs = "";
393
	ereg("(Content-Length:) (.*)", $string, $regs);
394
	if($regs[2] <> "") {
395
	$file_size = intval($regs[2]);
396
	}
397
	ob_flush();
398
	return $length;
399
}
400

    
401
function read_body($ch, $string) {
402
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $pkg_interface;
403
	$length = strlen($string);
404
	$downloaded += intval($length);
405
	$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
406
	$downloadProgress = 100 - $downloadProgress;
407
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
408
		if($sendto == "status") {
409
			$tostatus = $static_status . $downloadProgress . "%";
410
			update_status($tostatus);
411
		} else {
412
			$tooutput = $static_output . $downloadProgress . "%";
413
			update_output_window($tooutput);
414
		}
415
		update_progress_bar($downloadProgress);
416
		$lastseen = $downloadProgress;
417
	}
418
	if($fout)
419
		fwrite($fout, $string);
420
	ob_flush();
421
	return $length;
422
}
423

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

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

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

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

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

    
540
	/* pkg_add the package and its dependencies */
541
	if($pkg_info['depends_on_package_base_url'] != "") {
542
		if($pkg_interface == "console") 
543
			echo "\n";
544
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
545
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
546
		$static_orig = $static_output;
547
		$static_output .= "\n";
548
		update_output_window($static_output);
549
		foreach((array) $pkg_info['depends_on_package'] as $pkgdep) {
550
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
551
			if(isset($pkg_info['skip_install_checks'])) {
552
				$pkg_installed = true;
553
			} else {
554
				$pkg_installed = is_freebsd_pkg_installed($pkg_name);
555
			}
556
			if($pkg_installed == false) pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url']);
557
			$static_output = $static_orig . "done.\nChecking for successful package installation... ";
558
			update_output_window($static_output);
559
			/* make sure our package was successfully installed */
560
			if($pkg_installed == false) $pkg_installed = is_freebsd_pkg_installed($pkg_name);
561
			if($pkg_installed == true) {
562
				$static_output .= "done.\n";
563
				update_output_window($static_output);
564
				fwrite($fd_log, "pkg_add successfully completed.\n");
565
			} else {
566
				$static_output .= "failed!\n\nInstallation aborted.";
567
				update_output_window($static_output);
568
				fwrite($fd_log, "Package WAS NOT installed properly.\n");
569
				fclose($fd_log);
570
				if($pkg_interface <> "console") {
571
					echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
572
					echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
573
				}
574
				sleep(1);
575
				die;
576
			}
577
		}
578
	}
579
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
580
	if(file_exists("/usr/local/pkg/" . $configfile)) {
581
		$static_output .= "Loading package configuration... ";
582
		update_output_window($static_output);
583
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
584
		$static_output .= "done.\n";
585
		update_output_window($static_output);
586
		$static_output .= "Configuring package components...\n";
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
				$static_output .= $filename . " ";
618
                                update_output_window($static_output);
619
				download_file_with_progress_bar($afn['item'][0], $prefix . $filename);
620
				if(stristr($filename, ".tgz") <> "") {
621
					fwrite($fd_log, "Extracting tarball to -C for " . $filename . "...\n");
622
					$tarout = "";
623
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
624
					fwrite($fd_log, print_r($tarout, true) . "\n");
625
				}
626
				if($pkg_chmod <> "") {
627
					fwrite($fd_log, "Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
628
					chmod($prefix . $filename, $pkg_chmod);
629
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
630
				}
631
				$static_output = $static_orig;
632
                                update_output_window($static_output);
633
			}
634
			$static_output .= "done.\n";
635
			update_output_window($static_output);
636
		}
637
		/*   if a require exists, include it.  this will
638
		 *   show us where an error exists in a package
639
		 *   instead of making us blindly guess
640
		 */
641
		if($pkg_config['include_file'] <> "") {
642
			$static_output = "Loading package instructions...";
643
			update_output_window($static_output);
644
			fwrite($fd_log, "require_once('include_file')\n");
645
			require_once($pkg_config['include_file']);
646
		}
647
		/* sidebar items */
648
		if($pkg_config['menu'] != "") {
649
			$static_output .= "\tMenu items... ";
650
			update_output_window($static_output);
651
			if(is_array($pkg_config['menu'])) {
652
				foreach($pkg_config['menu'] as $menu) {
653
					if(is_array($config['installedpackages']['menu'])) {
654
						foreach($config['installedpackages']['menu'] as $amenu) {
655
							if($amenu['name'] == $menu['name']) continue 2;
656
						}
657
					}
658
					$config['installedpackages']['menu'][] = $menu;
659
				}
660
			}
661
			$static_output .= "done.\n";
662
			update_output_window($static_output);
663
		}
664
		/* services */
665
		if($pkg_config['service'] != "") {
666
			$static_output .= "\tServices... ";
667
			update_output_window($static_output);
668
			foreach($pkg_config['service'] as $service) {
669
				$config['installedpackages']['service'][] = $service;
670
			}
671
			$static_output .= "done.\n";
672
			update_output_window($static_output);
673
		}
674
		/* custom commands */
675
		$static_output .= "\tCustom commands... ";
676
		update_output_window($static_output);
677
		if($pkg_config['custom_php_global_functions'] <> "") {
678
			$static_output = "Executing custom_php_global_functions()...";
679
			update_output_window($static_output);
680
			eval_once($pkg_config['custom_php_global_functions']);
681
		}
682
		if($pkg_config['custom_php_install_command']) {
683
			$static_output = "Executing custom_php_install_command()...";
684
			update_output_window($static_output);
685
			eval_once($pkg_config['custom_php_install_command']);
686
		}
687
		if($pkg_config['custom_php_resync_config_command'] <> "") {
688
			$static_output = "Executing custom_php_resync_config_command()...";
689
			update_output_window($static_output);
690
			eval_once($pkg_config['custom_php_resync_config_command']);
691
		}
692
		$static_output .= "done.\n";
693
		update_output_window($static_output);
694
	} else {
695
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
696
		update_output_window($static_output);
697
		fwrite($fd_log, "Unable to load package configuration. Installation aborted.\n");
698
		fclose($fd_log);
699
		if($pkg_interface <> "console") {
700
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
701
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
702
		}
703
		sleep(1);
704
		return;
705
	}
706
}
707

    
708
function delete_package($pkg, $pkgid) {
709
	global $g, $config, $fd_log, $static_output;
710
	update_status("Removing package...");
711
	$static_output .= "Removing package... ";
712
	update_output_window($static_output);
713
	$pkgid = get_pkg_id($pkgid);
714
	$pkg_info = $config['installedpackages']['package'][$pkgid];
715

    
716
	$configfile = $pkg_info['configurationfile'];
717
	if(file_exists("/usr/local/pkg/" . $configfile)) {
718
		$static_output .= "\nLoading package configuration $configfile... ";
719
		update_output_window($static_output);
720
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
721
		/*   if a require exists, include it.  this will
722
		 *   show us where an error exists in a package
723
		 *   instead of making us blindly guess
724
		 */
725
		if($pkg_config['include_file'] <> "") {
726
			$static_output .= "\nLoading package instructions...\n";
727
			update_output_window($static_output);
728
			require_once($pkg_config['include_file']);
729
		}
730
	}
731
	$static_output .= "\Starting package deletion...\n";
732
	update_output_window($static_output);
733
	delete_package_recursive($pkg);
734
	$static_output .= "done.\n";
735
	update_output_window($static_output);
736
	return;
737
}
738

    
739
function delete_package_recursive($pkg) {
740
	$info = "";
741
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
742
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
743
	$pkgdb = "";
744
	exec("/bin/ls /var/db/pkg", $pkgdb);
745
	if(stristr($info[0], "can't find package") != false) return;
746
	foreach($info as $line) {
747
		$depend = trim(array_pop(explode(":", $line)));
748
		if(in_array($depend, $pkgdb)) delete_package_recursive($depend);
749
	}
750
	$fd = fopen("{$g['tmp_path']}/y", "w");
751
	for($line = 0; $line < 10; $line++) {
752
		fwrite($fd, "y\n");
753
	}
754
	fclose($fd);
755
	return;
756
}
757

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

    
904
function expand_to_bytes($size) {
905
	$conv = array(
906
			"G" =>	"3",
907
			"M" =>  "2",
908
			"K" =>  "1",
909
			"B" =>  "0"
910
		);
911
	$suffix = substr($size, -1);
912
	if(!in_array($suffix, array_keys($conv))) return $size;
913
	$size = substr($size, 0, -1);
914
	for($i = 0; $i < $conv[$suffix]; $i++) {
915
		$size *= 1024;
916
	}
917
	return $size;
918
}
919

    
920
function get_pkg_db() {
921
	global $g;
922
	return return_dir_as_array($g['vardb_path'] . '/pkg');
923
}
924

    
925
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
926
	if(!$pkgdb) $pkgdb = get_pkg_db();
927
	if(!$alreadyseen) $alreadyseen = array();
928
	foreach($depend as $adepend) {
929
		$pkgname = reverse_strrchr($adepend['name'], '.');
930
		if(in_array($pkgname, $alreadyseen)) {
931
			continue;
932
		} elseif(!in_array($pkgname, $pkgdb)) {
933
			$size += expand_to_bytes($adepend['size']);
934
			$alreadyseen[] = $pkgname;
935
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
936
		} else {
937
			continue;
938
		}
939
	}
940
	return $size;
941
}
942

    
943
function get_package_install_size($pkg = 'all', $pkg_info = "") {
944
	global $config, $g;
945
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
946
	$pkgdb = get_pkg_db();
947
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
948
	foreach($pkg as $apkg) {
949
		if(!$pkg_info[$apkg]) continue;
950
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
951
	}
952
	return $toreturn;
953
}
954

    
955
function squash_from_bytes($size, $round = "") {
956
	$conv = array(1 => "B", "K", "M", "G");
957
	foreach($conv as $div => $suffix) {
958
		$sizeorig = $size;
959
		if(($size /= 1024) < 1) {
960
			if($round) {
961
				$sizeorig = round($sizeorig, $round);
962
			}
963
			return $sizeorig . $suffix;
964
		}
965
	}
966
	return;
967
}
968
?>
(16-16/29)