Project

General

Profile

Download (33.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 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
require_once("xmlrpc.inc");
36
require_once("xmlparse.inc");
37
require_once("service-utils.inc");
38
require_once("pfsense-utils.inc");
39
require_once("globals.inc");
40

    
41
safe_mkdir("/var/db/pkg");
42
safe_mkdir("/usr/local/pkg");
43
safe_mkdir("/usr/local/pkg/pf");
44

    
45
/****f* pkg-utils/is_package_installed
46
 * NAME
47
 *   is_package_installed - Check whether a package is installed.
48
 * INPUTS
49
 *   $packagename	- name of the package to check
50
 * RESULT
51
 *   boolean	- true if the package is installed, false otherwise
52
 * NOTES
53
 *   This function is deprecated - get_pkg_id() can already check for installation.
54
 ******/
55
function is_package_installed($packagename) {
56
	$pkg = get_pkg_id($packagename);
57
	if($pkg == -1) return false;
58
	return true;
59
}
60
            
61
/****f* pkg-utils/get_pkg_id
62
 * NAME
63
 *   get_pkg_id - Find a package's numeric ID.
64
 * INPUTS
65
 *   $pkg_name	- name of the package to check
66
 * RESULT
67
 *   integer    - -1 if package is not found, >-1 otherwise
68
 ******/
69
function get_pkg_id($pkg_name) {
70
    global $config;
71
    if(is_array($config['installedpackages']['package'])) {
72
        $i = 0;
73
        foreach($config['installedpackages']['package'] as $pkg) {
74
            if($pkg['name'] == $pkg_name) return $i;
75
            $i++;
76
        }
77
    }
78
    return -1;
79
}
80

    
81
/****f* pkg-utils/get_pkg_info
82
 * NAME
83
 *   get_pkg_info - Retrive package information from pfsense.com.
84
 * INPUTS
85
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
86
 *   $info - 'all' to retrive all information, an array containing keys otherwise
87
 * RESULT
88
 *   $raw_versions - Array containing retrieved information, indexed by package name.
89
 ******/
90
function get_pkg_info($pkgs = 'all', $info = 'all') {
91
	global $g;
92
        $params = array("pkg" => $pkgs, "info" => $info);
93
        $msg = new XML_RPC_Message('pfsense.get_pkgs', array(php_value_to_xmlrpc($params)));
94
        $cli = new XML_RPC_Client($g['xmlrpcpath'], $g['xmlrpcbaseurl']);
95
        $resp = $cli->send($msg, 10);
96
	if($resp and !$resp->faultCode()) {
97
        	$raw_versions = $resp->value();
98
		return xmlrpc_value_to_php($raw_versions);
99
	} else {
100
		return array();
101
	}
102
}
103

    
104
function get_pkg_sizes($pkgs = 'all') {
105
	global $g;
106
        $params = array("pkg" => $pkgs);
107
        $msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
108
        $cli = new XML_RPC_Client($g['xmlrpcpath'], $g['xmlrpcbaseurl']);
109
        $resp = $cli->send($msg, 10);  
110
        if($resp and !$resp->faultCode()) {
111
                $raw_versions = $resp->value();
112
                return xmlrpc_value_to_php($raw_versions);
113
        } else {
114
                return array();
115
        } 
116
}
117

    
118
/*
119
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
120
 * This function may also print output to the terminal indicating progress.
121
 */
122
function resync_all_package_configs($show_message = false) {
123
    global $config;
124
    $i = 0;
125
    log_error("Resyncing configuration for all packages.");
126
    if(!$config['installedpackages']['package']) return;
127
    if($show_message == true) print "Syncing packages:";
128
    foreach($config['installedpackages']['package'] as $package) {
129
        if($show_message == true) print " " . $package['name'];
130
        sync_package($i, true, true);
131
        $i++;
132
    }
133
    if($show_message == true) print ".\n";
134
}
135

    
136
/*
137
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
138
 *				package is installed.
139
 */
140
function is_freebsd_pkg_installed($pkg) {
141
	global $g;
142
	if(in_array($pkg, return_dir_as_array("{$g['vardb_path']}/pkg"))) return true;
143
	return false;
144
}
145

    
146
/*
147
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
148
 *
149
 * $filetype = "all" || ".xml", ".tgz", etc.
150
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
151
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
152
 *
153
 */
154
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
155
    global $config;                                                                             
156
    if(!is_numeric($pkg_name)) {
157
        $pkg_id = get_pkg_id($pkg_name);
158
        if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
159
    } else {                                                                                  
160
        if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
161
    }                                                                                                                                    
162
    $package = $config['installedpackages']['package'][$pkg_id];
163
    if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
164
        file_notice($package['name'], "The {$package['name']} package is missing its configuration file and must be reinstalled.", "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1);
165
		return;
166
	}
167
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
168
    if($pkg_xml['additional_files_needed'] != "") {                                                  
169
        foreach($pkg_xml['additional_files_needed'] as $item) {
170
            if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
171
            $depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
172
            $depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
173
            if (($filetype != "all") && (!preg_match("/${filetype}/i", $depend_file))) continue;
174
            if ($item['prefix'] != "") {
175
                $prefix = $item['prefix'];
176
            } else {
177
                $prefix = "/usr/local/pkg/";
178
            }
179
            if(!file_exists($prefix . $pkg_name)) {
180
				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);
181
            }
182
            switch ($format) {
183
            case "files":
184
                $depends[] = $depend_file;
185
                break;
186
            case "names":
187
                switch ($filetype) {
188
                case "all":
189
                    if(preg_match("/\.xml/i", $depend_file)) {
190
                        $depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
191
                        $depends[] = $depend_xml['name'];
192
                        break;
193
                    } else {
194
                        $depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
195
                        break;
196
                    }
197
                case ".xml":
198
                    $depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
199
                    $depends[] = $depend_xml['name'];
200
                    break;
201
                default:
202
                    $depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
203
                    break;
204
                }
205
            }
206
        }
207
        return $depends;
208
    }
