Project

General

Profile

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

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

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

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

    
64
if (!function_exists("pkg_debug")) {
65
	/* set up logging if needed */
66
	function pkg_debug($msg) {
67
		global $g, $debug, $fd_log;
68

    
69
		if (!$debug)
70
			return;
71

    
72
		if (!$fd_log) {
73
			if (!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$package}.log", "w"))
74
				update_output_window("Warning, could not open log for writing.");
75
		}
76
		@fwrite($fd_log, $msg);
77
	}
78
}
79

    
80
$vardb = "/var/db/pkg";
81
safe_mkdir($vardb);
82
$g['platform'] = trim(file_get_contents("/etc/platform"));
83

    
84
conf_mount_rw();
85
if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
86
	safe_mkdir("/usr/local/pkg");
87
	safe_mkdir("/usr/local/pkg/pf");	
88
}
89
conf_mount_ro();
90

    
91
/****f* pkg-utils/remove_package
92
 * NAME
93
 *   remove_package - Removes package from FreeBSD if it exists
94
 * INPUTS
95
 *   $packagestring	- name/string to check for
96
 * RESULT
97
 *   none
98
 * NOTES
99
 *   
100
 ******/
101
function remove_freebsd_package($packagestring) {
102
	$todel = substr(reverse_strrchr($packagestring, "."), 0, -1);
103
	exec("/usr/sbin/pkg_delete -x {$todel}");
104
}
105

    
106
/****f* pkg-utils/is_package_installed
107
 * NAME
108
 *   is_package_installed - Check whether a package is installed.
109
 * INPUTS
110
 *   $packagename	- name of the package to check
111
 * RESULT
112
 *   boolean	- true if the package is installed, false otherwise
113
 * NOTES
114
 *   This function is deprecated - get_pkg_id() can already check for installation.
115
 ******/
116
function is_package_installed($packagename) {
117
	$pkg = get_pkg_id($packagename);
118
	if($pkg == -1)
119
		return false;
120
	return true;
121
}
122

    
123
/****f* pkg-utils/get_pkg_id
124
 * NAME
125
 *   get_pkg_id - Find a package's numeric ID.
126
 * INPUTS
127
 *   $pkg_name	- name of the package to check
128
 * RESULT
129
 *   integer    - -1 if package is not found, >-1 otherwise
130
 ******/
131
function get_pkg_id($pkg_name) {
132
	global $config;
133

    
134
	if (is_array($config['installedpackages']['package'])) {
135
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
136
			if($pkg['name'] == $pkg_name)
137
				return $idx;
138
		}
139
	}
140
	return -1;
141
}
142

    
143
/****f* pkg-utils/get_pkg_info
144
 * NAME
145
 *   get_pkg_info - Retrive package information from pfsense.com.
146
 * INPUTS
147
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
148
 *   $info - 'all' to retrive all information, an array containing keys otherwise
149
 * RESULT
150
 *   $raw_versions - Array containing retrieved information, indexed by package name.
151
 ******/
152
function get_pkg_info($pkgs = 'all', $info = 'all') {
153
	global $g;
154

    
155
	$freebsd_version = php_uname("r");
156
	$freebsd_machine = php_uname("m");
157
	$params = array(
158
		"pkg" => $pkgs, 
159
		"info" => $info, 
160
		"freebsd_version" => $freebsd_version[0],
161
		"freebsd_machine" => $freebsd_machine
162
	);
163
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
164
	return $resp ? $resp : array();
165
}
166

    
167
function get_pkg_sizes($pkgs = 'all') {
168
	global $config, $g;
169

    
170
	$freebsd_version = php_uname("r");
171
	$freebsd_machine = php_uname("m");
172
	$params = array(
173
		"pkg" => $pkgs, 
174
		"freebsd_version" => $freebsd_version,
175
		"freebsd_machine" => $freebsd_machine
176
	);
177
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
178
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
179
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
180
	$resp = $cli->send($msg, 10);
181
	if(!is_object($resp))
182
		log_error("Could not get response from XMLRPC server!");
183
 	else if (!$resp->faultCode()) {
184
		$raw_versions = $resp->value();
185
		return xmlrpc_value_to_php($raw_versions);
186
	}
187

    
188
	return array();
189
}
190

    
191
/*
192
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
193
 * This function may also print output to the terminal indicating progress.
194
 */
