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)
105
		return false;
106
	return true;
107
}
108

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

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

    
131
/****f* pkg-utils/get_pkg_info
132
 * NAME
133
 *   get_pkg_info - Retrive package information from pfsense.com.
134
 * INPUTS
135
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
136
 *   $info - 'all' to retrive all information, an array containing keys otherwise
137
 * RESULT
138
 *   $raw_versions - Array containing retrieved information, indexed by package name.
139
 ******/
140
function get_pkg_info($pkgs = 'all', $info = 'all') {
141
	global $g;
142

    
143
	$freebsd_version = str_replace("\n", "", `uname -r | cut -d'-' -f1 | cut -d'.' -f1`);
144
	$freebsd_machine = str_replace("\n", "", `uname -m`);
145
	$params = array(
146
		"pkg" => $pkgs, 
147
		"info" => $info, 
148
		"freebsd_version" => $freebsd_version,
149
		"freebsd_machine" => $freebsd_machine
150
	);
151
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
152
	return $resp ? $resp : array();
153
}
154

    
155
function get_pkg_sizes($pkgs = 'all') {
156
	global $g;
157

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

    
168
	return array();
169
}
170

    
171
/*
172
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
173
 * This function may also print output to the terminal indicating progress.
174
 */
175
function resync_all_package_configs($show_message = false) {
176
	global $config, $restart_sync, $pkg_interface;
177

    
178
	$i = 0;
179
	log_error("Resyncing configuration for all packages.");
180
	if(!$config['installedpackages']['package'])
181
		return;
182
	if($show_message == true)
183
		echo "Syncing packages:";
184

    
185
	if (is_array($config['installedpackages']['package'])) {
186
		foreach($config['installedpackages']['package'] as $package) {
187
			if (empty($package['name']))
188
				continue;
189
			if($show_message == true)
190
				echo " " . $package['name'];
191
			get_pkg_depends($package['name'], "all");
192
			stop_service($package['name']);
193
			sync_package($i, true, true);
194
			if($restart_sync == true) {
195
				$restart_sync = false;
196
				if($pkg_interface == "console") 
197
					echo "\nSyncing packages:";
198
			}
199
			$i++;
200
		}
201
	}
202
	if($show_message == true)
203
		echo " done.\n";
204
	@unlink("/conf/needs_package_sync");
205
}
206

    
207
/*
208
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
209
 *				package is installed.
210
 */
211
function is_freebsd_pkg_installed($pkg) {
212
	global $g;
213

    
214
	if(in_array($pkg, return_dir_as_array("{$g['vardb_path']}/pkg")))
215
		return true;
216
	return false;
217
}
218

    
219
/*
220
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
221
 *
222
 * $filetype = "all" || ".xml", ".tgz", etc.
223
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
224
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
225
 *
226
 */
227
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
228
	global $config;
229
	require_once("notices.inc");
230

    
231
	$pkg_id = get_pkg_id($pkg_name);
232
	if($pkg_id == -1)
233
		return -1; // This package doesn't really exist - exit the function.
234
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
235
		return; // No package belongs to the pkg_id passed to this function.
236

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

    
291
function uninstall_package($pkg_name) {
292
	global $config;
293

    
294
	$id = get_pkg_id($pkg_name);
295
	if ($id >= 0) {
296
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
297
		if (is_array($pkg_depends)) {
298
			foreach ($pkg_depends as $pkg_depend)
299
				delete_package($pkg_depend, $id);
300
		}
301
	}
302
	delete_package_xml($pkg_name);
303
}
304

    
305
function force_remove_package($pkg_name) {
306
	global $config;
307
	delete_package_xml($pkg_name);
308
}
309

    
310
/*
311
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
312
 */
313
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
314
	global $config;
315
	require_once("notices.inc");
316
	
317
	if(empty($config['installedpackages']['package']))
318
		return;
319
	if(!is_numeric($pkg_name)) {
320
		$pkg_id = get_pkg_id($pkg_name);
321
		if($pkg_id == -1)
322
			return -1; // This package doesn't really exist - exit the function.
323
	} else {
324
		$pkg_id = $pkg_name;
325
		if(empty($config['installedpackages']['package'][$pkg_id]))
326
			return;  // No package belongs to the pkg_id passed to this function.
327
	}
328
        if (is_array($config['installedpackages']['package'][$pkg_id]))
329
		$package =& $config['installedpackages']['package'][$pkg_id];
330
        else