209
}
210

    
211
/*
212
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
213
 */
214
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
215
	global $config;
216

    
217
	if(!file_exists("/usr/local/pkg")) mwexec("/bin/mkdir -p /usr/local/pkg/pf");
218
	if(!$config['installedpackages']['package']) return;
219
	if(!is_numeric($pkg_name)) {
220
		$pkg_id = get_pkg_id($pkg_name);
221
		if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
222
	} else {
223
		$pkg_id = $pkg_name;
224
		if(!isset($config['installedpackages']['package'][$pkg_id]))
225
		return;  // No package belongs to the pkg_id passed to this function.
226
	}
227
	$package = $config['installedpackages']['package'][$pkg_id];
228
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
229
		file_notice($package['name'], "The {$package['name']} package is missing its configuration file and must be reinstalled.", "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1);
230
	} else {
231
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
232
		/* XXX: Zend complains about the next line "Wrong break depth"
233
		 * The code is obviously wrong, but I'm not sure what it's supposed to do?
234
		 */
235
		if(isset($pkg_config['nosync'])) continue;
236
		if($pkg['custom_php_global_functions'] <> "")
237
		eval($pkg['custom_php_global_functions']);
238
		if($pkg_config['custom_php_resync_config_command'] <> "")
239
		eval($pkg_config['custom_php_resync_config_command']);
240
		if($sync_depends == true) {
241
			$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
242
			if(is_array($depends)) {
243
				foreach($depends as $item) {
244
					if(!file_exists("/usr/local/pkg" . $item)) {
245
						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);
246
					} else {
247
						$item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
248
						if(isset($item_config['nosync'])) continue;
249
						if($item_config['custom_php_command_before_form'] <> "") {
250
							eval($item_config['custom_php_command_before_form']);
251
						}
252
						if($item_config['custom_php_resync_config_command'] <> "") {
253
							eval($item_config['custom_php_resync_config_command']);
254
						}
255
						if($show_message == true) print " " . $item_config['name'];
256
					}
257
				}
258
			}
259
		}
260
	}
261
}
262

    
263
/*
264
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
265
 * 			a progress bar and output window.
266
 *
267
 * XXX: This function needs to return where a pkg_add fails. Our current error messages aren't very descriptive.
268
 */