195
function resync_all_package_configs($show_message = false) {
196
	global $config, $pkg_interface;
197

    
198
	log_error("Resyncing configuration for all packages.");
199
	if (!is_array($config['installedpackages']['package']))
200
		return;
201
	if($show_message == true)
202
		echo "Syncing packages:";
203

    
204
	foreach($config['installedpackages']['package'] as $idx => $package) {
205
		if (empty($package['name']))
206
			continue;
207
		if($show_message == true)
208
			echo " " . $package['name'];
209
		get_pkg_depends($package['name'], "all");
210
		stop_service($package['name']);
211
		sync_package($idx, true, true);
212
		if($pkg_interface == "console") 
213
			echo "\nSyncing packages:";
214
	}
215
	if($show_message == true)
216
		echo " done.\n";
217
	@unlink("/conf/needs_package_sync");
218
}
219

    
220
/*
221
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
222
 *				package is installed.
223
 */
224
function is_freebsd_pkg_installed($pkg) {
225
	$output = "";
226
	exec("/usr/sbin/pkg_info -E \"{$pkg}*\"", $output, $retval);
227

    
228
	return (intval($retval) == 0);
229
}
230

    
231
/*
232
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
233
 *
234
 * $filetype = "all" || ".xml", ".tgz", etc.
235
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
236
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
237
 *
238
 */
239
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
240
	global $config;
241

    
242
	$pkg_id = get_pkg_id($pkg_name);
243
	if($pkg_id == -1)
244
		return -1; // This package doesn't really exist - exit the function.
245
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
246
		return; // No package belongs to the pkg_id passed to this function.
247

    
248
	$package =& $config['installedpackages']['package'][$pkg_id];
249
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
250
		log_error("The {$package['name']} package is missing required dependencies and is being reinstalled." . $package['configurationfile']);
251
		uninstall_package($package['name']);
252
		if (install_package($package['name']) < 0) {
253
			log_error("Failed reinstalling package {$package['name']}.");
254
			return false;
255
		}
256
	}
257
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
258
	if (!empty($pkg_xml['additional_files_needed'])) {
259
		foreach($pkg_xml['additional_files_needed'] as $item) {
260
			if ($return_nosync == 0 && isset($item['nosync']))
261
				continue; // Do not return depends with nosync set if not required.
262
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
263
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
264
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file)))
265
					continue;
266
			if ($item['prefix'] != "")
267
				$prefix = $item['prefix'];
268
			else
269
				$prefix = "/usr/local/pkg/";
270
			// Ensure that the prefix exists to avoid installation errors.
271
			if(!is_dir($prefix)) 
272
				exec("/bin/mkdir -p {$prefix}");
273
			if(!file_exists($prefix . $depend_file))
274
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
275
			switch ($format) {
276
			case "files":
277
				$depends[] = $prefix . $depend_file;
278
				break;
279
			case "names":
280
				switch ($filetype) {
281
				case "all":
282
					if(preg_match("/\.xml/i", $depend_file)) {
283
						$depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui");
284
						if (!empty($depend_xml))
285
							$depends[] = $depend_xml['name'];
286
					} else
287
						$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
288
					break;
289
				case ".xml":
290
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
291
					if (!empty($depend_xml))
292
						$depends[] = $depend_xml['name'];
293
					break;
294
				default:
295
					$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
296
					break;
297
				}
298
			}
299
		}
300
		return $depends;
301
	}
302
}
303

    
304
function uninstall_package($pkg_name) {
305
	global $config, $static_output;
306

    
307
	$id = get_pkg_id($pkg_name);
308
	if ($id >= 0) {
309
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
310
		$static_output .= "Removing package...\n";
311
		update_output_window($static_output);
312
		if (is_array($pkg_depends)) {
313
			foreach ($pkg_depends as $pkg_depend)
314
				delete_package($pkg_depend);
315
		}
316
	}
317
	delete_package_xml($pkg_name);
318
}
319

    
320
function force_remove_package($pkg_name) {
321
	delete_package_xml($pkg_name);
322
}
323

    
324
/*
325
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
326
 */
327
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
328
	global $config, $config_parsed;
329
	
330
	if(empty($config['installedpackages']['package']))
331
		return;
332
	if(!is_numeric($pkg_name)) {
333
		$pkg_id = get_pkg_id($pkg_name);
334
		if($pkg_id == -1)
335
			return -1; // This package doesn't really exist - exit the function.
336
	} else {
337
		$pkg_id = $pkg_name;
338
		if(empty($config['installedpackages']['package'][$pkg_id]))
339
			return;  // No package belongs to the pkg_id passed to this function.
340
	}
