Location: PHPKode > scripts > WSN Links > autosetup/autosetup.php
<?php

$tweaksdata = ''; // list tweaks to include -- tweaks.php without the opening and closing tags, and with any needed escaping

if (isset($_GET['defaultscript'])) $defaultscript = $_GET['defaultscript'];
else $defaultscript = 'wsnlinks';
$prefix = $defaultscript.'_'; // default tables prefix
$ourfilename = 'autosetup.php';
$defaultemail = '';

$scriptname = getscripttitle($defaultscript); // don't know why we assign title to name but we do at first and then change back later

// Begin translation area:
$lang['welcomeemailsubject'] = "{SCRIPTTITLE} Installation";
$lang['welcomeemailbody'] = "Congratulations, you've just installed {SCRIPTTITLE}!

Guided start: {DIRURL}/{ADMINDIR}/guided.php
Admin panel: {DIRURL}/{ADMINDIR}/
Front end: {DIRURL}/

Here's an introductory guide which will help you get started: http://scripts.webmastersite.net/{SCRIPTSITEPATHBIT}/manual.html

If you have any questions or encounter any problems, please contact support by clicking the 'Support' menu option in the admin panel. {TRIALBIT}";
$lang['welcomeemailbodytrial'] = "Even as a trial user you can still get support.

Your trial lasts 30 days. When you're ready to buy, go here: {PURCHASELINK}
If you need more time to evaluate, contact support to request an extension.
";
$lang['windowspermissions'] = "<p>PHP needs write access to the directory which autosetup.php is in (and the directory WSN is being installed to, if different). Since you're running a Microsoft Windows server that doesn't support chmod and is configured to run PHP under a different user than your FTP user, you need to contact your web host and ask them to give PHP's user write permissions to this directory.</p>
<p><a href=\"$ourfilename\">Go Back and Try Again</a></p>";
$lang['incorrectcustomerlogin'] = "<p>The customer login you typed is incorrect. You need to type the same customer email and password which you use to login to the downloads area which you got this autosetup.php from.</p>";
$lang['dirused'] = "<p>You already have an index file at that location. If it's a WSN install and you want to replace it, uninstall it first by visiting <a href=\"{DIRURL}/admin/uninstall.php\">{DIRURL}/admin/uninstall.php</a>.</p>";
$lang['prefixused'] = "<p>You already have a WSN installation in that database using that tables prefix. If you want to replace it, uninstall it first by visiting admin/uninstall.php.</p>";
$lang['pleasechmod'] = "<p>Please CHMOD 777 the installation location (or its parent if it doesn't exist yet), as well as  the directory you've placed autosetup.php in (if different). If you don't know how to do this, ask your web host to help you give full write permissions to the directory.</p><p><a href=\"$ourfilename\">Go Back and Try Again</a></p>";
$lang['installfailed'] = "<p>Installation could not complete, some of the information you provided seems to have been invalid. Please select one of following ways to proceed:</p>
<ul>
<li>Go back and <a href=\"".$ourfilename."\">try again</a>.</li>
<li>Get <a href=\"{INSTALLFORM}\">free professional installation</a>.</li>
<li>Get in touch with <a href=\"{SUPPORTURL}\">support</a>.</p>
</ul>
";
$lang['oldphp5'] = "<p>This server is running an extremely old version of PHP -- at least six years out of date -- which is vulnerable to intrusion. WSN no longer supports this version since it's an open invitation to hackers.</p>";
$lang['oldphp'] = "<p>WSN requires PHP 5.2.3 or newer. Your web server defaults to PHP 4, an extremely old and long-depreciated version of PHP. You need to enable PHP 5. The method to do this varies by web host, so you should really talk to your web host, but on most hosts one of the following methods will work. Add an .htaccess file containing <b>one</b> of the following lines to the directory above where you plan to install WSN, or just to the root directory of your site:</p>
<ul>
<li>AddType x-mapp-php5 .php</i>
<li>AddHandler application/x-httpd-php5 .php</li>
<li>AddHandler cgi-php5 .php</li>
</ul>
<p>Save the first line (AddType x-mapp-php5 .php) to a .htaccess file, then come back and check if PHP 5 has been enabled. If it hasn't, go back and replace that line with the second line. Check again, and if it still doesn't work try the third line. If nothing works, and your host won't do it for you either, your web host has been asleep since 2004 and it's time to move on.</p>";
$lang['bug'] = "There was an issue with attempting to download the software, the WSN downloads area seems to not be functioning properly. Please contact support.";
$lang['passtext'] = "<font color=\"#00AA00\">optimal</font>";
$lang['partialtext'] = "<font color=\"#bbbb00\">acceptable but not optimal</font>";
$lang['failtext'] = "<font color=\"#AA0000\">fail</font>";
$lang['pagetitle'] = "Server Test";
$lang['bufftext'] = "Output buffering";
$lang['phptext'] = "PHP version";
$lang['mysqltext'] = "MySQL version";
$lang['mysqlbadlogin'] = "<p>The MySQL login username and password combo you typed were incorrect. Perhaps you've forgotten the prefix which goes before all the names you create.</p>";
$lang['mysqlbadserver'] = "<p>There's no MySQL server on the specified host. Please check the host name you typed.</p>";
$lang['oldmysql'] = "MySQL 4.1 or newer is required. You have {YOURVERSION}.";
$lang['mysqlworked'] = "<p>Access to the database was established. Everything is good.</p>";
$lang['mysqldbissue'] = "<p>The connection was established, but access to the database was denied. You've probably forgotten to grant the user access to the database in your hosting control panel.</p>";
$lang['gdtext'] = "GD";
$congratstext = "<p>This server meets all the recommendations.</p>";
$lang['toobadtext'] = "<p>Some changes need to be made before you can install $scriptname:</p>";
$lang['gdexplain'] = "If you know that you have ImageMagick available on your server, do not worry about not having GD -- you only need one or the other, not both. If you do not have ImageMagick, then you will need to install it before you can use the thumbnail and image editing features of WSN Gallery. Most hosts should be willing to install ImageMagick on request if they do not already have it. If your host refuses, ImageMagick can also be installed on a shared account, it does not require root access as long as you have telnet access. Please see <a href=\"http://www.imagemagick.org\">here</a> for instructions. <br /><br />";
$lang['bufferexplain'] = "Your PHP version seems to have output buffering disabled. Contact your web host to have it enabled.";
$lang['ifyouwishtext'] = "You also need MySQL, which requires access info to test. If you'd like to test MySQL to ensure your version is recent enough, type your connection data below:";
$lang['usuallylocal'] = "(usually localhost)";
$lang['hosttext'] = "Database Host";
$lang['usertext'] = "Database Username";
$lang['passwordtext'] = "Database Password";
$lang['dbnametext'] = "Database Name";
$lang['testtext'] = "Test MySQL Info";
$lang['nonethelesstext'] = "<p>Your server meets the requirements for running $scriptname. Nonetheless, there are some points you should take note of:</p>";
$lang['ftpexplain'] = "Your PHP install lacks the FTP extension, and is running in apache mode without suPHP. This means any files/directories which you manually upload via FTP will have to be CHMODed manually. It'd be simpler to use a host with suPHP or the FTP extension.";
$lang['gdrec'] = "Your PHP install lacks the GD extension. Unless you have ImageMagick you won't be able to do thumbnails or resizing of images, but everything else will be fine."; 
$lang['runtimequotes'] = "magic_quotes_runtime needs to be off, as it is by default in PHP.";
$lang['urltext'] = "Remote URL functions";
$lang['urlexplain'] = "Your web host has disabled both fopen URL wrappers and CURL. This prevents your site from accessing the rest of the internet, thus disabling many important features. Disabled features will be greyed out on your switches page. You need to ask your web host to enable at least one of fopen URL wrappers or cURL in order to enjoy all options.";
$lang['firewallexplain'] = "Your web host has a firewall rule which is preventing the loading of data from the WSN server. Please contact your web host and ask them to unblock webmastersite.net and wsnforum.com so that data can be retrieved from them with cURL or fopen url wrappers. Once they've done that, return here to continue.";
$lang['apachesafeexplain'] = "Your web host is running PHP in safe_mode without suPHP. This can interfere with automatic setup or automatic upgrades, disables a few features, and generally makes your life more a pain than it needs to be. It's recommended that you ask your host to disable safe_mode on your account. Remind them that safe_mode is depreciated and will be removed from PHP 6, openbasedir should be used instead. <span style=\"font-weight: bold; color: red;\">If this automatic setup fails, and you can't turn off safe_mode, you'll need to do a manual installation!</span> To do a manual installation, download <a href=\"http://scripts.webmastersite.net/downloads.php?type=trial&format=targz&series=62&scriptname=$defaultscript\">trial62.tar.gz</a> extract it on your hard drive and see readme.html within it for instructions.";
$lang['windowsexplain'] = "Windows IIS doesn't support URL rewriting by default. If you want the SEO advantages of rewriting you'll have to buy an IIS add-on product like ISAPI_Rewrite to enable the same functionality which Apache users get free. If you're not terribly concerned about URL rewriting, forget this -- you don't have to use rewriting.";
$lang['gdmissingtext'] = "GD extension not installed";
$lang['executiontime'] = "Your host has set a maximum execution time of less than 20 seconds and disabled the ability to increase it. This might prevent automated setup/upgrades.";
$lang['maxexecutiontime'] = "Maximum Execution Time";
$lang['seconds'] = "seconds";
$lang['allowedmemory'] = "Allowed Memory";
$lang['memoryexplain'] = "$scriptname needs a memory limit of at least 10M for reliable operation. 16M or more is recommended, and if you'll be using the script to process exceptionally large image files (big images, huge xml files) you might require a very large value. Please contact your web host to have them set memory_limit = 16M; in php.ini, or you may be able to set php_value memory_limit 16M yourself in an .htaccess file.";
$lang['ftpdomanual'] = "Since the install location is the same as the FTP drop point, you'll have to manually chmod the directory to 777.";
$lang['ftppathmismatch'] = "The FTP path you specified doesn't end in the same directory as the install path you specified.";
$lang['badhost'] = "MySQL is not installed at {HOST}. Please ask your web host what your MySQL host name is.";
$lang['badmysqllogin'] = "The MySQL username and password you specified are invalid. Check if you've forgotten a prefix_ value on the username, or ask your web host what your MySQL login is.";
$lang['nodbaccess'] = "The MySQL login you specified does not have access to the database you specified. Either the database name is wrong (check if you forgot a prefix_ value) or you need to assign the user access to the database in your hosting control panel. You can ask WSN support or your host to do this for you.";
$lang['softcat'] = "software categories";
$lang['softlistings'] = "80,000+ software listings";
$lang['counties'] = "USA counties by state";
$lang['states'] = "USA states";
$lang['countries'] = "world countries";
$lang['cities'] = "USA cities by county by state";
$lang['chmodmarkertext'] = "<p style=\"font-size: 16px; color: red; font-weight: bold;\">Since your server lacks suPHP, you must CHMOD both the parent of the installation directory (or the installation directory if you've created it yourself already) and the directory this autosetup.php is in (if different) to 777.</p>";
$lang['quotesruntime'] = "magic_quotes_runtime is enabled on this server. It must be disabled before anything can function properly.";
$lang['tryanyway'] = "Try to Install Anyway";
$lang['nosuphp'] = "Your server's PHP install does not have suPHP and is not running in CGI mode. This means PHP-created files and FTP-uploaded files have different owners and cannot be modified from the other without 777 permissions. As a result, file and directory permissions become an unreliable mess. WSN will work around this by using your FTP information to try to manage your file permissions for you, but you would enjoy much simpler and more reliable operation on a web host that offers suPHP.";
$lang['nopermissionforseries'] = "Your customer account doesn't have permission to download the series you selected. Please <a href=\"{URL}\">purchase access</a>.";
$lang['maxpost'] = "post_max_size";
$lang['maxupload'] = "upload_max_filesize";
$lang['lowpost'] = "Your web host's php.ini file has a low limit set for post_max_size. You will not be able to upload files larger than this limit. If you plan to host videos or other large user-contributed files you'll need to increase the limit.";
$lang['lowupload'] = "Your web host's php.ini file has a low limit set for upload_max_filesize. You will not be able to upload files larger than this limit. If you plan to host videos or other large user-contributed files you'll need to increase the limit.";
$lang['localurltext'] = "Local URL functions";
$lang['localurlexplain'] = "Something -- probably a firewall rule -- prevents the server from accessing URLs on your own site.";
$lang['needsmanualupload'] = "<span style=\"font-size: 18px; color: #FF0000;\">Since this web host doesn't allow scripts to access the rest of the internet, you need to download <a href=\"http://scripts.webmastersite.net/downloads.php?type=trial&format=targz&series=62&scriptname=$defaultscript\">trial62.tar.gz</a> and upload it to the same directory this autosetup.php file is in. Be sure you've done this before you submit the setup form below.</span>"; 
$lang['totallylobotomizedhost'] = "This web host has disabled the ability to use most basic core PHP functions, such as mkdir for creating a new directory. You will need to switch to a web host that fully supports PHP. Here's a few examples of the thousands of hosts that give you a complete PHP well-suited to running WSN and other full-featured scripts: <a href='http://www.dreamhost.com'>dreamhost</a>, <a href='http://www.dualrack.com/wsnlinks-hosting'>dualrack</a>, <a href='http://www.futurehosting.com'>future hosting</a>, <a href='http://www.liquidweb.com'>liquid web</a>.";
$lang['baddownload'] = "There seems to be a problem with the download, please contact support.";
// End translation area
// Begin configuration area:
$header = '<html>
<head>
<title>WSN Setup</title>
<link rel="stylesheet" href="http://links.webmastersite.net/templates/styles/default.css" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style type="text/css">
.hideit { display: none; }
</style>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
    $("input[name=\'thedbserver\']").change(function() { checkhost(); });
    $("input[name=\'thedbpassword\']").change(function() { checkmysql(); });
    $("input[name=\'thedbuser\']").change(function() { checkmysql(); });
    $("input[name=\'thedbname\']").change(function() { checkmysql(); });
});

