Project

General

Profile

Download (33 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
        exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
276
        $workingdir = preg_grep("/instmp/", $slaveout);
277
        $workingdir = $workingdir[0];
278
        $raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
279
        if($raw_depends_list != "") {
280
                if($pkgent['exclude_dependency'] != "")
281
                        $raw_depends_list = array_values(preg_grep($pkgent['exclude_dependency'], PREG_GREP_INVERT));
282
                foreach($raw_depends_list as $adepend) {
283
                        $working_depend = explode(" ", $adepend);
284
                        //$working_depend = explode("-", $working_depend[1]);
285
                        $depend_filename = $working_depend[1] . $pkg_extension;
286
                        if(is_freebsd_pkg_installed($working_depend[1]) === false) {
287
                                pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url);
288
                        } else {
289
//                              $dependlevel++;
290
                                $static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " ";
291
                                @fwrite($fd_log, $working_depend[1] . "\n");
292
                        }
293
                }
294
        }
295
        exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
296
        @fwrite($fd_log, $pkgname . " " . print_r($pkgaddout, true) . "\n");
297
        return true;
298
}
299

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

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

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

    
318
        curl_exec($ch);
319
        fclose($fout);
320
        curl_close($ch);
321

    
322
        return 1;
323
}
324

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

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

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

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

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

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

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

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

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

    
604
function delete_package($pkg) {
605
	global $g, $config, $fd_log, $static_output;
606
	update_status("Removing package...");
607
	$static_output .= "Removing package... ";
608
	update_output_window($static_output);
609
	delete_package_recursive($pkg);
610
	$static_output .= "done.\n";
611
	update_output_window($static_output);
612
	return;
613
}
614

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

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

    
760
function expand_to_bytes($size) {
761
	$conv = array(
762
			"G" =>	"3",
763
			"M" =>  "2",
764
			"K" =>  "1",
765
			"B" =>  "0"
766
		);
767
	$suffix = substr($size, -1);
768
	if(!in_array($suffix, array_keys($conv))) return $size;
769
	$size = substr($size, 0, -1);
770
	for($i = 0; $i < $conv[$suffix]; $i++) {
771
		$size *= 1024;
772
	}
773
	return $size;
774
}
775

    
776
function get_pkg_db() {
777
	global $g;
778
	return return_dir_as_array($g['vardb_path'] . '/pkg');
779
}
780

    
781
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
782
	if(!$pkgdb) $pkgdb = get_pkg_db();
783
	if(!$alreadyseen) $alreadyseen = array();
784
	foreach($depend as $adepend) {
785
		$pkgname = reverse_strrchr($adepend['name'], '.');
786
		if(in_array($pkgname, $alreadyseen)) {
787
			continue;
788
		} elseif(!in_array($pkgname, $pkgdb)) {
789
			$size += expand_to_bytes($adepend['size']);
790
			$alreadyseen[] = $pkgname;
791
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
792
		} else {
793
			continue;
794
		}
795
	}
796
	return $size;
797
}
798

    
799
function get_package_install_size($pkg = 'all', $pkg_info = "") {
800
	global $config, $g;
801
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
802
	$pkgdb = get_pkg_db();
803
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
804
	foreach($pkg as $apkg) {
805
		if(!$pkg_info[$apkg]) continue;
806
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
807
	}
808
	return $toreturn;
809
}
810

    
811
function squash_from_bytes($size, $round = "") {
812
	$conv = array(1 => "B", "K", "M", "G");
813
	foreach($conv as $div => $suffix) {
814
		$sizeorig = $size;
815
		if(($size /= 1024) < 1) {
816
			if($round) {
817
				$sizeorig = round($sizeorig, $round);
818
			}
819
			return $sizeorig . $suffix;
820
		}
821
	}
822
	return;
823
}
824
?>
(13-13/23)