331
		return; /* empty package tag */
332
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
333
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
334
		force_remove_package($package['name']);
335
		return -1;
336
	}
337
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
338

    
339
	/* Bring in package include files */
340
	if (!empty($pkg_config['include_file'])) {
341
		$include_file = $pkg_config['include_file'];
342
		if (file_exists($include_file))
343
			require_once($include_file);
344
		else {
345
			/* XXX: What the heck is this?! */
346
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
347
			uninstall_package($package['name']);
348
			if (install_package($package['name']) < 0) {
349
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
350
				return -1;
351
			}
352
		}
353
	}
354

    
355
	/* XXX: Zend complains about the next line "Wrong break depth"
356
	 * The code is obviously wrong, but I'm not sure what it's supposed to do?
357
	 */
358
	if(isset($pkg_config['nosync']))
359
		continue;
360
	if(!empty($pkg_config['custom_php_global_functions']))
361
		eval($pkg_config['custom_php_global_functions']);
362
	if(!empty($pkg_config['custom_php_resync_config_command']))
363
		eval($pkg_config['custom_php_resync_config_command']);
364
	if($sync_depends == true) {
365
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
366
		if(is_array($depends)) {
367
			foreach($depends as $item) {
368
				if(!file_exists($item)) {
369
					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);
370
					log_error("Could not find {$item}. Reinstalling package.");
371
					uninstall_package($pkg_name);
372
					install_package($pkg_name);
373
				} else {
374
					$item_config = parse_xml_config_pkg($item, "packagegui");
375
					if (empty($item_config))
376
						continue;
377
					if(isset($item_config['nosync']))
378
						continue;
379
					if($item_config['custom_php_command_before_form'] <> "")
380
						eval($item_config['custom_php_command_before_form']);
381
					if($item_config['custom_php_resync_config_command'] <> "")
382
						eval($item_config['custom_php_resync_config_command']);
383
					if($show_message == true)
384
						print " " . $item_config['name'];
385
				}
386
			}
387
		}
388
	}
389
}
390

    
391
/*
392
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
393
 * 			a progress bar and output window.
394
 *
395
 * XXX: This function needs to return where a pkg_add fails. Our current error messages aren't very descriptive.
396
 */
397
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = 'http://ftp2.freebsd.org/pub/FreeBSD/ports/i386/packages-8.1-release/Latest') {
398
	global $pkgent, $static_output, $g, $fd_log;
399

    
400
	$pkg_extension = strrchr($filename, '.');
401
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
402
	$fetchto = "{$g['tmp_path']}/apkg_{$pkgname}{$pkg_extension}";
403
	download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto);
404
	$static_output .= " (extracting)";
405
	update_output_window($static_output);
406
	$slaveout = "";
407
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
408
	$workingdir = preg_grep("/instmp/", $slaveout);
409
	$workingdir = $workingdir[0];
410
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
411
	if($raw_depends_list != "") {
412
		if($pkgent['exclude_dependency'] != "")
413
			$raw_depends_list = array_values(preg_grep($pkgent['exclude_dependency'], PREG_GREP_INVERT));
414
		foreach($raw_depends_list as $adepend) {
415
			$working_depend = explode(" ", $adepend);
416
			//$working_depend = explode("-", $working_depend[1]);
417
			$depend_filename = $working_depend[1] . $pkg_extension;
418
			if(is_freebsd_pkg_installed($working_depend[1]) === false) {
419
				pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url);
420
			} else {
421
				//$dependlevel++;
422
				$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " ";
423
				@fwrite($fd_log, $working_depend[1] . "\n");
424
			}
425
		}
426
	}
427
	$pkgaddout = "";