341
        if (is_array($config['installedpackages']['package'][$pkg_id]))
342
		$package =& $config['installedpackages']['package'][$pkg_id];
343
        else
344
		return; /* empty package tag */
345
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
346
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
347
		force_remove_package($package['name']);
348
		return -1;
349
	}
350
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
351
	if(isset($pkg_config['nosync']))
352
		return;
353
	/* Bring in package include files */
354
	if (!empty($pkg_config['include_file'])) {
355
		$include_file = $pkg_config['include_file'];
356
		if (file_exists($include_file))
357
			require_once($include_file);
358
		else {
359
			/* XXX: What the heck is this?! */
360
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
361
			uninstall_package($package['name']);
362
			if (install_package($package['name']) < 0) {
363
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
364
				return -1;
365
			}
366
		}
367
	}
368

    
369
	if(!empty($pkg_config['custom_php_global_functions']))
370
		eval($pkg_config['custom_php_global_functions']);
371
	if(!empty($pkg_config['custom_php_resync_config_command']))
372
		eval($pkg_config['custom_php_resync_config_command']);
373
	if($sync_depends == true) {
374
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
375
		if(is_array($depends)) {
376
			foreach($depends as $item) {
377
				if(!file_exists($item)) {
378
					require_once("notices.inc");
379
					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);
380
					log_error("Could not find {$item}. Reinstalling package.");
381
					uninstall_package($pkg_name);
382
					if (install_package($pkg_name) < 0) {
383
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
384
						return -1;
385
					}
386
				} else {
387
					$item_config = parse_xml_config_pkg($item, "packagegui");
388
					if (empty($item_config))
389
						continue;
390
					if(isset($item_config['nosync']))
391
						continue;
392
					if (!empty($item_config['include_file'])) {
393
						if (file_exists($item_config['include_file']))	
394
							require_once($item_config['include_file']);
395
						else {
396
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
397
							continue;
398
						}
399
					}
400
					if($item_config['custom_php_global_functions'] <> "")
401
						eval($item_config['custom_php_global_functions']);
402
					if($item_config['custom_php_resync_config_command'] <> "")
403
						eval($item_config['custom_php_resync_config_command']);
404
					if($show_message == true)
405
						print " " . $item_config['name'];
406
				}
407
			}
408
		}
409
	}
410
}
411

    
412
/*
413
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
414
 * 			a progress bar and output window.
415
 */
416
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
417
	global $static_output, $g;
418

    
419
	$osname = php_uname("s");
420
	$arch =  php_uname("m");
421
	$rel = php_uname("r");
422
	$rel = substr($rel, 0, strrpos($rel, "-"));
423
	$priv_url = "http://ftp2.{$osname}.org/pub/{$osname}/ports/{$arch}/packages-{$rel}/Latest";
424
	if (empty($base_url))
425
		$base_url = $priv_url;
426
	if (substr($base_url, -1) == "/")
427
		$base_url = substr($base_url, 0, -1);
428
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
429
	$fetchto = "{$g['tmp_path']}/apkg_{$filename}";
430
	if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
431
		if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
432
			$static_output .= " could not download.\n";
433
			update_output_window($static_output);
434
			return false;
435
		} else if ($base_url == $priv_url) {
436
			$static_output .= " failed to download.\n";
437
			update_output_window($static_output);
438
			return false;
439
		} else {
440
			$static_output .= " downloaded from {$osname} repository instead of provided one.\n";
441
			update_output_window($static_output);
442
		}
443
	}
444
	$static_output .= " (extracting)";
445
	update_output_window($static_output);
446
	$slaveout = "";
447
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
448
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
449
	if ($raw_depends_list != "") {
450
		$pkg_extension = ".tbz";
451
		foreach($raw_depends_list as $adepend) {
452
			$working_depend = explode(" ", trim($adepend, "\n"));
453
			if (substr($working_depend[1], -4) != ".tbz")
454
				$depend_filename = $working_depend[1] . $pkg_extension;
455
			else
456
				$depend_filename = $working_depend[1];
457
			if (is_freebsd_pkg_installed($working_depend[1]) === false) {
458
				if (pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url) == false)
459
					return false;
460
			} else {
461
				//$dependlevel++;
462
				$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " already installed.";
463
				pkg_debug($working_depend[1] . "\n");
464
			}
465
		}
