Project

General

Profile

Download (32.9 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
	if(isset($pkg_config['nosync'])) continue;                                                          
233
	if($pkg['custom_php_global_functions'] <> "")            
234
	    eval($pkg['custom_php_global_functions']);
235
	if($pkg_config['custom_php_resync_config_command'] <> "")
236
	    eval($pkg_config['custom_php_resync_config_command']);
237
	if($sync_depends == true) {
238
	    $depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
239
	if(is_array($depends)) {
240
		foreach($depends as $item) {
241
					if(!file_exists("/usr/local/pkg" . $item)) {
242
						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);
243
					} else {
244
		                $item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
245
		                if(isset($item_config['nosync'])) continue;
246
		                if($item_config['custom_php_command_before_form'] <> "") {
247
		                    eval($item_config['custom_php_command_before_form']);
248
		                }
249
		                if($item_config['custom_php_resync_config_command'] <> "") {
250
		                    eval($item_config['custom_php_resync_config_command']);
251
		                }
252
		                if($show_message == true) print " " . $item_config['name'];
253
                  }
254
              }
255
          }
256
      }
257
    }
258
}
259

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

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

    
304
        /*
305
                Originally by Author: Keyvan Minoukadeh
306
                Modified by Scott Ullrich to return Content-Length size
307
        */
308

    
309
        $ch = curl_init();
310
        curl_setopt($ch, CURLOPT_URL, $url_file);
311
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
312
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
313
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
314

    
315
        curl_exec($ch);
316
        fclose($fout);
317
        curl_close($ch);
318

    
319
        return 1;
320
}
321

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

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

    
353
function install_package($package, $pkg_info = "") {
354
	global $g, $config, $pkg_interface, $fd_log, $static_output;
355
	/* open logfiles and begin installation */
356
	if(!$fd_log) {
357
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
358
			update_output_window("Warning, could not open log for writing.");
359
		}
360
	}
361
	@fwrite($fd_log, "Beginning package installation.\n");
362
	log_error('Beginning package installation for ' . $package . '.');
363
	update_status("Beginning package installation for " . $package . "...");
364
	/* fetch package information if needed */
365
	if(!$pkg_info or !is_array($pkg_info[$package])) {
366
		$pkg_info = get_pkg_info(array($package));
367
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
368
	}
369
	/* set up package logging streams */
370
	if($pkg_info['logging']) {
371
		mwexec("/usr/sbin/clog -i -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
372
		chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
373
		@fwrite($fd_log, "Adding text to file /etc/syslog.conf\n");
374
		system_syslogd_start();
375
	}
376
	/* fetch the package's configuration file */
377
	if($pkg_info['config_file'] != "") {
378
		$static_output .= "Downloading package configuration file... ";
379
		update_output_window($static_output);
380
		@fwrite($fd_log, "Downloading package configuration file...\n");
381
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
382
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
383
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
384
			@fwrite($fd_log, "ERROR! Unable to fetch package configuration file. Aborting installation.\n");
385
			if($pkg_interface == "console") {
386
				print "\nERROR! Unable to fetch package configuration file. Aborting package installation.\n";
387
				return;
388
			} else {
389
				$static_output .= "failed!\n\nInstallation aborted.";
390
				update_output_window($static_output);
391
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
392
			 	exit;
393
			}
394
		}
395
		$static_output .= "done.\n";
396
		update_output_window($static_output);
397
	}
398
	/* make 'y' file */
399
	$fd = fopen("{$g['tmp_path']}/y", "w");
400
	for($line = 0; $line < 10; $line++) {
401
		fwrite($fd, "y\n");
402
	}
403
	fclose($fd);
404

    
405
	/* pkg_add the package and its dependencies */
406
	if($pkg_info['depends_on_package_base_url'] != "") {
407
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
408
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
409
		$static_orig = $static_output;
410
		$static_output .= "\n";
411
		update_output_window($static_output);
412
		$pkg_name = substr(reverse_strrchr($pkg_info['depends_on_package'], "."), 0, -1);
413
		if(isset($pkg_info['skip_install_checks'])) {
414
			$pkg_installed = true;
415
		} else {
416
			$pkg_installed = is_freebsd_pkg_installed($pkg_name);
417
		}
418
		if($pkg_installed == false) pkg_fetch_recursive($pkg_name, $pkg_info['depends_on_package'], 0, $pkg_info['depends_on_package_base_url']);
419
		$static_output = $static_orig . "done.\nChecking for successful package installation... ";
420
		update_output_window($static_output);
421
		/* make sure our package was successfully installed */
422
		if($pkg_installed == false) $pkg_installed = is_freebsd_pkg_installed($pkg_name);
423
		if($pkg_installed == true) {
424
			$static_output .= "done.\n";
425
			update_output_window($static_output);
426
			fwrite($fd_log, "pkg_add successfully completed.\n");
427
		} else {
428
			$static_output .= "failed!\n\nInstallation aborted.";
429
			update_output_window($static_output);
430
			fwrite($fd_log, "Package WAS NOT installed properly.\n");
431
			fclose($fd_log);
432
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
433
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
434
			sleep(1);
435
			die;
436
		}
437
	}
438
	/* add package information to config.xml */
439
	$pkgid = get_pkg_id($pkg_info['name']);
440
	$static_output .= "Saving updated package information... ";
441
	update_output_window($static_output);
442
	if($pkgid == -1) {
443
		$config['installedpackages']['package'][] = $pkg_info;
444
		$changedesc = "Installed {$pkg_info['name']} package.";
445
		$to_output = "done.\n";
446
	} else {
447
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
448
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
449
		$to_output = "overwrite!\n";
450
	}
451
	$static_output .= $to_output;
452
	update_output_window($static_output);
453
	/* install other package components */
454
	install_package_xml($package);
455
	$static_output .= "Writing configuration... ";
456
	update_output_window($static_output);
457
	write_config($changedesc);
458
	$static_output .= "done.";
459
	update_output_window($static_output);
460
}
461

    
462
function eval_once($toeval) {
463
	global $evaled;
464
	if(!$evaled) $evaled = array();
465
	$evalmd5 = md5($toeval);
466
	if(!in_array($evalmd5, $evaled)) {
467
		eval($toeval);
468
		$evaled[] = $evalmd5;
469
	}
470
	return;
471
}
472
	
473

    
474
function install_package_xml($pkg) {
475
	global $g, $config, $fd_log, $static_output;
476
	if(($pkgid = get_pkg_id($pkg)) == -1) {
477
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
478
		update_output_window($static_output);
479
		echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
480
		echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
481
		sleep(1);
482
		return;
483
	} else {
484
		$pkg_info = $config['installedpackages']['package'][$pkgid];
485
	}
486
	/* set up logging if needed */
487
	if(!$fd_log) {
488
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
489
			update_output_window("Warning, could not open log for writing.");
490
		}
491
	}
492

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

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

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

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

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

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

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

    
798
function get_package_install_size($pkg = 'all', $pkg_info = "") {
799
	global $config, $g;
800
	if((!is_array($pkg)) and ($pkg != 'all')) $pkg = array($pkg);
801
	$pkgdb = get_pkg_db();
802
	if(!$pkg_info) $pkg_info = get_pkg_sizes($pkg);
803
	foreach($pkg as $apkg) {
804
		$size = 0;
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
?>
(12-12/21)