Project

General

Profile

Download (34.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6
 *   This file contains various functions used by the pfSense package system.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11
 * Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
12
 * All rights reserved.
13
 * Redistribution and use in source and binary forms, with or without
14
 * modification, are permitted provided that the following conditions are met:
15
 *
16
 * 1. Redistributions of source code must retain the above copyright notice,
17
 * this list of conditions and the following disclaimer.
18
 *
19
 * 2. Redistributions in binary form must reproduce the above copyright
20
 * notice, this list of conditions and the following disclaimer in the
21
 * documentation and/or other materials provided with the distribution.
22
 *
23
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
25
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
27
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 */
35
require_once("xmlrpc.inc");
36
require_once("xmlparse.inc");
37
require_once("service-utils.inc");
38
require_once("pfsense-utils.inc");
39
require_once("globals.inc");
40

    
41
safe_mkdir("/var/db/pkg");
42
$g['platform'] = trim(file_get_contents("/etc/platform"));
43
if($g['platform'] == "pfSense") {
44
	safe_mkdir("/usr/local/pkg");
45
	safe_mkdir("/usr/local/pkg/pf");
46
}
47

    
48
/****f* pkg-utils/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. Deinstalling.");
184
		install_package($package['name']);
185
		return;
186
	}
187
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
188
	if($pkg_xml['additional_files_needed'] != "") {
189
		foreach($pkg_xml['additional_files_needed'] as $item) {
190
			if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
191
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
192
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
193
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file))) continue;
194
			if ($item['prefix'] != "") {
195
				$prefix = $item['prefix'];
196
			} else {
197
				$prefix = "/usr/local/pkg/";
198
			}
199
			if(!file_exists($prefix . $depend_file))
200
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
201
			switch ($format) {
202
				case "files":
203
				$depends[] = $depend_file;
204
			break;
205
            			case "names":
206
                		switch ($filetype) {
207

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

    
231
function force_remove_package($pkg_name) {
232
	global $config;
233
	delete_package_xml($pkg_name);
234
}
235

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

    
261
		/* Bring in package include files */
262
		if (isset($pkg_config['include_file']) && $pkg_config['include_file'] != "") {
263
			$include_file = $pkg_config['include_file'];
264
			if (file_exists($include_file))
265
				require_once($include_file);
266
			else
267
				if (file_exists($include_file)) {
268
					require_once($include_file);
269
				} else {
270
					log_error("Could not locate {$include_file}.");
271
					install_package($package['name']);
272
				}
273
		}
274

    
275
		/* XXX: Zend complains about the next line "Wrong break depth"
276
		 * The code is obviously wrong, but I'm not sure what it's supposed to do?
277
		 */
278
		if(isset($pkg_config['nosync'])) continue;
279
		if($pkg_config['custom_php_global_functions'] <> "")
280
		eval($pkg_config['custom_php_global_functions']);
281
		if($pkg_config['custom_php_resync_config_command'] <> "")
282
		eval($pkg_config['custom_php_resync_config_command']);
283
		if($sync_depends == true) {
284
			$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
285
			if(is_array($depends)) {
286
				foreach($depends as $item) {
287
					if(!file_exists("/usr/local/pkg" . $item)) {
288
						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);
289
						install_package($pkg_name);
290
					} else {
291
						$item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
292
						if(isset($item_config['nosync'])) continue;
293
						if($item_config['custom_php_command_before_form'] <> "") {
294
							eval($item_config['custom_php_command_before_form']);
295
						}
296
						if($item_config['custom_php_resync_config_command'] <> "") {
297
							eval($item_config['custom_php_resync_config_command']);
298
						}
299
						if($show_message == true) print " " . $item_config['name'];
300
					}
301
				}
302
			}
303
		}
304
	}
305
}
306

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

    
348
function download_file_with_progress_bar($url_file, $destination_file) {
349
	global $ch, $fout, $file_size, $downloaded, $pkg_interface;
350
	$file_size  = 1;
351
	$downloaded = 1;
352
	/* open destination file */
353
	$fout = fopen($destination_file, "wb");
354

    
355
	/*
356
	 *	Originally by Author: Keyvan Minoukadeh
357
	 *	Modified by Scott Ullrich to return Content-Length size
358
         */
359

    
360
	$ch = curl_init();
361
	curl_setopt($ch, CURLOPT_URL, $url_file);
362
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
363
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
364
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
365

    
366
	curl_exec($ch);
367
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
368
	if($fout)
369
		fclose($fout);
370
	curl_close($ch);
371
	return ($http_code == 200) ? true : $http_code;
372
}
373

    
374
function read_header($ch, $string) {
375
	global $file_size, $fout;
376
	$length = strlen($string);
377
	$regs = "";
378
	ereg("(Content-Length:) (.*)", $string, $regs);
379
	if($regs[2] <> "") {
380
	$file_size = intval($regs[2]);
381
	}
382
	ob_flush();
383
	return $length;
384
}
385

    
386
function read_body($ch, $string) {
387
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $pkg_interface;
388
	$length = strlen($string);
389
	$downloaded += intval($length);
390
	$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
391
	$downloadProgress = 100 - $downloadProgress;
392
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
393
		if($sendto == "status") {
394
			$tostatus = $static_status . $downloadProgress . "%";
395
			update_status($tostatus);
396
		} else {
397
			$tooutput = $static_output . $downloadProgress . "%";
398
			update_output_window($tooutput);
399
		}
400
		update_progress_bar($downloadProgress);
401
		$lastseen = $downloadProgress;
402
	}
403
	if($fout)
