Project

General

Profile

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

    
42
safe_mkdir("/var/db/pkg");
43

    
44
$g['platform'] = trim(file_get_contents("/etc/platform"));
45
if($g['platform'] == "pfSense") {
46
	safe_mkdir("/usr/local/pkg");
47
	safe_mkdir("/usr/local/pkg/pf");
48
} else {
49
	if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
50
	conf_mount_rw();
51
	safe_mkdir("/usr/local/pkg");
52
	safe_mkdir("/usr/local/pkg/pf");	
53
	conf_mount_ro();
54
	}
55
}
56

    
57
/****f* pkg-utils/remove_package
58
 * NAME
59
 *   remove_package - Removes package from FreeBSD if it exists
60
 * INPUTS
61
 *   $packagestring	- name/string to check for
62
 * RESULT
63
 *   none
64
 * NOTES
65
 *   
66
 ******/
67
function remove_freebsd_package($packagestring) {
68
	
69
	exec("cd /var/db/pkg && pkg_delete `ls | grep $packagestring`");
70
	log_error("cd /var/db/pkg && pkg_delete ls | grep $packagestring");
71
}
72

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

    
89
/****f* pkg-utils/get_pkg_id
90
 * NAME
91
 *   get_pkg_id - Find a package's numeric ID.
92
 * INPUTS
93
 *   $pkg_name	- name of the package to check
94
 * RESULT
95
 *   integer    - -1 if package is not found, >-1 otherwise
96
 ******/
97
function get_pkg_id($pkg_name) {
98
	global $config;
99

    
100
	if(is_array($config['installedpackages']['package'])) {
101
		$i = 0;
102
		foreach($config['installedpackages']['package'] as $pkg) {
103
			if($pkg['name'] == $pkg_name) return $i;
104
			$i++;
105
		}
106
	}
107
	return -1;
108
}
109

    
110
/****f* pkg-utils/get_pkg_info
111
 * NAME
112
 *   get_pkg_info - Retrive package information from pfsense.com.
113
 * INPUTS
114
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
115
 *   $info - 'all' to retrive all information, an array containing keys otherwise
116
 * RESULT
117
 *   $raw_versions - Array containing retrieved information, indexed by package name.
118
 ******/
119
function get_pkg_info($pkgs = 'all', $info = 'all') {
120
	global $g;
121
	$freebsd_version = str_replace("\n", "", `uname -r | cut -d'-' -f1 | cut -d'.' -f1`);
122
	$params = array(
123
		"pkg" => $pkgs, 
124
		"info" => $info, 
125
		"freebsd_version" => $freebsd_version
126
		);
127
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
128
	return $resp ? $resp : array();
129
}
130

    
131
function get_pkg_sizes($pkgs = 'all') {
132
	global $g;
133
	$params = array("pkg" => $pkgs);
134
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
135
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $g['xmlrpcbaseurl']);
136
	$resp = $cli->send($msg, 10);
137
	if($resp and !$resp->faultCode()) {
138
		$raw_versions = $resp->value();
139
		return xmlrpc_value_to_php($raw_versions);
140
	} else {
141
		return array();
142
	}
143
}
144

    
145
/*
146
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
147
 * This function may also print output to the terminal indicating progress.
148
 */
149
function resync_all_package_configs($show_message = false) {
150
	global $config, $restart_sync, $pkg_interface;
151
	$i = 0;
152
	log_error("Resyncing configuration for all packages.");
153
	if(!$config['installedpackages']['package']) return;
154
	if($show_message == true) print "Syncing packages:";
155
	foreach($config['installedpackages']['package'] as $package) {
156
		if($show_message == true) print " " . $package['name'];
157
		get_pkg_depends($package['name'], "all");
158
		stop_service($package['name']);
159
		sync_package($i, true, true);
160
		if($restart_sync == true) {
161
			$restart_sync = false;
162
			if($pkg_interface == "console") 
163
				echo "\nSyncing packages:";
164
		}
165
		$i++;
166
	}
167
	if($show_message == true) print ".\n";
168
}
169

    
170
/*
171
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
172
 *				package is installed.
173
 */
174
function is_freebsd_pkg_installed($pkg) {
175
	global $g;
176
	if(in_array($pkg, return_dir_as_array("{$g['vardb_path']}/pkg"))) return true;
177
	return false;
178
}
179

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

    
227
				case "all":
