Project

General

Profile

Download (30.5 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

    
38
/* add package specific listtags to XML parser */
39
$listtags = array_merge($listtags, array("onetoone", "queue", "rule", "servernat", "alias", "additional_files_needed", "tab", "template", "menu", "rowhelperfield", "service", "step", "package", "columnitem", "option", "item", "field", "package"));
40

    
41
require_once("pfsense-utils.inc");
42
require_once("globals.inc");
43

    
44
safe_mkdir("/var/db/pkg");
45
safe_mkdir("/usr/local/pkg");
46
safe_mkdir("/usr/local/pkg/pf");
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['versioncheckpath'], $g['versioncheckbaseurl']);
99
        $resp = $cli->send($msg);
100
        $raw_versions = $resp->value();
101
	return xmlrpc_value_to_php($raw_versions);
102
}
103

    
104
/*
105
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
106
 * This function may also print output to the terminal indicating progress.
107
 */
108
function resync_all_package_configs($show_message = false) {
109
    global $config;
110
    $i = 0;
111
    log_error("Resyncing configuration for all packages.");
112
    if(!$config['installedpackages']['package']) return;
113
    if($show_message == true) print "Syncing packages:";
114
    foreach($config['installedpackages']['package'] as $package) {
115
        if($show_message == true) print " " . $package['name'];
116
        sync_package($i, true, true);
117
        $i++;
118
    }
119
    if($show_message == true) print ".\n";
120
}
121

    
122
/*
123
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
124
 *				package is installed.
125
 */
126
function is_freebsd_pkg_installed($pkg) {
127
	global $g;
128
	if(in_array($pkg, return_dir_as_array("{$g['vardb_path']}/pkg"))) return true;
129
	return false;
130
}
131

    
132
/*
133
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
134
 *
135
 * $filetype = "all" || ".xml", ".tgz", etc.
136
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
137
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
138
 *
139
 */
140
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
141
    global $config;                                                                             
142
    if(!is_numeric($pkg_name)) {
143
        $pkg_id = get_pkg_id($pkg_name);
144
        if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
145
    } else {                                                                                  
146
        if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
147
    }                                                                                                                                    
148
    $package = $config['installedpackages']['package'][$pkg_id];
149
    if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { // If the package's config file doesn't exist, log an error and fetch it.
150
        log_error("Fetching missing configuration XML for " . $package['name']);
151
        mwexec("/usr/bin/fetch -o /usr/local/pkg/" . $package['configurationfile'] . " http://www.pfsense.com/packages/config/" . $package['configurationfile']);
152
    }                                                                                                                                                            
153
    $pkg_xml = parse_xml_config("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
154
    if($pkg_xml['additional_files_needed'] != "") {                                                  
155
        foreach($pkg_xml['additional_files_needed'] as $item) {
156
            if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
157
            $depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
158
            $depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
159
            if (($filetype != "all") && (!preg_match("/${filetype}/i", $depend_file))) continue;
160
            if ($item['prefix'] != "") {
161
                $prefix = $item['prefix'];
162
            } else {
163
                $prefix = "/usr/local/pkg/";
164
            }
165
            if(!file_exists($prefix . $pkg_name)) {
166
                log_error("Fetching missing dependency (" . $depend_name . ") for " . $pkg_name);
167
                mwexec("/usr/local/bin/fetch -o " . $prefix . $depend_file . " " . $item['name']['0']);
168
                if($item['chmod'] != "")
169
                    chmod($prefix . $depend_file, $item['chmod']); // Handle chmods.
170
            }
171
            switch ($format) {
172
            case "files":
173
                $depends[] = $depend_file;
174
                break;
175
            case "names":
176
                switch ($filetype) {
177
                case "all":
178
                    if(preg_match("/\.xml/i", $depend_file)) {
179
                        $depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
180
                        $depends[] = $depend_xml['name'];
181
                        break;
182
                    } else {
183
                        $depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
184
                        break;
185
                    }
186
                case ".xml":
187
                    $depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
188
                    $depends[] = $depend_xml['name'];
189
                    break;
190
                default:
191
                    $depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
192
                    break;
193
                }
194
            }
195
        }
196
        return $depends;
197
    }
198
}
199

    
200
/*
201
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
202
 */
203
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
204
    global $config;
205

    
206
    if(!file_exists("/usr/local/pkg")) mwexec("/bin/mkdir -p /usr/local/pkg/pf");