function checkhost()
{
 var hostname = $("[name=thedbserver]").val();
 $.post("'.$ourfilename.'",{ action: \'checkhost\', hostname: hostname },
  function(xml) 
  {
   if (xml != "") $("#hosterror").html(xml).removeClass("hideit");
   else $("#hosterror").html("").addClass("hideit");
  });
}

function geotoggle()
{
 if ($("input[name=series]:checked").val() >= 70) $(".geo").show();
 else $(".geo").hide();
}

function typetoggle()
{
 if ($("input[name=installtype]:checked").val() == "full") $("#fullversion").show();
 else $("#fullversion").hide();
}

function checkmysql()
{
 var hostname = $("[name=thedbserver]").val();
 var password = $("[name=thedbpassword]").val();
 var username = $("[name=thedbuser]").val();
 var database = $("[name=thedbname]").val();
 $.post("'.$ourfilename.'",{ action: \'checkmysql\', hostname: hostname, password: password, username: username, database: database },
  function(xml) 
  {
   if (xml != "") $("#mysqlerror").html(xml).removeClass("hideit");
   else $("#mysqlerror").html("").addClass("hideit");
  });
}

function showorhide(id) 
{ 
 if (document.getElementById(id).style.display == "none") document.getElementById(id).style.display = "block";
 else document.getElementById(id).style.display = "none";
}

function showdiv(id) 
{ 
 document.getElementById(id).style.display = "table-row";
 document.getElementById(id).style.visibility = "visible";
 document.getElementById(id).style.height = "100%";
}

function hidediv(id) 
{ 
 document.getElementById(id).style.display = "none";
 document.getElementById(id).style.visibility = "hidden";
 document.getElementById(id).style.height = 0;
}

function scriptchange(script)
{
 document.setupform.prefix.value = script + "_";
 var olddirurl = document.setupform.dirurl.value;
 var newdirurl = olddirurl.replace(/wsn[a-z]+/, script);
 document.setupform.dirurl.value = newdirurl;

 var scriptpath = script;

 document.getElementById(\'logo\').src = "http://scripts.webmastersite.net/" + scriptpath + "/logo.png";

 $("#scriptdetails").html("For information about the script, <a href=http://scripts.webmastersite.net/" + scriptpath + "/>visit the website</a>.");

 if (script == "wsnsd") $("[name=loaddata]").html("<option value=\"\">no data</option><option value=\"pad\">software categories</option><option value=\"padlistings\">80,000+ software listings</option><option value=\"cities\">USA cities by county by state</option><option value=\"counties\">USA counties by state</option><option value=\"states\">USA states</option>"); 
 else if (script == "wsnforum") $("[name=loaddata]").html("<option value=\"\">no data</option>"); 
 else $("[name=loaddata]").html("<option value=\"\">no data</option><option value=\"cities\">USA cities by county by state</option><option value=\"counties\">USA counties by state</option><option value=\"states\">USA states</option>"); 

}
</script>
<style>
.labelscolumn { border: 0; background-color: #E4EAEF; }
.optionscolumn { border: 0; background-color: #F1F2F5; }
.button
{
 font-size: 16px;
 margin: 5px;
 padding: 10px;
 padding-left: 20px;
 padding-right: 20px;
 border: 1px outset black;
 background-color: #FAFBFC;
 color: black; 
}
.tableheader 
{
 background-image: url(\'http://links.webmastersite.net/templates/images_default/boxbar.png\');
 line-height: 20px;
 color: white;
 border: 0;
 padding: 3px;
 font-size: 16px;
}
.labelscolumn
{
 background-image: url(\'http://links.webmastersite.net/templates/images_default/optionsbg.png\');
 opacity: .7;
}
.optionscolumn
{
 background-image: url(\'http://links.webmastersite.net/templates/images_default/optionsbg.png\');
}
INPUT { margin: 2px; padding: 2px; }
</style>
</head>
<body>
<div class="logobg"></div>
<div class="logo"><img id="logo" src="{LOGOURL}" alt="logo" /></div>
<div style="clear: both;"></div>
';
$footer = '</body></html>';
$formtemplate = '<form name="setupform" action="'.$ourfilename.'?filled=1" method="post">

<input type="hidden" name="dbtype" value="mysql" />

<table>
<tr>
 <th colspan="2" class="tableheader">WSN Automatic Installer</th>
</tr>
<tr>
 <td class="labelscolumn"><span class="labels">Server Evaluation:</span></td>
 <td class="optionscolumn">{SERVEREVALUATION}</td>
</tr>';
$formworkstemplate = '
<tr>
 <td class="labelscolumn"><span class="labels">Script:</span><br />Which WSN script do you want to install? You can return to do another later.</td>
 <td class="optionscolumn">
<select name="scriptname" onchange="scriptchange(this.value)">
<option value="wsnlinks">WSN Links</option>
<option value="wsngallery">WSN Gallery</option>
<option value="wsnkb">WSN Knowledge Base</option>
<option value="wsnforum">WSN Forum</option>
<option value="wsnclassifieds">WSN Classifieds</option>
<option value="wsndirectory">WSN Directory</option>
<option value="wsnsd">WSN Software Directory</option>
<option value="wsnshop">WSN Shop</option>
</select>
<div id="scriptdetails"></div>
 </td>
</tr>
{CUSTOMERLOGIN}
<tr>
 <td class="labelscolumn"><span class="labels">Select Series:</span></td>
 <td class="optionscolumn">
<input type="radio" name="series" value="70" onchange="geotoggle()" checked="checked" /> 7.0 - Current Series (latest and greatest)
<br />
<input type="radio" name="series" value="62" onchange="geotoggle()" /> 6.2 - Stable Series (fewer changes)
<br />
<input type="radio" name="series" value="61" onchange="geotoggle()" /> 6.1 - Old Series (rarely updated)
<br />
<input type="radio" name="series" value="60" onchange="geotoggle()" /> 6.0 - Legacy Series (security updates only)
<br />
<input type="radio" name="series" value="51" onchange="geotoggle()" /> 5.1 - Antique Series (security updates only)
 </td>
</tr>
<tr>
 <td class="labelscolumn"><span class="labels">Database Information:</span><br />If you don\'t have one set up, do so with your host\'s tools. Make sure the user is granted access to the DB.</td>
 <td class="optionscolumn">Database Server: <input type="text" name="thedbserver" size="20" value="localhost" required="required" />
<div id="hosterror" style="border: 1px solid red; padding: 5px; margin: 5px; font-size: 16px; background-color: #FFFAFA;" class="hideit"></div>
<br />Database Name: <input type="text" name="thedbname" size="20" required="required" />
<br />Database Username: <input type="text" name="thedbuser" size="20" required="required" />
<br />Database Password: <input type="password" name="thedbpassword" size="20" />
<div id="mysqlerror" style="border: 1px solid red; padding: 5px; margin: 5px; font-size: 16px; background-color: #FFFAFA;" class="hideit"></div>
<br />Tables Prefix: <input type="text" name="prefix" size="20" value="{PREFIX}" />
 </td>
</tr>
<tr>
 <td class="labelscolumn"><span class="labels">Initial Configuration:</span> <br />You can always change the switches later.</td>
 <td class="optionscolumn">
<input type="radio" name="complexity" value="simple" /> Simple - Just the basics on by default.
<br /><input type="radio" name="complexity" value="recommended" checked="checked" /> Recommended - Pre-configured as most people want.
<br /><input type="radio" name="complexity" value="advanced" /> Kitchen sink - Almost everything on by default.
 </td>
 </tr>
 <tr>
   <td class="labelscolumn"><span class="labels">Pre-Load Data:</span><br />If you would like one of the available types of data loaded into your site, select it. Otherwise, select "no data".</td>
   <td class="optionscolumn"><select name="loaddata"><option value="">no data</option>{LOADDATA}</select>
<div class="geo">
<br /><input type="checkbox" name="geolocation" value="1" checked="checked" /> Include geolocation data?*
</div>
  </td>
 </tr>
 <tr>
  <td class="labelscolumn"><span class="labels">Administrative Login:</span></td>
  <td class="optionscolumn">Username: <input type="text" name="username" size="20" value="admin" required="required" />
<br />Password: <input type="text" name="userpassword" size="20" value="{PASSWORD}" required="required" />
<br />E-Mail: <input type="text" name="accountemail" size="20" value="{DEFAULTEMAIL}" required="required" />
</td>
  </tr>
  <tr>
   <td class="labelscolumn"><span class="labels">URL To Install To:</span><br />An empty box means it\'ll use the current directory. {CHMODMARKER}</td>
   <td class="optionscolumn">{CURRENTDIRURL}<input type="text" name="dirurl" size="25" value="{DIRURLGUESS}" /></td>
  </tr>
{FTPBIT}
  <tr>
   <td class="labelscolumn"><span class="labels">Multilingual or English-only:</span><br />You must choose a multilingual install to use or create a language other than English. English-only makes the templates more easily readable and slightly faster. </td>
  <td class="optionscolumn">
 <table width="100%"><tr><td width="33%" valign="top">
 <input type="radio" name="multilingual" onclick="javascript:showorhide(\'div1\');showorhide(\'div2\');" value="english" checked="checked" />English-only installation <br />
 <input type="radio" name="multilingual" onclick="javascript:showorhide(\'div1\');showorhide(\'div2\');" value="multi" />Multilingual installation<br />
</td>
<td width="33%" valign="top">
<div id="div1" style="position: relative; display: none;">
Choose languages to install: 
<br />(Press ctrl to select multiple.) <br />
<select multiple name="languages[]" size="5">
<option value="fullenglish">English</option>
<option value="Spanish">Spanish (partial)</option>
<option value="German">German (partial)</option>
</select>
</div>
</td>
<td width="33%" valign="top">
<div id="div2" style="position: relative; display: none;">
Choose a default language:<br />
<select name="defaultlang">
<option value="fullenglish">English</option>
<option value="Spanish">Spanish (partial)</option>
<option value="German">German (partial)</option>
</select>
</div>
</td>
</tr></table>
</td></tr>
<tr>
 <td class="labelscolumn"><span class="labels">Special Options:</span><br />If you want to install over existing table prefixes or directories, you can bypass safety checks. If having problems, you can show debug output to relay to support.</td>
 <td class="optionscolumn">
<input type="checkbox" name="bypasschecks" value="1" /> Bypass safety checks<br />
<input type="checkbox" name="debug" value="1" /> Show debug output<br />
<input type="checkbox" name="testing" value="1" /> Install testing release<br />
<input type="checkbox" name="deleteme" value="1" checked="checked" /> Delete autosetup.php when done<br />
 </td>
</tr>
</table>
<button type="submit" class="button">Install</button>
</form>

<div class="geo">
<p style="font-size: 10px;">* Geolocation acknowledgement: This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com/.</p>
</div>
<script type="text/javascript">
if ($("input[name=series]:checked").val() < 70) $(".geo").hide(); // start hidden until we default the 70 series
if ($("input[name=installversion]:checked").val() == "full") $("#fullversion").show(); else $("#fullversion").hide();
</script>
';
$customerlogin = '<tr>
 <td class="labelscolumn"><span class="labels">Installation Type:</span><br />If you have purchased the software, select the full unlimited version and enter your customer login -- if not, you can install a 30 day trial version.</td>
 <td class="optionscolumn">
<input type="radio" name="installtype" value="trial" checked="checked" onchange="typetoggle()" /> Free 30 day trial
<br /><input type="radio" name="installtype" value="full" onchange="typetoggle()" /> Full unlimited version
<div id="fullversion">
Customer Account E-Mail: <input type="text" name="customeremail" size="20" value="{DEFAULTEMAIL}" />
<br />Customer Account Password: <input type="text" name="customerpass" size="20" value="" />
</div>
 </td>
</tr>';
$ftpbit = '<tr>
 <td class="labelscolumn"><span class="labels">FTP Information:</span><br />Since your server runs in apache mode without suPHP, the script requires FTP information in order to perform CHMODs for you.</td>
 <td class="optionscolumn">
FTP Host Name: <input type="text" name="ftphost" value="" size="20" /> (ex: ftp.yourdomain.com)<br />
FTP User Name: <input type="text" name="ftpuser" value="" size="20" /> (ex: you, or hide@address.com)<br />
FTP Password: <input type="password" name="ftppass" value="" size="20" /><br />
Relative Path to WSN: <input type="text" name="ftpdir" value="" size="20" /> (ex: public_html/wsn)
 </td>
</tr>';
$downloadurl = "http://scripts.webmastersite.net/downloads.php?type=full&format=targz&series={SERIES}&scriptname={SCRIPTNAME}&";
$trialdownloadurl = "http://scripts.webmastersite.net/downloads.php?type=trial&format=targz&series={SERIES}&scriptname={SCRIPTNAME}";

// End configuration area
if (ini_get('magic_quotes_runtime')) die($lang['quotesruntime']);

$trial = false; // set true to install 30 day free trial

if (isset($_REQUEST['action']))
{ // jquery ajax checks
 if ($_REQUEST['action'] == 'checkhost')
 {
  ob_start();
  $check = mysql_connect($_REQUEST['hostname']);
  $collecterror = ob_get_contents();
  ob_clean();
  if ($check === false && strstr($collecterror, 'Unknown MySQL server host')) echo str_replace('{HOST}', $_REQUEST['hostname'], $lang['badhost']);
  die();
 }
 if ($_REQUEST['action'] == 'checkmysql')
 {
  if (!$_REQUEST['hostname'] || !$_REQUEST['username'] || !$_REQUEST['password'] || !$_REQUEST['database']) die(); // don't check until all data is filled
  ob_start();
  $check = mysql_connect($_REQUEST['hostname'], $_REQUEST['username'], $_REQUEST['password']);
  $dbworked = mysql_select_db($_REQUEST['database'], $check);
  $collecterror = ob_get_contents();
  ob_clean();
  if ($check === false && strstr($collecterror, 'Unknown MySQL server host')) echo str_replace('{HOST}', $_REQUEST['hostname'], $lang['badhost']).' ';
  if ($check === false) echo $lang['badmysqllogin'].' ';
  if ($check !== false && !$dbworked) echo $lang['nodbaccess'].' '; // no point in showing when login wrong
  die();
 }
}

if (isset($_REQUEST['scriptname'])) $scriptname = $_REQUEST['scriptname'];
else $scriptname = $defaultscript; 
$scripttitle = getscripttitle($scriptname);

$scriptsitepathbit = $scriptname;

if (allowed_bytes() < 12000000) ini_set("memory_limit", "12M"); // probably not allowed, but try to allow more memory

$logourl = 'http://scripts.webmastersite.net/'.$scriptsitepathbit.'/logo.png';

if (isset($_REQUEST['debug'])) $debug = $_REQUEST['debug']; else $debug = false;

if (!$debug) error_reporting(0);

$header = str_replace('{LOGOURL}', $logourl, $header);

$formworkstemplate = str_replace('<option value="'.$scriptname.'">', '<option value="'.$scriptname.'" selected="selected">', $formworkstemplate); // pre-select the proper script

$formworkstemplate = str_replace('{PASSWORD}', str_replace(array('0', '1', '2', '3', '4', '5', '6'), array('z', 'y', 'x', 'w', 'v', 'm', 'k'), substr(md5(time()), 0, 5)), $formworkstemplate);

if (!strstr(php_sapi_name(), 'cgi')) $formworkstemplate = str_replace('{CHMODMARKER}', $lang['chmodmarkertext'], $formworkstemplate);
else $formworkstemplate = str_replace('{CHMODMARKER}', '', $formworkstemplate);

 if (isset($_REQUEST['series'])) $series = $_REQUEST['series']; else $series = 62;

$downloadurl = str_replace("{SCRIPTNAME}", $scriptsitepathbit, str_replace('{SERIES}', $series, $downloadurl));
$trialdownloadurl = str_replace("{SCRIPTNAME}", $scriptsitepathbit, str_replace('{SERIES}', $series, $trialdownloadurl));

echo $header;

if (isset($_REQUEST['filled']))
{
 if (isset($_POST['customerpass']) && !$_POST['customerpass']) $trial = true; // if they don't give their password, install a trial for them

 if ($_REQUEST['series'] > 62) $_POST['admindir'] = 'wsnadmin'; else $_POST['admindir'] = 'admin';

 $merged = array_merge($_GET, $_POST);
 while(list($key, $value) = each($merged)) { if (!is_array($value)) { $$key = urldecode($value); } }

 if (!$dirurl) $installtocurrentdir = true; else $installtocurrentdir = false;
 $dirurl = trim(str_replace(' ', '-', $dirurl), '/ '); // remove trailing slash and spaces, transform middle spaces
 $uploadpath = currentpath().$dirurl;
 $uploadpath = rtrim($uploadpath, '/').'/';
 fakerequest('uploadpath', $uploadpath);
 $dirurl = currentdirurl().$dirurl; // turn into complete url
 $dirurl = rtrim($dirurl, '/'); // if it's just current url, strip slash off that too
 fakerequest('dirurl', $dirurl);

 $uploadbits = explode('/', rtrim($uploadpath, '/'));
 $parentdir = str_replace(end($uploadbits).'/', '', $uploadpath);

 if ($installtocurrentdir) $parentdir = currentpath(); // installing to current directory

 if ((!isset($ftphost) || !$ftphost) && !strstr(php_sapi_name(), 'cgi') && extension_loaded('ftp'))
 { // really, lack of FTP isn't a big deal for autosetup like it is for manual setup. don't throw away potential customers. give them a prompt to chmod instead
  if ($_POST['dirurl'] != '' && !is_writeable($parentdir))
  {
   if (stristr(PHP_OS, 'win')) die($lang['windowspermissions']);
   else die($lang['pleasechmod']);
  }
 }

 if (isset($_REQUEST['ftphost']) && $_REQUEST['ftphost'])
 {
  $ftpdir = trim($ftpdir, '/'); // no leading or trailing slashes please
  $_POST['ftpdir'] = $ftpdir;
  $ftpc = ftp_connect($ftphost);
  $ftpr = ftp_login($ftpc, $ftpuser, $ftppass);  
  if ($ftpdir)
  {
   if (!strstr($ftpdir, '/')) $wsndir = $ftpdir;
   else $wsndir = end($pieces = explode('/', $ftpdir));
   $pathwsndir = end($x=explode('/',trim($uploadpath,'/')));
   if ($wsndir != $pathwsndir) die($lang['ftppathmismatch']);
   $parentdir = trim(str_replace($wsndir, '', $ftpdir), '/');
   if ($parentdir && isset($pieces) && count($pieces) > 1)
   { // chmod the install directory to 777. assume it's already created.
    $childindex = count($pieces) - 1;
    $tochmod = $pieces[$childindex];
    ftp_chdir($ftpc, $parentdir); 
   }
   else $tochmod = $wsndir; // if installed in public_html for example -- assume already exists
   ftp_chmod($ftpc, 0777, $tochmod);
  }
  else die($lang['ftpdomanual']);
 }


 if (!isset($_REQUEST['bypasschecks']) && hasindex($_POST['uploadpath'])) die(str_replace('{DIRURL}', $_POST['dirurl'], $lang['dirused']));
 if (!isset($_REQUEST['bypasschecks']) && prefixused()) die($lang['prefixused']);

// download and extract, then
// simply pass all the $_POST values into a post to setup.php
if ($trial) $d = $trialdownloadurl.'&dirurl='.urlencode($dirurl).'&adminemail='.urlencode($accountemail);
else
{
 $d = $downloadurl .'dirurl='. urlencode($dirurl) .'&username='. urlencode($customeremail) .'&userpassword='. urlencode($customerpass);
}
if (isset($_REQUEST['testing'])) $d .= '&testing=1';
if (file_exists('trial71.tar.gz')) rename('trial71.tar.gz', 'current.tar.gz');
if (file_exists('trial70.tar.gz')) rename('trial70.tar.gz', 'current.tar.gz');
if (file_exists('trial62.tar.gz')) rename('trial62.tar.gz', 'current.tar.gz');
if (file_exists('trial61.tar.gz')) rename('trial61.tar.gz', 'current.tar.gz');
if (file_exists('trial60.tar.gz')) rename('trial60.tar.gz', 'current.tar.gz');
if (!file_exists('current.tar.gz')) 
{
 $f = geturl($d);
 if ($f == 'bad login') 
 {
  die($lang['incorrectcustomerlogin']);
 }
 if ($f == 'no permission for this series')
 {
  $url = "http://scripts.webmastersite.net/$scriptname/members/?custom=yes&TID=upgrade&username=". urlencode($customeremail) ."&userpassword=". urlencode($customerpass);
  die(str_replace('{URL}', $url, $lang['nopermissionforseries']));
 }
 if (!$f) die($lang['bug']); // fopen/curl ARE working or we wouldn't have gotten this far, so WSN must be broken
 filewrite('current.tar.gz', $f);
}
if (filesize('current.tar.gz') < 250000) { unlink('current.tar.gz'); die($lang['baddownload']); }
$tar_object = new tar("current.tar.gz");
$test = makethedirectory("temp");
if (!$test && !file_exists("temp")) die($lang['pleasechmod']);
$tar_object->extract('temp');  
unset($tar_object);
$dir = end($x=explode('/', $dirurl));
recursivecopy("temp/$scriptname", $uploadpath);
removedirectory("temp");

if (isset($tweakdata) && $tweakdata)
{
 $tweakdata = '<'.'?php
'.$tweakdata.'
?'.'>';
 file_put_contents($uploadpath.'tweaks.php', $tweakdata);
} 

$uploadpath = str_replace('/attachments/', '/', $uploadpath); 
$uploadpath .= 'attachments/';
$_POST['uploadpath'] = $uploadpath;
$_GET['uploadpath'] = $uploadpath;

$qs = '';
$merged = array_merge($_GET, $_POST);
while(list($key, $value) = each($merged))
{
 if (is_array($value))
 {
  while(list($k, $v) = each($value)) $qs .= '&'.$key.'['.$k.']='.urlencode($v);
 }
 else $qs .= '&'.$key.'='.urlencode($value);
}
$qs = '?agree=yes&action=create&fromautosetup=1&nolocalurls='.$_REQUEST['nolocalurls']. $qs;
$setupurl = $dirurl.'/setup.php'.$qs;
if (!$nolocalurls) $out = geturl($setupurl); else $out = false;
if (!$out)
{ // on some strange servers, the files all download and copy fine but the setup.php call returns blank
  // for them, give a manual click option
 die('<a href="'.$setupurl.'">Click here to complete setup</a><meta http-equiv="refresh" content="1;url='.$setupurl.'" /></body></html>');
}
$out = str_replace('"index.php"', $dirurl, $out);
if ($debug) $finalout = $out;
else
{
 $start = strpos($out, '<div class="main">');
 if ($start)
 {
  $end = strpos($out, '</div>');
  $out = substr($out, $start, ($end - $start));
 }
 $finalout = str_replace('adminlogin.php', $_POST['dirurl'].'/'.$_POST['admindir'].'/', $out);
}
echo $finalout;
$basepath = str_replace('/attachments', '', urldecode($_POST['uploadpath']));
if (!file_exists($basepath.'config.php'))
{
 $failed = $lang['installfailed'];
 $failed = str_replace('{INSTALLFORM}', 'http://scripts.webmastersite.net/'.$scriptsitepathbit.'/?section=trial', $failed);
 $failed = str_replace('{SUPPORTURL}', 'http://scripts.webmastersite.net/'.$scriptsitepathbit.'/?section=support', $failed);
 $failed = str_replace('{HOSTEDURL}', 'http://scripts.webmastersite.net/'.$scriptsitepathbit.'/?section=hosted', $failed);
 echo $failed;
 removeinstall($basepath); // we can't delete the whole directory, because they may install to base directory they have other scripts under
}
else
{ // success!
 $subject = $lang['welcomeemailsubject'];
 $subject = str_replace('{SCRIPTNAME}', $scriptname, $subject);
 $subject = str_replace('{SCRIPTTITLE}', $scripttitle, $subject);
 $body = $lang['welcomeemailbody'];
 if ($trial) $body = str_replace('{TRIALBIT}', $lang['welcomeemailbodytrial'], $body);
 else $body = str_replace('{TRIALBIT}', '', $body);
 $body = str_replace('{SCRIPTNAME}', $scriptname, $body);
 $body = str_replace('{SCRIPTTITLE}', $scripttitle, $body);
 $body = str_replace('{SCRIPTSITEPATHBIT}', $scriptsitepathbit, $body);
 $body = str_replace('{DIRURL}', $_POST['dirurl'], $body);
 $body = str_replace('{ADMINDIR}', $_POST['admindir'], $body);
 $purchaselink = 'http://scripts.webmastersite.net/'.$scriptsitepathbit.'/index.php?section=payquantity&quantity=1';
 if (strstr($_POST['dirurl'], '.org')) $purchaselink .= '&discount=org';
 $body = str_replace('{PURCHASELINK}', $purchaselink, $body);
 mail($_POST['accountemail'], $subject, $body, 'From: '.$_POST['accountemail']); // send them an email with their administrative details
// why is it everything looks right here but there's nothing in my email? die("email sent to {$_POST['accountemail']} subject $subject body $body");
 unlink("current.tar.gz"); // clean up
 if (isset($_POST['deleteme']) && $_POST['deleteme']) unlink("autosetup.php");
}

}
else
{

// BEGIN SERVER TEST AREA

 ob_start();
 eval("echo 'OK';");
 $bufferoutput = ob_get_contents();
 ob_end_clean();

$partial = ''; $failed = ''; $server = '';

if ($bufferoutput == 'OK') $server .= "{$lang['bufftext']} - {$lang['passtext']} <br />";
else { $server .= "{$lang['bufftext']} - {$lang['failtext']} <br />"; $failed .= '|||buffering|||';  }

if (!version_compare(PHP_VERSION, "5.2.3", ">="))
{
 if (version_compare(PHP_VERSION, "5.0.0", ">=")) die($lang['oldphp5']); else die($lang['oldphp']);
 $server .= "{$lang['phptext']} ". PHP_VERSION ." - {$lang['partialtext']} <br />"; $failed .= '|||PHP|||'; 
}
else
{
 $server .= "{$lang['phptext']} ". PHP_VERSION ." - {$lang['passtext']} <br />";
}

//if (!functionwillwork('mkdir')) die($lang['totallylobotomizedhost']); // this gave false negative on one guy's host

if (!isset($_REQUEST['nourlcheck']))
{
$test = geturl("http://scripts.webmastersite.net/versiondata.txt", 3);
if ($test) $server .= "{$lang['urltext']} - {$lang['passtext']} <br />";
else if ($test === false) { $server .= "{$lang['urltext']} - {$lang['partialtext']} <br />"; $partial .= '|||url|||'; } // neither url wrappers nor curl
else { $server .= "{$lang['urltext']} - {$lang['partialtext']} <br />"; $partial .= '|||firewall|||'; } // host firewall issue

$nolocalurls = 0;
$test = geturl(currenturl()."?nourlcheck=1", 3);
if ($test) $server .= "{$lang['localurltext']} - {$lang['passtext']} <br />";
else
{
 $nolocalurls = 1;
 if ($test === false) { $server .= "{$lang['localurltext']} - {$lang['partialtext']} <br />"; $partial .= '|||localurl|||'; } // neither url wrappers nor curl
 else { $server .= "{$lang['localurltext']} - {$lang['partialtext']} <br />"; $partial .= '|||localurl||||||firewall|||'; } // host firewall issue
}
}

$exts = '';
foreach (get_loaded_extensions() as $extension) $exts .= " $extension ";

if (strstr(php_sapi_name(), 'cgi')) $server .= "CGI mode "; else { $server .= "Apache mode "; if (strstr($exts, ' ftp ')) $server .= "with FTP extension"; else $server .= "without FTP extension"; }

if (!strstr(php_sapi_name(), 'cgi') && ini_get('safe_mode')) { $server .= " in safe mode"; $partial .= '|||apachesafe|||'; $server .= " - {$lang['partialtext']} <br />"; }
else if (!strstr($exts, ' ftp ') && !strstr(php_sapi_name(), 'cgi')) { $partial .= '|||ftp|||'; $server .= " - {$lang['partialtext']} <br />"; } 
else if (!strstr(php_sapi_name(), 'cgi')) { $server .= " - {$lang['partialtext']} <br />"; $partial .= '|||nosuphp|||'; }
else $server .= " - {$lang['passtext']} <br />";

if (!stristr(PHP_OS, 'win')) $server .= PHP_OS." - {$lang['passtext']} <br />";
else { $server .= PHP_OS." - {$lang['partialtext']} <br />"; $partial .= '|||win|||'; }


$gdworks = '';
if (function_exists("gd_info"))
{
 $gdinfo = gd_info();
 $gdworks = $gdinfo["GD Version"];
}
if ($gdworks != '')
{
 $server .= "{$lang['gdtext']} ". $gdworks ." - {$lang['passtext']} <br />";
}
else
{ // DON'T fail wsngallery on lack of GD, because they might have imagemagick and still need to run autosetup
 $server .= "{$lang['gdmissingtext']} - {$lang['partialtext']} <br />"; $partial .= '|||GD|||'; 
}

$maxtime = ini_get('max_execution_time');
if (!functionwillwork('set_time_limit') && $maxtime < 20) { $partial .= '|||time|||'; $server .= "{$lang['maxexecutiontime']} ($maxtime {$lang['seconds']}) - {$lang['partialtext']}<br />"; }
else $server .= "{$lang['maxexecutiontime']} ($maxtime {$lang['seconds']}) - {$lang['passtext']}<br />";

$allowedmemory = ini_get("memory_limit");
if (allowed_bytes() < 9000000) { $failed .= '|||memory|||'; $server .= "{$lang['allowedmemory']} ($allowedmemory) - {$lang['failtext']}<br />"; }
else $server .= "{$lang['allowedmemory']} ($allowedmemory) - {$lang['passtext']}<br />";

$maxpost = ini_get("post_max_size");
if (allowed_bytes($maxpost) < 9000000) { $partial .= '|||post|||'; $server .= "{$lang['maxpost']} ($maxpost) - {$lang['partialtext']}<br />"; }
else $server .= "{$lang['maxpost']} ($maxpost) - {$lang['passtext']}<br />";

$maxupload = ini_get("upload_max_filesize");
if (allowed_bytes($maxupload) < 9000000) { $partial .= '|||upload|||'; $server .= "{$lang['maxupload']} ($maxpost) - {$lang['partialtext']}<br />"; }
else $server .= "{$lang['maxupload']} ($maxupload) - {$lang['passtext']}<br />";


if ($failed == '') $alltrue = true; else $alltrue = false;
if ($alltrue) 
{
 if ($partial) $server .= $lang['nonethelesstext'];	
 else $server .= "<span style=\"color: #00AA00; font-size: 14px;\">$congratstext</span>";
} 
else $server .= $lang['toobadtext'];
$server .= "<ul>";
if (strstr($failed, '|||GD|||') || strstr($partial, '|||GD|||'))
 $server .= "<li> {$lang['gdexplain']} </li>";

if (strstr($failed, '|||buffer|||'))
 $server .= "<li> {$lang['bufferexplain']} </li>";

if (strstr($failed, '|||memory|||'))
 $server .= "<li> {$lang['memoryexplain']} </li>";

if (strstr($partial, '|||url|||'))
 $server .= "<li> ".$lang['needsmanualupload']." </li><li> ".str_replace('{SCRIPT}', $scriptsitepathbit, $lang['urlexplain'])." </li>";

if (strstr($partial, '|||localurl|||'))
 $server .= "<li> ".str_replace('{CURRENTURL}', currenturl(), $lang['localurlexplain'])." </li>";

if (strstr($partial, '|||firewall|||'))
 $server .= "<li> {$lang['firewallexplain']} </li>";

if (strstr($partial, '|||apachesafe|||'))
 $server .= "<li> {$lang['apachesafeexplain']} </li>";

if (strstr($partial, '|||ftp|||'))
 $server .= "<li> {$lang['ftpexplain']} </li>";

if (strstr($partial, '|||win|||'))
 $server .= "<li> {$lang['windowsexplain']} </li>";

if (strstr($partial, '|||time|||'))
 $server .= "<li> {$lang['executiontime']} </li>";

if (strstr($partial, '|||nosuphp|||'))
 $server .= "<li> {$lang['nosuphp']} </li>";

if (strstr($partial, '|||post|||'))
 $server .= "<li> {$lang['lowpost']} </li>";

if (strstr($partial, '|||upload|||'))
 $server .= "<li> {$lang['lowupload']} </li>";

$server .= "</ul>";

if (!$alltrue)
{
 $server .= "<div style='padding: 20px;'><a href='$ourfilename?bypasschecks=1' class='button'>{$lang['tryanyway']}</a></div>";
}

// END SERVER TEST AREA

$path = guesspath();
$url = dirurlguess();
if (!hasindex($path))
{ // if current directory is available, use it
 $path = str_replace($scriptname.'/', '', $path);
 $url = str_replace('/'.$scriptname, '', $url);
}
if (!$failed || isset($_REQUEST['bypasschecks'])) $formtemplate .= $formworkstemplate;
if (isset($_REQUEST['bypasschecks'])) $formtemplate = str_replace('name="bypasschecks"', 'name="bypasschecks" checked="checked"', $formtemplate);
$formtemplate = str_replace('{SERVEREVALUATION}', $server, $formtemplate);
$formtemplate = str_replace('{DIRURLGUESS}', $url, $formtemplate);
$formtemplate = str_replace('{CURRENTDIRURL}', currentdirurl(), $formtemplate);
$formtemplate = str_replace('{PATHGUESS}', $path, $formtemplate);
$formtemplate = str_replace('{PREFIX}', $prefix, $formtemplate);
if ($trial) $formtemplate = str_replace('{CUSTOMERLOGIN}', '', $formtemplate);
else $formtemplate = str_replace('{CUSTOMERLOGIN}', $customerlogin, $formtemplate);
if (!strstr(php_sapi_name(), 'cgi') && extension_loaded('ftp') && !(strstr(strtolower($_ENV['OS']), 'windows') || strstr($_SERVER['SERVER_SOFTWARE'], 'Win'))) $formtemplate = str_replace('{FTPBIT}', $ftpbit, $formtemplate);
else $formtemplate = str_replace('{FTPBIT}', '', $formtemplate);

$loaddata = '';
if ($defaultscript == 'wsnsd') $loaddata .= '<option value="pad">'.$lang['softcat'].'</opton><option value="padlistings" selected="selected">'.$lang['softlistings'].'</option>';
if ($defaultscript != 'wsnforum') $loaddata .= '<option value="cities">'.$lang['cities'].'</option><option value="counties">'.$lang['counties'].'</option><option value="states">'.$lang['states'].'</option><option value="countries">'.$lang['countries'].'</option>';
$formtemplate = str_replace('{LOADDATA}', $loaddata, $formtemplate);

$formtemplate = str_replace('</form>', '<input type="hidden" name="nolocalurls" value="'.$nolocalurls.'" /></form>', $formtemplate); // pass on the value

$formtemplate = str_replace('{DEFAULTEMAIL}', $defaultemail, $formtemplate);

echo $formtemplate;
}


echo $footer;

// now, helper functions

function hasindex($path)
{
 $has = false;
 $f = getfiles($path);
 if (is_array($f))
 {
  foreach ($f as $o)
  {
   if (strstr($o, 'index')) $has = true;
  }
 }
 return $has;
}

function prefixused()
{ // see if the tables prefix is already in use
 global $lang;
 $ret = false;
 $c = mysql_connect($_POST['thedbserver'], $_POST['thedbuser'], $_POST['thedbpassword']);
 mysql_select_db($_POST['thedbname'], $c);
 $mysqlversion = @mysql_get_server_info($c);
 if ($mysqlversion)
 {
  preg_match("/([0-9]+)\.([0-9]+)\.[0-9]+/", $mysqlversion, $getseries);
  $old = true;
  if ($getseries[1] > 4) $old = false;
  else if ($getseries[1] == 4 && $getseries[2] >= 1) $old = false;
  if ($old) { die(str_replace('{YOURVERSION}', $mysqlversion, $lang['oldmysql'])); }
 }
 // connected. now, check for prefix_settings
 $q = mysql_query("SHOW TABLES", $c);
 while($r = mysql_fetch_row($q))
 {
  if (preg_match('/'.preg_quote($_POST['prefix']).'(.*?)/', $r[0])) $ret = true;
 }
 return $ret;
}

function removeinstall($installdir)
{ // we can't delete the whole directory, because they may install to base directory they have other scripts under
 $installdir = rtrim($installdir, '/');
 $base = explode(',', file_get_contents("$installdir/schemas/basefiles.wsn"));
 foreach ($base as $b)
 {
  if (!strstr($b, '.')) removedirectory("$installdir/$b"); // must be a directory
  else if ($b == 'config.php' && !file_exists("$installdir/config.php")) unlink("$installdir/config.php.txt");
  else unlink("$installdir/$b");
 }
 return true;
}

function dirurlguess()
{
 global $scriptname, $ourfilename;
 $dirurl = currenturl();
 if (strstr($dirurl, '?')) { $pts = explode('?', $dirurl); $dirurl = $pts[0]; }
 $dirurl = str_replace('/'.$ourfilename, '', $dirurl);
 if (strstr(guesspath(), $scriptname)) $dirurl .= "/$scriptname"; // if path says to use subdir, trust it
 $dirurl = ltrim(str_replace(currentdirurl(), '', "$dirurl/"), '/');
 return $dirurl;
}

function currentdirurl()
{
 global $ourfilename;
 $dirurl = currenturl();
 if (strstr($dirurl, '?')) { $pts = explode('?', $dirurl); $dirurl = $pts[0]; }
 $dirurl = str_replace('/'.$ourfilename, '/', $dirurl);
 return $dirurl;
}

function guesspath()
{
 global $scriptname;
  $realpath = '';
  $path = getenv("SCRIPT_FILENAME");
  $path = str_replace('\\', '/', $path);
  $path = explode('/', $path);
  for ($x=0; $x < (sizeof($path)-1) ; $x++)
  {
   $realpath .= $path[$x] .'/';
  }
  $testdir = getfiles($realpath);
  if (count($testdir) > 1) $realpath .= $scriptname.'/'; // if there's more than the autosetup.php, assume directory is in use
  return $realpath;
}	

function currentpath()
{
  $realpath = '';
  $path = $_SERVER["SCRIPT_FILENAME"];
  if (!$path) $path = $_SERVER["ORIG_SCRIPT_FILENAME"];
  if (!$path) die("Could not calculate file path! Must be a previously unknown server configuration. Please report this.");
  $path = str_replace('\\', '/', $path);
  $path = explode('/', $path);
  for ($x=0; $x < (sizeof($path)-1) ; $x++)
  {
   $realpath .= $path[$x] .'/';
  }
  return $realpath;
}	

function getfiles($path, $extension = '')
{ // collect all files from directory
 global $debug;
 $sets = false;
  if($handle = @opendir($path))
  {
   // Loop through all files
   while(false !== ($file = readdir($handle)))
   {  
    // Ignore hidden files
    if(!preg_match("/^\./", $file))
    {    
     // Put files in $files[]
     $full = $path.'/'.$file;
     if (!is_dir($full) && $file != '')
     {
	$sets[] = $file; 
     }
    }
   }
  }
  @closedir($handle);
 return $sets;
}

function currenturl()
{
  if (strstr($_SERVER['SERVER_PROTOCOL'], 'HTTPS')) $protocol = 'https://';
  else $protocol = 'http://';
  $url = $protocol . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
  if ($_SERVER['QUERY_STRING'] && !strstr($url, $_SERVER['QUERY_STRING'])) $url .= '?'. $_SERVER['QUERY_STRING'];
  return $url; 
}

function filewrite($filename, $data)
{
 global $debug, $langextras, $lang;
// supply a file name and I'll write your data to it
 if (!$data) $data = " "; // some servers seem to give error if we write a blank, so write space instead 
 $fd = @fopen($filename, 'wb');
 $check = @fwrite ($fd, $data); 
 if (!$check && !is_writeable($filename)) { echo $lang['pleasechmod']; }
 fclose ($fd);
 return $check;
}

function geturl($url, $seconds = 35)
{
 $url = str_replace('&amp;', '&', $url); // would fail on &amp;
 if (ini_get('allow_url_fopen') == '1')
 {
  $ctx = stream_context_create(array('http' => array('timeout' => $seconds)));
  $filecontents = file_get_contents($url, false, $ctx);
 }
 else if (extension_loaded('curl')) 
 { // curl seems to randomly timeout more
   $user_agent = 'Mozilla/4.0 (compatible; WSN Scripts +http://www.webmastersite.net)';
   $ch = curl_init(); 
   curl_setopt ($ch, CURLOPT_URL, $url); 
   curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent); 
   curl_setopt ($ch, CURLOPT_HEADER, false); 
   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); 
   curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $seconds);  // timeout after 15 seconds
   curl_setopt ($ch, CURLOPT_TIMEOUT, $seconds);  // timeout after 15 seconds   
   @curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true); // sometimes generates error in safe mode
   $filecontents = curl_exec ($ch); 
   curl_close ($ch); 
// curl_error($ch); // for debugging
 }
 else return false;
 return $filecontents;
}

// now, the tar.php contents:

/* vim: set ts=4 sw=4: */
// +----------------------------------------------------------------------+
// | PHP Version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license,      |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | hide@address.com so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Author: Vincent Blavet <hide@address.com>                          |
// +----------------------------------------------------------------------+
//
// $Id: Tar.php,v 1.13 2003/05/28 07:08:43 vblavet Exp $


/**
* Creates a (compressed) Tar archive
*
* @author   Vincent Blavet <hide@address.com>
* @version  $Revision: 1.13 $
* @package  Archive
*/
class tar
{
    /**
    * @var string Name of the Tar
    */
    var $_tarname='';

    /**
    * @var boolean if true, the Tar file will be gzipped
    */
    var $_compress=false;

    /**
    * @var string Type of compression : 'none', 'gz' or 'bz2'
    */
    var $_compress_type='none';

    /**
    * @var file descriptor
    */
    var $_file=0;

    /**
    * @var string Local Tar name of a remote Tar (http:// or ftp://)
    */
    var $_temp_tarname='';

    // {{{ constructor
    /**
    * Archive_Tar Class constructor. This flavour of the constructor only
    * declare a new Archive_Tar object, identifying it by the name of the
    * tar file.
    * If the compress argument is set the tar will be read or created as a
    * gzip or bz2 compressed TAR file.
    *
    * @param    string  $p_tarname  The name of the tar archive to create
    * @param    string  $p_compress can be null, 'gz' or 'bz2'. This
    *                   parameter indicates if gzip or bz2 compression
    *                   is required.  For compatibility reason the
    *                   boolean value 'true' means 'gz'.
    * @access public
    */
    function tar($p_tarname, $p_compress = null)
    {
        $this->_compress = false;
        $this->_compress_type = 'none';
        if ($p_compress === null) {
            if (@file_exists($p_tarname)) {
                if ($fp = @fopen($p_tarname, "rb")) {
                    // look for gzip magic cookie
                    $data = fread($fp, 2);
                    fclose($fp);
                    if ($data == "\37\213") {
                        $this->_compress = true;
                        $this->_compress_type = 'gz';
                    // No sure it's enought for a magic code ....
                    } elseif ($data == "BZ") {
                        $this->_compress = true;
                        $this->_compress_type = 'bz2';
                    }
                }
            } else {
                // probably a remote file or some file accessible
                // through a stream interface
                if (substr($p_tarname, -2) == 'gz') {
                    $this->_compress = true;
                    $this->_compress_type = 'gz';
                } elseif ((substr($p_tarname, -3) == 'bz2') ||
                          (substr($p_tarname, -2) == 'bz')) {
                    $this->_compress = true;
                    $this->_compress_type = 'bz2';
                }
            }
        } else {
            if (($p_compress == true) || ($p_compress == 'gz')) {
                $this->_compress = true;
                $this->_compress_type = 'gz';
            } else if ($p_compress == 'bz2') {
                $this->_compress = true;
                $this->_compress_type = 'bz2';
            }
        }
        $this->_tarname = $p_tarname;
        if ($this->_compress) { // assert zlib or bz2 extension support
            if ($this->_compress_type == 'gz')
                $extname = 'zlib';
            else if ($this->_compress_type == 'bz2')
                $extname = 'bz2';

            if (!extension_loaded($extname)) {
                PEAR::loadExtension($extname);
            }
            if (!extension_loaded($extname)) {
                die("The extension '$extname' couldn't be found.\n".
                    "Please make sure your version of PHP was built ".
                    "with '$extname' support.\n");
                return false;
            }
        }
    }
    // }}}

    // {{{ destructor
    function _Archive_Tar()
    {
        $this->_close();
        // ----- Look for a local copy to delete
        if ($this->_temp_tarname != '')
            @unlink($this->_temp_tarname);
        $this->_PEAR();
    }
    // }}}

    // {{{ create()
    /**
    * This method creates the archive file and add the files / directories
    * that are listed in $p_filelist.
    * If a file with the same name exist and is writable, it is replaced
    * by the new tar.
    * The method return false and a PEAR error text.
    * The $p_filelist parameter can be an array of string, each string
    * representing a filename or a directory name with their path if
    * needed. It can also be a single string with names separated by a
    * single blank.
    * For each directory added in the archive, the files and
    * sub-directories are also added.
    * See also createModify() method for more details.
    *
    * @param array  $p_filelist An array of filenames and directory names, or a single
    *                           string with names separated by a single blank space.
    * @return                   true on success, false on error.
    * @see createModify()
    * @access public
    */
    function create($p_filelist)
    {
        return $this->createModify($p_filelist, '', '');
    }
    // }}}

    // {{{ add()
    /**
    * This method add the files / directories that are listed in $p_filelist in
    * the archive. If the archive does not exist it is created.
    * The method return false and a PEAR error text.
    * The files and directories listed are only added at the end of the archive,
    * even if a file with the same name is already archived.
    * See also createModify() method for more details.
    *
    * @param array  $p_filelist An array of filenames and directory names, or a single
    *                           string with names separated by a single blank space.
    * @return                   true on success, false on error.
    * @see createModify()
    * @access public
    */
    function add($p_filelist)
    {
        return $this->addModify($p_filelist, '', '');
    }
    // }}}

    // {{{ extract()
    function extract($p_path='')
    {
        return $this->extractModify($p_path, '');
    }
    // }}}

    // {{{ listContent()
    function listContent()
    {
        $v_list_detail = array();

        if ($this->_openRead()) {
            if (!$this->_extractList('', $v_list_detail, "list", '', '')) {
                unset($v_list_detail);
                $v_list_detail = 0;
            }
            $this->_close();
        }

        return $v_list_detail;
    }
    // }}}

    // {{{ createModify()
    /**
    * This method creates the archive file and add the files / directories
    * that are listed in $p_filelist.
    * If the file already exists and is writable, it is replaced by the
    * new tar. It is a create and not an add. If the file exists and is
    * read-only or is a directory it is not replaced. The method return
    * false and a PEAR error text.
    * The $p_filelist parameter can be an array of string, each string
    * representing a filename or a directory name with their path if
    * needed. It can also be a single string with names separated by a
    * single blank.
    * The path indicated in $p_remove_dir will be removed from the
    * memorized path of each file / directory listed when this path
    * exists. By default nothing is removed (empty path '')
    * The path indicated in $p_add_dir will be added at the beginning of
    * the memorized path of each file / directory listed. However it can
    * be set to empty ''. The adding of a path is done after the removing
    * of path.
    * The path add/remove ability enables the user to prepare an archive
    * for extraction in a different path than the origin files are.
    * See also addModify() method for file adding properties.
    *
    * @param array  $p_filelist     An array of filenames and directory names, or a single
    *                               string with names separated by a single blank space.
    * @param string $p_add_dir      A string which contains a path to be added to the
    *                               memorized path of each element in the list.
    * @param string $p_remove_dir   A string which contains a path to be removed from
    *                               the memorized path of each element in the list, when
    *                               relevant.
    * @return boolean               true on success, false on error.
    * @access public
    * @see addModify()
    */
    function createModify($p_filelist, $p_add_dir, $p_remove_dir='', $namelist=false)
    {
        $v_result = true;

        if (!$this->_openWrite())
            return false;

        if ($p_filelist != '') {
            if (is_array($p_filelist))
                $v_list = $p_filelist;
            elseif (is_string($p_filelist))
                $v_list = explode(" ", $p_filelist);
            else {
                $this->_cleanFile();
                $this->_error('Invalid file list');
                return false;
            }

            $v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir, $namelist);
        }

        if ($v_result) {
            $this->_writeFooter();
            $this->_close();
        } else
            $this->_cleanFile();

        return $v_result;
    }
    // }}}

    // {{{ addModify()
    /**
    * This method add the files / directories listed in $p_filelist at the
    * end of the existing archive. If the archive does not yet exists it
    * is created.
    * The $p_filelist parameter can be an array of string, each string
    * representing a filename or a directory name with their path if
    * needed. It can also be a single string with names separated by a
    * single blank.
    * The path indicated in $p_remove_dir will be removed from the
    * memorized path of each file / directory listed when this path
    * exists. By default nothing is removed (empty path '')
    * The path indicated in $p_add_dir will be added at the beginning of
    * the memorized path of each file / directory listed. However it can
    * be set to empty ''. The adding of a path is done after the removing
    * of path.
    * The path add/remove ability enables the user to prepare an archive
    * for extraction in a different path than the origin files are.
    * If a file/dir is already in the archive it will only be added at the
    * end of the archive. There is no update of the existing archived
    * file/dir. However while extracting the archive, the last file will
    * replace the first one. This results in a none optimization of the
    * archive size.
    * If a file/dir does not exist the file/dir is ignored. However an
    * error text is send to PEAR error.
    * If a file/dir is not readable the file/dir is ignored. However an
    * error text is send to PEAR error.
    *
    * @param array      $p_filelist     An array of filenames and directory names, or a single
    *                                   string with names separated by a single blank space.
    * @param string     $p_add_dir      A string which contains a path to be added to the
    *                                   memorized path of each element in the list.
    * @param string     $p_remove_dir   A string which contains a path to be removed from
    *                                   the memorized path of each element in the list, when
    *                                   relevant.
    * @return                           true on success, false on error.
    * @access public
    */
    function addModify($p_filelist, $p_add_dir, $p_remove_dir='')
    {
        $v_result = true;

        if (!@is_file($this->_tarname))
            $v_result = $this->createModify($p_filelist, $p_add_dir, $p_remove_dir);
        else {
            if (is_array($p_filelist))
                $v_list = $p_filelist;
            elseif (is_string($p_filelist))
                $v_list = explode(" ", $p_filelist);
            else {
                $this->_error('Invalid file list');
                return false;
            }

            $v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir);
        }

        return $v_result;
    }
    // }}}

    // {{{ addString()
    /**
    * This method add a single string as a file at the
    * end of the existing archive. If the archive does not yet exists it
    * is created.
    *
    * @param string     $p_filename     A string which contains the full filename path
    *                                   that will be associated with the string.
    * @param string     $p_string       The content of the file added in the archive.
    * @return                           true on success, false on error.
    * @access public
    */
    function addString($p_filename, $p_string)
    {
        $v_result = true;

        if (!@is_file($this->_tarname)) {
            if (!$this->_openWrite()) {
                return false;
            }
            $this->_close();
        }
        
        if (!$this->_openAppend())
            return false;

        // Need to check the get back to the temporary file ? ....
        $v_result = $this->_addString($p_filename, $p_string);

        $this->_writeFooter();

        $this->_close();

        return $v_result;
    }
    // }}}

    // {{{ extractModify()
    /**
    * This method extract all the content of the archive in the directory
    * indicated by $p_path. When relevant the memorized path of the
    * files/dir can be modified by removing the $p_remove_path path at the
    * beginning of the file/dir path.
    * While extracting a file, if the directory path does not exists it is
    * created.
    * While extracting a file, if the file already exists it is replaced
    * without looking for last modification date.
    * While extracting a file, if the file already exists and is write
    * protected, the extraction is aborted.
    * While extracting a file, if a directory with the same name already
    * exists, the extraction is aborted.
    * While extracting a directory, if a file with the same name already
    * exists, the extraction is aborted.
    * While extracting a file/directory if the destination directory exist
    * and is write protected, or does not exist but can not be created,
    * the extraction is aborted.
    * If after extraction an extracted file does not show the correct
    * stored file size, the extraction is aborted.
    * When the extraction is aborted, a PEAR error text is set and false
    * is returned. However the result can be a partial extraction that may
    * need to be manually cleaned.
    *
    * @param string $p_path         The path of the directory where the files/dir need to be
    *                               extracted.
    * @param string $p_remove_path  Part of the memorized path that can be removed if
    *                               present at the beginning of the file/dir path.
    * @return boolean               true on success, false on error.
    * @access public
    * @see extractList()
    */
    function extractModify($p_path, $p_remove_path)
    {
        $v_result = true;
        $v_list_detail = array();

        if ($v_result = $this->_openRead()) {
            $v_result = $this->_extractList($p_path, $v_list_detail, "complete", 0, $p_remove_path);
            $this->_close();
        }

        return $v_result;
    }
    // }}}

    // {{{ extractInString()
    /**
    * This method extract from the archive one file identified by $p_filename.
    * The return value is a string with the file content, or NULL on error.
    * @param string $p_filename     The path of the file to extract in a string.
    * @return                       a string with the file content or NULL.
    * @access public
    */
    function extractInString($p_filename)
    {
        if ($this->_openRead()) {
            $v_result = $this->_extractInString($p_filename);
            $this->_close();
        } else {
            $v_result = NULL;
        }

        return $v_result;
    }
    // }}}

    // {{{ extractList()
    /**
    * This method extract from the archive only the files indicated in the
    * $p_filelist. These files are extracted in the current directory or
    * in the directory indicated by the optional $p_path parameter.
    * If indicated the $p_remove_path can be used in the same way as it is
    * used in extractModify() method.
    * @param array  $p_filelist     An array of filenames and directory names, or a single
    *                               string with names separated by a single blank space.
    * @param string $p_path         The path of the directory where the files/dir need to by
    *                               extracted.
    * @param string $p_remove_path  Part of the memorized path that can be removed if
    *                               present at the beginning of the file/dir path.
    * @return                       true on success, false on error.
    * @access public
    * @see extractModify()
    */
    function extractList($p_filelist, $p_path='', $p_remove_path='')
    {
        $v_result = true;
        $v_list_detail = array();

        if (is_array($p_filelist))
            $v_list = $p_filelist;
        elseif (is_string($p_filelist))
            $v_list = explode(" ", $p_filelist);
        else {
            $this->_error('Invalid string list');
            return false;
        }

        if ($v_result = $this->_openRead()) {
            $v_result = $this->_extractList($p_path, $v_list_detail, "partial", $v_list, $p_remove_path);
            $this->_close();
        }

        return $v_result;
    }
    // }}}

    // {{{ _error()
    function _error($p_message)
    {
        // ----- To be completed
        echo $p_message;
    }
    // }}}

    // {{{ _warning()
    function _warning($p_message)
    {
        // ----- To be completed
        echo $p_message;
    }
    // }}}

    // {{{ _openWrite()
    function _openWrite()
    {
        if ($this->_compress_type == 'gz')
            $this->_file = @gzopen($this->_tarname, "wb");
        else if ($this->_compress_type == 'bz2')
            $this->_file = @bzopen($this->_tarname, "wb");
        else if ($this->_compress_type == 'none')
            $this->_file = @fopen($this->_tarname, "wb");
        else
            $this->_error('Unknown or missing compression type ('.$this->_compress_type.')');

        if ($this->_file == 0) {
            $this->_error('Unable to open in write mode \''.$this->_tarname.'\'');
            return false;
        }

        return true;
    }
    // }}}

    // {{{ _openRead()
    function _openRead()
    {
        if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') {

          // ----- Look if a local copy need to be done
          if ($this->_temp_tarname == '') {
              $this->_temp_tarname = uniqid('tar').'.tmp';
              if (!$v_file_from = @fopen($this->_tarname, 'rb')) {
                $this->_error('Unable to open in read mode \''.$this->_tarname.'\'');
                $this->_temp_tarname = '';
                return false;
              }
              if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) {
                $this->_error('Unable to open in write mode \''.$this->_temp_tarname.'\'');
                $this->_temp_tarname = '';
                return false;
              }
              while ($v_data = @fread($v_file_from, 1024))
                  @fwrite($v_file_to, $v_data);
              @fclose($v_file_from);
              @fclose($v_file_to);
          }

          // ----- File to open if the local copy
          $v_filename = $this->_temp_tarname;

        } else
          // ----- File to open if the normal Tar file
          $v_filename = $this->_tarname;

        if ($this->_compress_type == 'gz')
            $this->_file = @gzopen($v_filename, "rb");
        else if ($this->_compress_type == 'bz2')
            $this->_file = @bzopen($v_filename, "rb");
        else if ($this->_compress_type == 'none')
            $this->_file = @fopen($v_filename, "rb");
        else
            $this->_error('Unknown or missing compression type ('.$this->_compress_type.')');

        if ($this->_file == 0) {
            $this->_error('Unable to open in read mode \''.$v_filename.'\'');
            return false;
        }

        return true;
    }
    // }}}

    // {{{ _openReadWrite()
    function _openReadWrite()
    {
        if ($this->_compress_type == 'gz')
            $this->_file = @gzopen($this->_tarname, "r+b");
        else if ($this->_compress_type == 'bz2')
            $this->_file = @bzopen($this->_tarname, "r+b");
        else if ($this->_compress_type == 'none')
            $this->_file = @fopen($this->_tarname, "r+b");
        else
            $this->_error('Unknown or missing compression type ('.$this->_compress_type.')');

        if ($this->_file == 0) {
            $this->_error('Unable to open in read/write mode \''.$this->_tarname.'\'');
            return false;
        }

        return true;
    }
    // }}}

    // {{{ _close()
    function _close()
    {
        if (isset($this->_file)) {
            if ($this->_compress_type == 'gz')
                @gzclose($this->_file);
            else if ($this->_compress_type == 'bz2')
                @bzclose($this->_file);
            else if ($this->_compress_type == 'none')
                @fclose($this->_file);
            else
                $this->_error('Unknown or missing compression type ('.$this->_compress_type.')');

            $this->_file = 0;
        }

        // ----- Look if a local copy need to be erase
        // Note that it might be interesting to keep the url for a time : ToDo
        if ($this->_temp_tarname != '') {
            @unlink($this->_temp_tarname);
            $this->_temp_tarname = '';
        }

        return true;
    }
    // }}}

    // {{{ _cleanFile()
    function _cleanFile()
    {
        $this->_close();

        // ----- Look for a local copy
        if ($this->_temp_tarname != '') {
            // ----- Remove the local copy but not the remote tarname
            @unlink($this->_temp_tarname);
            $this->_temp_tarname = '';
        } else {
            // ----- Remove the local tarname file
            @unlink($this->_tarname);
        }
        $this->_tarname = '';

        return true;
    }
    // }}}

    // {{{ _writeBlock()
    function _writeBlock($p_binary_data, $p_len=null)
    {
      if ($this->_file) {
          if ($p_len === null) {
              if ($this->_compress_type == 'gz')
                  @gzputs($this->_file, $p_binary_data);
              else if ($this->_compress_type == 'bz2')
                  @bzwrite($this->_file, $p_binary_data);
              else if ($this->_compress_type == 'none')
                  @fputs($this->_file, $p_binary_data);
              else
                  $this->_error('Unknown or missing compression type ('.$this->_compress_type.')');
          } else {
              if ($this->_compress_type == 'gz')
                  @gzputs($this->_file, $p_binary_data, $p_len);
              else if ($this->_compress_type == 'bz2')
                  @bzwrite($this->_file, $p_binary_data, $p_len);
              else if ($this->_compress_type == 'none')
                  @fputs($this->_file, $p_binary_data, $p_len);
              else
                  $this->_error('Unknown or missing compression type ('.$this->_compress_type.')');

          }
      }
      return true;
    }
    // }}}

    // {{{ _readBlock()
    function _readBlock($p_len=null)
    {
      $v_block = null;
      if ($this->_file) {
          if ($p_len === null)
              $p_len = 512;
              
          if ($this->_compress_type == 'gz')
              $v_block = @gzread($this->_file, 512);
          else if ($this->_compress_type == 'bz2')
              $v_block = @bzread($this->_file, 512);
          else if ($this->_compress_type == 'none')
              $v_block = @fread($this->_file, 512);
          else
              $this->_error('Unknown or missing compression type ('.$this->_compress_type.')');

      }
      return $v_block;
    }
    // }}}

    // {{{ _jumpBlock()
    function _jumpBlock($p_len=null)
    {
      if ($this->_file) {
          if ($p_len === null)
              $p_len = 1;

          if ($this->_compress_type == 'gz')
              @gzseek($this->_file, @gztell($this->_file)+($p_len*512));
          else if ($this->_compress_type == 'bz2') {
              // ----- Replace missing bztell() and bzseek()
              for ($i=0; $i<$p_len; $i++)
                  $this->_readBlock();
          } else if ($this->_compress_type == 'none')
              @fseek($this->_file, @ftell($this->_file)+($p_len*512));
          else
              $this->_error('Unknown or missing compression type ('.$this->_compress_type.')');

      }
      return true;
    }
    // }}}

    // {{{ _writeFooter()
    function _writeFooter()
    {
      if ($this->_file) {
          // ----- Write the last 0 filled block for end of archive
          $v_binary_data = pack("a512", '');
          $this->_writeBlock($v_binary_data);
      }
      return true;
    }
    // }}}

    // {{{ _addList()
    function _addList($p_list, $p_add_dir, $p_remove_dir, $namelist=false)
    {
      $v_result=true;
      $v_header = array();

      // ----- Remove potential windows directory separator
      $p_add_dir = $this->_translateWinPath($p_add_dir);
      $p_remove_dir = $this->_translateWinPath($p_remove_dir, false);

      if (!$this->_file) {
          $this->_error('Invalid file descriptor');
          return false;
      }

      if (count($p_list) == 0)
          return true;

      for ($j=0; ($j<count($p_list)) && ($v_result); $j++) {
        $v_filename = $p_list[$j];
        $v_namelist = $namelist[$j]; 
        // ----- Skip the current tar name
        if ($v_filename == $this->_tarname)
            continue;

        if ($v_filename == '')
            continue;

        if (!file_exists($v_filename)) {
            $this->_warning("File '$v_filename' does not exist");
            continue;
        }

        // ----- Add the file or directory header
        if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir, $v_namelist))
            return false;

        if (@is_dir($v_filename)) {
            if (!($p_hdir = opendir($v_filename))) {
                $this->_warning("Directory '$v_filename' can not be read");
                continue;
            }
            $p_hitem = readdir($p_hdir); // '.' directory
            $p_hitem = readdir($p_hdir); // '..' directory
            while (false !== ($p_hitem = readdir($p_hdir))) {
                if ($v_filename != ".")
                    $p_temp_list[0] = $v_filename.'/'.$p_hitem;
                else
                    $p_temp_list[0] = $p_hitem;

                $v_result = $this->_addList($p_temp_list, $p_add_dir, $p_remove_dir);
            }

            unset($p_temp_list);
            unset($p_hdir);
            unset($p_hitem);
        }
      }

      return $v_result;
    }
    // }}}

    // {{{ _addFile()
    function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir, $v_namelist=false)
    {
      if (!$this->_file) {
          $this->_error('Invalid file descriptor');
          return false;
      }

      if ($p_filename == '') {
          $this->_error('Invalid file name');
          return false;
      }

      // ----- Calculate the stored filename
      $p_filename = $this->_translateWinPath($p_filename, false);;
      $v_stored_filename = $p_filename;
	  if ($v_namelist) $v_stored_filename = $v_namelist;  
      if (strcmp($p_filename, $p_remove_dir) == 0) {
          return true;
      }
      if ($p_remove_dir != '') {
          if (substr($p_remove_dir, -1) != '/')
              $p_remove_dir .= '/';

          if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir)
              $v_stored_filename = substr($p_filename, strlen($p_remove_dir));
      }
      $v_stored_filename = $this->_translateWinPath($v_stored_filename);
      if ($p_add_dir != '') {
          if (substr($p_add_dir, -1) == '/')
              $v_stored_filename = $p_add_dir.$v_stored_filename;
          else
              $v_stored_filename = $p_add_dir.'/'.$v_stored_filename;
      }

      $v_stored_filename = $this->_pathReduction($v_stored_filename);

      if (is_file($p_filename)) {
          if (($v_file = @fopen($p_filename, "rb")) == 0) {
              $this->_warning("Unable to open file '$p_filename' in binary read mode");
              return true;
          }

          if (!$this->_writeHeader($p_filename, $v_stored_filename))
              return false;

          while (($v_buffer = fread($v_file, 512)) != '') {
              $v_binary_data = pack("a512", "$v_buffer");
              $this->_writeBlock($v_binary_data);
          }

          fclose($v_file);

      } else {
          // ----- Only header for dir
          if (!$this->_writeHeader($p_filename, $v_stored_filename))
              return false;
      }

      return true;
    }
    // }}}

    // {{{ _addString()
    function _addString($p_filename, $p_string)
    {
      if (!$this->_file) {
          $this->_error('Invalid file descriptor');
          return false;
      }

      if ($p_filename == '') {
          $this->_error('Invalid file name');
          return false;
      }

      // ----- Calculate the stored filename
      $p_filename = $this->_translateWinPath($p_filename, false);;

      if (!$this->_writeHeaderBlock($p_filename, strlen($p_string), 0, 0, "", 0, 0))
          return false;

      $i=0;
      while (($v_buffer = substr($p_string, (($i++)*512), 512)) != '') {
          $v_binary_data = pack("a512", $v_buffer);
          $this->_writeBlock($v_binary_data);
      }

      return true;
    }
    // }}}

    // {{{ _writeHeader()
    function _writeHeader($p_filename, $p_stored_filename)
    {
        if ($p_stored_filename == '')
            $p_stored_filename = $p_filename;
        $v_reduce_filename = $this->_pathReduction($p_stored_filename);

        if (strlen($v_reduce_filename) > 99) {
          if (!$this->_writeLongHeader($v_reduce_filename))
            return false;
        }

        $v_info = stat($p_filename);
        $v_uid = sprintf("%6s ", DecOct($v_info[4]));
        $v_gid = sprintf("%6s ", DecOct($v_info[5]));
        $v_perms = sprintf("%6s ", DecOct(fileperms($p_filename)));

        $v_mtime = sprintf("%11s", DecOct(filemtime($p_filename)));

        if (@is_dir($p_filename)) {
          $v_typeflag = "5";
          $v_size = sprintf("%11s ", DecOct(0));
        } else {
          $v_typeflag = '';
          clearstatcache();
          $v_size = sprintf("%11s ", DecOct(filesize($p_filename)));
        }

        $v_linkname = '';

        $v_magic = '';

        $v_version = '';

        $v_uname = '';

        $v_gname = '';

        $v_devmajor = '';

        $v_devminor = '';

        $v_prefix = '';

        $v_binary_data_first = pack("a100a8a8a8a12A12", $v_reduce_filename, $v_perms, $v_uid, $v_gid, $v_size, $v_mtime);
        $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $v_typeflag, $v_linkname, $v_magic, $v_version, $v_uname, $v_gname, $v_devmajor, $v_devminor, $v_prefix, '');

        // ----- Calculate the checksum
        $v_checksum = 0;
        // ..... First part of the header
        for ($i=0; $i<148; $i++)
            $v_checksum += ord(substr($v_binary_data_first,$i,1));
        // ..... Ignore the checksum value and replace it by ' ' (space)
        for ($i=148; $i<156; $i++)
            $v_checksum += ord(' ');
        // ..... Last part of the header
        for ($i=156, $j=0; $i<512; $i++, $j++)
            $v_checksum += ord(substr($v_binary_data_last,$j,1));

        // ----- Write the first 148 bytes of the header in the archive
        $this->_writeBlock($v_binary_data_first, 148);

        // ----- Write the calculated checksum
        $v_checksum = sprintf("%6s ", DecOct($v_checksum));
        $v_binary_data = pack("a8", $v_checksum);
        $this->_writeBlock($v_binary_data, 8);

        // ----- Write the last 356 bytes of the header in the archive
        $this->_writeBlock($v_binary_data_last, 356);

        return true;
    }
    // }}}

    // {{{ _writeHeaderBlock()
    function _writeHeaderBlock($p_filename, $p_size, $p_mtime=0, $p_perms=0, $p_type='', $p_uid=0, $p_gid=0)
    {
        $p_filename = $this->_pathReduction($p_filename);

        if (strlen($p_filename) > 99) {
          if (!$this->_writeLongHeader($p_filename))
            return false;
        }

        if ($p_type == "5") {
          $v_size = sprintf("%11s ", DecOct(0));
        } else {
          $v_size = sprintf("%11s ", DecOct($p_size));
        }

        $v_uid = sprintf("%6s ", DecOct($p_uid));
        $v_gid = sprintf("%6s ", DecOct($p_gid));
        $v_perms = sprintf("%6s ", DecOct($p_perms));

        $v_mtime = sprintf("%11s", DecOct($p_mtime));

        $v_linkname = '';

        $v_magic = '';

        $v_version = '';

        $v_uname = '';

        $v_gname = '';

        $v_devmajor = '';

        $v_devminor = '';

        $v_prefix = '';

        $v_binary_data_first = pack("a100a8a8a8a12A12", $p_filename, $v_perms, $v_uid, $v_gid, $v_size, $v_mtime);
        $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $p_type, $v_linkname, $v_magic, $v_version, $v_uname, $v_gname, $v_devmajor, $v_devminor, $v_prefix, '');

        // ----- Calculate the checksum
        $v_checksum = 0;
        // ..... First part of the header
        for ($i=0; $i<148; $i++)
            $v_checksum += ord(substr($v_binary_data_first,$i,1));
        // ..... Ignore the checksum value and replace it by ' ' (space)
        for ($i=148; $i<156; $i++)
            $v_checksum += ord(' ');
        // ..... Last part of the header
        for ($i=156, $j=0; $i<512; $i++, $j++)
            $v_checksum += ord(substr($v_binary_data_last,$j,1));

        // ----- Write the first 148 bytes of the header in the archive
        $this->_writeBlock($v_binary_data_first, 148);

        // ----- Write the calculated checksum
        $v_checksum = sprintf("%6s ", DecOct($v_checksum));
        $v_binary_data = pack("a8", $v_checksum);
        $this->_writeBlock($v_binary_data, 8);

        // ----- Write the last 356 bytes of the header in the archive
        $this->_writeBlock($v_binary_data_last, 356);

        return true;
    }
    // }}}

    // {{{ _writeLongHeader()
    function _writeLongHeader($p_filename)
    {
        $v_size = sprintf("%11s ", DecOct(strlen($p_filename)));

        $v_typeflag = 'L';

        $v_linkname = '';

        $v_magic = '';

        $v_version = '';

        $v_uname = '';

        $v_gname = '';

        $v_devmajor = '';

        $v_devminor = '';

        $v_prefix = '';

        $v_binary_data_first = pack("a100a8a8a8a12A12", '././@LongLink', 0, 0, 0, $v_size, 0);
        $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $v_typeflag, $v_linkname, $v_magic, $v_version, $v_uname, $v_gname, $v_devmajor, $v_devminor, $v_prefix, '');

        // ----- Calculate the checksum
        $v_checksum = 0;
        // ..... First part of the header
        for ($i=0; $i<148; $i++)
            $v_checksum += ord(substr($v_binary_data_first,$i,1));
        // ..... Ignore the checksum value and replace it by ' ' (space)
        for ($i=148; $i<156; $i++)
            $v_checksum += ord(' ');
        // ..... Last part of the header
        for ($i=156, $j=0; $i<512; $i++, $j++)
            $v_checksum += ord(substr($v_binary_data_last,$j,1));

        // ----- Write the first 148 bytes of the header in the archive
        $this->_writeBlock($v_binary_data_first, 148);

        // ----- Write the calculated checksum
        $v_checksum = sprintf("%6s ", DecOct($v_checksum));
        $v_binary_data = pack("a8", $v_checksum);
        $this->_writeBlock($v_binary_data, 8);

        // ----- Write the last 356 bytes of the header in the archive
        $this->_writeBlock($v_binary_data_last, 356);

        // ----- Write the filename as content of the block
        $i=0;
        while (($v_buffer = substr($p_filename, (($i++)*512), 512)) != '') {
            $v_binary_data = pack("a512", "$v_buffer");
            $this->_writeBlock($v_binary_data);
        }

        return true;
    }
    // }}}

    // {{{ _readHeader()
    function _readHeader($v_binary_data, &$v_header)
    {
        if (strlen($v_binary_data)==0) {
            $v_header['filename'] = '';
            return true;
        }

        if (strlen($v_binary_data) != 512) {
            $v_header['filename'] = '';
            $this->_error('Invalid block size : '.strlen($v_binary_data));
            return false;
        }

        // ----- Calculate the checksum
        $v_checksum = 0;
        // ..... First part of the header
        for ($i=0; $i<148; $i++)
            $v_checksum+=ord(substr($v_binary_data,$i,1));
        // ..... Ignore the checksum value and replace it by ' ' (space)
        for ($i=148; $i<156; $i++)
            $v_checksum += ord(' ');
        // ..... Last part of the header
        for ($i=156; $i<512; $i++)
           $v_checksum+=ord(substr($v_binary_data,$i,1));

        $v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor", $v_binary_data);

        // ----- Extract the checksum
        $v_header['checksum'] = OctDec(trim($v_data['checksum']));
        if ($v_header['checksum'] != $v_checksum) {
            $v_header['filename'] = '';

            // ----- Look for last block (empty block)
            if (($v_checksum == 256) && ($v_header['checksum'] == 0))
                return true;

            $this->_error('Invalid checksum for file "'.$v_data['filename'].'" : '.$v_checksum.' calculated, '.$v_header['checksum'].' expected');
            return false;
        }

        // ----- Extract the properties
        $v_header['filename'] = trim($v_data['filename']);
        $v_header['mode'] = 0644;
        $v_header['uid'] = OctDec(trim($v_data['uid']));
        $v_header['gid'] = OctDec(trim($v_data['gid']));
        $v_header['size'] = OctDec(trim($v_data['size']));
        $v_header['mtime'] = OctDec(trim($v_data['mtime']));
        if (($v_header['typeflag'] = $v_data['typeflag']) == "5") {
          $v_header['size'] = 0;
        }
        /* ----- All these fields are removed form the header because they do not carry interesting info
        $v_header[link] = trim($v_data[link]);
        $v_header[magic] = trim($v_data[magic]);
        $v_header[version] = trim($v_data[version]);
        $v_header[uname] = trim($v_data[uname]);
        $v_header[gname] = trim($v_data[gname]);
        $v_header[devmajor] = trim($v_data[devmajor]);
        $v_header[devminor] = trim($v_data[devminor]);
        */

        return true;
    }
    // }}}

    // {{{ _readLongHeader()
    function _readLongHeader(&$v_header)
    {
      $v_filename = '';
      $n = floor($v_header['size']/512);
      for ($i=0; $i<$n; $i++) {
        $v_content = $this->_readBlock();
        $v_filename .= $v_content;
      }
      if (($v_header['size'] % 512) != 0) {
        $v_content = $this->_readBlock();
        $v_filename .= $v_content;
      }

      // ----- Read the next header
      $v_binary_data = $this->_readBlock();

      if (!$this->_readHeader($v_binary_data, $v_header))
        return false;

      $v_header['filename'] = $v_filename;

      return true;
    }
    // }}}

    // {{{ _extractInString()
    /**
    * This method extract from the archive one file identified by $p_filename.
    * The return value is a string with the file content, or NULL on error.
    * @param string $p_filename     The path of the file to extract in a string.
    * @return                       a string with the file content or NULL.
    * @access private
    */
    function _extractInString($p_filename)
    {
        $v_result_str = "";

        While (strlen($v_binary_data = $this->_readBlock()) != 0)
        {
          if (!$this->_readHeader($v_binary_data, $v_header))
            return NULL;

          if ($v_header['filename'] == '')
            continue;

          // ----- Look for long filename
          if ($v_header['typeflag'] == 'L') {
            if (!$this->_readLongHeader($v_header))
              return NULL;
          }

          if ($v_header['filename'] == $p_filename) {
              if ($v_header['typeflag'] == "5") {
                  $this->_error('Unable to extract in string a directory entry {'.$v_header['filename'].'}');
                  return NULL;
              } else {
                  $n = floor($v_header['size']/512);
                  for ($i=0; $i<$n; $i++) {
                      $v_result_str .= $this->_readBlock();
                  }
                  if (($v_header['size'] % 512) != 0) {
                      $v_content = $this->_readBlock();
                      $v_result_str .= substr($v_content, 0, ($v_header['size'] % 512));
                  }
                  return $v_result_str;
              }
          } else {
              $this->_jumpBlock(ceil(($v_header['size']/512)));
          }
        }

        return NULL;
    }
    // }}}

    // {{{ _extractList()
    function _extractList($p_path, &$p_list_detail, $p_mode, $p_file_list, $p_remove_path)
    {
    $v_result=true;
    $v_nb = 0;
    $v_extract_all = true;
    $v_listing = false;

    $p_path = $this->_translateWinPath($p_path, false);
    if ($p_path == '' || (substr($p_path, 0, 1) != '/' && substr($p_path, 0, 3) != "../" && !strstr($p_path, ':'))) {
      $p_path = "./".$p_path;
    }
    $p_remove_path = $this->_translateWinPath($p_remove_path);

    // ----- Look for path to remove format (should end by /)
    if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/'))
      $p_remove_path .= '/';
    $p_remove_path_size = strlen($p_remove_path);

    switch ($p_mode) {
      case "complete" :
        $v_extract_all = TRUE;
        $v_listing = FALSE;
      break;
      case "partial" :
          $v_extract_all = FALSE;
          $v_listing = FALSE;
      break;
      case "list" :
          $v_extract_all = FALSE;
          $v_listing = TRUE;
      break;
      default :
        $this->_error('Invalid extract mode ('.$p_mode.')');
        return false;
    }

    clearstatcache();

    While (strlen($v_binary_data = $this->_readBlock()) != 0)
    {
      $v_extract_file = FALSE;
      $v_extraction_stopped = 0;

      if (!$this->_readHeader($v_binary_data, $v_header))
        return false;

      if ($v_header['filename'] == '')
        continue;

      // ----- Look for long filename
      if ($v_header['typeflag'] == 'L') {
        if (!$this->_readLongHeader($v_header))
          return false;
      }

      if ((!$v_extract_all) && (is_array($p_file_list))) {
        // ----- By default no unzip if the file is not found
        $v_extract_file = false;

        for ($i=0; $i<count($p_file_list); $i++) {
          // ----- Look if it is a directory
          if (substr($p_file_list[$i], -1) == '/') {
            // ----- Look if the directory is in the filename path
            if ((strlen($v_header['filename']) > strlen($p_file_list[$i])) && (substr($v_header['filename'], 0, strlen($p_file_list[$i])) == $p_file_list[$i])) {
              $v_extract_file = TRUE;
              break;
            }
          }

          // ----- It is a file, so compare the file names
          elseif ($p_file_list[$i] == $v_header['filename']) {
            $v_extract_file = TRUE;
            break;
          }
        }
      } else {
        $v_extract_file = TRUE;
      }

      // ----- Look if this file need to be extracted
      if (($v_extract_file) && (!$v_listing))
      {
        if (($p_remove_path != '')
            && (substr($v_header['filename'], 0, $p_remove_path_size) == $p_remove_path))
          $v_header['filename'] = substr($v_header['filename'], $p_remove_path_size);
        if (($p_path != './') && ($p_path != '/')) {
          while (substr($p_path, -1) == '/')
            $p_path = substr($p_path, 0, strlen($p_path)-1);

          if (substr($v_header['filename'], 0, 1) == '/')
              $v_header['filename'] = $p_path.$v_header['filename'];
          else
            $v_header['filename'] = $p_path.'/'.$v_header['filename'];
        }
        if (file_exists($v_header['filename'])) {
          if ((@is_dir($v_header['filename'])) && ($v_header['typeflag'] == '')) {
            $this->_error('File '.$v_header['filename'].' already exists as a directory');
            return false;
          }
          if ((is_file($v_header['filename'])) && ($v_header['typeflag'] == "5")) {
            $this->_error('Directory '.$v_header['filename'].' already exists as a file');
            return false;
          }
          if (!is_writeable($v_header['filename'])) {
            $this->_error('File '.$v_header['filename'].' already exists and is write protected');
            return false;
          }
          if (filemtime($v_header['filename']) > $v_header['mtime']) {
            // To be completed : An error or silent no replace ?
          }
        }

        // ----- Check the directory availability and create it if necessary
        elseif (($v_result = $this->_dirCheck(($v_header['typeflag'] == "5"?$v_header['filename']:dirname($v_header['filename'])))) != 1) {
            $this->_error('Unable to create path for '.$v_header['filename']);
            return false;
        }

        if ($v_extract_file) {
          if ($v_header['typeflag'] == "5") {
            if (!@file_exists($v_header['filename'])) {
                if (!makethedirectory($v_header['filename'])) {
                    $this->_error('Unable to create directory {'.$v_header['filename'].'}');
                    return false;
                }
            }
          } else {
              if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) {
                  $this->_error('Error while opening {'.$v_header['filename'].'} in write binary mode');
                  return false;
              } else {
                  $n = floor($v_header['size']/512);
                  for ($i=0; $i<$n; $i++) {
                      $v_content = $this->_readBlock();
                      fwrite($v_dest_file, $v_content, 512);
                  }
            if (($v_header['size'] % 512) != 0) {
              $v_content = $this->_readBlock();
              fwrite($v_dest_file, $v_content, ($v_header['size'] % 512));
            }

            @fclose($v_dest_file);

            // ----- Change the file mode, mtime
            @touch($v_header['filename'], $v_header['mtime']);
            // To be completed
            //chmod($v_header[filename], DecOct($v_header[mode]));
          }

          // ----- Check the file size
          clearstatcache();
          if (filesize($v_header['filename']) != $v_header['size']) {
              $this->_error('Extracted file '.$v_header['filename'].' does not have the correct file size \''.filesize($v_filename).'\' ('.$v_header['size'].' expected). Archive may be corrupted.');
              return false;
          }
          }
        } else {
          $this->_jumpBlock(ceil(($v_header['size']/512)));
        }
      } else {
          $this->_jumpBlock(ceil(($v_header['size']/512)));
      }

      /* TBC : Seems to be unused ...
      if ($this->_compress)
        $v_end_of_file = @gzeof($this->_file);
      else
        $v_end_of_file = @feof($this->_file);
        */

      if ($v_listing || $v_extract_file || $v_extraction_stopped) {
        // ----- Log extracted files
        if (($v_file_dir = dirname($v_header['filename'])) == $v_header['filename'])
          $v_file_dir = '';
        if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == ''))
          $v_file_dir = '/';

        $p_list_detail[$v_nb++] = $v_header;
      }
    }

        return true;
    }
    // }}}

    // {{{ _openAppend()
    function _openAppend()
    {
        if (filesize($this->_tarname) == 0)
          return $this->_openWrite();
          
        if ($this->_compress) {
            $this->_close();

            if (!@rename($this->_tarname, $this->_tarname.".tmp")) {
                $this->_error('Error while renaming \''.$this->_tarname.'\' to temporary file \''.$this->_tarname.'.tmp\'');
                return false;
            }

            if ($this->_compress_type == 'gz')
                $v_temp_tar = @gzopen($this->_tarname.".tmp", "rb");
            elseif ($this->_compress_type == 'bz2')
                $v_temp_tar = @bzopen($this->_tarname.".tmp", "rb");
                
            if ($v_temp_tar == 0) {
                $this->_error('Unable to open file \''.$this->_tarname.'.tmp\' in binary read mode');
                @rename($this->_tarname.".tmp", $this->_tarname);
                return false;
            }

            if (!$this->_openWrite()) {
                @rename($this->_tarname.".tmp", $this->_tarname);
                return false;
            }

            if ($this->_compress_type == 'gz') {
                $v_buffer = @gzread($v_temp_tar, 512);

                // ----- Read the following blocks but not the last one
                if (!@gzeof($v_temp_tar)) {
                    do{
                        $v_binary_data = pack("a512", $v_buffer);
                        $this->_writeBlock($v_binary_data);
                        $v_buffer = @gzread($v_temp_tar, 512);

                    } while (!@gzeof($v_temp_tar));
                }

                @gzclose($v_temp_tar);
            }
            elseif ($this->_compress_type == 'bz2') {
                $v_buffered_lines   = array();
                $v_buffered_lines[] = @bzread($v_temp_tar, 512);

                // ----- Read the following blocks but not the last one
                while (strlen($v_buffered_lines[] = @bzread($v_temp_tar, 512)) > 0) {
                    $v_binary_data = pack("a512", array_shift($v_buffered_lines));
                    $this->_writeBlock($v_binary_data);
                }

                @bzclose($v_temp_tar);
            }

            if (!@unlink($this->_tarname.".tmp")) {
                $this->_error('Error while deleting temporary file \''.$this->_tarname.'.tmp\'');
            }

        } else {
            // ----- For not compressed tar, just add files before the last 512 bytes block
            if (!$this->_openReadWrite())
               return false;

            clearstatcache();
            $v_size = filesize($this->_tarname);
            fseek($this->_file, $v_size-512);
        }

        return true;
    }
    // }}}

    // {{{ _append()
    function _append($p_filelist, $p_add_dir='', $p_remove_dir='')
    {
        if (!$this->_openAppend())
            return false;
            
        if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir))
           $this->_writeFooter();

        $this->_close();

        return true;
    }
    // }}}

    // {{{ _dirCheck()

    /**
     * Check if a directory exists and create it (including parent
     * dirs) if not.
     *
     * @param string $p_dir directory to check
     *
     * @return bool TRUE if the directory exists or was created
     */
    function _dirCheck($p_dir)
    {
        if ((@is_dir($p_dir)) || ($p_dir == ''))
            return true;

        $p_parent_dir = dirname($p_dir);

        if (($p_parent_dir != $p_dir) &&
            ($p_parent_dir != '') &&
            (!$this->_dirCheck($p_parent_dir)))
             return false;

        if (!makethedirectory($p_dir)) {
            $this->_error("Unable to create directory '$p_dir'");
            return false;
        }

        return true;
    }

    // }}}

    // {{{ _pathReduction()

    /**
     * Compress path by changing for example "/dir/foo/../bar" to "/dir/bar", and
     * remove double slashes.
     *
     * @param string $p_dir path to reduce
     *
     * @return string reduced path
     *
     * @access private
     *
     */
    function _pathReduction($p_dir)
    {
        $v_result = '';

        // ----- Look for not empty path
        if ($p_dir != '') {
            // ----- Explode path by directory names
            $v_list = explode('/', $p_dir);

            // ----- Study directories from last to first
            for ($i=count($v_list)-1; $i>=0; $i--) {
                // ----- Look for current path
                if ($v_list[$i] == ".") {
                    // ----- Ignore this directory
                    // Should be the first $i=0, but no check is done
                }
                else if ($v_list[$i] == "..") {
                    // ----- Ignore it and ignore the $i-1
                    $i--;
                }
                else if (($v_list[$i] == '') && ($i!=(count($v_list)-1)) && ($i!=0)) {
                    // ----- Ignore only the double '//' in path,
                    // but not the first and last /
                } else {
                    $v_result = $v_list[$i].($i!=(count($v_list)-1)?'/'.$v_result:'');
                }
            }
        }
        $v_result = strtr($v_result, '\\', '/');
        return $v_result;
    }

    // }}}

    // {{{ _translateWinPath()
    function _translateWinPath($p_path, $p_remove_disk_letter=true)
    {
      if (PHP_OS == 'WINNT') {
          // ----- Look for potential disk letter
          if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
              $p_path = substr($p_path, $v_position+1);
          }
          // ----- Change potential windows directory separator
          if ((strstr($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
              $p_path = strtr($p_path, '\\', '/');
          }
      }
     return $p_path;
    }
    // }}}

}