466
	}
467
	$pkgaddout = "";
468
	exec("/usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
469
	pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\npkg_add successfully completed.\n");
470

    
471
	return true;
472
}
473

    
474
function install_package($package, $pkg_info = "") {
475
	global $g, $config, $static_output, $pkg_interface;
476

    
477
	/* safe side. Write config below will send to ro again. */
478
	conf_mount_rw();
479

    
480
	if($pkg_interface == "console") 	
481
		echo "\n";
482
	/* fetch package information if needed */
483
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
484
		$pkg_info = get_pkg_info(array($package));
485
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
486
		if (empty($pkg_info)) {
487
			conf_mount_ro();
488
			return -1;
489
		}
490
	}
491
	pkg_debug("Beginning package installation.\n");
492
	log_error('Beginning package installation for ' . $pkg_info['name'] . '.');
493
	$static_output .= "Beginning package installation for " . $pkg_info['name'] . "...";
494
	update_status($static_output);
495
	/* fetch the package's configuration file */
496
	if($pkg_info['config_file'] != "") {
497
		$static_output .= "\nDownloading package configuration file... ";
498
		update_output_window($static_output);
499
		pkg_debug("Downloading package configuration file...\n");
500
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
501
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
502
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
503
			pkg_debug("ERROR! Unable to fetch package configuration file. Aborting installation.\n");
504
			if($pkg_interface == "console")
505
				print "\nERROR! Unable to fetch package configuration file. Aborting package installation.\n";
506
			else {
507
				$static_output .= "failed!\n\nInstallation aborted.";
508
				update_output_window($static_output);
509
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
510
			}
511
			conf_mount_ro();
512
			return -1;
513
		}
514
		$static_output .= "done.\n";
515
		update_output_window($static_output);
516
	}
517
	/* add package information to config.xml */
518
	$pkgid = get_pkg_id($pkg_info['name']);
519
	$static_output .= "Saving updated package information... ";
520
	update_output_window($static_output);
521
	if($pkgid == -1) {
522
		$config['installedpackages']['package'][] = $pkg_info;
523
		$changedesc = "Installed {$pkg_info['name']} package.";
524
		$to_output = "done.\n";
525
	} else {
526
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
527
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
528
		$to_output = "overwrite!\n";
529
	}
530
	/* XXX: Fix inclusion of config.inc that causes data loss! */
531
	conf_mount_ro();
532
	write_config();
533
	$static_output .= $to_output;
534
	update_output_window($static_output);
535
	/* install other package components */
536
	if (!install_package_xml($package)) {
537
		uninstall_package($package);
538
		write_config($changedesc);
539
		$static_output .= "Failed to install package.\n";
540
		update_output_window($static_output);
541
		return -1;
542
	} else {
543
		$static_output .= "Writing configuration... ";
544
		update_output_window($static_output);
545
		write_config($changedesc);
546
		$static_output .= "done.\n";
547
		update_output_window($static_output);
548
		$static_output .= "Starting service.\n";
549
		update_output_window($static_output);
550
		if($pkg_info['after_install_info']) 
551
			update_output_window($pkg_info['after_install_info']);	
552
		start_service($pkg_info['name']);
553
	}
