Project

General

Profile

Download (35.1 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
$version = split("-", trim(file_get_contents("/etc/version")));
49
$ver = split("\.", $version[0]);
50
$g['version'] = intval($ver[1]);
51

    
52
/****f* pkg-utils/remove_package
53
 * NAME
54
 *   remove_package - Removes package from FreeBSD if it exists
55
 * INPUTS
56
 *   $packagestring	- name/string to check for
57
 * RESULT
58
 *   none
59
 * NOTES
60
 *   
61
 ******/
62
function remove_freebsd_package($packagestring) {
63
	exec("cd /var/db/pkg && echo y | pkg_delete `ls | grep $packagestring`");
64
}
65

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

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

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

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

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

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

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

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

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

    
237
function uninstall_package_from_name($pkg_name) {
238
	global $config;
239
	$id = get_pkg_id($pkg_name);
240
	$todel = substr(reverse_strrchr($config['installedpackages']['package'][$id]['depends_on_package'], "."), 0, -1);
241
	delete_package($todel, $pkg_name);
242
	delete_package_xml($pkg_name);
243
	remove_freebsd_package($pkg_name);
244
}
245

    
246
function force_remove_package($pkg_name) {
247
	global $config;
248
	delete_package_xml($pkg_name);
249
}
250

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

    
276
		/* Bring in package include files */
277
		if (isset($pkg_config['include_file']) && $pkg_config['include_file'] != "") {
278
			$include_file = $pkg_config['include_file'];
279
			if (file_exists($include_file))
280
				require_once($include_file);
281
			else
282
				if (file_exists($include_file)) {
283
					require_once($include_file);
284
				} else {
285
					log_error("Could not locate {$include_file}.");
286
					install_package($package['name']);
287
					uninstall_package_from_name($package['name']);
288
					remove_freebsd_package($package['name']);
289
					install_package($package['name']);
290
				}
291
		}
292

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

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

    
370
function download_file_with_progress_bar($url_file, $destination_file) {
371
	global $ch, $fout, $file_size, $downloaded, $pkg_interface;
372
	$file_size  = 1;
373
	$downloaded = 1;
374
	/* open destination file */
375
	$fout = fopen($destination_file, "wb");
376

    
377
	/*
378
	 *	Originally by Author: Keyvan Minoukadeh
379
	 *	Modified by Scott Ullrich to return Content-Length size
380
         */
381

    
382
	$ch = curl_init();
383
	curl_setopt($ch, CURLOPT_URL, $url_file);
384
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
385
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
386
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
387

    
388
	curl_exec($ch);
389
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
390
	if($fout)
391
		fclose($fout);
392
	curl_close($ch);
393
	return ($http_code == 200) ? true : $http_code;
394
}
395

    
396
function read_header($ch, $string) {
397
	global $file_size, $fout;
398
	$length = strlen($string);
399
	$regs = "";
400
	ereg("(Content-Length:) (.*)", $string, $regs);
401
	if($regs[2] <> "") {
402
	$file_size = intval($regs[2]);
403
	}
404
	ob_flush();
405
	return $length;
406
}
407

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

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

    
499
function eval_once($toeval) {
500
	global $evaled;
501
	if(!$evaled) $evaled = array();
502
	$evalmd5 = md5($toeval);
503
	if(!in_array($evalmd5, $evaled)) {
504
		eval($toeval);
505
		$evaled[] = $evalmd5;
506
	}
507
	return;
508
}
509

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

    
531
	/* set up package logging streams */
532
	if($pkg_info['logging']) {
533
		mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
534
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
535
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
536
		mwexec("killall syslogd");
537
		system_syslogd_start();
538
	}
539

    
540
	/* make 'y' file */
541
	$fd = fopen("{$g['tmp_path']}/y", "w");
542
	for($line = 0; $line < 10; $line++) {
543
		fwrite($fd, "y\n");
544
	}
545
	fclose($fd);
546

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

    
715
function delete_package($pkg, $pkgid) {
716
	global $g, $config, $fd_log, $static_output;
717
	update_status("Removing package...");
718
	$static_output .= "Removing package... ";
719
	update_output_window($static_output);
720
	$pkgid = get_pkg_id($pkgid);
721
	$pkg_info = $config['installedpackages']['package'][$pkgid];
722

    
723
	$configfile = $pkg_info['configurationfile'];
724
	if(file_exists("/usr/local/pkg/" . $configfile)) {
725
		$static_output .= "\nLoading package configuration $configfile... ";
726
		update_output_window($static_output);
727
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
728
		/*   if a require exists, include it.  this will
729
		 *   show us where an error exists in a package
730
		 *   instead of making us blindly guess
731
		 */
732
		if($pkg_config['include_file'] <> "") {
733
			$static_output .= "\nLoading package instructions...\n";
734
			update_output_window($static_output);
735
			require_once($pkg_config['include_file']);
736
		}
737
	}
738
	$static_output .= "\nStarting package deletion for {$pkg_info['name']}...\n";
739
	update_output_window($static_output);
740
	delete_package_recursive($pkg);
741
	remove_freebsd_package($pkg);
742
	$static_output .= "done.\n";
743
	update_output_window($static_output);
744
	return;
745
}
746

    
747
function delete_package_recursive($pkg) {
748
	global $config, $g;
749
	$fd = fopen("{$g['tmp_path']}/y", "w");
750
	for($line = 0; $line < 10; $line++) {
751
		fwrite($fd, "y\n");
752
	}
753
	fclose($fd);
754
	$info = "";
755
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
756
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
757
	remove_freebsd_package($pkg);
758
	$pkgdb = "";
759
	exec("/bin/ls /var/db/pkg", $pkgdb);
760
	foreach($info as $line) {
761
		$depend = trim(array_pop(explode(":", $line)));
762
		if(in_array($depend, $pkgdb)) 
763
			delete_package_recursive($depend);
764
	}
765
	return;
766
}
767

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

    
914
function expand_to_bytes($size) {
915
	$conv = array(
916
			"G" =>	"3",
917
			"M" =>  "2",
918
			"K" =>  "1",
919
			"B" =>  "0"
920
		);
921
	$suffix = substr($size, -1);
922
	if(!in_array($suffix, array_keys($conv))) return $size;
923
	$size = substr($size, 0, -1);
924
	for($i = 0; $i < $conv[$suffix]; $i++) {
925
		$size *= 1024;
926
	}
927
	return $size;
928
}
929

    
930
function get_pkg_db() {
931
	global $g;
932
	return return_dir_as_array($g['vardb_path'] . '/pkg');
933
}
934

    
935
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
936
	if(!$pkgdb) $pkgdb = get_pkg_db();
937
	if(!$alreadyseen) $alreadyseen = array();
938
	foreach($depend as $adepend) {
939
		$pkgname = reverse_strrchr($adepend['name'], '.');
940
		if(in_array($pkgname, $alreadyseen)) {
941
			continue;
942
		} elseif(!in_array($pkgname, $pkgdb)) {
943
			$size += expand_to_bytes($adepend['size']);
944
			$alreadyseen[] = $pkgname;
945
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
946
		} else {
947
			continue;
948
		}
949
	}
950
	return $size;
951
}
952

    
953
function get_package_install_size($pkg = 'all', $pkg_info = "") {
954
	global $config, $g;
955
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
956
	$pkgdb = get_pkg_db();
957
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
958
	foreach($pkg as $apkg) {
959
		if(!$pkg_info[$apkg]) continue;
960
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
961
	}
962
	return $toreturn;
963
}
964

    
965
function squash_from_bytes($size, $round = "") {
966
	$conv = array(1 => "B", "K", "M", "G");
967
	foreach($conv as $div => $suffix) {
968
		$sizeorig = $size;
969
		if(($size /= 1024) < 1) {
970
			if($round) {
971
				$sizeorig = round($sizeorig, $round);
972
			}
973
			return $sizeorig . $suffix;
974
		}
975
	}
976
	return;
977
}
978
?>
(16-16/29)