// File functions

function removedirectory($directory, $empty = false, $leaveitself = false)
{ // recursively empties and removes specified directory
 // if the path has a slash at the end we remove it here
 if(substr($directory,-1) == '/') $directory = substr($directory,0,-1);
 // if the path is not valid or is not a directory ...
 if (!file_exists($directory) || !is_dir($directory)) return false;
 else if (!is_readable($directory)) return false;
 else
 {
  $handle = opendir($directory);
  while (FALSE !== ($item = readdir($handle)))
  {
	if($item != '.' && $item != '..')
	{
		$path = $directory.'/'.$item;
		if(is_dir($path)) removedirectory($path);
		else	
		{
		 @unlink($path);
		 if (file_exists($path)) { unlink($path); }
		} 
	}
  }
  closedir($handle);
  if ($empty == false && !$leaveitself) { rmdir($directory); }
  return true;
 }
}


function recursivecopy($source, $dest, $directory = false)
{ // recursively copies specified directory.
// bug: need to copy empty directories too!
 if (!$directory) $directory = $source;
 // if the path has a slash at the end we remove it here
 if(substr($directory,-1) == '/') $directory = substr($directory,0,-1);
 // if the path is not valid or is not a directory ...
 if (!is_dir($directory)) die("Fatal error: $directory is not a directory.");
 else if (!is_readable($directory)) die ("Fatal error: $directory is not readable.");
 else
 {
  $handle = opendir($directory);
  while (FALSE !== ($item = readdir($handle)))
  {
   if($item != '.' && $item != '..')
   {
    $path = $directory.'/'.$item;
    $newdirectory = str_replace(rtrim($source, '/'), rtrim($dest, '/'), $directory);
    if (!file_exists($newdirectory)) makethedirectory($newdirectory);
    $newpath = $newdirectory.'/'.$item;
    if(is_dir($path)) recursivecopy($source, $dest, $path);
    else { copy($path, $newpath); @chmod($newpath, 0644); }
   }
  }
  $newdirectory = str_replace(rtrim($source, '/'), rtrim($dest, '/'), $directory);
  if (!file_exists($newdirectory)) makethedirectory($newdirectory); // include empty directories
  closedir($handle);
 }
 return true;
}

 function functionwillwork($func) 
 { // a function disabled via suhosin can return true with plain function_exists, so here's a method that'll return false for a disabled function no matter how it was disabled
  $ret = true;
  if (extension_loaded('suhosin')) 
  {
   $suhosin = @ini_get("suhosin.executor.func.blacklist");
   if (empty($suhosin) == false) 
   {
    $suhosin = explode(',', $suhosin);
    $suhosin = array_map('trim', $suhosin);
    $suhosin = array_map('strtolower', $suhosin);
    $ret = (function_exists($func) == true && array_search($func, $suhosin) === false);
   }
  }
  else $ret = function_exists($func);
  if (($func == 'set_time_limit' || $func == 'shell_exec') && ini_get('safe_mode')) $ret = false; // it won't work in safe_mode, but will still show as existing annoyingly enough
  return $ret;
 }


 function allowed_bytes($inival = false)
 { // convert memory limit from php.ini into bytes
  $bytes = 0;
  if (!$inival) $inival = ini_get("memory_limit");
  $test = preg_match('/([0-9]+)M/', $inival, $match);
  if ($test) $bytes = $match[1] * 1024 * 1024;
  return $bytes;
 }

