Project

General

Profile

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

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

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

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

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

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

    
73
$version = split("-", trim(file_get_contents("/etc/version")));
74
$ver = split("\.", $version[0]);
75
$g['version'] = intval($ver[1]);
76

    
77
/****f* pkg-utils/remove_package
78
 * NAME
79
 *   remove_package - Removes package from FreeBSD if it exists
80
 * INPUTS
81
 *   $packagestring	- name/string to check for
82
 * RESULT
83
 *   none
84
 * NOTES
85
 *   
86
 ******/
87
function remove_freebsd_package($packagestring) {
88
	$todel = substr(reverse_strrchr($packagestring, "."), 0, -1);
89
	exec("echo y | /usr/sbin/pkg_delete -x {$todel}");
90
}
91

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

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

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

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

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

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

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

    
205
/*
206
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
207
 *
208
 * $filetype = "all" || ".xml", ".tgz", etc.
209
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
210
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
211
 *
212
 */
213
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
214
	global $config;
215
	require_once("notices.inc");
216
	$pkg_id = get_pkg_id($pkg_name);
217
	if(!is_numeric($pkg_name)) {
218
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
219
	} else {
220
		if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
221
	}
222
	$package = $config['installedpackages']['package'][$pkg_id];
223
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
224
		log_error("The {$package['name']} package is missing required dependencies and must be reinstalled." . $package['configurationfile']);
225
		install_package($package['name']);
226
		uninstall_package_from_name($package['name']);
227
		install_package($package['name']);
228
		return;
229
	}
230
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
231
	if($pkg_xml['additional_files_needed'] != "") {
232
		foreach($pkg_xml['additional_files_needed'] as $item) {
233
			if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
234
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
235
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
236
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file))) continue;
237
			if ($item['prefix'] != "") {
238
				$prefix = $item['prefix'];
239
			} else {
240
				$prefix = "/usr/local/pkg/";
241
			}
242
			// Ensure that the prefix exists to avoid installation errors.
243
			if(!is_dir($prefix)) 
244
				exec("mkdir -p {$prefix}");
245
			if(!file_exists($prefix . $depend_file))
246
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
247
			switch ($format) {
248
				case "files":
249
					$depends[] = $depend_file;
250
					break;
251
				case "names":
252
					switch ($filetype) {
253
						case "all":
254
						if(preg_match("/\.xml/i", $depend_file)) {
255
							$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
256
							$depends[] = $depend_xml['name'];
257
							break;
258
						} else {
259
							$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
260
							break;
261
						}
262
						case ".xml":
263
							$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
264
							$depends[] = $depend_xml['name'];
265
							break;
266
						default:
267
							$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
268
							break;
269
						}
270
					}
271
			}
272
		return $depends;
273
	}
274
}
275

    
276
function uninstall_package_from_name($pkg_name) {
277
	global $config;
278
	$id = get_pkg_id($pkg_name);
279
	$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
280
	delete_package($pkg_depends[0], $pkg_name);
281
	if (is_array($pkg_depends)) {
282
		foreach ($pkg_depends as $pkg_depend)
283
			remove_freebsd_package($pkg_depend);
284
	}
285
	delete_package_xml($pkg_name);
286
}
287

    
288
function force_remove_package($pkg_name) {
289
	global $config;
290
	delete_package_xml($pkg_name);
291
}
292

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

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

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

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

    
408
function install_package($package, $pkg_info = "") {
409
	global $g, $config, $pkg_interface, $fd_log, $static_output, $pkg_interface, $restart_sync;
410
	/* safe side. Write config below will send to ro again. */
411
	conf_mount_rw();
412

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

    
486
function get_after_install_info($package) {
487
	global $pkg_info;
488
	/* fetch package information if needed */
489
	if(!$pkg_info or !is_array($pkg_info[$package])) {
490
		$pkg_info = get_pkg_info(array($package));
491
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
492
	}
493
	if($pkg_info['after_install_info'])
494
		return $pkg_info['after_install_info'];
495
}
496

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

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

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

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

    
546
	/* pkg_add the package and its dependencies */
547
	if($pkg_info['depends_on_package_base_url'] != "") {
548
		if($pkg_interface == "console") 
549
			echo "\n";
550
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
551
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
552
		$static_orig = $static_output;
553
		$static_output .= "\n";
554
		update_output_window($static_output);
555
		foreach((array) $pkg_info['depends_on_package'] as $pkgdep) {
556
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
557
			if(isset($pkg_info['skip_install_checks'])) {
558
				$pkg_installed = true;
559
			} else {
560
				$pkg_installed = is_freebsd_pkg_installed($pkg_name);
561
			}
562
			if($pkg_installed == false)
563
				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)
568
				$pkg_installed = is_freebsd_pkg_installed($pkg_name);
569
			if($pkg_installed == true) {
570
				$static_output .= "done.\n";
571
				update_output_window($static_output);
572
				fwrite($fd_log, "pkg_add successfully completed.\n");
573
			} else {
574
				$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
575
				update_output_window($static_output);
576
				fwrite($fd_log, "Package WAS NOT installed properly.\n");
577
				fclose($fd_log);
578
				if($pkg_interface <> "console") {
579
					echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
580
					echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
581
				}
582
				sleep(1);
583
				die;
584
			}
585
		}
586
	}
