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'])
176
		return;
177
	if($show_message == true)
178
		echo "Syncing packages:";
179
	foreach($config['installedpackages']['package'] as $package) {
180
		if (empty($package['name']))
181
			continue;
182
		if($show_message == true) print " " . $package['name'];
183
		get_pkg_depends($package['name'], "all");
184
		stop_service($package['name']);
185
		sync_package($i, true, true);
186
		if($restart_sync == true) {
187
			$restart_sync = false;
188
			if($pkg_interface == "console") 
189
				echo "\nSyncing packages:";
190
		}
191
		$i++;
192
	}
193
	if($show_message == true) print ".\n";
194
	@unlink("/conf/needs_package_sync");
195
}
196

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

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

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

    
293
function force_remove_package($pkg_name) {
294
	global $config;
295
	delete_package_xml($pkg_name);
296
}
297

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

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

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

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

    
413
function install_package($package, $pkg_info = "") {
414
	global $g, $config, $pkg_interface, $fd_log, $static_output, $pkg_interface, $restart_sync;
415
	/* safe side. Write config below will send to ro again. */
416
	conf_mount_rw();
417

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

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

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

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

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

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

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

    
737
function delete_package($pkg, $pkgid) {
738
	global $g, $config, $fd_log, $static_output;
739
	update_status("Removing package...");
740
	$static_output .= "Removing package... ";
741
	update_output_window($static_output);
742
	$pkgid = get_pkg_id($pkgid);
743
	$pkg_info = $config['installedpackages']['package'][$pkgid];
744

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

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

    
793
function delete_package_xml($pkg) {
794
	global $g, $config, $fd_log, $static_output, $pkg_interface;
795
	conf_mount_rw();
796

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

    
967
	// Go RW again since the write_config above will put it back to RO
968
	conf_mount_rw();
969
	rename("{$g['tmp_path']}/crontab", "/etc/crontab");
970
	conf_mount_ro();
971
}
972

    
973
function expand_to_bytes($size) {
974
	$conv = array(
975
			"G" =>	"3",
976
			"M" =>  "2",
977
			"K" =>  "1",
978
			"B" =>  "0"
979
		);
980
	$suffix = substr($size, -1);
981
	if(!in_array($suffix, array_keys($conv))) return $size;
982
	$size = substr($size, 0, -1);
983
	for($i = 0; $i < $conv[$suffix]; $i++) {
984
		$size *= 1024;
985
	}
986
	return $size;
987
}
988

    
989
function get_pkg_db() {
990
	global $g;
991
	return return_dir_as_array($g['vardb_path'] . '/pkg');
992
}
993

    
994
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
995
	if(!$pkgdb)
996
		$pkgdb = get_pkg_db();
997
	if(!is_array($alreadyseen))
998
		$alreadyseen = array();
999
	if (!is_array($depend))
1000
		$depend = array();
1001
	foreach($depend as $adepend) {
1002
		$pkgname = reverse_strrchr($adepend['name'], '.');
1003
		if(in_array($pkgname, $alreadyseen)) {
1004
			continue;
1005
		} elseif(!in_array($pkgname, $pkgdb)) {
1006
			$size += expand_to_bytes($adepend['size']);
1007
			$alreadyseen[] = $pkgname;
1008
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1009
		}
1010
	}
1011
	return $size;
1012
}
1013

    
1014
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1015
	global $config, $g;
1016
	if((!is_array($pkg)) and ($pkg != 'all'))
1017
		$pkg = array($pkg);
1018
	$pkgdb = get_pkg_db();
1019
	if(!$pkg_info)
1020
		$pkg_info = get_pkg_sizes($pkg);
1021
	foreach($pkg as $apkg) {
1022
		if(!$pkg_info[$apkg]) continue;
1023
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1024
	}
1025
	return $toreturn;
1026
}
1027

    
1028
function squash_from_bytes($size, $round = "") {
1029
	$conv = array(1 => "B", "K", "M", "G");
1030
	foreach($conv as $div => $suffix) {
1031
		$sizeorig = $size;
1032
		if(($size /= 1024) < 1) {
1033
			if($round) {
1034
				$sizeorig = round($sizeorig, $round);
1035
			}
1036
			return $sizeorig . $suffix;
1037
		}
1038
	}
1039
	return;
1040
}
1041

    
1042
?>
(30-30/51)