228
				if(preg_match("/\.xml/i", $depend_file)) {
229
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
230
					$depends[] = $depend_xml['name'];
231
					break;
232
				} else {
233
					$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
234
				break;
235
				}
236
				case ".xml":
237
				$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
238
				$depends[] = $depend_xml['name'];
239
				break;
240
				default:
241
				$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
242
				break;
243
				}
244
			}
245
		}
246
		return $depends;
247
	}
248
}
249

    
250
function uninstall_package_from_name($pkg_name) {
251
	global $config;
252
	$id = get_pkg_id($pkg_name);
253
	$todel = substr(reverse_strrchr($config['installedpackages']['package'][$id]['depends_on_package'], "."), 0, -1);
254
	delete_package($todel, $pkg_name);
255
	delete_package_xml($pkg_name);
256
	remove_freebsd_package($pkg_name);
257
}
258

    
259
function force_remove_package($pkg_name) {
260
	global $config;
261
	delete_package_xml($pkg_name);
262
	remove_freebsd_package($pkg_name);
263
}
264

    
265
/*
266
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
267
 */
268
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
269
	global $config;
270
	require_once("notices.inc");
271
	if(!$config['installedpackages']['package']) return;
272
	if(!is_numeric($pkg_name)) {
273
		$pkg_id = get_pkg_id($pkg_name);
274
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
275
	} else {
276
		$pkg_id = $pkg_name;
277
		if(!isset($config['installedpackages']['package'][$pkg_id]))
278
		return;  // No package belongs to the pkg_id passed to this function.
279
	}
280
        if (is_array($config['installedpackages']['package'][$pkg_id]))
281
			$package = $config['installedpackages']['package'][$pkg_id];
282
        else
283
			return; /* empty package tag */
284
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
285
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
286
		force_remove_package($package['name']);
287
	} else {
288
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
289

    
290
		/* Bring in package include files */
291
		if (isset($pkg_config['include_file']) && $pkg_config['include_file'] != "") {
292
			$include_file = $pkg_config['include_file'];
293
			if (file_exists($include_file))
294
				require_once($include_file);
295
			else
296
				if (file_exists($include_file)) {
297
					require_once($include_file);
298
				} else {
299
					log_error("Could not locate {$include_file}.");
300
					install_package($package['name']);
301
					uninstall_package_from_name($package['name']);
302
					install_package($package['name']);
303
				}
304
		}
305

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

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

    
382
function download_file_with_progress_bar($url_file, $destination_file) {
383
	global $ch, $fout, $file_size, $downloaded, $pkg_interface;
384
	$file_size  = 1;
385
	$downloaded = 1;
386
	/* open destination file */
387
	$fout = fopen($destination_file, "wb");
388

    
389
	/*
390
	 *	Originally by Author: Keyvan Minoukadeh
391
	 *	Modified by Scott Ullrich to return Content-Length size
392
         */
393

    
394
	$ch = curl_init();
395
	curl_setopt($ch, CURLOPT_URL, $url_file);
396
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
397
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
398
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
399
	curl_setopt($ch, CURLOPT_TIMEOUT, 0); 
400
	
401
	curl_exec($ch);
402
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
403
	if($fout)
404
		fclose($fout);
405
	curl_close($ch);
406
	return ($http_code == 200) ? true : $http_code;
407
}
408

    
409
function read_header($ch, $string) {
410
	global $file_size, $fout;
411
	$length = strlen($string);
412
	$regs = "";
413
	ereg("(Content-Length:) (.*)", $string, $regs);
414
	if($regs[2] <> "") {
415
	$file_size = intval($regs[2]);
416
	}
417
	ob_flush();
418
	return $length;
419
}
420

    
421
function read_body($ch, $string) {
422
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $pkg_interface;
423
	$length = strlen($string);
424
	$downloaded += intval($length);
425
	$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
426
	$downloadProgress = 100 - $downloadProgress;
427
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
428
		if($sendto == "status") {
429
			$tostatus = $static_status . $downloadProgress . "%";
430
			update_status($tostatus);
431
		} else {
432
			$tooutput = $static_output . $downloadProgress . "%";
433
			update_output_window($tooutput);
434
		}
435
		update_progress_bar($downloadProgress);
436
		$lastseen = $downloadProgress;
437
	}
438
	if($fout)
439
		fwrite($fout, $string);
440
	ob_flush();
441
	return $length;
442
}
443

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

    
514
function eval_once($toeval) {
515
	global $evaled;
516
	if(!$evaled) $evaled = array();
517
	$evalmd5 = md5($toeval);
518
	if(!in_array($evalmd5, $evaled)) {
519
		eval($toeval);
520
		$evaled[] = $evalmd5;
521
	}
522
	return;
523
}
524

    
525
function install_package_xml($pkg) {
526
	global $g, $config, $fd_log, $static_output, $pkg_interface;
527
	if(($pkgid = get_pkg_id($pkg)) == -1) {
528
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
529
		update_output_window($static_output);
530
		if($pkg_interface <> "console") {
531
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
532
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
533
		}
534
		sleep(1);
535
		return;
536
	} else {
537
		$pkg_info = $config['installedpackages']['package'][$pkgid];
538
	}
539
	/* set up logging if needed */
540
	if(!$fd_log) {
541
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
542
			update_output_window("Warning, could not open log for writing.");
543
		}
544
	}
