Project

General

Profile

Download (30.8 KB) Statistics
| Branch: | Tag: | Revision:
1 7597c8e8 Colin Smith
<?php
2 8c6516d1 Colin Smith
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6 33b7cc0d Colin Smith
 *   This file contains various functions used by the pfSense package system.
7 8c6516d1 Colin Smith
 * 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 33b7cc0d Colin Smith
require_once("xmlrpc.inc");
36 7597c8e8 Colin Smith
require_once("xmlparse.inc");
37
38
/* add package specific listtags to XML parser */
39 fd371d6d Colin Smith
$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 7597c8e8 Colin Smith
41
require_once("pfsense-utils.inc");
42
require_once("globals.inc");
43 33b7cc0d Colin Smith
44 7597c8e8 Colin Smith
safe_mkdir("/var/db/pkg");
45
safe_mkdir("/usr/local/pkg");
46
safe_mkdir("/usr/local/pkg/pf");
47 33b7cc0d Colin Smith
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 8c6516d1 Colin Smith
function is_package_installed($packagename) {
60 33b7cc0d Colin Smith
	$pkg = get_pkg_id($packagename);
61
	if($pkg == -1) return false;
62
	return true;
63 8c6516d1 Colin Smith
}
64
            
65 33b7cc0d Colin Smith
/****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 8c6516d1 Colin Smith
function get_pkg_id($pkg_name) {
74
    global $config;
75
    if(is_array($config['installedpackages']['package'])) {
76
        $i = 0;
77 33b7cc0d Colin Smith
        foreach($config['installedpackages']['package'] as $pkg) {
78 8c6516d1 Colin Smith
            if($pkg['name'] == $pkg_name) return $i;
79
            $i++;
80
        }
81
    }
82
    return -1;
83
}
84
85 33b7cc0d Colin Smith
/****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 7597c8e8 Colin Smith
	global $g;
96 33b7cc0d Colin Smith
        $params = array("pkg" => $pkgs, "info" => $info);
97
        $msg = new XML_RPC_Message('pfsense.get_pkgs', array(php_value_to_xmlrpc($params)));
98 7597c8e8 Colin Smith
        $cli = new XML_RPC_Client($g['versioncheckpath'], $g['versioncheckbaseurl']);
99 33b7cc0d Colin Smith
        $resp = $cli->send($msg);
100
        $raw_versions = $resp->value();
101 7597c8e8 Colin Smith
	return xmlrpc_value_to_php($raw_versions);
102 8c6516d1 Colin Smith
}
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 7597c8e8 Colin Smith
/*
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 8c6516d1 Colin Smith
/*
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 7597c8e8 Colin Smith
        $pkg_id = get_pkg_id($pkg_name);
144 8c6516d1 Colin Smith
        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 7597c8e8 Colin Smith
    $pkg_xml = parse_xml_config("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
154 8c6516d1 Colin Smith
    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 7597c8e8 Colin Smith
/*
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 8c6516d1 Colin Smith
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = 'http://ftp2.freebsd.org/pub/FreeBSD/ports/i386/packages-5.4-release/Latest') {
257 f1853637 Colin Smith
        global $pkgent, $static_status, $static_output, $g, $pkg_interface, $fd_log;
258 8c6516d1 Colin Smith
        $pkg_extension = strrchr($filename, '.');
259
        $static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
260
        $fetchto = "/tmp/apkg_" . $pkgname . $pkg_extension;
261 7597c8e8 Colin Smith
	download_file_with_progress_bar($base_url . '/' . $filename, $fetchto);
262 8c6516d1 Colin Smith
//      update_output_window($static_output . "\n\n" . $pkg_progress);
263 f8a52ee0 Colin Smith
        exec("/usr/bin/tar -O -f {$fetchto} -x +CONTENTS", $slaveout);
264 8c6516d1 Colin Smith
        $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 7597c8e8 Colin Smith
                        if(is_freebsd_pkg_installed($working_depend[1]) === false) {
276 8c6516d1 Colin Smith
                                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 f8a52ee0 Colin Smith
                                @fwrite($fd_log, $working_depend[1] . "\n");
281 8c6516d1 Colin Smith
                        }
282
                }
283
        }
284
        exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
285 f8a52ee0 Colin Smith
        @fwrite($fd_log, $pkgname . " " . print_r($pkgaddout, true) . "\n");
286 8c6516d1 Colin Smith
        return true;
287
}
288
289
function download_file_with_progress_bar($url_file, $destination_file) {
290 f1853637 Colin Smith
        global $ch, $fout, $file_size, $downloaded, $counter, $pkg_interface;
291 8c6516d1 Colin Smith
        $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 f1853637 Colin Smith
        global $fout, $file_size, $downloaded, $counter, $sendto, $static_output, $lastseen, $pkg_interface;
326 8c6516d1 Colin Smith
        $length = strlen($string);
327
        $downloaded += intval($length);
328
        $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
329
        $downloadProgress = 100 - $downloadProgress;
330 f1853637 Colin Smith
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
331 8c6516d1 Colin Smith
                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 f8a52ee0 Colin Smith
	fwrite($fout, $string);
342
	return $length;
343 8c6516d1 Colin Smith
}
344 7597c8e8 Colin Smith
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 407bf67a Colin Smith
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
350 7597c8e8 Colin Smith
			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 16a5dc45 Colin Smith
	update_status("Beginning package installation for " . $package . "...");
356 7597c8e8 Colin Smith
	/* 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 89b7daa9 Colin Smith
	/* 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 7597c8e8 Colin Smith
	/* 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 859d9733 Colin Smith
		$pkg_name = substr(reverse_strrchr($pkg_info['depends_on_package'], "."), 0, -1);
406 7597c8e8 Colin Smith
		if(isset($pkg_info['skip_install_checks'])) {
407
			$pkg_installed = true;
408
		} else {
409 859d9733 Colin Smith
			$pkg_installed = is_freebsd_pkg_installed($pkg_name);
410 7597c8e8 Colin Smith
		}
411 859d9733 Colin Smith
		if($pkg_installed == false) pkg_fetch_recursive($pkg_name, $pkg_info['depends_on_package'], 0, $pkg_info['depends_on_package_base_url']);
412 7597c8e8 Colin Smith
		$static_output = $static_orig . "done.\nChecking for successful package installation... ";
413
		update_output_window($static_output);
414
		/* make sure our package was successfully installed */