554
}
555

    
556
function get_after_install_info($package) {
557
	global $pkg_info;
558
	/* fetch package information if needed */
559
	if(!$pkg_info or !is_array($pkg_info[$package])) {
560
		$pkg_info = get_pkg_info(array($package));
561
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
562
	}
563
	if($pkg_info['after_install_info'])
564
		return $pkg_info['after_install_info'];
565
}
566

    
567
function eval_once($toeval) {
568
	global $evaled;
569
	if(!$evaled) $evaled = array();
570
	$evalmd5 = md5($toeval);
571
	if(!in_array($evalmd5, $evaled)) {
572
		@eval($toeval);
573
		$evaled[] = $evalmd5;
574
	}
575
	return;
576
}
577

    
578
function install_package_xml($pkg) {
579
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
580

    
581
	if(($pkgid = get_pkg_id($pkg)) == -1) {
582
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
583
		update_output_window($static_output);
584
		if($pkg_interface <> "console") {
585
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
586
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
587
		}
588
		sleep(1);
589
		return false;
590
	} else
591
		$pkg_info = $config['installedpackages']['package'][$pkgid];
592

    
593
	/* pkg_add the package and its dependencies */
594
	if($pkg_info['depends_on_package_base_url'] != "") {
595
		if($pkg_interface == "console") 
596
			echo "\n";
597
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
598
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
599
		$static_orig = $static_output;
600
		$static_output .= "\n";
601
		update_output_window($static_output);
602
		foreach((array) $pkg_info['depends_on_package'] as $pkgdep) {
603
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
604
			$static_output = $static_orig . "\nChecking for package installation... ";
605
			update_output_window($static_output);
606
			// FIXME: Not sure what the logic is for this. I see nothing that sets this variable, and it was causing some steps to be skipped.
607
			//        Should be fixed or removed.
608
			//if (!isset($pkg_info['skip_install_checks']))
609
			//	continue;
610
			if (!is_freebsd_pkg_installed($pkg_name)) {
611
				if (pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url']) == true) {
612
					$static_output .= "done.\n";
613
					update_output_window($static_output);
614
				} else {
615
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
616
					update_output_window($static_output);
617
					pkg_debug("Package WAS NOT installed properly.\n");
618
					if($pkg_interface <> "console") {
619
						echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
620
						echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
621
					}
622
					sleep(1);
623
					return false;
624
				}
625
			}
626
		}
627
	}
628
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
629
	if(file_exists("/usr/local/pkg/" . $configfile)) {
630
		$static_output .= "\nLoading package configuration... ";
631
		update_output_window($static_output);
632
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
633
		$static_output .= "done.\n";
634
		update_output_window($static_output);
635
		$static_output .= "\tConfiguring package components...\n";
636
		if (!empty($pkg_config['filter_rules_needed']))
637
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
638
		update_output_window($static_output);
639
		/* modify system files */
640
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
641
			$static_output .= "\tSystem files... ";
642
			update_output_window($static_output);
643
			foreach($pkg_config['modify_system']['item'] as $ms) {
644
				if($ms['textneeded']) {
645
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
646
				}
647
			}
648
			$static_output .= "done.\n";
649
			update_output_window($static_output);
650
		}
651
		/* download additional files */
652
		if(is_array($pkg_config['additional_files_needed'])) {
653
			$static_output .= "\tAdditional files... ";
654
			$static_orig = $static_output;
655
			update_output_window($static_output);
656
			foreach($pkg_config['additional_files_needed'] as $afn) {
657
				$filename = get_filename_from_url($afn['item'][0]);
658
				if($afn['chmod'] <> "")
659
					$pkg_chmod = $afn['chmod'];
660
				else
661
					$pkg_chmod = "";
662

    
663
				if($afn['prefix'] <> "")
664
					$prefix = $afn['prefix'];
665
				else
666
					$prefix = "/usr/local/pkg/";
667

    
668
				if(!is_dir($prefix)) 
669
					safe_mkdir($prefix);
670
 				$static_output .= $filename . " ";
671
                                update_output_window($static_output);
672
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
673
					$static_output .= "failed.\n";
674
					update_output_window($static_output);
675
					return false;
676
				}
677
				if(stristr($filename, ".tgz") <> "") {
678
					pkg_debug("Extracting tarball to -C for " . $filename . "...\n");
679
					$tarout = "";
680
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
681
					pkg_debug(print_r($tarout, true) . "\n");
682
				}
683
				if($pkg_chmod <> "") {
684
					pkg_debug("Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
685
					@chmod($prefix . $filename, $pkg_chmod);
686
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
687
				}
688
				$static_output = $static_orig;
689
                                update_output_window($static_output);
690
			}
691
			$static_output .= "done.\n";
692
			update_output_window($static_output);
693
		}
694
		/*   if a require exists, include it.  this will
695
		 *   show us where an error exists in a package
696
		 *   instead of making us blindly guess
697
		 */
698
		$missing_include = false;
699
		if($pkg_config['include_file'] <> "") {
700
			$static_output .= "Loading package instructions...\n";
701
			update_output_window($static_output);
702
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
703
			if (file_exists($pkg_config['include_file']))
704
				require_once($pkg_config['include_file']);
705
			else {
706
				$missing_include = true;
707
				$static_output .= "\tInclude " . basename($pkg_config['include_file']) . " is missing!\n";
708
				update_output_window($static_output);
709
				/* XXX: Should undo the steps before this?! */
710
				return false;
711
			}
712
		}
713
		/* sidebar items */
714
		if(is_array($pkg_config['menu'])) {
715
			$static_output .= "\tMenu items... ";
716
			update_output_window($static_output);
717
			foreach($pkg_config['menu'] as $menu) {
718
				if(is_array($config['installedpackages']['menu']))
719
					foreach($config['installedpackages']['menu'] as $amenu)
720
						if($amenu['name'] == $menu['name'])
721
							continue 2;
722
				$config['installedpackages']['menu'][] = $menu;
723
			}
724
			$static_output .= "done.\n";
725
			update_output_window($static_output);
726
		}
727
		/* integrated tab items */
728
		if(is_array($pkg_config['tabs']['tab'])) {
729
			$static_output .= "\tIntegrated Tab items... ";
730
			update_output_window($static_output);
731
			foreach($pkg_config['tabs']['tab'] as $tab) {
732
				if(is_array($config['installedpackages']['tab']))
733
					foreach($config['installedpackages']['tab'] as $atab)
734
						if($atab['name'] == $tab['name'])
735
							continue 2;
736
				$config['installedpackages']['tab'][] = $tab;
737
			}
738
			$static_output .= "done.\n";
739
			update_output_window($static_output);
740
		}
741
		/* services */
742
		if(is_array($pkg_config['service'])) {
743
			$static_output .= "\tServices... ";
744
			update_output_window($static_output);
745
			foreach($pkg_config['service'] as $service) {
746
				if(is_array($config['installedpackages']['service']))
747
					foreach($config['installedpackages']['service'] as $aservice)
748
						if($aservice['name'] == $service['name'])
749
							continue 2;
750
				$config['installedpackages']['service'][] = $service;
751
			}
752
			$static_output .= "done.\n";
753
			update_output_window($static_output);
754
		}
755
		/* custom commands */
756
		$static_output .= "Custom commands...\n";
757
		update_output_window($static_output);
758
		if ($missing_include == false) {
759
			if($pkg_config['custom_php_global_functions'] <> "") {
760
				$static_output .= "\tExecuting custom_php_global_functions()...";
761
				update_output_window($static_output);
762
				eval_once($pkg_config['custom_php_global_functions']);
763
				$static_output .= "done.\n";
764
				update_output_window($static_output);
765
			}
766
			if($pkg_config['custom_php_install_command']) {
767
				$static_output .= "\tExecuting custom_php_install_command()...";
768
				update_output_window($static_output);
769
				eval_once($pkg_config['custom_php_install_command']);
770
				$static_output .= "done.\n";
771
				update_output_window($static_output);
772
			}
773
			if($pkg_config['custom_php_resync_config_command'] <> "") {
774
				$static_output .= "\tExecuting custom_php_resync_config_command()...";
775
				update_output_window($static_output);
776
				eval_once($pkg_config['custom_php_resync_config_command']);
777
				$static_output .= "done.\n";
778
				update_output_window($static_output);
779
			}
780
		}
781
	} else {
782
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
783
		update_output_window($static_output);
784
		pkg_debug("Unable to load package configuration. Installation aborted.\n");
785
		if($pkg_interface <> "console") {
786
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
787
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
788
		}
789
		sleep(1);
790
		return false;
791
	}