269
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = 'http://ftp2.freebsd.org/pub/FreeBSD/ports/i386/packages-5.4-release/Latest') {
270
        global $pkgent, $static_output, $g, $fd_log;
271
        $pkg_extension = strrchr($filename, '.');
272
        $static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
273
        $fetchto = "/tmp/apkg_" . $pkgname . $pkg_extension;
274
	download_file_with_progress_bar($base_url . '/' . $filename, $fetchto);
275
	$static_output .= " (extracting)";
276
	update_output_window($static_output);	
277
        exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
278
        $workingdir = preg_grep("/instmp/", $slaveout);
279
        $workingdir = $workingdir[0];
280
        $raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
281
        if($raw_depends_list != "") {
282
                if($pkgent['exclude_dependency'] != "")
283
                        $raw_depends_list = array_values(preg_grep($pkgent['exclude_dependency'], PREG_GREP_INVERT));
284
                foreach($raw_depends_list as $adepend) {
285
                        $working_depend = explode(" ", $adepend);
286
                        //$working_depend = explode("-", $working_depend[1]);
287
                        $depend_filename = $working_depend[1] . $pkg_extension;
288
                        if(is_freebsd_pkg_installed($working_depend[1]) === false) {
289
                                pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url);
290
                        } else {
291
//                              $dependlevel++;
292
                                $static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " ";
293
                                @fwrite($fd_log, $working_depend[1] . "\n");
294
                        }
295
                }
296
        }
297
        exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
298
        @fwrite($fd_log, $pkgname . " " . print_r($pkgaddout, true) . "\n");
299
        return true;
300
}
301

    
302
function download_file_with_progress_bar($url_file, $destination_file) {
303
        global $ch, $fout, $file_size, $downloaded, $pkg_interface;
304
        $file_size  = 1;
305
        $downloaded = 1;
306
        /* open destination file */
307
        $fout = fopen($destination_file, "wb");
308

    
309
        /*
310
                Originally by Author: Keyvan Minoukadeh
311
                Modified by Scott Ullrich to return Content-Length size
312
        */
313

    
314
        $ch = curl_init();
315
        curl_setopt($ch, CURLOPT_URL, $url_file);
316
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
317
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
318
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
319

    
320
        curl_exec($ch);
321
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
322
        fclose($fout);
323
        curl_close($ch);
324
	return ($http_code == 200) ? true : $http_code;
325
}
326

    
327
function read_header($ch, $string) {
328
        global $file_size, $fout;
329
        $length = strlen($string);
330
        ereg("(Content-Length:) (.*)", $string, $regs);
331
        if($regs[2] <> "") {
332
                $file_size = intval($regs[2]);
333
        }
334
        return $length;
335
}
336

    
337
function read_body($ch, $string) {
338
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $pkg_interface;
339
        $length = strlen($string);
340
        $downloaded += intval($length);
341
        $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
342
        $downloadProgress = 100 - $downloadProgress;
343
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
344
                if($sendto == "status") {
345
                        $tostatus = $static_status . $downloadProgress . "%";
346
                        update_status($tostatus);
347
                } else {
348
                        $tooutput = $static_output . $downloadProgress . "%";
349
                        update_output_window($tooutput);
350
                }
351
                update_progress_bar($downloadProgress);
352
                $lastseen = $downloadProgress;
353
        }
354
	fwrite($fout, $string);
355
	return $length;
356
}
357

    
358
function install_package($package, $pkg_info = "") {
359
	global $g, $config, $pkg_interface, $fd_log, $static_output;
360
	/* open logfiles and begin installation */
361
	if(!$fd_log) {
362
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$package}.log", "w")) {
363
			update_output_window("Warning, could not open log for writing.");
364
		}
365
	}
366
	@fwrite($fd_log, "Beginning package installation.\n");
367
	log_error('Beginning package installation for ' . $package . '.');
368
	update_status("Beginning package installation for " . $package . "...");
369
	/* fetch package information if needed */
370
	if(!$pkg_info or !is_array($pkg_info[$package])) {
371
		$pkg_info = get_pkg_info(array($package));
372
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
373
	}
374
	/* fetch the package's configuration file */