function fakerequest($var, $val)
{
 global $$var;
 $$var = $val;
 $_REQUEST[$var] = $val;
 $_GET[$var] = $val;
 $_POST[$var] = $val;
 return true;
}

function makethedirectory($dir)
{
 global $ftpc;
 $dir = rtrim($dir, '/'); // suggestion of php manual comment
 //$dir = str_replace('./', '', $dir);
 if (!stristr(php_sapi_name(), 'cgi')) $test = mkdir($dir, 0777);
 else 
 {
  if (ini_get('safe_mode') && $ftpc) { $test = ftp_mkdir($ftpc, $dir); ftp_chmod($ftpc, 0777, $dir); }
  else $test = mkdir($dir);
 }
 return $test;
}

function getscripttitle($scriptname)
{
 if ($scriptname == 'wsnlinks') $scripttitle = 'WSN Links';
 else if ($scriptname == 'wsngallery') $scripttitle = 'WSN Gallery';
 else if ($scriptname == 'wsnkb') $scripttitle = 'WSN KB';
 else if ($scriptname == 'wsnforum') $scripttitle = 'WSN Forum';
 else if ($scriptname == 'wsnclassifieds') $scripttitle = 'WSN Classifieds';
 else if ($scriptname == 'wsnsd') $scripttitle = 'WSN Software Directory';
 else if ($scriptname == 'wsndirectory') $scripttitle = 'WSN Directory';
 else if ($scriptname == 'wsnshop') $scripttitle = 'WSN Shop';
 return $scripttitle;
}

?>
Return current item: WSN Links