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[] = $prefix . $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
	if ($id >= 0) {
280
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
281
		delete_package($pkg_depends[0], $pkg_name);
282
		if (is_array($pkg_depends)) {
283
			foreach ($pkg_depends as $pkg_depend)
284
				remove_freebsd_package($pkg_depend);
285
		}
286
	}
287
	delete_package_xml($pkg_name);
288
}
289

    
290
function force_remove_package($pkg_name) {
291
	global $config;
292
	delete_package_xml($pkg_name);
293
}
294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1037
?>
(30-30/50)