375
	if($pkg_info['config_file'] != "") {
376
		$static_output .= "Downloading package configuration file... ";
377
		update_output_window($static_output);
378
		@fwrite($fd_log, "Downloading package configuration file...\n");
379
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
380
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
381
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
382
			@fwrite($fd_log, "ERROR! Unable to fetch package configuration file. Aborting installation.\n");
383
			if($pkg_interface == "console") {
384
				print "\nERROR! Unable to fetch package configuration file. Aborting package installation.\n";
385
				return;
386
			} else {
387
				$static_output .= "failed!\n\nInstallation aborted.";
388
				update_output_window($static_output);
389
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
390
			 	return -1;
391
			}
392
		}
393
		$static_output .= "done.\n";
394
		update_output_window($static_output);
395
	}
396
	/* add package information to config.xml */
397
	$pkgid = get_pkg_id($pkg_info['name']);
398
	$static_output .= "Saving updated package information... ";
399
	update_output_window($static_output);
400
	if($pkgid == -1) {
401
		$config['installedpackages']['package'][] = $pkg_info;
402
		$changedesc = "Installed {$pkg_info['name']} package.";
403
		$to_output = "done.\n";
404
	} else {
405
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
406
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
407
		$to_output = "overwrite!\n";
408
	}
409
	$static_output .= $to_output;
410
	update_output_window($static_output);
411
	/* install other package components */
412
	install_package_xml($package);
413
	$static_output .= "Writing configuration... ";
414
	update_output_window($static_output);
415
	write_config($changedesc);
416
	$static_output .= "done.";
417
	update_output_window($static_output);
418
}
419

    
420
function eval_once($toeval) {
421
	global $evaled;
422
	if(!$evaled) $evaled = array();
423
	$evalmd5 = md5($toeval);
424
	if(!in_array($evalmd5, $evaled)) {
425
		eval($toeval);
426
		$evaled[] = $evalmd5;
427
	}
428
	return;
429
}
430

    
431
function install_package_xml($pkg) {
432
	global $g, $config, $fd_log, $static_output;
433
	if(($pkgid = get_pkg_id($pkg)) == -1) {
434
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
435
		update_output_window($static_output);
436
		echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
437
		echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
438
		sleep(1);
439
		return;
440
	} else {
441
		$pkg_info = $config['installedpackages']['package'][$pkgid];
442
	}
443
	/* set up logging if needed */
444
	if(!$fd_log) {
445
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
446
			update_output_window("Warning, could not open log for writing.");
447
		}
448
	}
449

    
450
	/* set up package logging streams */
451
        if($pkg_info['logging']) {
452
                mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
453
                chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
454
                @fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
455
		mwexec("killall syslogd");
456
                system_syslogd_start();
457
        }
458

    
459
	/* make 'y' file */
460
        $fd = fopen("{$g['tmp_path']}/y", "w");
461
        for($line = 0; $line < 10; $line++) {
462
                fwrite($fd, "y\n");
463
        }
464
        fclose($fd);
465

    
466
	/* pkg_add the package and its dependencies */
467
        if($pkg_info['depends_on_package_base_url'] != "") {
468
                update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
469
                $static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
470
                $static_orig = $static_output;
471
                $static_output .= "\n";
472
                update_output_window($static_output);
473
                $pkg_name = substr(reverse_strrchr($pkg_info['depends_on_package'], "."), 0, -1);
474
                if(isset($pkg_info['skip_install_checks'])) {
475
                        $pkg_installed = true;
476
                } else {
477
                        $pkg_installed = is_freebsd_pkg_installed($pkg_name);
478
                }
479
                if($pkg_installed == false) pkg_fetch_recursive($pkg_name, $pkg_info['depends_on_package'], 0, $pkg_info['depends_on_package_base_url']);
480
                $static_output = $static_orig . "done.\nChecking for successful package installation... ";
481
                update_output_window($static_output);
482
                /* make sure our package was successfully installed */
483
                if($pkg_installed == false) $pkg_installed = is_freebsd_pkg_installed($pkg_name);
484
                if($pkg_installed == true) {
485
                        $static_output .= "done.\n";
486
                        update_output_window($static_output);
487
                        fwrite($fd_log, "pkg_add successfully completed.\n");
488
                } else {
489
                        $static_output .= "failed!\n\nInstallation aborted.";
490
                        update_output_window($static_output);
491
                        fwrite($fd_log, "Package WAS NOT installed properly.\n");
492
                        fclose($fd_log);
493
                        echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
494
                        echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
495
                        sleep(1);
496
                        die;
497
                }
498
        }