415 859d9733 Colin Smith
		if($pkg_installed == false) $pkg_installed = is_freebsd_pkg_installed($pkg_name);
416 7597c8e8 Colin Smith
		if($pkg_installed == true) {
417
			$static_output .= "done.\n";
418
			update_output_window($static_output);
419
			fwrite($fd_log, "pkg_add successfully completed.\n");
420
		} else {
421
			$static_output .= "failed!\n\nInstallation aborted.";
422
			update_output_window($static_output);
423
			fwrite($fd_log, "Package WAS NOT installed properly.\n");
424
			fclose($fd_log);
425
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
426
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
427
			sleep(1);
428
			die;
429
		}
430
	}
431
	/* add package information to config.xml */
432
	$pkgid = get_pkg_id($pkg_info['name']);
433
	$static_output .= "Saving updated package information... ";
434
	update_output_window($static_output);
435
	if($pkgid == -1) {
436
		$config['installedpackages']['package'][] = $pkg_info;
437
		$changedesc = "Installed {$pkg_info['name']} package.";
438
		$to_output = "done.\n";
439
	} else {
440
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
441
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
442
		$to_output = "overwrite!\n";
443
	}
444
	$static_output .= $to_output;
445
	update_output_window($static_output);
446
	/* install other package components */
447
	install_package_xml($package);
448 6ae2ac8d Colin Smith
	$static_output .= "Writing configuration... ";
449
	update_output_window($static_output);
450 7597c8e8 Colin Smith
	write_config($changedesc);
451 407bf67a Colin Smith
	$static_output .= "done.";
452 6ae2ac8d Colin Smith
	update_output_window($static_output);