428
	exec("/bin/cat {$g['tmp_path']}/y | /usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
429
	@fwrite($fd_log, $pkgname . " " . print_r($pkgaddout, true) . "\n");
430

    
431
	return true;
432
}
433

    
434
function install_package($package, $pkg_info = "") {
435
	global $g, $config, $pkg_interface, $fd_log, $static_output, $pkg_interface, $restart_sync;
436

    
437
	/* safe side. Write config below will send to ro again. */
438
	conf_mount_rw();
439

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

    
519
function get_after_install_info($package) {
520
	global $pkg_info;
521
	/* fetch package information if needed */
522
	if(!$pkg_info or !is_array($pkg_info[$package])) {
523
		$pkg_info = get_pkg_info(array($package));
524
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
525
	}
526
	if($pkg_info['after_install_info'])
527
		return $pkg_info['after_install_info'];
528
}
529

    
530
function eval_once($toeval) {
531
	global $evaled;
532
	if(!$evaled) $evaled = array();
533
	$evalmd5 = md5($toeval);
534
	if(!in_array($evalmd5, $evaled)) {
535
		@eval($toeval);
536
		$evaled[] = $evalmd5;
537
	}
538
	return;
539
}
540

    
541
function install_package_xml($pkg) {
542
	global $g, $config, $fd_log, $static_output, $pkg_interface;
543

    
544
	if(($pkgid = get_pkg_id($pkg)) == -1) {
545
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
546
		update_output_window($static_output);
547
		if($pkg_interface <> "console") {
548
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
549
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
550
		}
551
		sleep(1);
552
		return false;
553
	} else
554
		$pkg_info = $config['installedpackages']['package'][$pkgid];
555

    
556
	/* set up logging if needed */
557
	if(!$fd_log) {
558
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
559
			update_output_window("Warning, could not open log for writing.");
560
		}
561
	}
562

    
563
	/* make 'y' file */
564
	$fd = fopen("{$g['tmp_path']}/y", "w");
565
	for($line = 0; $line < 10; $line++) {
566
		fwrite($fd, "y\n");
567
	}
568
	fclose($fd);
569

    
570
	/* pkg_add the package and its dependencies */
571
	if($pkg_info['depends_on_package_base_url'] != "") {
572
		if($pkg_interface == "console") 
573
			echo "\n";
574
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
575
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
576
		$static_orig = $static_output;
577
		$static_output .= "\n";
578
		update_output_window($static_output);
579
		foreach((array) $pkg_info['depends_on_package'] as $pkgdep) {
580
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
581
			if(isset($pkg_info['skip_install_checks']))
582
				$pkg_installed = true;
583
			else
584
				$pkg_installed = is_freebsd_pkg_installed($pkg_name);
585

    
586
			if($pkg_installed == false)
587
				pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url']);
588
			$static_output = $static_orig . "done.\nChecking for successful package installation... ";
589
			update_output_window($static_output);
590
			/* make sure our package was successfully installed */
591
			if($pkg_installed == false)
592
				$pkg_installed = is_freebsd_pkg_installed($pkg_name);
593
			if($pkg_installed == true) {
594
				$static_output .= "done.\n";
595
				update_output_window($static_output);
596
				fwrite($fd_log, "pkg_add successfully completed.\n");
597
			} else {
598
				$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
599
				update_output_window($static_output);
600
				fwrite($fd_log, "Package WAS NOT installed properly.\n");
601
				fclose($fd_log);
602
				if($pkg_interface <> "console") {
603
					echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
604
					echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
605
				}
606
				sleep(1);
607
				return false;
608
			}
609
		}
610
	}
611
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
612
	if(file_exists("/usr/local/pkg/" . $configfile)) {
613
		$static_output .= "Loading package configuration... ";
614
		update_output_window($static_output);
615
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
616
		$static_output .= "done.\n";
617
		update_output_window($static_output);
618
		$static_output .= "Configuring package components...\n";
619
		if (!empty($pkg_config['filter_rules_needed']))
620
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
621
		update_output_window($static_output);
622
		/* modify system files */
623
		if(is_array($pkg_config['modify_system']['item'])) {
624
			$static_output .= "\tSystem files... ";
625
			update_output_window($static_output);
626
			foreach($pkg_config['modify_system']['item'] as $ms) {
627
				if($ms['textneeded']) {
628
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
629
				}
630
			}
631
			$static_output .= "done.\n";
632
			update_output_window($static_output);
633
		}
634
		/* download additional files */
635
		if(is_array($pkg_config['additional_files_needed'])) {
636
			$static_output .= "\tAdditional files... ";
637
			$static_orig = $static_output;
638
			update_output_window($static_output);
639
			foreach($pkg_config['additional_files_needed'] as $afn) {
640
				$filename = get_filename_from_url($afn['item'][0]);
641
				if($afn['chmod'] <> "")
642
					$pkg_chmod = $afn['chmod'];
643
				else
644
					$pkg_chmod = "";
645

    
646
				if($afn['prefix'] <> "")
647
					$prefix = $afn['prefix'];
648
				else
649
					$prefix = "/usr/local/pkg/";
650

    
651
				if(!is_dir($prefix)) 
652
					safe_mkdir($prefix);
653
 				$static_output .= $filename . " ";
654
                                update_output_window($static_output);
655
				download_file_with_progress_bar($afn['item'][0], $prefix . $filename);
656
				if(stristr($filename, ".tgz") <> "") {
657
					fwrite($fd_log, "Extracting tarball to -C for " . $filename . "...\n");
658
					$tarout = "";
659
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
660
					fwrite($fd_log, print_r($tarout, true) . "\n");
661
				}
662
				if($pkg_chmod <> "") {
663
					fwrite($fd_log, "Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
664
					@chmod($prefix . $filename, $pkg_chmod);
665
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
666
				}
667
				$static_output = $static_orig;
668
                                update_output_window($static_output);
669
			}
670
			$static_output .= "done.\n";
671
			update_output_window($static_output);
672
		}
673
		/*   if a require exists, include it.  this will
674
		 *   show us where an error exists in a package
675
		 *   instead of making us blindly guess
676
		 */
677
		if($pkg_config['include_file'] <> "") {
678
			$static_output = "Loading package instructions...";
679
			update_output_window($static_output);
680
			fwrite($fd_log, "require_once('{$pkg_config['include_file']}')\n");
681
			if (file_exists($pkg_config['include_file']))
682
				require_once($pkg_config['include_file']);
683
		}
684
		/* sidebar items */
685
		if(is_array($pkg_config['menu'])) {
686
			$static_output .= "\tMenu items... ";
687
			update_output_window($static_output);
688
			foreach($pkg_config['menu'] as $menu) {
689
				if(is_array($config['installedpackages']['menu']))
690
					foreach($config['installedpackages']['menu'] as $amenu)
691
						if($amenu['name'] == $menu['name'])
692
							continue 2;
693
				$config['installedpackages']['menu'][] = $menu;
694
			}
695
			$static_output .= "done.\n";
696
			update_output_window($static_output);
697
		}
698
		/* integrated tab items */
699
		if(is_array($pkg_config['tabs']['tab'])) {
700
			$static_output .= "\tIntegrated Tab items... ";
701
			update_output_window($static_output);
702
			foreach($pkg_config['tabs']['tab'] as $tab) {
703
				if(is_array($config['installedpackages']['tab']))
704
					foreach($config['installedpackages']['tab'] as $atab)
705
						if($atab['name'] == $tab['name'])
706
							continue 2;
707
				$config['installedpackages']['tab'][] = $tab;
708
			}
709
			$static_output .= "done.\n";
710
			update_output_window($static_output);
711
		}
712
		/* services */
713
		if(is_array($pkg_config['service'])) {
714
			$static_output .= "\tServices... ";
715
			update_output_window($static_output);
716
			foreach($pkg_config['service'] as $service) {
717
				if(is_array($config['installedpackages']['service']))
718
					foreach($config['installedpackages']['service'] as $aservice)
719
						if($aservice['name'] == $service['name'])
720
							continue 2;
721
				$config['installedpackages']['service'][] = $service;
722
			}
723
			$static_output .= "done.\n";
724
			update_output_window($static_output);
725
		}
726
		/* custom commands */
727
		$static_output .= "\tCustom commands... ";
728
		update_output_window($static_output);
729
		if($pkg_config['custom_php_global_functions'] <> "") {
730
			$static_output = "Executing custom_php_global_functions()...";
731
			update_output_window($static_output);
732
			eval_once($pkg_config['custom_php_global_functions']);
733
		}
734
		if($pkg_config['custom_php_install_command']) {
735
			$static_output = "Executing custom_php_install_command()...";
736
			update_output_window($static_output);
737
			eval_once($pkg_config['custom_php_install_command']);
738
		}
739
		if($pkg_config['custom_php_resync_config_command'] <> "") {
740
			$static_output = "Executing custom_php_resync_config_command()...";
741
			update_output_window($static_output);
742
			eval_once($pkg_config['custom_php_resync_config_command']);
743
		}
744
		$static_output .= "done.\n";
745
		update_output_window($static_output);
746
	} else {
747
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
748
		update_output_window($static_output);
749
		fwrite($fd_log, "Unable to load package configuration. Installation aborted.\n");
750
		fclose($fd_log);
751
		if($pkg_interface <> "console") {
752
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
753
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
754
		}
755
		sleep(1);
756
		return false;
757
	}
758

    
759
	/* set up package logging streams */
760
	if($pkg_info['logging']) {
761
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
762
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
763
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
764
		if(is_process_running("syslogd"))
765
			mwexec("killall syslogd");
766
		system_syslogd_start();
767
	}
768

    
769
	return true;
770
}
771

    
772
function delete_package($pkg, $pkgid) {
773
	global $g, $config, $fd_log, $static_output;
774

    
775
	update_status("Removing package...");
776
	$static_output .= "Removing package... ";
777
	update_output_window($static_output);
778
	if (!is_array($config['installedpackages']['package']))
779
		return;
780

    
781
	$pkg_info =& $config['installedpackages']['package'][$pkgid];
782
	if (empty($pkg_info))
783
		return;
784
	if (empty($pkg_info['configurationfile'])) 
785
		return;
786

    
787
	$static_output .= "\nStarting package deletion for {$pkg_info['name']}...\n";
788
	update_output_window($static_output);
789
	if (!empty($pkg))
790
		delete_package_recursive($pkg);
791
	$static_output .= "done.\n";
792
	update_output_window($static_output);
793

    
794
	return;
795
}
796

    
797
function delete_package_recursive($pkg) {
798
	global $config, $g;
799

    
800
	$fd = fopen("{$g['tmp_path']}/y", "w");
801
	for($line = 0; $line < 10; $line++) {
802
		fwrite($fd, "y\n");
803
	}
804
	fclose($fd);
805
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
806
	$info = "";
807
	exec("/usr/sbin/pkg_info -r {$pkg} 2>&1", $info);
808
	remove_freebsd_package($pkg);
809
	$pkgdb = "";
810
	exec("/bin/ls {$g['vardb_path']}/pkg", $pkgdb);
811
	foreach($info as $line) {
812
		$depend = trim(array_pop(explode(":", $line)));
813
		if(in_array($depend, $pkgdb)) 
814
			delete_package_recursive($depend);
815
	}
816
	return;
817
}
818

    
819
function delete_package_xml($pkg) {
820
	global $g, $config, $fd_log, $static_output, $pkg_interface;
821

    
822
	conf_mount_rw();
823

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

    
911
		/*
912
		 * If a require exists, include it.  this will
913
		 * show us where an error exists in a package
914
		 * instead of making us blindly guess
915
		 */
916
		if($pkg_config['include_file'] <> "") {
917
			$static_output = "Loading package instructions...";
918
			update_output_window($static_output);
919
			fwrite($fd_log, "require_once(\"{$pkg_config['include_file']}\")\n");
920
			if(file_exists($pkg_config['include_file']))
921
				require_once($pkg_config['include_file']);
922
			fwrite($fd_log, "require_once(\"{$pkg_config['include_file']}\") included\n");
923
		}
924
		/* evalate this package's global functions and pre deinstall commands */
925
		if($pkg_config['custom_php_global_functions'] <> "")
926
			eval_once($pkg_config['custom_php_global_functions']);
927
		if($pkg_config['custom_php_pre_deinstall_command'] <> "")
928
			eval_once($pkg_config['custom_php_pre_deinstall_command']);
929
		/* system files */
930
		if(is_array($pkg_config['modify_system']['item'])) {
931
			$static_output .= "\tSystem files... ";
932
			update_output_window($static_output);
933
			foreach($pkg_config['modify_system']['item'] as $ms)
934
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
935

    
936
			$static_output .= "done.\n";
937
			update_output_window($static_output);
938
		}
939
		/* syslog */
940
		if($pkg_config['logging']['logfile_name'] <> "") {
941
			$static_output .= "\tSyslog entries... ";
942
			update_output_window($static_output);
943
			remove_text_from_file("/etc/syslog.conf", $pkg_config['logging']['facilityname'] . "\t\t\t\t" . $pkg_config['logging']['logfilename']);
944
			$static_output .= "done.\n";
945
			update_output_window($static_output);
946
		}
947
		/* deinstall commands */
948
		if($pkg_config['custom_php_deinstall_command'] <> "") {
949
			$static_output .= "\tDeinstall commands... ";
950
			update_output_window($static_output);
951
			eval_once($pkg_config['custom_php_deinstall_command']);
952
			$static_output .= "done.\n";
953
			update_output_window($static_output);
954
		}
955
		if($pkg_config['include_file'] <> "") {
956
                        $static_output = "\tRemoving package instructions...";
957
                        update_output_window($static_output);
958
                        fwrite($fd_log, "Remove '{$pkg_config['include_file']}'\n");
959
                        unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
960
			$static_output .= "done.\n";
961
                        update_output_window($static_output);
962
			
963
                }
964
		/* remove all additional files */
965
		if(is_array($pkg_config['additional_files_needed'])) {
966
			$static_output .= "\tAuxiliary files... ";
967
			update_output_window($static_output);
968
			foreach($pkg_config['additional_files_needed'] as $afn) {
969
				$filename = get_filename_from_url($afn['item'][0]);
970
				if($afn['prefix'] <> "")
971
					$prefix = $afn['prefix'];
972
				else
973
					$prefix = "/usr/local/pkg/";
974

    
975
				unlink_if_exists($prefix . $filename);
976
			}
977
			$static_output .= "done.\n";
978
			update_output_window($static_output);
979
		}
980
		/* package XML file */
981
		$static_output .= "\tPackage XML... ";
982
		update_output_window($static_output);
983
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
984
		$static_output .= "done.\n";
985
		update_output_window($static_output);
986
	}
987
	/* remove config.xml entries */
988
	conf_mount_ro();
989
	$static_output .= "\tConfiguration... ";
990
	update_output_window($static_output);
991
	unset($config['installedpackages']['package'][$pkgid]);
992
	$static_output .= "done.\n";
993
	update_output_window($static_output);
994
	write_config("Removed {$pkg} package.");
995
	/* file cleanup */
996
	$ctag = file("/etc/crontab");
997
	foreach($ctag as $line)
998
		if(trim($line) != "")
999
			$towrite[] = $line;
1000

    
1001
	$tmptab = fopen("{$g['tmp_path']}/crontab", "w");
1002
	foreach($towrite as $line)
1003
		fwrite($tmptab, $line);
1004
	fclose($tmptab);
1005

    
1006
	// Go RW again since the write_config above will put it back to RO
1007
	conf_mount_rw();
1008
	rename("{$g['tmp_path']}/crontab", "/etc/crontab");
1009
	conf_mount_ro();
1010
}
1011

    
1012
function expand_to_bytes($size) {
1013
	$conv = array(
1014
			"G" =>	"3",
1015
			"M" =>  "2",
1016
			"K" =>  "1",
1017
			"B" =>  "0"
1018
		);
1019
	$suffix = substr($size, -1);
1020
	if(!in_array($suffix, array_keys($conv))) return $size;
1021
	$size = substr($size, 0, -1);
1022
	for($i = 0; $i < $conv[$suffix]; $i++) {
1023
		$size *= 1024;
1024
	}
1025
	return $size;
1026
}
1027

    
1028
function get_pkg_db() {
1029
	global $g;
1030
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1031
}
1032

    
1033
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1034
	if(!$pkgdb)