499

    
500
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
501
	if(file_exists("/usr/local/pkg/" . $configfile)) {
502
		$static_output .= "Loading package configuration... ";
503
		update_output_window($static_output);
504
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
505
		$static_output .= "done.\n";
506
		update_output_window($static_output);
507
		$static_output .= "Configuring package components...\n";
508
		update_output_window($static_output);
509
		/* modify system files */
510
		if($pkg_config['modify_system']['item'] <> "") {
511
			$static_output .= "\tSystem files... ";
512
			update_output_window($static_output);
513
			foreach($pkg_config['modify_system']['item'] as $ms) {
514
				if($ms['textneeded']) {
515
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
516
				}
517
			}
518
			$static_output .= "done.\n";
519
			update_output_window($static_output);
520
		}
521
		/* download additional files */
522
		if($pkg_config['additional_files_needed'] <> "") {
523
			$static_output .= "\tAdditional files... ";
524
			$static_orig = $static_output;
525
			update_output_window($static_output);
526
			foreach($pkg_config['additional_files_needed'] as $afn) {
527
				$filename = get_filename_from_url($afn['item'][0]);
528
				if($afn['chmod'] <> "") {
529
					$pkg_chmod = $afn['chmod'];
530
				} else {
531
					$pkg_chmod = "";
532
				}
533
				if($afn['prefix'] <> "") {
534
					$prefix = $afn['prefix'];
535
				} else {
536
					$prefix = "/usr/local/pkg/";
537
				}
538
				$static_output .= $filename . " ";
539
                                update_output_window($static_output);
540
				download_file_with_progress_bar($afn['item'][0], $prefix . $filename);
541
				if(stristr($filename, ".tgz") <> "") {
542
					fwrite($fd_log, "Extracting tarball to -C for " . $filename . "...\n");
543
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
544
					fwrite($fd_log, print_r($tarout, true) . "\n");
545
				}
546
				if($pkg_chmod <> "") {
547
					fwrite($fd_log, "Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
548
					chmod($prefix . $filename, $pkg_chmod);
549
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
550
				}
551
				$static_output = $static_orig;
552
                                update_output_window($static_output);
553
			}
554
			$static_output .= "done.\n";
555
			update_output_window($static_output);
556
		}
557
		/* sidebar items */
558
		if($pkg_config['menu'] != "") {
559
			$static_output .= "\tMenu items... ";
560
			update_output_window($static_output);
561
			if(is_array($pkg_config['menu'])) {
562
				foreach($pkg_config['menu'] as $menu) {
563
					if(is_array($config['installedpackages']['menu'])) {
564
						foreach($config['installedpackages']['menu'] as $amenu) {
565
							if($amenu['name'] == $menu['name']) continue 2;
566
						}
567
					}
568
					$config['installedpackages']['menu'][] = $menu;
569
				}
570
			}
571
			$static_output .= "done.\n";
572
			update_output_window($static_output);
573
		}
574
		/* services */
575
		if($pkg_config['service'] != "") {
576
			$static_output .= "\tServices... ";
577
			update_output_window($static_output);
578
			foreach($pkg_config['service'] as $service) {
579
				$config['installedpackages']['service'][] = $service;
580
			}
581
			$static_output .= "done.\n";
582
			update_output_window($static_output);
583
		}
584
		/* custom commands */
585
		$static_output .= "\tCustom commands... ";
586
		update_output_window($static_output);
587
		if($pkg_config['custom_php_global_functions'] <> "") {
588
			eval_once($pkg_config['custom_php_global_functions']);
589
		}
590
		if($pkg_config['custom_php_install_command']) {
591
			eval_once($pkg_config['custom_php_install_command']);
592
		}
593
		if($pkg_config['custom_php_resync_config_command'] <> "") {
594
                        eval_once($pkg_config['custom_php_resync_config_command']);
595
                }
596
		$static_output .= "done.\n";
597
		update_output_window($static_output);
598
	} else {
599
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
600
		update_output_window($static_output);
601
		fwrite($fd_log, "Unable to load package configuration. Installation aborted.\n");
602
                fclose($fd_log);
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
                sleep(1);
606
		return;
607
	}
608
}
609

    
610
function delete_package($pkg) {
611
	global $g, $config, $fd_log, $static_output;
612
	update_status("Removing package...");
613
	$static_output .= "Removing package... ";
614
	update_output_window($static_output);
615
	delete_package_recursive($pkg);
616
	$static_output .= "done.\n";
617
	update_output_window($static_output);
618
	return;
619
}
620

    
621
function delete_package_recursive($pkg) {
622
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
623
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
624
	exec("/bin/ls /var/db/pkg", $pkgdb);
625
	if(stristr($info[0], "can't find package") != false) return;
626
	foreach($info as $line) {
627
		$depend = trim(array_pop(explode(":", $line)));
628
		if(in_array($depend, $pkgdb)) delete_package_recursive($depend);
629
	}
630
	$fd = fopen("{$g['tmp_path']}/y", "w");
631
	for($line = 0; $line < 10; $line++) {
632
		fwrite($fd, "y\n");
633
	}
634
	fclose($fd);
635
	return;
636
}
637

    
638
function delete_package_xml($pkg) {
639
	global $g, $config, $fd_log, $static_output;
640
	if(($pkgid = get_pkg_id($pkg)) == -1) {
641
                $static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
642
                update_output_window($static_output);
643
                echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
644
                echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
645
                sleep(1);
646
                return;
647
        }
648
	/* set up logging if needed */
649
        if(!$fd_log) {
650
                if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
651
                        update_output_window("Warning, could not open log for writing.");
652
                }
653
        }