453 7597c8e8 Colin Smith
}
454
455
function install_package_xml($pkg) {
456
	global $g, $config, $fd_log, $static_output;
457
	if(($pkgid = get_pkg_id($pkg)) == -1) {
458
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
459
		update_output_window($static_output);
460
		echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
461
		echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
462
		sleep(1);
463 3f01fe47 Colin Smith
		return;
464 7597c8e8 Colin Smith
	} else {
465
		$pkg_info = $config['installedpackages']['package'][$pkgid];
466
	}
467
	/* set up logging if needed */
468
	if(!$fd_log) {
469 407bf67a Colin Smith
		if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
470 7597c8e8 Colin Smith
			update_output_window("Warning, could not open log for writing.");
471
		}
472
	}
473
474
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
475
	if(file_exists("/usr/local/pkg/" . $configfile)) {
476
		$static_output .= "Loading package configuration... ";
477
		update_output_window($static_output);
478
		$pkg_config = parse_xml_config("/usr/local/pkg/" . $configfile, "packagegui");
479
		$static_output .= "done.\n";
480
		update_output_window($static_output);
481
		$static_output .= "Configuring package components...\n";
482
		update_output_window($static_output);
483
		/* modify system files */
484
		if($pkg_config['modify_system']['item'] <> "") {
485
			$static_output .= "\tSystem files... ";
486
			update_output_window($static_output);
487
			foreach($pkg_config['modify_system']['item'] as $ms) {
488
				if($ms['textneeded']) {
489
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
490
				}
491
			}
492
			$static_output .= "done.\n";
493
			update_output_window($static_output);
494
		}
495
		/* download additional files */
496
		if($pkg_config['additional_files_needed'] <> "") {
497
			$static_output .= "\tAdditional files... ";
498
			$static_orig = $static_output;
499
			update_output_window($static_output);
500
			foreach($pkg_config['additional_files_needed'] as $afn) {
501
				$filename = get_filename_from_url($afn['item'][0]);
502
				if($afn['chmod'] <> "") {
503
					$pkg_chmod = $afn['chmod'];
504
				} else {
505
					$pkg_chmod = "";
506
				}
507
				if($afn['prefix'] <> "") {
508
					$prefix = $afn['prefix'];
509
				} else {
510
					$prefix = "/usr/local/pkg/";
511
				}
512
				$static_output .= $filename . " ";
513
                                update_output_window($static_output);
514
				download_file_with_progress_bar($afn['item'][0], $prefix . $filename);
515
				if(stristr($filename, ".tgz") <> "") {
516
					fwrite($fd_log, "Extracting tarball to -C for " . $filename . "...\n");
517
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C /", $tarout);
518
					fwrite($fd_log, print_r($tarout, true) . "\n");
519
				}
520
				if($pkg_chmod <> "") {
521
					fwrite($fd_log, "Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
522
					chmod($prefix . $filename, $pkg_chmod);
523
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
524
				}
525
				$static_output = $static_orig;
526
                                update_output_window($static_output);
527
			}
528
			$static_output .= "done.\n";
529
			update_output_window($static_output);
530
		}
531
		/* sidebar items */
532
		if($pkg_config['menu'] != "") {
533
			$static_output .= "\tMenu items... ";
534
			update_output_window($static_output);
535
			foreach($pkg_config['menu'] as $menu) {
536
				$config['installedpackages']['menu'][] = $menu;
537
			}
538
			$static_output .= "done.\n";
539
			update_output_window($static_output);
540
		}
541
		/* custom commands */
542
		if($pkg_config['custom_php_install_command'] <> "") {
543
			$static_output .= "\tCustom commands... ";
544
			update_output_window($static_output);
545
			if($pkg_config['custom_php_global_functions'] <> "") {
546
				eval($pkg_config['custom_php_global_functions']);
547
			}
548
			fwrite($fd_log, "Executing post install commands...\n");
549
			eval($pkg_config['custom_php_install_command']);
550
			$static_output .= "done.\n";
551
			update_output_window($static_output);
552
		}
553 33ef3f7c Scott Ullrich
		/* call our before form property since we may be declaring functions
554
		   in it that are called later */
555
		if($pkg_config['custom_php_command_before_form'] <> "") {
556
			eval($pkg_config['custom_php_command_before_form']);
557
		}
558 149dbafd Scott Ullrich
		/* call our resync function */
559
		if($pkg_config['custom_php_resync_config_command'] <> "") {
560
			eval($pkg_config['custom_php_resync_config_command']);
561
		}
562 7597c8e8 Colin Smith
	} else {
563
		$static_output .= "Loading package configuration... failed!\n\nInstallation aborted.";
564
		update_output_window($static_output);
565
		fwrite($fd_log, "Unable to load package configuration. Installation aborted.\n");
566
                fclose($fd_log);
567
                echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
568
                echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
569
                sleep(1);
570 3f01fe47 Colin Smith
		return;
571 7597c8e8 Colin Smith
	}
572
}
573 407bf67a Colin Smith
574 62c55268 Colin Smith
function delete_package($pkg) {
575
	global $g, $config, $fd_log, $static_output;
576
	update_status("Removing package...");
577
	$static_output .= "Removing package... ";
578
	update_output_window($static_output);
579
	delete_package_recursive($pkg);
580
	$static_output .= "done.\n";
581
	update_output_window($static_output);
582
	return;
583
}
584
585 249a6b95 Colin Smith
function delete_package_recursive($pkg) {
586 62c55268 Colin Smith
	exec("/usr/sbin/pkg_info -r " . $pkg . " 2>&1", $info);
587 249a6b95 Colin Smith
	exec("cat {$g['tmp_path']}/y | /usr/sbin/pkg_delete " . $pkg ." > /dev/null 2>&1");
588
	exec("/bin/ls /var/db/pkg", $pkgdb);
589 407bf67a Colin Smith
	if(stristr($info[0], "can't find package") != false) return;
590
	foreach($info as $line) {
591 249a6b95 Colin Smith
		$depend = trim(array_pop(explode(":", $line)));
592
		if(in_array($depend, $pkgdb)) delete_package_recursive($depend);
593 407bf67a Colin Smith
	}
594 62c55268 Colin Smith
	$fd = fopen("{$g['tmp_path']}/y", "w");
595
	for($line = 0; $line < 10; $line++) {
596
		fwrite($fd, "y\n");
597
	}
598
	fclose($fd);
599 407bf67a Colin Smith
	return;
600
}
601
602
function delete_package_xml($pkg) {
603
	global $g, $config, $fd_log, $static_output;
604
	if(($pkgid = get_pkg_id($pkg)) == -1) {
605 62c55268 Colin Smith
                $static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
606 407bf67a Colin Smith
                update_output_window($static_output);
607
                echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
608
                echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
609
                sleep(1);
610 3f01fe47 Colin Smith
                return;
611 407bf67a Colin Smith
        }
612
	/* set up logging if needed */
613
        if(!$fd_log) {
614
                if(!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$pkg}.log", "w")) {
615
                        update_output_window("Warning, could not open log for writing.");
616
                }
617
        }