587
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
588
	if(file_exists("/usr/local/pkg/" . $configfile)) {
589
		$static_output .= "Loading package configuration... ";
590
		update_output_window($static_output);
591
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
592
		$static_output .= "done.\n";
593
		update_output_window($static_output);
594
		$static_output .= "Configuring package components...\n";
595
		if (!empty($pkg_config['filter_rules_needed']))
596
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
597
		update_output_window($static_output);
598
		/* modify system files */
599
		if(is_array($pkg_config['modify_system']['item'])) {
600
			$static_output .= "\tSystem files... ";
601
			update_output_window($static_output);
602
			foreach($pkg_config['modify_system']['item'] as $ms) {
603
				if($ms['textneeded']) {
604
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
605
				}
606
			}
607
			$static_output .= "done.\n";
608
			update_output_window($static_output);
609
		}
610
		/* download additional files */
611
		if(is_array($pkg_config['additional_files_needed'])) {
612
			$static_output .= "\tAdditional files... ";
613
			$static_orig = $static_output;
614
			update_output_window($static_output);
615
			foreach($pkg_config['additional_files_needed'] as $afn) {
616
				$filename = get_filename_from_url($afn['item'][0]);
617
				if($afn['chmod'] <> "") {
618
					$pkg_chmod = $afn['chmod'];
619
				} else {
620
					$pkg_chmod = "";
621
				}
622
				if($afn['prefix'] <> "") {
623
					$prefix = $afn['prefix'];
624
				} else {
625
					$prefix = "/usr/local/pkg/";
626
				}
627
				if(!is_dir($prefix)) 
628
					safe_mkdir($prefix);
629
 				$static_output .= $filename . " ";
630
                                update_output_window($static_output);
631
				download_file_with_progress_bar($afn['item'][0], $prefix . $filename);
632
				if(stristr($filename, ".tgz") <> "") {
633
					fwrite($fd_log, "Extracting tarball to -C for " . $filename . "...\n");
634
					$tarout = "";
635
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
636
					fwrite($fd_log, print_r($tarout, true) . "\n");
637
				}
638
				if($pkg_chmod <> "") {
639
					fwrite($fd_log, "Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
640
					@chmod($prefix . $filename, $pkg_chmod);
641
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
642
				}
643
				$static_output = $static_orig;
644
                                update_output_window($static_output);
645
			}
646
			$static_output .= "done.\n";
647
			update_output_window($static_output);
648
		}
649
		/*   if a require exists, include it.  this will
650
		 *   show us where an error exists in a package
651
		 *   instead of making us blindly guess
652
		 */
653
		if($pkg_config['include_file'] <> "") {
654
			$static_output = "Loading package instructions...";
655
			update_output_window($static_output);
656
			fwrite($fd_log, "require_once('{$pkg_config['include_file']}')\n");
657
			if (file_exists($pkg_config['include_file']))
658
				require_once($pkg_config['include_file']);
659
		}
660
		/* sidebar items */
661
		if(is_array($pkg_config['menu'])) {
662
			$static_output .= "\tMenu items... ";
663
			update_output_window($static_output);
664
			foreach($pkg_config['menu'] as $menu) {
665
				if(is_array($config['installedpackages']['menu']))
666
					foreach($config['installedpackages']['menu'] as $amenu)
667
						if($amenu['name'] == $menu['name'])
668
							continue 2;
669
				$config['installedpackages']['menu'][] = $menu;
670
			}
671
			$static_output .= "done.\n";
672
			update_output_window($static_output);
673
		}
674
		/* integrated tab items */
675
		if(is_array($pkg_config['tabs']['tab'])) {
676
			$static_output .= "\tIntegrated Tab items... ";
677
			update_output_window($static_output);
678
			foreach($pkg_config['tabs']['tab'] as $tab) {
679
				if(is_array($config['installedpackages']['tab']))
680
					foreach($config['installedpackages']['tab'] as $atab)
681
						if($atab['name'] == $tab['name'])
682
							continue 2;
683
				$config['installedpackages']['tab'][] = $tab;
684
			}
685
			$static_output .= "done.\n";
686
			update_output_window($static_output);
687
		}
688
		/* services */
689
		if(is_array($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
			if (file_exists($pkg_config['include_file']))
753
				require_once($pkg_config['include_file']);
754
		}
755
	}
756
	$static_output .= "\nStarting package deletion for {$pkg_info['name']}...\n";
757
	update_output_window($static_output);
758
	if (!empty($pkg))
759
		delete_package_recursive($pkg);
760
	$static_output .= "done.\n";
761
	update_output_window($static_output);
762
	return;
763
}
764

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

    
786
function delete_package_xml($pkg) {
787
	global $g, $config, $fd_log, $static_output, $pkg_interface;
788
	conf_mount_rw();
789

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

    
960
	// Go RW again since the write_config above will put it back to RO
961
	conf_mount_rw();
962
	rename("{$g['tmp_path']}/crontab", "/etc/crontab");
963
	conf_mount_ro();
964
}
965

    
966
function expand_to_bytes($size) {
967
	$conv = array(
968
			"G" =>	"3",
969
			"M" =>  "2",
970
			"K" =>  "1",
971
			"B" =>  "0"
972
		);
973
	$suffix = substr($size, -1);
974
	if(!in_array($suffix, array_keys($conv))) return $size;
975
	$size = substr($size, 0, -1);
976
	for($i = 0; $i < $conv[$suffix]; $i++) {
977
		$size *= 1024;
978
	}
979
	return $size;
980
}
981

    
982
function get_pkg_db() {
983
	global $g;
984
	return return_dir_as_array($g['vardb_path'] . '/pkg');
985
}
986

    
987
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
988
	if(!$pkgdb)
989
		$pkgdb = get_pkg_db();
990
	if(!is_array($alreadyseen))
991
		$alreadyseen = array();
992
	if (!is_array($depend))
993
		$depend = array();
994
	foreach($depend as $adepend) {
995
		$pkgname = reverse_strrchr($adepend['name'], '.');
996
		if(in_array($pkgname, $alreadyseen)) {
997
			continue;
998
		} elseif(!in_array($pkgname, $pkgdb)) {
999
			$size += expand_to_bytes($adepend['size']);
1000
			$alreadyseen[] = $pkgname;
1001
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1002
		}
1003
	}
1004
	return $size;
1005
}
1006

    
1007
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1008
	global $config, $g;
1009
	if((!is_array($pkg)) and ($pkg != 'all'))
1010
		$pkg = array($pkg);
1011
	$pkgdb = get_pkg_db();
1012
	if(!$pkg_info)
1013
		$pkg_info = get_pkg_sizes($pkg);
1014
	foreach($pkg as $apkg) {
1015
		if(!$pkg_info[$apkg]) continue;
1016
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1017
	}
1018
	return $toreturn;
1019
}
1020

    
1021
function squash_from_bytes($size, $round = "") {
1022
	$conv = array(1 => "B", "K", "M", "G");
1023
	foreach($conv as $div => $suffix) {
1024
		$sizeorig = $size;
1025
		if(($size /= 1024) < 1) {
1026
			if($round) {
1027
				$sizeorig = round($sizeorig, $round);
1028
			}
1029
			return $sizeorig . $suffix;
1030
		}
1031
	}
1032
	return;
1033
}
1034

    
1035
?>
(30-30/50)