792

    
793
	/* set up package logging streams */
794
	if($pkg_info['logging']) {
795
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
796
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
797
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
798
		pkg_debug("Adding text to file /etc/syslog.conf\n");
799
		system_syslogd_start();
800
	}
801

    
802
	return true;
803
}
804

    
805
function delete_package($pkg) {
806
	global $config, $g, $static_output, $vardb;
807

    
808
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
809

    
810

    
811
	if (file_exists("{$vardb}/{$pkg}/+REQUIRED_BY") && count(file("{$vardb}/{$pkg}/+REQUIRED_BY")) > 0) {
812
		$static_output .= "\tSkipping package deletion for {$pkg} because it is required by other packages.\n";
813
		update_output_window($static_output);
814
		return;
815
	} else {
816
		$static_output .= "\tStarting package deletion for {$pkg}...";
817
		update_output_window($static_output);
818
	}
819
	$info = "";
820
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
821
	remove_freebsd_package($pkg);
822
	$static_output .= "done.\n";
823
	update_output_window($static_output);
824
	foreach($info as $line) {
825
		$depend = trim(str_replace("@pkgdep", "", $line), " \n");
826
		delete_package($depend);
827
	}
828

    
829
	return;
830
}
831

    
832
function delete_package_xml($pkg) {
833
	global $g, $config, $static_output, $pkg_interface;
834

    
835
	conf_mount_rw();
836

    
837
	$pkgid = get_pkg_id($pkg);
838
	if ($pkgid == -1) {
839
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
840
		update_output_window($static_output);
841
		if($pkg_interface <> "console") {
842
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
843
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
844
		}
845
		ob_flush();
846
		sleep(1);
847
		conf_mount_ro();
848
		return;
849
	}
850
	pkg_debug("Removing {$pkg} package... ");
851
	$static_output .= "Removing {$pkg} components...\n";
852
	update_output_window($static_output);
853
	/* parse package configuration */
854
	$packages = &$config['installedpackages']['package'];
855
	$tabs =& $config['installedpackages']['tab'];
856
	$menus =& $config['installedpackages']['menu'];
857
	$services = &$config['installedpackages']['service'];
858
	$pkg_info =& $packages[$pkgid];
859
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
860
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
861
		/* remove tab items */
862
		if(is_array($pkg_config['tabs'])) {
863
			$static_output .= "\tTabs items... ";
864
			update_output_window($static_output);
865
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
866
				foreach($pkg_config['tabs']['tab'] as $tab) {
867
					foreach($tabs as $key => $insttab) {
868
						if($insttab['name'] == $tab['name']) {
869
							unset($tabs[$key]);
870
							break;
871
						}
872
					}
873
				}
874
			}
875
			$static_output .= "done.\n";
876
			update_output_window($static_output);
877
		}