618 62c55268 Colin Smith
	update_status("Removing {$pkg} components...");
619 407bf67a Colin Smith
	fwrite($fd_log, "Removing {$pkg} package... ");
620 62c55268 Colin Smith
	$static_output .= "Removing {$pkg} components...\n";
621 407bf67a Colin Smith
	update_output_window($static_output);
622
	/* parse package configuration */
623
	$packages = &$config['installedpackages']['package'];
624
	$menus = &$config['installedpackages']['menu'];
625 b783468f Colin Smith
	if(file_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'])) {
626 3f01fe47 Colin Smith
		$pkg_config = parse_xml_config("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
627
		/* remove menu items */
628
		if(is_array($pkg_config['menu'])) {
629
			$static_output .= "\tMenu items... ";
630
			update_output_window($static_output);
631
			foreach($menus as $menu) $instmenus[] = $menu['name'];
632
			foreach($pkg_config['menu'] as $menu) {
633
				foreach($instmenus as $key => $instmenu) {
634
					if($instmenu == $menu['name']) unset($menus[$key]);
635
				}
636 407bf67a Colin Smith
			}
637 3f01fe47 Colin Smith
			$static_output .= "done.\n";
638
			update_output_window($static_output);
639 407bf67a Colin Smith
		}
640 3f01fe47 Colin Smith
		/* evalate this package's global functions and pre deinstall commands */
641
		if($pkg_config['custom_php_global_functions'] <> "")
642
			eval($pkg_config['custom_php_global_functions']);
643
		if($pkg_config['custom_php_pre_deinstall_command'] <> "") 
644
			eval($pkg_config['custom_php_pre_deinstall_command']);
645
		/* remove all additional files */
646
		if($pkg_config['additional_files_needed'] <> "") {
647
			$static_output .= "\tAuxiliary files... ";
648
			update_output_window($static_output);
649
			foreach($pkg_config['additional_files_needed'] as $afn) {
650
				$filename = get_filename_from_url($afn['item'][0]);
651
				if($afn['prefix'] <> "") {
652
					$prefix = $afn['prefix'];
653
				} else {
654
					$prefix = "/usr/local/pkg/";
655
				}
656
				unlink_if_exists($prefix . $filename);
657 05ac89d8 Scott Ullrich
				if(file_exists($prefix . $filename))
658
				    mwexec("rm -rf {$prefix}{$filename}");
659 3f01fe47 Colin Smith
			}
660
			$static_output .= "done.\n";
661
			update_output_window($static_output);
662
		}
663
		/* system files */
664
		if($pkg_config['modify_system']['item'] <> "") {
665
			$static_output .= "\tSystem files... ";
666
			update_output_window($static_output);
667
			foreach($pkg_config['modify_system']['item'] as $ms) {
668
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
669 407bf67a Colin Smith
			}
670 3f01fe47 Colin Smith
			$static_output .= "done.\n";
671
			update_output_window($static_output);
672 407bf67a Colin Smith
		}
673 3f01fe47 Colin Smith
		/* syslog */
674
		if($pkg_config['logging']['logfile_name'] <> "") {
675
			$static_output .= "\tSyslog entries... ";
676
			update_output_window($static_output);
677
			remove_text_from_file("/etc/syslog.conf", $pkg_config['logging']['facilityname'] . "\t\t\t\t" . $pkg_config['logging']['logfilename']);
678
			$static_output .= "done.\n";
679
			update_output_window($static_output);
680 407bf67a Colin Smith
		}
681 644d2d59 Colin Smith
		/* deinstall commands */
682
		if($pkg_config['custom_php_deinstall_command'] <> "") {
683
			$static_output .= "\tDeinstall commands... ";
684
			update_output_window($static_output);
685
			eval($pkg_config['custom_php_deinstall_command']);
686
			$static_output .= "done.\n";
687
			update_output_window($static_output);
688
		}
689 047c40c4 Colin Smith
		/* package XML file */
690
		$static_output .= "\tPackage XML... ";
691
		update_output_window($static_output);
692
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
693
		$static_output .= "done.\n";
694
		update_output_window($static_output);
695 407bf67a Colin Smith
	}
696
	/* remove config.xml entries */
697
	$static_output .= "\tConfiguration... ";
698
	update_output_window($static_output);
699
	unset($config['installedpackages']['package'][$pkgid]);
700
	$static_output .= "done.\n";
701
	update_output_window($static_output);
702 62c55268 Colin Smith
	write_config("Removed {$pkg} package.");
703 407bf67a Colin Smith
	/* file cleanup */
704
	$ctag = file("/etc/crontab");
705
	foreach($ctag as $line) {
706
		if(trim($line) != "") $towrite[] = $line;
707
	}
708
	$tmptab = fopen("/tmp/crontab", "w");
709
	foreach($towrite as $line) {
710
		fwrite($tmptab, $line);
711
	}
712
	fclose($tmptab);
713
	rename("/tmp/crontab", "/etc/crontab");
714
}
715 7597c8e8 Colin Smith
?>