404
		fwrite($fout, $string);
405
	ob_flush();
406
	return $length;
407
}
408

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

    
477
function eval_once($toeval) {
478
	global $evaled;
479
	if(!$evaled) $evaled = array();
480
	$evalmd5 = md5($toeval);
481
	if(!in_array($evalmd5, $evaled)) {
482
		eval($toeval);
483
		$evaled[] = $evalmd5;
484
	}
485
	return;
486
}
487

    
488
function install_package_xml($pkg) {
489
	global $g, $config, $fd_log, $static_output, $pkg_interface;
490
	if(($pkgid = get_pkg_id($pkg)) == -1) {
491
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
492
		update_output_window($static_output);
493
		if($pkg_interface <> "console") {
494
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
495
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
496
		}
497
		sleep(1);
498
		return;
499
	} else {
500
		$pkg_info = $config['installedpackages']['package'][$pkgid];
501
	}
502
	/* set up logging if needed */
503
	if(!$fd_log) {
504
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
505
			update_output_window("Warning, could not open log for writing.");
506
		}
507
	}
508

    
509
	/* set up package logging streams */
510
	if($pkg_info['logging']) {
511
		mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
512
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
513
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
514
		mwexec("killall syslogd");
515
		system_syslogd_start();
516
	}
517

    
518
	/* make 'y' file */
519
	$fd = fopen("{$g['tmp_path']}/y", "w");
520
	for($line = 0; $line < 10; $line++) {
521
		fwrite($fd, "y\n");
522
	}
523
	fclose($fd);
524

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

    
693
function delete_package($pkg, $pkgid) {
694
	global $g, $config, $fd_log, $static_output;
695
	update_status("Removing package...");
696
	$static_output .= "Removing package... ";
697
	update_output_window($static_output);
698
	$pkgid = get_pkg_id($pkgid);
699
	$pkg_info = $config['installedpackages']['package'][$pkgid];
700

    
701
	$configfile = $pkg_info['configurationfile'];
702
	if(file_exists("/usr/local/pkg/" . $configfile)) {
703
		$static_output .= "\nLoading package configuration $configfile... ";
704
		update_output_window($static_output);
705
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
706
		/*   if a require exists, include it.  this will
707
		 *   show us where an error exists in a package
708
		 *   instead of making us blindly guess
709
		 */
710
		if($pkg_config['include_file'] <> "") {
711
			$static_output .= "\nLoading package instructions...\n";
712
			update_output_window($static_output);
713
			require_once($pkg_config['include_file']);
714
		}
715
	}
716
	$static_output .= "\Starting package deletion...\n";
717
	update_output_window($static_output);
718
	delete_package_recursive($pkg);
719
	$static_output .= "done.\n";
720
	update_output_window($static_output);
721
	return;
722
}
723

    
724
function delete_package_recursive($pkg) {
725
	$info = "";
726
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
727
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
728
	$pkgdb = "";
729
	exec("/bin/ls /var/db/pkg", $pkgdb);
730
	if(stristr($info[0], "can't find package") != false) return;
731
	foreach($info as $line) {
732
		$depend = trim(array_pop(explode(":", $line)));
733
		if(in_array($depend, $pkgdb)) delete_package_recursive($depend);
734
	}
735
	$fd = fopen("{$g['tmp_path']}/y", "w");
736
	for($line = 0; $line < 10; $line++) {
737
		fwrite($fd, "y\n");
738
	}
739
	fclose($fd);
740
	return;
741
}
742

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

    
889
function expand_to_bytes($size) {
890
	$conv = array(
891
			"G" =>	"3",
892
			"M" =>  "2",
893
			"K" =>  "1",
894
			"B" =>  "0"
895
		);
896
	$suffix = substr($size, -1);
897
	if(!in_array($suffix, array_keys($conv))) return $size;
898
	$size = substr($size, 0, -1);
899
	for($i = 0; $i < $conv[$suffix]; $i++) {
900
		$size *= 1024;
901
	}
902
	return $size;
903
}
904

    
905
function get_pkg_db() {
906
	global $g;
907
	return return_dir_as_array($g['vardb_path'] . '/pkg');
908
}
909

    
910
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
911
	if(!$pkgdb) $pkgdb = get_pkg_db();
912
	if(!$alreadyseen) $alreadyseen = array();
913
	foreach($depend as $adepend) {
914
		$pkgname = reverse_strrchr($adepend['name'], '.');
915
		if(in_array($pkgname, $alreadyseen)) {
916
			continue;
917
		} elseif(!in_array($pkgname, $pkgdb)) {
918
			$size += expand_to_bytes($adepend['size']);
919
			$alreadyseen[] = $pkgname;
920
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
921
		} else {
922
			continue;
923
		}
924
	}
925
	return $size;
926
}
927

    
928
function get_package_install_size($pkg = 'all', $pkg_info = "") {
929
	global $config, $g;
930
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
931
	$pkgdb = get_pkg_db();
932
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
933
	foreach($pkg as $apkg) {
934
		if(!$pkg_info[$apkg]) continue;
935
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
936
	}
937
	return $toreturn;
938
}
939

    
940
function squash_from_bytes($size, $round = "") {
941
	$conv = array(1 => "B", "K", "M", "G");
942
	foreach($conv as $div => $suffix) {
943
		$sizeorig = $size;
944
		if(($size /= 1024) < 1) {
945
			if($round) {
946
				$sizeorig = round($sizeorig, $round);
947
			}
948
			return $sizeorig . $suffix;
949
		}
950
	}
951
	return;
952
}
953
?>
(15-15/27)