878
		/* remove menu items */
879
		if(is_array($pkg_config['menu'])) {
880
			$static_output .= "\tMenu items... ";
881
			update_output_window($static_output);
882
			if (is_array($pkg_config['menu']) && is_array($menus)) {
883
				foreach($pkg_config['menu'] as $menu) {
884
					foreach($menus as $key => $instmenu) {
885
						if($instmenu['name'] == $menu['name']) {
886
							unset($menus[$key]);
887
							break;
888
						}
889
					}
890
				}
891
			}
892
			$static_output .= "done.\n";
893
			update_output_window($static_output);
894
		}
895
		/* remove services */
896
		if(is_array($pkg_config['service'])) {
897
			$static_output .= "\tServices... ";
898
			update_output_window($static_output);
899
			if (is_array($pkg_config['service']) && is_array($services)) {
900
				foreach($pkg_config['service'] as $service) {
901
					foreach($services as $key => $instservice) {
902
						if($instservice['name'] == $service['name']) {
903
							stop_service($service['name']);
904
							unset($services[$key]);
905
						}
906
					}
907
				}
908
			}
909
			$static_output .= "done.\n";
910
			update_output_window($static_output);
911
		}
912
		/*
913
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
914
		 * 	Same is done during installation.
915
		 */
916
		write_config();
917

    
918
		/*
919
		 * If a require exists, include it.  this will
920
		 * show us where an error exists in a package
921
		 * instead of making us blindly guess
922
		 */
923
		$missing_include = false;
924
		if($pkg_config['include_file'] <> "") {
925
			$static_output .= "Loading package instructions...\n";
926
			update_output_window($static_output);
927
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
928
			if (file_exists($pkg_config['include_file']))
929
				require_once($pkg_config['include_file']);
930
			else {
931
				$missing_include = true;
932
				update_output_window($static_output);
933
				$static_output .= "\tInclude file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
934
			}
935
		}
936
		/* ermal
937
		 * NOTE: It is not possible to handle parse errors on eval.
938
		 * So we prevent it from being run at all to not interrupt all the other code.
939
		 */
940
		if ($missing_include == false) {
941
			/* evalate this package's global functions and pre deinstall commands */
942
			if($pkg_config['custom_php_global_functions'] <> "")
943
				eval_once($pkg_config['custom_php_global_functions']);
944
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
945
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
946
		}
947
		/* system files */
948
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
949
			$static_output .= "\tSystem files... ";
950
			update_output_window($static_output);
951
			foreach($pkg_config['modify_system']['item'] as $ms)
952
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
953

    
954
			$static_output .= "done.\n";
955
			update_output_window($static_output);
956
		}
957
		/* deinstall commands */
958
		if($pkg_config['custom_php_deinstall_command'] <> "") {
959
			$static_output .= "\tDeinstall commands... ";
960
			update_output_window($static_output);
961
			if ($missing_include == false) {
962
				eval_once($pkg_config['custom_php_deinstall_command']);
963
				$static_output .= "done.\n";
964
			} else
965
				$static_output .= "\n\tNot executing custom deinstall hook because an include is missing.\n";
966
			update_output_window($static_output);
967
		}
