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
$g['platform'] = trim(file_get_contents("/etc/platform"));
43
if($g['platform'] == "pfSense") {
44
	safe_mkdir("/usr/local/pkg");
45
	safe_mkdir("/usr/local/pkg/pf");
46
}
47

    
48

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

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

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

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

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

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

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

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

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

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

    
312
        /*
313
                Originally by Author: Keyvan Minoukadeh
314
                Modified by Scott Ullrich to return Content-Length size
315
        */
316

    
317
        $ch = curl_init();
318
        curl_setopt($ch, CURLOPT_URL, $url_file);
319
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
320
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
321
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
322

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
788
function get_pkg_db() {
789
	global $g;
790
	return return_dir_as_array($g['vardb_path'] . '/pkg');
791
}
792

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

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

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