545

    
546
	/* set up package logging streams */
547
	if($pkg_info['logging']) {
548
		mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
549
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
550
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
551
		mwexec("killall syslogd");
552
		system_syslogd_start();
553
	}
554

    
555
	/* make 'y' file */
556
	$fd = fopen("{$g['tmp_path']}/y", "w");
557
	for($line = 0; $line < 10; $line++) {
558
		fwrite($fd, "y\n");
559
	}
560
	fclose($fd);
561

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

    
732
function delete_package($pkg, $pkgid) {
733
	global $g, $config, $fd_log, $static_output;
734
	update_status("Removing package...");
735
	$static_output .= "Removing package... ";
736
	update_output_window($static_output);
737
	$pkgid = get_pkg_id($pkgid);
738
	$pkg_info = $config['installedpackages']['package'][$pkgid];
739

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

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

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

    
931
function expand_to_bytes($size) {
932
	$conv = array(
933
			"G" =>	"3",
934
			"M" =>  "2",
935
			"K" =>  "1",
936
			"B" =>  "0"
937
		);
938
	$suffix = substr($size, -1);
939
	if(!in_array($suffix, array_keys($conv))) return $size;
940
	$size = substr($size, 0, -1);
941
	for($i = 0; $i < $conv[$suffix]; $i++) {
942
		$size *= 1024;
943
	}
944
	return $size;
945
}
946

    
947
function get_pkg_db() {
948
	global $g;
949
	return return_dir_as_array($g['vardb_path'] . '/pkg');
950
}
951

    
952
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
953
	if(!$pkgdb) $pkgdb = get_pkg_db();
954
	if(!$alreadyseen) $alreadyseen = array();
955
	foreach($depend as $adepend) {
956
		$pkgname = reverse_strrchr($adepend['name'], '.');
957
		if(in_array($pkgname, $alreadyseen)) {
958
			continue;
959
		} elseif(!in_array($pkgname, $pkgdb)) {
960
			$size += expand_to_bytes($adepend['size']);
961
			$alreadyseen[] = $pkgname;
962
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
963
		} else {
964
			continue;
965
		}
966
	}
967
	return $size;
968
}
969

    
970
function get_package_install_size($pkg = 'all', $pkg_info = "") {
971
	global $config, $g;
972
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
973
	$pkgdb = get_pkg_db();
974
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
975
	foreach($pkg as $apkg) {
976
		if(!$pkg_info[$apkg]) continue;
977
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
978
	}
979
	return $toreturn;
980
}
981

    
982
function squash_from_bytes($size, $round = "") {
983
	$conv = array(1 => "B", "K", "M", "G");
984
	foreach($conv as $div => $suffix) {
985
		$sizeorig = $size;
986
		if(($size /= 1024) < 1) {
987
			if($round) {
988
				$sizeorig = round($sizeorig, $round);
989
			}
990
			return $sizeorig . $suffix;
991
		}
992
	}
993
	return;
994
}
995

    
996
?>
(15-15/27)