207
    if(!$config['installedpackages']['package']) return;                         
208
    if(!is_numeric($pkg_name)) {                        
209
        $pkg_id = get_pkg_id($pkg_name);
210
        if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
211
    } else {                                                                                  
212
        $pkg_id = $pkg_name;
213
        if(!isset($config['installedpackages']['package'][$pkg_id]))
214
            return;  // No package belongs to the pkg_id passed to this function.
215
    }                                                                            
216
    $package = $config['installedpackages']['package'][$pkg_id];
217
    if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
218
        //if($show_message == true) print "(f)"; Don't mess with this until the package system has settled.
219
        log_error("Fetching missing configuration XML for " . $package['name']);
220
        mwexec("/usr/bin/fetch -o /usr/local/pkg/" . $package['configurationfile'] . " http://www.pfsense.com/packages/config/" . $package['configurationfile']);
221
    }                                                                                                                                                            
222
    $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
223
    if(isset($pkg_config['nosync'])) continue;                                                          
224
    //if($show_message == true) print "Syncing " . $pkg_name;
225
    if($pkg['custom_php_global_functions'] <> "")            
226
        eval($pkg['custom_php_global_functions']);
227
    if($pkg_config['custom_php_command_before_form'] <> "")
228
        eval($pkg_config['custom_php_command_before_form']);
229
    if($pkg_config['custom_php_resync_config_command'] <> "")
230
        eval($pkg_config['custom_php_resync_config_command']);
231
    if($sync_depends == true) {
232
        $depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
233
        if(is_array($depends)) {
234
            foreach($depends as $item) {
235
                $item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
236
                if(isset($item_config['nosync'])) continue;
237
                if($item_config['custom_php_command_before_form'] <> "") {
238
                    eval($item_config['custom_php_command_before_form']);
239
                }
240
                if($item_config['custom_php_resync_config_command'] <> "") {
241
                    eval($item_config['custom_php_resync_config_command']);
242
                }
243
                if($show_message == true) print " " . $item_config['name'];
244
            }
245
        }
246
    }
247
    // if($show_message == true) print ".";
248
}
249

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

    
289
function download_file_with_progress_bar($url_file, $destination_file) {
290
        global $ch, $fout, $file_size, $downloaded, $counter, $pkg_interface;
291
        $file_size  = 1;
292
        $downloaded = 1;
293
        /* open destination file */
294
        $fout = fopen($destination_file, "wb");
295

    
296
        /*
297
                Originally by Author: Keyvan Minoukadeh
298
                Modified by Scott Ullrich to return Content-Length size
299
        */
300

    
301
        $ch = curl_init();
302
        curl_setopt($ch, CURLOPT_URL, $url_file);
303
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
304
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'read_body');
305
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
306

    
307
        curl_exec($ch);
308
        fclose($fout);
309
        curl_close($ch);
310

    
311
        return 1;
312
}
313

    
314
function read_header($ch, $string) {
315
        global $file_size, $ch, $fout;
316
        $length = strlen($string);
317
        ereg("(Content-Length:) (.*)", $string, $regs);
318
        if($regs[2] <> "") {
319
                $file_size = intval($regs[2]);
320
        }
321
        return $length;
322
}
323

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

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

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

    
454
function install_package_xml($pkg) {
455
	global $g, $config, $fd_log, $static_output;
456
	if(($pkgid = get_pkg_id($pkg)) == -1) {
457
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
458
		update_output_window($static_output);
459
		echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
460
		echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
461
		sleep(1);
462
		return;
463
	} else {
464
		$pkg_info = $config['installedpackages']['package'][$pkgid];
465
	}
466
	/* set up logging if needed */
467
	if(!$fd_log) {
468
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
469
			update_output_window("Warning, could not open log for writing.");
470
		}
471
	}