1035
		$pkgdb = get_pkg_db();
1036
	if(!is_array($alreadyseen))
1037
		$alreadyseen = array();
1038
	if (!is_array($depend))
1039
		$depend = array();
1040
	foreach($depend as $adepend) {
1041
		$pkgname = reverse_strrchr($adepend['name'], '.');
1042
		if(in_array($pkgname, $alreadyseen)) {
1043
			continue;
1044
		} elseif(!in_array($pkgname, $pkgdb)) {
1045
			$size += expand_to_bytes($adepend['size']);
1046
			$alreadyseen[] = $pkgname;
1047
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1048
		}
1049
	}
1050
	return $size;
1051
}
1052

    
1053
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1054
	global $config, $g;
1055
	if((!is_array($pkg)) and ($pkg != 'all'))
1056
		$pkg = array($pkg);
1057
	$pkgdb = get_pkg_db();
1058
	if(!$pkg_info)
1059
		$pkg_info = get_pkg_sizes($pkg);
1060
	foreach($pkg as $apkg) {
1061
		if(!$pkg_info[$apkg]) continue;
1062
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1063
	}
1064
	return $toreturn;
1065
}
1066

    
1067
function squash_from_bytes($size, $round = "") {
1068
	$conv = array(1 => "B", "K", "M", "G");
1069
	foreach($conv as $div => $suffix) {
1070
		$sizeorig = $size;
1071
		if(($size /= 1024) < 1) {
1072
			if($round) {
1073
				$sizeorig = round($sizeorig, $round);
1074
			}
1075
			return $sizeorig . $suffix;
1076
		}
1077
	}
1078
	return;
1079
}
1080

    
1081
?>
(31-31/54)