654
	update_status("Removing {$pkg} components...");
655
	fwrite($fd_log, "Removing {$pkg} package... ");
656
	$static_output .= "Removing {$pkg} components...\n";
657
	update_output_window($static_output);
658
	/* parse package configuration */
659
	$packages = &$config['installedpackages']['package'];
660
	$menus = &$config['installedpackages']['menu'];
661
	$services = &$config['installedpackages']['service'];
662
	if(file_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'])) {
663
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
664
		/* remove menu items */
665
		if(is_array($pkg_config['menu'])) {
666
			$static_output .= "\tMenu items... ";
667
			update_output_window($static_output);
668
			foreach($menus as $menu) $instmenus[] = $menu['name'];
669
			foreach($pkg_config['menu'] as $menu) {
670
				foreach($instmenus as $key => $instmenu) {
671
					if($instmenu == $menu['name']) unset($menus[$key]);
672
				}
673
			}
674
			$static_output .= "done.\n";
675
			update_output_window($static_output);
676
		}
677
		/* remove services */
678
		if(is_array($pkg_config['service'])) {
679
			$static_output .= "\tServices... ";
680
			update_output_window($static_output);
681
			foreach($services as $service) $instservices[] = $service['name'];
682
			foreach($pkg_config['service'] as $service) {
683
				foreach($instservices as $key => $instservice) {
684
					if($instservice == $service['name']) {
685
						stop_service($service['name']);
686
						unset($services[$key]);
687
					}
688
				}
689
			}
690
			$static_output .= "done.\n";
691
			update_output_window($static_output);
692
		}
693
		/* evalate this package's global functions and pre deinstall commands */
694
		if($pkg_config['custom_php_global_functions'] <> "")
695
			eval_once($pkg_config['custom_php_global_functions']);
696
		if($pkg_config['custom_php_pre_deinstall_command'] <> "") 
697
			eval_once($pkg_config['custom_php_pre_deinstall_command']);
698
		/* remove all additional files */
699
		if($pkg_config['additional_files_needed'] <> "") {
700
			$static_output .= "\tAuxiliary files... ";
701
			update_output_window($static_output);
702
			foreach($pkg_config['additional_files_needed'] as $afn) {
703
				$filename = get_filename_from_url($afn['item'][0]);
704
				if($afn['prefix'] <> "") {
705
					$prefix = $afn['prefix'];
706
				} else {
707
					$prefix = "/usr/local/pkg/";
708
				}
709
				unlink_if_exists($prefix . $filename);
710
				if(file_exists($prefix . $filename))
711
				    mwexec("rm -rf {$prefix}{$filename}");
712
			}
713
			$static_output .= "done.\n";
714
			update_output_window($static_output);
715
		}
716
		/* system files */
717
		if($pkg_config['modify_system']['item'] <> "") {
718
			$static_output .= "\tSystem files... ";
719
			update_output_window($static_output);
720
			foreach($pkg_config['modify_system']['item'] as $ms) {
721
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
722
			}
723
			$static_output .= "done.\n";
724
			update_output_window($static_output);
725
		}
726
		/* syslog */
727
		if($pkg_config['logging']['logfile_name'] <> "") {
728
			$static_output .= "\tSyslog entries... ";
729
			update_output_window($static_output);
730
			remove_text_from_file("/etc/syslog.conf", $pkg_config['logging']['facilityname'] . "\t\t\t\t" . $pkg_config['logging']['logfilename']);
731
			$static_output .= "done.\n";
732
			update_output_window($static_output);
733
		}
734
		/* deinstall commands */
735
		if($pkg_config['custom_php_deinstall_command'] <> "") {
736
			$static_output .= "\tDeinstall commands... ";
737
			update_output_window($static_output);
738
			eval_once($pkg_config['custom_php_deinstall_command']);
739
			$static_output .= "done.\n";
740
			update_output_window($static_output);
741
		}
742
		/* package XML file */
743
		$static_output .= "\tPackage XML... ";
744
		update_output_window($static_output);
745
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
746
		$static_output .= "done.\n";
747
		update_output_window($static_output);
748
	}