968
		if($pkg_config['include_file'] <> "") {
969
                        $static_output .= "\tRemoving package instructions...";
970
                        update_output_window($static_output);
971
                        pkg_debug("Remove '{$pkg_config['include_file']}'\n");
972
                        unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
973
			$static_output .= "done.\n";
974
                        update_output_window($static_output);
975
			
976
                }
977
		/* remove all additional files */
978
		if(is_array($pkg_config['additional_files_needed'])) {
979
			$static_output .= "\tAuxiliary files... ";
980
			update_output_window($static_output);
981
			foreach($pkg_config['additional_files_needed'] as $afn) {
982
				$filename = get_filename_from_url($afn['item'][0]);
983
				if($afn['prefix'] <> "")
984
					$prefix = $afn['prefix'];
985
				else
986
					$prefix = "/usr/local/pkg/";
987

    
988
				unlink_if_exists($prefix . $filename);
989
			}
990
			$static_output .= "done.\n";
991
			update_output_window($static_output);
992
		}
993
		/* package XML file */
994
		$static_output .= "\tPackage XML... ";
995
		update_output_window($static_output);
996
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
997
		$static_output .= "done.\n";
998
		update_output_window($static_output);
999
	}
1000
	/* syslog */
1001
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
1002
		$static_output .= "\tSyslog entries... ";
1003
		update_output_window($static_output);
1004
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1005
		system_syslogd_start();
1006
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1007
		$static_output .= "done.\n";
1008
		update_output_window($static_output);
1009
	}
1010
	conf_mount_ro();
1011
	/* remove config.xml entries */
1012
	$static_output .= "\tConfiguration... ";
1013
	update_output_window($static_output);
1014
	unset($config['installedpackages']['package'][$pkgid]);
1015
	$static_output .= "done.\n";
1016
	update_output_window($static_output);
1017
	write_config("Removed {$pkg} package.\n");
1018
}
1019

    
1020
function expand_to_bytes($size) {
1021
	$conv = array(
1022
			"G" =>	"3",
1023
			"M" =>  "2",
1024
			"K" =>  "1",
1025
			"B" =>  "0"
1026
		);
1027
	$suffix = substr($size, -1);
1028
	if(!in_array($suffix, array_keys($conv))) return $size;
1029
	$size = substr($size, 0, -1);
1030
	for($i = 0; $i < $conv[$suffix]; $i++) {
1031
		$size *= 1024;
1032
	}
1033
	return $size;
1034
}
1035

    
1036
function get_pkg_db() {
1037
	global $g;
1038
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1039
}
1040

    
1041
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1042
	if(!$pkgdb)
1043
		$pkgdb = get_pkg_db();
1044
	if(!is_array($alreadyseen))
1045
		$alreadyseen = array();
1046
	if (!is_array($depend))
1047
		$depend = array();
1048
	foreach($depend as $adepend) {
1049
		$pkgname = reverse_strrchr($adepend['name'], '.');
1050
		if(in_array($pkgname, $alreadyseen)) {
1051
			continue;
1052
		} elseif(!in_array($pkgname, $pkgdb)) {
1053
			$size += expand_to_bytes($adepend['size']);
1054
			$alreadyseen[] = $pkgname;
1055
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1056
		}
1057
	}
1058
	return $size;
1059
}
1060

    
1061
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1062
	global $config, $g;
1063
	if((!is_array($pkg)) and ($pkg != 'all'))
1064
		$pkg = array($pkg);
1065
	$pkgdb = get_pkg_db();
1066
	if(!$pkg_info)
1067
		$pkg_info = get_pkg_sizes($pkg);
1068
	foreach($pkg as $apkg) {
1069
		if(!$pkg_info[$apkg])
1070
			continue;
1071
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1072
	}
1073
	return $toreturn;
1074
}
1075

    
1076
function squash_from_bytes($size, $round = "") {
1077
	$conv = array(1 => "B", "K", "M", "G");
1078
	foreach($conv as $div => $suffix) {
1079
		$sizeorig = $size;
1080
		if(($size /= 1024) < 1) {
1081
			if($round) {
1082
				$sizeorig = round($sizeorig, $round);
1083
			}
1084
			return $sizeorig . $suffix;
1085
		}
1086
	}
1087
	return;
1088
}
1089

    
1090
?>
(31-31/54)