472

    
473
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
474
	if(file_exists("/usr/local/pkg/" . $configfile)) {
475
		$static_output .= "Loading package configuration... ";
476
		update_output_window($static_output);
477
		$pkg_config = parse_xml_config("/usr/local/pkg/" . $configfile, "packagegui");
478
		$static_output .= "done.\n";
479
		update_output_window($static_output);
480
		$static_output .= "Configuring package components...\n";
481
		update_output_window($static_output);
482
		/* modify system files */
483
		if($pkg_config['modify_system']['item'] <> "") {
484
			$static_output .= "\tSystem files... ";
485
			update_output_window($static_output);
486
			foreach($pkg_config['modify_system']['item'] as $ms) {
487
				if($ms['textneeded']) {
488
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
489
				}
490
			}
491
			$static_output .= "done.\n";
492
			update_output_window($static_output);
493
		}
494
		/* download additional files */
495
		if($pkg_config['additional_files_needed'] <> "") {
496
			$static_output .= "\tAdditional files... ";
497
			$static_orig = $static_output;
498
			update_output_window($static_output);
499
			foreach($pkg_config['additional_files_needed'] as $afn) {
500
				$filename = get_filename_from_url($afn['item'][0]);
501
				if($afn['chmod'] <> "") {
502
					$pkg_chmod = $afn['chmod'];
503
				} else {
504
					$pkg_chmod = "";
505
				}
506
				if($afn['prefix'] <> "") {
507
					$prefix = $afn['prefix'];
508
				} else {
509
					$prefix = "/usr/local/pkg/";
510
				}
511
				$static_output .= $filename . " ";
512
                                update_output_window($static_output);
513
				download_file_with_progress_bar($afn['item'][0], $prefix . $filename);
514
				if(stristr($filename, ".tgz") <> "") {
515
					fwrite($fd_log, "Extracting tarball to -C for " . $filename . "...\n");
516
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C /", $tarout);
517
					fwrite($fd_log, print_r($tarout, true) . "\n");
518
				}
519
				if($pkg_chmod <> "") {
520
					fwrite($fd_log, "Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
521
					chmod($prefix . $filename, $pkg_chmod);
522
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
523
				}
524
				$static_output = $static_orig;
525
                                update_output_window($static_output);
526
			}
527
			$static_output .= "done.\n";
528
			update_output_window($static_output);
529
		}
530
		/* sidebar items */
531
		if($pkg_config['menu'] != "") {
532
			$static_output .= "\tMenu items... ";
533
			update_output_window($static_output);
534
			foreach($pkg_config['menu'] as $menu) {
535
				$config['installedpackages']['menu'][] = $menu;
536
			}
537
			$static_output .= "done.\n";
538
			update_output_window($static_output);
539
		}
540
		/* custom commands */
541
		if($pkg_config['custom_php_install_command'] <> "") {
542
			$static_output .= "\tCustom commands... ";
543
			update_output_window($static_output);
544
			if($pkg_config['custom_php_global_functions'] <> "") {
545
				eval($pkg_config['custom_php_global_functions']);
546
			}
547
			fwrite($fd_log, "Executing post install commands...\n");
548
			eval($pkg_config['custom_php_install_command']);
549
			$static_output .= "done.\n";
550
			update_output_window($static_output);
551
		}
552
		/* call our before form property since we may be declaring functions
553
		   in it that are called later */
554
		if($pkg_config['custom_php_command_before_form'] <> "") {
555
			eval($pkg_config['custom_php_command_before_form']);
556
		}
557
		/* call our resync function */
558
		if($pkg_config['custom_php_resync_config_command'] <> "") {
559
			eval($pkg_config['custom_php_resync_config_command']);
560
		}
561
	} else {
562
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
563
		update_output_window($static_output);
564
		fwrite($fd_log, "Unable to load package configuration. Installation aborted.\n");
565
                fclose($fd_log);
566
                echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
567
                echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
568
                sleep(1);
569
		return;
570
	}
571
}
572

    
573
function delete_package($pkg) {
574
	global $g, $config, $fd_log, $static_output;
575
	update_status("Removing package...");
576
	$static_output .= "Removing package... ";
577
	update_output_window($static_output);
578
	delete_package_recursive($pkg);
579
	$static_output .= "done.\n";
580
	update_output_window($static_output);
581
	return;
582
}
583

    
584
function delete_package_recursive($pkg) {
585
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
586
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
587
	exec("/bin/ls /var/db/pkg", $pkgdb);
588
	if(stristr($info[0], "can't find package") != false) return;
589
	foreach($info as $line) {
590
		$depend = trim(array_pop(explode(":", $line)));
591
		if(in_array($depend, $pkgdb)) delete_package_recursive($depend);
592
	}
593
	$fd = fopen("{$g['tmp_path']}/y", "w");
594
	for($line = 0; $line < 10; $line++) {
595
		fwrite($fd, "y\n");
596
	}
597
	fclose($fd);
598
	return;
599
}
600

    
601
function delete_package_xml($pkg) {
602
	global $g, $config, $fd_log, $static_output;
603
	if(($pkgid = get_pkg_id($pkg)) == -1) {
604
                $static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
605
                update_output_window($static_output);
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
	/* set up logging if needed */
612
        if(!$fd_log) {
613
                if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
614
                        update_output_window("Warning, could not open log for writing.");
615
                }
616
        }
617
	update_status("Removing {$pkg} components...");
618
	fwrite($fd_log, "Removing {$pkg} package... ");
619
	$static_output .= "Removing {$pkg} components...\n";
620
	update_output_window($static_output);
621
	/* parse package configuration */
622
	$packages = &$config['installedpackages']['package'];
623
	$menus = &$config['installedpackages']['menu'];
624
	if(file_exists("/usr/local/pkg" . $packages[$pkgid]['configurationfile'])) {
625
		$pkg_config = parse_xml_config("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
626
		/* remove menu items */
627
		if(is_array($pkg_config['menu'])) {
628
			$static_output .= "\tMenu items... ";
629
			update_output_window($static_output);
630
			foreach($menus as $menu) $instmenus[] = $menu['name'];
631
			foreach($pkg_config['menu'] as $menu) {
632
				foreach($instmenus as $key => $instmenu) {
633
					if($instmenu == $menu['name']) unset($menus[$key]);
634
				}
635
			}
636
			$static_output .= "done.\n";
637
			update_output_window($static_output);
638
		}
639
		/* evalate this package's global functions and pre deinstall commands */
640
		if($pkg_config['custom_php_global_functions'] <> "")
641
			eval($pkg_config['custom_php_global_functions']);
642
		if($pkg_config['custom_php_pre_deinstall_command'] <> "") 
643
			eval($pkg_config['custom_php_pre_deinstall_command']);
644
		/* remove all additional files */
645
		if($pkg_config['additional_files_needed'] <> "") {
646
			$static_output .= "\tAuxiliary files... ";
647
			update_output_window($static_output);
648
			foreach($pkg_config['additional_files_needed'] as $afn) {
649
				$filename = get_filename_from_url($afn['item'][0]);
650
				if($afn['prefix'] <> "") {
651
					$prefix = $afn['prefix'];
652
				} else {
653
					$prefix = "/usr/local/pkg/";
654
				}
655
				unlink_if_exists($prefix . $filename);
656
				if(file_exists($prefix . $filename))
657
				    mwexec("rm -rf {$prefix}{$filename}");
658
			}
659
			$static_output .= "done.\n";
660
			update_output_window($static_output);
661
		}
662
		/* system files */
663
		if($pkg_config['modify_system']['item'] <> "") {
664
			$static_output .= "\tSystem files... ";
665
			update_output_window($static_output);
666
			foreach($pkg_config['modify_system']['item'] as $ms) {
667
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
668
			}
669
			$static_output .= "done.\n";
670
			update_output_window($static_output);
671
		}
672
		/* syslog */
673
		if($pkg_config['logging']['logfile_name'] <> "") {
674
			$static_output .= "\tSyslog entries... ";
675
			update_output_window($static_output);
676
			remove_text_from_file("/etc/syslog.conf", $pkg_config['logging']['facilityname'] . "\t\t\t\t" . $pkg_config['logging']['logfilename']);
677
			$static_output .= "done.\n";
678
			update_output_window($static_output);
679
		}
680
		/* deinstall commands */
681
		if($pkg_config['custom_php_deinstall_command'] <> "") {
682
			$static_output .= "\tDeinstall commands... ";
683
			update_output_window($static_output);
684
			eval($pkg_config['custom_php_deinstall_command']);
685
			$static_output .= "done.\n";
686
			update_output_window($static_output);
687
		}
688
	}
689
	/* remove config.xml entries */
690
	$static_output .= "\tConfiguration... ";
691
	update_output_window($static_output);
692
	unset($config['installedpackages']['package'][$pkgid]);
693
	$static_output .= "done.\n";
694
	update_output_window($static_output);
695
	write_config("Removed {$pkg} package.");
696
	/* file cleanup */
697
	$ctag = file("/etc/crontab");
698
	foreach($ctag as $line) {
699
		if(trim($line) != "") $towrite[] = $line;
700
	}
701
	$tmptab = fopen("/tmp/crontab", "w");
702
	foreach($towrite as $line) {
703
		fwrite($tmptab, $line);
704
	}
705
	fclose($tmptab);
706
	rename("/tmp/crontab", "/etc/crontab");
707
}
708
?>
(11-11/19)