749
	/* remove config.xml entries */
750
	$static_output .= "\tConfiguration... ";
751
	update_output_window($static_output);
752
	unset($config['installedpackages']['package'][$pkgid]);
753
	$static_output .= "done.\n";
754
	update_output_window($static_output);
755
	write_config("Removed {$pkg} package.");
756
	/* file cleanup */
757
	$ctag = file("/etc/crontab");
758
	foreach($ctag as $line) {
759
		if(trim($line) != "") $towrite[] = $line;
760
	}
761
	$tmptab = fopen("/tmp/crontab", "w");
762
	foreach($towrite as $line) {
763
		fwrite($tmptab, $line);
764
	}
765
	fclose($tmptab);
766
	rename("/tmp/crontab", "/etc/crontab");
767
}
768

    
769
function expand_to_bytes($size) {
770
	$conv = array(
771
			"G" =>	"3",
772
			"M" =>  "2",
773
			"K" =>  "1",
774
			"B" =>  "0"
775
		);
776
	$suffix = substr($size, -1);
777
	if(!in_array($suffix, array_keys($conv))) return $size;
778
	$size = substr($size, 0, -1);
779
	for($i = 0; $i < $conv[$suffix]; $i++) {
780
		$size *= 1024;
781
	}
782
	return $size;
783
}
784

    
785
function get_pkg_db() {
786
	global $g;
787
	return return_dir_as_array($g['vardb_path'] . '/pkg');
788
}
789

    
790
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
791
	if(!$pkgdb) $pkgdb = get_pkg_db();
792
	if(!$alreadyseen) $alreadyseen = array();
793
	foreach($depend as $adepend) {
794
		$pkgname = reverse_strrchr($adepend['name'], '.');
795
		if(in_array($pkgname, $alreadyseen)) {
796
			continue;
797
		} elseif(!in_array($pkgname, $pkgdb)) {
798
			$size += expand_to_bytes($adepend['size']);
799
			$alreadyseen[] = $pkgname;
800
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
801
		} else {
802
			continue;
803
		}
804
	}
805
	return $size;
806
}
807

    
808
function get_package_install_size($pkg = 'all', $pkg_info = "") {
809
	global $config, $g;
810
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
811
	$pkgdb = get_pkg_db();
812
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
813
	foreach($pkg as $apkg) {
814
		if(!$pkg_info[$apkg]) continue;
815
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
816
	}
817
	return $toreturn;
818
}
819

    
820
function squash_from_bytes($size, $round = "") {
821
	$conv = array(1 => "B", "K", "M", "G");
822
	foreach($conv as $div => $suffix) {
823
		$sizeorig = $size;
824
		if(($size /= 1024) < 1) {
825
			if($round) {
826
				$sizeorig = round($sizeorig, $round);
827
			}
828
			return $sizeorig . $suffix;
829
		}
830
	}
831
	return;
832
}
833
?>
(14-14/25)