<?php
header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' ); ?><html>
<head>
<title>WPManagerDX - Setup/Upgrade</title>
<link rel="stylesheet" href="images/styles.css" type="text/css">
<style type="text/css">
.error { color:#F00000; }
.ok { color:#00D000; }
</style>
</head>
<body>

<TABLE width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<?php
if(strtoupper(substr(PHP_OS, 0, 3)) != "WIN") {
?>
<TR>
<TD align="center" style="background-image:url(images/header_bg.jpg);" height="126">
<IMG src="images/setup_header.jpg" width="795" height="126" border="0">

</td>
</tr>

<?php
}
?>

<tr>
<td valign="top">
	<table width="100%" border="0" cellpadding="0" cellspacing="10">
	<tr>
	<td width="100%" valign="top">
<?php
//   Author Richard Čepas <rch@online.lt>
//   Please address support questions to person from whom you purchased this script

# workaround for PHP bug
ini_set('include_path', ini_get('include_path'));

if ((int)ini_get('magic_quotes_runtime')) set_magic_quotes_runtime(0);

require_once("include/shell_exec_emulation.php");

$q = $_POST;
if (!$q and $_GET['upgrade'] == 22) $q = $_GET;
if ((int)ini_get('magic_quotes_gpc')) {
    $qs = $q;
    foreach ($qs as $key => $value) {
        if (is_array($qs[$key])) {
            $q[$key] = $qs[$key];
            foreach ($q[$key] as $k => $v) $q[key][$k] = stripslashes($v);
        } else {
            $q[$key] = stripslashes($qs[$key]);
        }
    }
    unset($qs);
}

$create_SQL = "
CREATE TABLE Anacron (
  job_id char(10) NOT NULL default '',
  modified timestamp(14) NOT NULL,
  PRIMARY KEY  (job_id)
) TYPE=MyISAM;

CREATE TABLE Log (
  id int(10) unsigned NOT NULL auto_increment,
  `type` enum('info','warning','error') not null default 'info',
  Message text,
  created timestamp(14) NOT NULL,
  PRIMARY KEY  (id)
) TYPE=MyISAM;

CREATE TABLE Projects (
  project_id int(10) NOT NULL auto_increment,
  ftp_hostname varchar(255) NOT NULL default '',
  domain varchar(255) NOT NULL default '',
  web_folder varchar(255) NOT NULL default '',
  cpanel_login varchar(255) NOT NULL default '',
  cpanel_password varchar(255) NOT NULL default '',
  site_name varchar(255) NOT NULL default '',
  description text NOT NULL,
  owner_name varchar(255) NOT NULL default '',
  owner_email varchar(255) NOT NULL default '',
  admin_login varchar(255) NOT NULL default '',
  admin_password varchar(255) NOT NULL default '',
  modified timestamp(14) NOT NULL,
  created timestamp(14) NOT NULL default 0,
  installed timestamp(14) NOT NULL default 0,
  PRIMARY KEY  (project_id),
  KEY owner_email (owner_email),
  UNIQUE KEY url (domain(225), cpanel_login(20), web_folder(255))
) TYPE=MyISAM DEFAULT CHARSET=latin1;

";

$update_SQL = "
CREATE TABLE IF NOT EXISTS Themes (
  theme_id int(10) NOT NULL auto_increment,
  filename varchar(255) NOT NULL default '',
  Theme_Name varchar(255) NOT NULL default '',
  Theme_URI varchar(255) NOT NULL default '',
  Description text NOT NULL,
  Version varchar(255) NOT NULL default '',
  Author varchar(255) NOT NULL default '',
  Author_URI varchar(255) NOT NULL default '',
  modified timestamp(14) NOT NULL,
  created timestamp(14) NOT NULL default 0,
  PRIMARY KEY  (theme_id),
  UNIQUE KEY filename (filename)
) TYPE=MyISAM;

CREATE TABLE IF NOT EXISTS Plugins (
  plugin_id int(10) NOT NULL auto_increment,
  filename varchar(255) NOT NULL default '',
  Plugin_Name varchar(255) NOT NULL default '',
  Plugin_URI varchar(255) NOT NULL default '',
  Description text NOT NULL,
  Version varchar(255) NOT NULL default '',
  Author varchar(255) NOT NULL default '',
  Author_URI varchar(255) NOT NULL default '',
  modified timestamp(14) NOT NULL,
  created timestamp(14) NOT NULL default 0,
  PRIMARY KEY  (plugin_id),
  UNIQUE KEY filename (filename)
) TYPE=MyISAM;

ALTER TABLE Projects ADD COLUMN theme VARCHAR(255) NOT NULL DEFAULT 'default' AFTER admin_password;
ALTER TABLE Projects ADD COLUMN plugins TEXT AFTER theme;
ALTER TABLE Projects ADD COLUMN first_category VARCHAR(255) NOT NULL DEFAULT '' AFTER plugins;
ALTER TABLE Projects ADD COLUMN first_post_title VARCHAR(255) NOT NULL DEFAULT '' AFTER plugins;
ALTER TABLE Projects ADD COLUMN first_post_content TEXT AFTER plugins;
ALTER TABLE Projects ADD COLUMN installed_version VARCHAR(255) NOT NULL DEFAULT '' AFTER installed;
ALTER TABLE Projects ADD COLUMN ping_urls TEXT AFTER first_post_content;
ALTER TABLE Projects ADD COLUMN posts_per_page SMALLINT(3) NOT NULL DEFAULT 10 AFTER ping_urls;
ALTER TABLE Projects ADD COLUMN rss_use_excerpt TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE Projects ADD COLUMN links_visible TINYINT(1) NOT NULL DEFAULT 1;
ALTER TABLE Projects ADD COLUMN permalink_structure VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE Projects ADD COLUMN mailserver_url VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE Projects ADD COLUMN mailserver_port SMALLINT(3) UNSIGNED NOT NULL DEFAULT 110;
ALTER TABLE Projects ADD COLUMN mailserver_login VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE Projects ADD COLUMN mailserver_pass VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE Projects ADD COLUMN first_post_excerpt TEXT AFTER first_post_content;
ALTER TABLE Projects ADD COLUMN category_names BLOB AFTER first_category;
ALTER TABLE Projects ADD COLUMN category_descriptions BLOB AFTER category_names;
UPDATE Projects set category_names=CONCAT('a:1:{i:0;s:',LENGTH(first_category),':\"',first_category,'\";}') WHERE first_category <>'';
ALTER TABLE Projects DROP COLUMN first_category;

# 1.19

CREATE TABLE IF NOT EXISTS Misc (
  name varchar(255) NOT NULL default '',
  value text,
  modified timestamp(14) NOT NULL,
  PRIMARY KEY  (name)
) TYPE=MyISAM;
INSERT IGNORE INTO Misc (name,value) VALUES ('default_ping_urls','
http://rpc.pingomatic.com
http://ping.weblogs.se/
http://blogmatcher.com/u.php
http://coreblog.org/ping/
http://www.blogpeople.net/servlet/weblogUpdates
http://bulkfeeds.net/rpc
http://trackback.bakeinu.jp/bakeping.php
http://ping.myblog.jp
http://ping.bitacoras.com
http://ping.bloggers.jp/rpc/
http://ping.blogmura.jp/rpc/
http://xmlrpc.blogg.de
http://1470.net/api/ping
http://bblog.com/ping.php
http://blog.goo.ne.jp/XMLRPC
');

#1.22

ALTER TABLE Projects ADD COLUMN links_delete TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE Projects ADD COLUMN disallow_comments TINYINT(1) NOT NULL DEFAULT 0;

CREATE TABLE IF NOT EXISTS `Profiles` (
  `profile_id` int(10) NOT NULL auto_increment,
  `profile_name` varchar(255) NOT NULL default '',
  `ftp_hostname` varchar(255) NOT NULL default '',
  `domain` varchar(255) NOT NULL default '',
  `web_folder` varchar(255) NOT NULL default '',
  `cpanel_login` varchar(255) NOT NULL default '',
  `cpanel_password` varchar(255) NOT NULL default '',
  `site_name` varchar(255) NOT NULL default '',
  `description` text NOT NULL,
  `owner_name` varchar(255) NOT NULL default '',
  `owner_email` varchar(255) NOT NULL default '',
  `admin_login` varchar(255) NOT NULL default '',
  `admin_password` varchar(255) NOT NULL default '',
  `theme` varchar(255) NOT NULL default 'default',
  `plugins` text,
  `first_post_content` text,
  `first_post_excerpt` text,
  `ping_urls` text,
  `posts_per_page` smallint(3) NOT NULL default '10',
  `first_post_title` varchar(255) NOT NULL default '',
  `category_names` blob,
  `category_descriptions` blob,
  `modified` timestamp(14) NOT NULL,
  `created` timestamp(14) NOT NULL default '00000000000000',
  `rss_use_excerpt` tinyint(1) NOT NULL default '0',
  `links_visible` tinyint(1) NOT NULL default '1',
  `permalink_structure` varchar(255) NOT NULL default '',
  `mailserver_url` varchar(255) NOT NULL default '',
  `mailserver_port` smallint(3) unsigned NOT NULL default '110',
  `mailserver_login` varchar(255) NOT NULL default '',
  `mailserver_pass` varchar(255) NOT NULL default '',
  `links_delete` tinyint(1) NOT NULL default '0',
  `disallow_comments` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`profile_id`),
  UNIQUE KEY `profile_name` (`profile_name`)
);

ALTER TABLE Projects ADD COLUMN upload_single_theme TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE Profiles ADD COLUMN upload_single_theme TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE Projects ADD COLUMN `links` blob;
ALTER TABLE Profiles ADD COLUMN `links` blob;
ALTER TABLE Projects ADD COLUMN cpanel_theme VARCHAR(64) NOT NULL DEFAULT 'x' AFTER cpanel_password;
ALTER TABLE Profiles ADD COLUMN cpanel_theme VARCHAR(64) NOT NULL DEFAULT 'x' AFTER cpanel_password;

# 1.42
ALTER TABLE Themes ADD COLUMN screenshot_ext varchar(5) NOT NULL default '' AFTER filename;

# 1.46
ALTER TABLE Projects ADD COLUMN single_db tinyint(1) NOT NULL default '0';
ALTER TABLE Profiles ADD COLUMN single_db tinyint(1) NOT NULL default '0';

CREATE TABLE IF NOT EXISTS Cpanel_Accounts (
  `cpanel_login` varchar(255) NOT NULL default '',
  `mysql_password` varchar(255) NOT NULL default '',
  modified timestamp(14) NOT NULL,
  created timestamp(14) NOT NULL,
  PRIMARY KEY  (cpanel_login)
) TYPE=MyISAM;

# 2.00
ALTER TABLE Projects ADD COLUMN upload_selected_plugins TINYINT(1) NOT NULL DEFAULT 0 AFTER upload_single_theme;
ALTER TABLE Profiles ADD COLUMN upload_selected_plugins TINYINT(1) NOT NULL DEFAULT 0 AFTER upload_single_theme;

#CREATE TABLE IF NOT EXISTS Install_Tasks (
#  `task_id` int(10) NOT NULL auto_increment,
#  `overwrite` tinyint(1) NOT NULL default '0',
#  `project_ids` text,
#  modified timestamp(14) NOT NULL,
#  created timestamp(14) NOT NULL,
#  PRIMARY KEY  (job_id)
#) TYPE=MyISAM;

# 2.18
ALTER TABLE Projects ADD COLUMN blog_public TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE Profiles ADD COLUMN blog_public TINYINT(1) NOT NULL DEFAULT 0;

# serg updates
ALTER TABLE Profiles ADD COLUMN random_theme TINYINT(1) NOT NULL DEFAULT 0;

# 2.33
ALTER TABLE Projects ADD COLUMN homedirpath VARCHAR(64) NOT NULL DEFAULT 'home' AFTER cpanel_password;
ALTER TABLE Projects ADD COLUMN domain_inside_folder TINYINT(1) NOT NULL DEFAULT 0 AFTER homedirpath;
ALTER TABLE Projects ADD COLUMN domain_folder_name VARCHAR(255) NOT NULL DEFAULT '' AFTER domain_inside_folder;

# 2.34
ALTER TABLE Projects ADD COLUMN enable_app TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE Profiles ADD COLUMN enable_app TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE Projects ADD COLUMN enable_xmlrpc TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE Profiles ADD COLUMN enable_xmlrpc TINYINT(1) NOT NULL DEFAULT 0;

# 2.35
CREATE TABLE IF NOT EXISTS `autoposter_projects` (
  `id` int(11) NOT NULL auto_increment,
  `server_id` int(11) NOT NULL default '0',
  `name` varchar(255) NOT NULL default '',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM  AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS `autoposter_articles` (
  `id` int(11) NOT NULL auto_increment,
  `project_id` int(11) NOT NULL default '0',
  `title` varchar(255) NOT NULL default '',
  `description` longtext NOT NULL,
  `mt_excerpt` text NOT NULL,
  `meta_keywords` text NOT NULL,
  `meta_description` text NOT NULL,
  `mt_keywords` text NOT NULL,
  `selpublish` varchar(255) NOT NULL default '',
  `selcat` text NOT NULL,
  `mm` varchar(255) NOT NULL default '01',
  `dd` varchar(255) NOT NULL default '',
  `yy` varchar(255) NOT NULL default '',
  `hh` varchar(255) NOT NULL default '',
  `mn` varchar(255) NOT NULL default '',
  `ss` varchar(255) NOT NULL default '',
  `posted` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM  AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS `autoposter_settings` (
  `id` int(11) default '1',
  `email_notification` varchar(255) NOT NULL default 'ON',
  `amazon_affiliate_id` varchar(255) NOT NULL default '',
  `ebay_partner_network_id` varchar(255) NOT NULL default '',
  `ebay_partner_custom_id` varchar(255) NOT NULL default '',
  `spltarticlexline` int(11) NOT NULL default '300',
  `mt_keywords` varchar(255) NOT NULL default '',
  `metakeywords` varchar(255) NOT NULL default '',
  `metadescription` text NOT NULL,
  `cron_is_runing` int(11) NOT NULL default '0'
) ENGINE=MyISAM;

INSERT INTO `autoposter_settings` (`id`, `email_notification`, `amazon_affiliate_id`, `ebay_partner_network_id`, `ebay_partner_custom_id`, `spltarticlexline`, `mt_keywords`, `metakeywords`, `metadescription`, `cron_is_runing`) VALUES
(1, 'ON', '', '', '', 5, '', '', '', 0);

# 2.40
ALTER TABLE autoposter_settings ADD COLUMN email_notification varchar(255) NOT NULL default 'ON';

# 2.45
ALTER TABLE Projects ADD COLUMN first_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER first_post_excerpt;
ALTER TABLE Projects ADD COLUMN first_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER first_page_title;
ALTER TABLE Projects ADD COLUMN first_page_content TEXT AFTER first_page_order;
ALTER TABLE Profiles ADD COLUMN first_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER first_post_excerpt;
ALTER TABLE Profiles ADD COLUMN first_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER first_page_title;
ALTER TABLE Profiles ADD COLUMN first_page_content TEXT AFTER first_page_order;

ALTER TABLE Projects ADD COLUMN second_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER first_page_content;
ALTER TABLE Projects ADD COLUMN second_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER second_page_title;
ALTER TABLE Projects ADD COLUMN second_page_content TEXT AFTER second_page_order;
ALTER TABLE Profiles ADD COLUMN second_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER first_page_content;
ALTER TABLE Profiles ADD COLUMN second_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER second_page_title;
ALTER TABLE Profiles ADD COLUMN second_page_content TEXT AFTER second_page_order;

ALTER TABLE Projects ADD COLUMN third_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER second_page_content;
ALTER TABLE Projects ADD COLUMN third_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER third_page_title;
ALTER TABLE Projects ADD COLUMN third_page_content TEXT AFTER third_page_order;
ALTER TABLE Profiles ADD COLUMN third_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER second_page_content;
ALTER TABLE Profiles ADD COLUMN third_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER third_page_title;
ALTER TABLE Profiles ADD COLUMN third_page_content TEXT AFTER third_page_order;

ALTER TABLE Projects ADD COLUMN fourth_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER third_page_content;
ALTER TABLE Projects ADD COLUMN fourth_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER fourth_page_title;
ALTER TABLE Projects ADD COLUMN fourth_page_content TEXT AFTER fourth_page_order;
ALTER TABLE Profiles ADD COLUMN fourth_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER third_page_content;
ALTER TABLE Profiles ADD COLUMN fourth_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER fourth_page_title;
ALTER TABLE Profiles ADD COLUMN fourth_page_content TEXT AFTER fourth_page_order;

ALTER TABLE Projects ADD COLUMN fifth_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER fourth_page_content;
ALTER TABLE Projects ADD COLUMN fifth_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER fifth_page_title;
ALTER TABLE Projects ADD COLUMN fifth_page_content TEXT AFTER fifth_page_order;
ALTER TABLE Profiles ADD COLUMN fifth_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER fourth_page_content;
ALTER TABLE Profiles ADD COLUMN fifth_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER fifth_page_title;
ALTER TABLE Profiles ADD COLUMN fifth_page_content TEXT AFTER fifth_page_order;

ALTER TABLE Projects ADD COLUMN sixth_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER fifth_page_content;
ALTER TABLE Projects ADD COLUMN sixth_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER sixth_page_title;
ALTER TABLE Projects ADD COLUMN sixth_page_content TEXT AFTER sixth_page_order;
ALTER TABLE Profiles ADD COLUMN sixth_page_title VARCHAR(255) NOT NULL DEFAULT '' AFTER fifth_page_content;
ALTER TABLE Profiles ADD COLUMN sixth_page_order VARCHAR(255) NOT NULL DEFAULT '0' AFTER sixth_page_title;
ALTER TABLE Profiles ADD COLUMN sixth_page_content TEXT AFTER sixth_page_order;

ALTER TABLE Profiles ADD COLUMN frontpagedisplays VARCHAR(255) NOT NULL DEFAULT 'posts' AFTER posts_per_page;
ALTER TABLE Projects ADD COLUMN frontpagedisplays VARCHAR(255) NOT NULL DEFAULT 'posts' AFTER posts_per_page;

# 3.00
ALTER TABLE Profiles ADD COLUMN homedirpath VARCHAR(64) NOT NULL DEFAULT 'home' AFTER cpanel_password;
ALTER TABLE Profiles ADD COLUMN domain_inside_folder TINYINT(1) NOT NULL DEFAULT 0 AFTER homedirpath;
ALTER TABLE Profiles ADD COLUMN domain_folder_name VARCHAR(255) NOT NULL DEFAULT '' AFTER domain_inside_folder;

# 3.03
ALTER TABLE Projects ADD COLUMN delete_other_plugins TINYINT(1) NOT NULL DEFAULT 0 AFTER upload_selected_plugins;
ALTER TABLE Profiles ADD COLUMN delete_other_plugins TINYINT(1) NOT NULL DEFAULT 0 AFTER upload_selected_plugins;

#3.04
CREATE TABLE IF NOT EXISTS `autoposter_meta_profiles` (
  `id` int(11) NOT NULL auto_increment,
  `profile_name` varchar(255) NOT NULL default '',
  `meta_keywords` text NOT NULL,
  `meta_description` text NOT NULL,
  `mt_keywords` text NOT NULL,
  PRIMARY KEY  (`id`)
) TYPE=MyISAM  AUTO_INCREMENT=1;

#3.05
ALTER TABLE Projects ADD COLUMN update_plugins_viacron TINYINT(1) NOT NULL DEFAULT '1' AFTER delete_other_plugins;
ALTER TABLE Profiles ADD COLUMN update_plugins_viacron TINYINT(1) NOT NULL DEFAULT '1' AFTER delete_other_plugins;

#3.09
ALTER TABLE Projects ADD COLUMN upload_single_theme_without_delete TINYINT(1) NOT NULL DEFAULT 0 AFTER upload_single_theme;
ALTER TABLE Profiles ADD COLUMN upload_single_theme_without_delete TINYINT(1) NOT NULL DEFAULT 0 AFTER upload_single_theme;

#3.11
ALTER TABLE Projects ADD COLUMN master_blog TINYINT(1) NOT NULL DEFAULT 0 AFTER project_id;
ALTER TABLE Profiles ADD COLUMN master_blog TINYINT(1) NOT NULL DEFAULT 0 AFTER profile_id;

ALTER TABLE Projects ADD COLUMN admin_new_password VARCHAR(255) NOT NULL DEFAULT '' AFTER admin_password;
";

#1.19 movies it into mysql
if (file_exists('Templates/default_ping_URLs.txt')) rename('Templates/default_ping_URLs.txt','Templates/default_ping_URLs.txt.BAK');

echo(((int)ini_get('safe_mode')?'Safe mode is On':'').'<br>
<div class=error>
');
$fatals = 0;
$required_version = '4.3.0';
if (version_compare(phpversion(), $required_version, '<')) echo("Your PHP version ".phpversion()." is too old, at least $required_version is required.<br>");
if ($_GET['upgrade'] != 22) {
foreach (array('.htaccess','include/.htaccess','backup/.htaccess','Config/.htaccess','tmp/.htaccess','wp-themes/.htaccess','wp-plugins/.htaccess','admin.php','include/Common.php','include/Admin.php','Config/config.php','Templates') as $file) {
    if (!file_exists($file)) { $fatals++; echo("Missing $file file. Please check that you unpacked archive correctly.<br>"); }
}
foreach (array('.','backup','Config','Templates','wp-themes','wp-plugins','tmp') as $file) {
    if (!is_dir($file) || !is_writable($file)) { $fatals++; echo("\"$file\" directory should be writable by PHP scripts. Please change it permissions (\"chmod\" it) to 777, or rwxrwxrwx in symbolic notion using your FTP program.<br>"); }
}
foreach (array('Config/config.php') as $file) {
    if (!is_writable($file)) { $fatals++; echo("$file should be writable by PHP scripts. Please change it permissions (\"chmod\" it) to 666, or rw-rw-rw- in symbolic notion using your FTP program.<br>"); }
}

if(strtoupper(substr(PHP_OS, 0, 3)) != "WIN") {
	foreach (array('include') as $file) {
    	if (substr(decoct(fileperms($file)),3) != '755' and substr(decoct(fileperms($file)),2) != '755') echo("Warning: $file directory (. means current directory) normally should NOT be writable by web server. Please change it permissions (\"chmod\" it) to 755, or rwxr-xr-x in symbolic notion using your FTP program.<br>");
	}

	foreach (array('.htaccess','include/.htaccess','backup/.htaccess','Config/.htaccess','tmp/.htaccess','wp-themes/.htaccess','wp-plugins/.htaccess','admin.php','include/Common.php','include/Admin.php') as $file) {
    	if (substr(decoct(fileperms($file)),3) != '644') echo("Warning: $file file normally should NOT be writable by web server.  Please change it permissions (\"chmod\" it) to 644, or rw-r--r-- in symbolic notion using your FTP program.<br>");
	}
}

foreach (array('Templates','wp-themes','wp-plugins','tmp') as $dir_name) {
    if (is_dir($dir_name) and is_writable($dir_name) and $dir = @opendir($dir_name)) {
      $count = 0;
      while (($file = readdir($dir)) !== false) {
        if (substr($file,0,1) != '.') {
            if (!is_writable("$dir_name/$file")) {
                $fatals++;
                echo("$file and other files in $dir_name/ subdirectory should be writable by PHP scripts.  Please change it permissions (\"chmod\" it) to 666, or rw-rw-rw- in symbolic notion using your FTP program.<br>");
                if (++$count > 2) break;
            }
        }
      }
      closedir($dir);
    }
}

if(strtoupper(substr(PHP_OS, 0, 3)) != "WIN") {
#if ((int)ini_get('magic_quotes_gpc')) { $fatals++; echo("You need to set PHP option magic_quotes_gpc to Off.  Please check hidden .htaccess file.<br>"); }
if (!(int)ini_get('file_uploads')) echo("You need to set PHP option file_uploads to On.  This is required for admin section to be able restore backups.  Please check hidden .htaccess file.<br>");
if (defined(ini_get('track_vars')) && !(int)ini_get('track_vars')) echo("You need to set PHP option track_vars to On.  Please check hidden .htaccess file.<br>");
if ((int)ini_get('register_globals')) echo("It is recommended to set PHP option register_globals to Off for security reasons.  Please check hidden .htaccess file.<br>");
#if (!function_exists('curl_init') and !(int)ini_get('safe_mode')) @dl('curl.so');
#if (!(function_exists('curl_init') && strstr(curl_version(), 'OpenSSL')) and !extension_loaded('openssl'))  echo("Warning (not error): You have neither 'curl' with SSL nor 'openssl' PHP extention, please check your PHP installation.  One of these extentions is recommended for PayPal payment processing.<br>");
if (!function_exists('preg_replace')) { $fatals++; echo("You don't have 'preg' support in PHP, please check your PHP installation.  This module is required.<br>"); }
if (!function_exists('shell_exec')) { $fatals++; echo("You don't have 'shell_exec' support in PHP, please check your PHP installation.  This function is required.<br>"); }
elseif (!shell_exec('tar --help')) { $fatals++; echo("You can't use 'shell_exec' support in PHP, please check your PHP installation.  This function is required.<br>"); }
if (!(int)ini_get('allow_url_fopen')) { $fatals++; echo("You don't have 'URL-aware fopen wrappers' support in PHP, please check your PHP installation.  This standard PHP feature is required.<br>"); }

$msg = trim(shell_exec($cmd = '{ echo 0 && echo $?; } 2>&1'));
if (substr($msg,-1) !== '0' ) {
    $fatals++; echo("Failed to use 'shell_exec' in PHP.  Please contact your hosting.<br>\nCommand was:<br>\n$cmd\n<br>Output: $msg\n<br>\n");
} else {

	$msg = trim(shell_exec($cmd = '{ export PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/local/cpanel/bin:/usr/local/mysql/bin:$HOME/bin" && unzip -h && echo $?; } 2>&1'));
    if (substr($msg,-1) !== '0' and strpos($msg, 'Usage:') === FALSE ) {

       	$fatals++; echo("Failed to run \"unzip\" command needed to extract .zip archives.  Please contact your hosting.<br>\nCommand was:<br>\n$cmd\n<br>Output: $msg\n<br>\n");
   	}
	
	$msg = trim(shell_exec($cmd = '{ export PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/local/cpanel/bin:/usr/local/mysql/bin:$HOME/bin" && mysqldump -help && echo $?; } 2>&1'));
    if (substr($msg,-1) !== '0' and strpos($msg, 'Usage:') === FALSE ) {

       	$fatals++; echo("Failed to run \"mysqldump\" command needed to export database.  Please contact your hosting.<br>\nCommand was:<br>\n$cmd\n<br>Output: $msg\n<br>\n");
   	}	

}
} # end if upgrade != 22
}

if (! include_once('Config/config.php')) { $fatals++; echo("Can't include Config/config.php file.<br>"); }
if (! include_once('DB.php')) { $fatals++; echo("You don't have DB.php in your include_path, please check that your PHP installation includes PEAR.<br>"); }
if (! include_once('HTML/Template/IT.php')) { $fatals++; echo("You don't have HTML/Template/IT.php in your include_path, please check that your PHP installation includes PEAR.<br>"); }


echo ' </div>';

if ($fatals) {
    echo("$fatals fatal error(s), can't continue.<br>");
    if ($_GET['upgrade'] == 22) echo("Please correct it and click Refresh button in your browser.<br>");
} else {
    $err_msg = '';
    if ($q['DB_HOST'] == '') $q['DB_HOST'] = 'localhost';
    $attr = array();
    if (array_key_exists('upgrade', $q)) {
        $cfg =& new Config();
        if ($q['ADMIN_USER_OLD'] != $cfg->ADMIN_USER or $q['ADMIN_PASS_OLD'] != $cfg->ADMIN_PASS) {
            $err_msg .= "Admin password or username doesn't match.<br>";
            $attr['ADMIN_USER_OLD'] = $attr['ADMIN_PASS_OLD'] = 'class=error';
        } else {
            $db = DB::connect("mysql://$cfg->DB_USER:$cfg->DB_PASS@$cfg->DB_HOST/$cfg->DB_DATABASE", false); # non-persistant
            if (DB::isError($db)) {
                $err_msg .= $db->getMessage()."<font face=verdana, arial size=2><br>Please check mysql login, password and database name in Config/config.php.<br>";
            } else {
                @mysql_query("delete from Misc where name='pass_as_encrypted'");
				@mysql_query("INSERT IGNORE INTO Misc set name='pass_as_encrypted', value='".$q['pass_as_encrypted']."'");
					
				$_ = "\n<br><font face=verdana, arial><center><h3>Please click button below to access 'Settings section' admin page, review new settings and <i>save them</i>. </h3><form method=POST action='admin.php'><input type=hidden name=action2 value=cfg><input type=hidden name=Username value='".$q['ADMIN_USER_OLD']."'><input type=hidden name=Password value='".$q['ADMIN_PASS_OLD']."'><input type=\"submit\" name=\"login\" value=\"Configure\" class=\"cssvsc\"></form></center>\n";
                echo $_;
                run_queries($db, $update_SQL);
                echo $_;
            }
        }
    } else if (array_key_exists('go', $q)) {
        foreach (array('ADMIN_USER_OLD','ADMIN_PASS_OLD','ADMIN_USER','ADMIN_PASS','ADMIN_PASS2','DB_HOST','DB_USER','DB_DATABASE') as $field) {
            $q[$field] = trim($q[$field]);
            if ($q[$field] == '') {
                $err_msg = "Please fill all fields.<br>";
                $attr[$field] = 'class=error';
            }
        }
        if ($err_msg == '') {
            $cfg =& new Config();

            if ($q['ADMIN_USER_OLD'] != $cfg->ADMIN_USER or $q['ADMIN_PASS_OLD'] != $cfg->ADMIN_PASS) {
                $err_msg .= "Admin password or username doesn't match.<br>";
                $attr['ADMIN_USER_OLD'] = $attr['ADMIN_PASS_OLD'] = 'class=error';
            } elseif ($q['ADMIN_PASS_OLD'] == $q['ADMIN_PASS']) {
                $err_msg .= "New admin password should be different than old.<br>";
                $attr['ADMIN_PASS_OLD'] = $attr['ADMIN_PASS'] = 'class=error';
            } elseif (strlen($q['ADMIN_PASS']) < 5) {
                $err_msg .= "New admin password should have at least 5 characters.<br>";
                $attr['ADMIN_PASS'] = 'class=error';
            } else {
                $db = DB::connect("mysql://${q['DB_USER']}:${q['DB_PASS']}@${q['DB_HOST']}/${q['DB_DATABASE']}", false); # non-persistant
                if (DB::isError($db)) {
                    $err_msg .= $db->getMessage()."<br>Please check mysql login, password and database name.<br>";
                    foreach (array('DB_HOST','DB_USER','DB_PASS','DB_DATABASE') as $field) { $attr[$field] = 'class=error'; }
                } else {
                    # connected to DB, but update Config/config.php first
                    $SELF = substr($_SERVER['PHP_SELF'],0,1) == '/' ? $_SERVER['PHP_SELF']:$_SERVER['PATH_INFO'];
                    $script_url_prefix = "http://${_SERVER['SERVER_NAME']}$SELF";
                    $script_url_prefix = substr($script_url_prefix, 0, strrpos($script_url_prefix, '/'));
					
					if(strtoupper(substr(PHP_OS, 0, 3)) == "WIN") {
						$script_url_prefix = "http://" . $_SERVER['HTTP_HOST'];
					}
					
                    $sendmail = '';
                    foreach (array('/usr/local/sbin/sendmail', '/usr/sbin/sendmail', '/usr/bin/sendmail', '/usr/lib/sendmail') as $file) {
                        if (@is_executable($file)) {
                            $sendmail = $file;
                            break;
                        }
                    }
                    $defaults = array(
                        'ADMIN_USER' => $q['ADMIN_USER'],
                        'ADMIN_PASS' => $q['ADMIN_PASS'],
                        'DB_DATABASE' => $q['DB_DATABASE'],
                        'DB_HOST' => $q['DB_HOST'],
                        'DB_USER' => $q['DB_USER'],
                        'DB_PASS' => $q['DB_PASS'],
                        'DEMO_MODE' => 0,
                        'OWNER_EMAIL' => $_SERVER['SERVER_ADMIN'],
                        'FULL_URL' => "$script_url_prefix/admin.php",
                    );
                    # check for qmail's incompatable sendmail command
                    $content = file('Config/config.php') or die("Can't read Config.config.php");
                    #$content = join("\n",$content);
                    foreach ($defaults as $param => $val) {
                        $val = str_replace("'", "\\'", $val);
                        $content = preg_replace("/var \\$$param = '.*';/","var \$$param = '$val';", $content);
                    }
                    umask(0);
                    # try keep the same ownership of files
                    #@unlink('Config/config.php.BAK');
                    copy('Config/config.php','Config/config.php.BAK') or die("Can't copy Config.config.php to Config/config.php.BAK");
                    $c = fopen('Config/config.php','w') or die("Can't write to Config.config.php");
                    flock($c, LOCK_EX);
                    foreach ($content as $line) {
                        fwrite($c, $line);
                    }
                    flock($c, LOCK_UN);
                    fclose($c);
					
					@mysql_query("delete from Misc where name='pass_as_encrypted'");
					@mysql_query("INSERT IGNORE INTO Misc set name='pass_as_encrypted', value='".$q['pass_as_encrypted']."'");
					
                    print "<font face=verdana, arial><h3>Creating/updating database structure</h3>\n";
                    # create v2.07 first
                    $_ = "\n<br><font face=verdana, arial><center><h3>Please click button below to access 'Settings section' admin page and finish with other settings </h3><form method=POST action='admin.php'><input type=hidden name=action2 value=cfg><input type=hidden name=Username value='".$q['ADMIN_USER']."'><input type=hidden name=Password value='".$q['ADMIN_PASS']."'><input type=submit name=login value=Configure></form></center>\n";
                    echo $_;
                    run_queries($db, $create_SQL);
                    run_queries($db, $update_SQL);
                    echo $_;
                }
            }
            if ($err_msg == '') {
            }
        }
    }

if(strtoupper(substr(PHP_OS, 0, 3)) == "WIN") {
	
	$cfg =& new Config();
	
	$q['ADMIN_USER_OLD'] = $cfg->ADMIN_USER;
	$q['ADMIN_PASS_OLD'] = $cfg->ADMIN_PASS;
	
	$q['DB_HOST'] = '127.0.0.1';
	$q['DB_USER'] = 'root';
	$q['DB_PASS'] = '';
	$q['DB_DATABASE'] = 'wpmdx';

}

    if (!array_key_exists('go', $q) && !array_key_exists('upgrade', $q) || $err_msg != '') {
        echo '
            <p align=center class=error>
            '.$err_msg.'
            </p>
            <center>
            <form method=POST><table align=center width=700 bgcolor=#ffcc33 border=0 cellpadding=2 cellspacing=2>
<tr><td align=center bgcolor=#dfefff><font face=verdana, arial color=#000080 size=6><b>SCRIPT SETUP</b></font><br><font size=2 color=#000080 face=verdana, arial>
(Follow Instructions Below)</font>
</td></tr>
</table>
            <table width=700 border=0 cellpadding=4 cellspacing=1>
            <tr><td colspan=2><font face=verdana, arial size=2> This setup script will create database structure and update information in Config/config.php file.<br>
            Please enter admin username and password that are in Config/config.php file for verification:<br><br>
            </td></tr>
            <tr '.$attr['ADMIN_USER_OLD'].' ><td align=right><font face=verdana, arial size=2>Current Username:</td><td align=left><input name=ADMIN_USER_OLD value="'.htmlspecialchars($q['ADMIN_USER_OLD']).'"></td></tr>
            <tr '.$attr['ADMIN_PASS_OLD'].' ><td align=right><font face=verdana, arial size=2>Current Password:</td><td align=left><input type=password name=ADMIN_PASS_OLD value="'.htmlspecialchars($q['ADMIN_PASS_OLD']).'"></td></tr>
            <tr><td align=right><font face=verdana, arial size=2>Show Password Encrypted (******):</td><td align=left><select name="pass_as_encrypted"><option value="yes">Yes</option><option value="no">No - Display as Normal Text</option></select> Affects only cPanel Password and WP Admin Password. This refers to the fields that are in your wpmdx admin area > Single Install Blog, Multiple Install Blog and Add/List Profiles sections.</td></tr>
			<tr><td colspan=2>
            <tr><td colspan=2> <font face=verdana, arial size=2><br>
            If you want to upgrade existing DB structure only, please enter current admin username/password and click <b>upgrade DB only</b> below:
            </td></tr>
            <tr><td colspan=2 align=center><input type="submit" name="upgrade" value="Upgrade DB only" class="cssvsc2"><br><br></td></tr>
            <tr><td colspan=2 align=center><font face=verdana, arial size=2>
            Please enter <b>new</b> admin username and password:
            </td></tr>
            <tr '.$attr['ADMIN_USER'].' ><td align=right><font face=verdana, arial size=2>New Username:</td><td align=left> <input name=ADMIN_USER value="'.htmlspecialchars($q['ADMIN_USER']).'"></td></tr>
            <tr '.$attr['ADMIN_PASS'].' ><td align=right><font face=verdana, arial size=2>New Password:</td><td align=left> <input type=password name=ADMIN_PASS value="'.htmlspecialchars($q['ADMIN_PASS']).'"></td></tr>
            <tr '.$attr['ADMIN_PASS2'].' ><td align=right><font face=verdana, arial size=2>Retype new password:</td><td align=left> <input type=password name=ADMIN_PASS2 value="'.htmlspecialchars($q['ADMIN_PASS2']).'"></td></tr>
            <tr><td colspan=2 align=left><font face=verdana, arial size=2><br>Please enter mysql login information (you should have mysql user and database already created):</td></tr>
            <tr '.$attr['DB_HOST'].' ><td align=right><font face=verdana, arial size=2>Host:</td><td align=left> <input name=DB_HOST value="'.htmlspecialchars($q['DB_HOST']).'"></td></tr>
            <tr '.$attr['DB_USER'].' ><td align=right><font face=verdana, arial size=2>User (mysql login):</td><td align=left> <input name=DB_USER value="'.htmlspecialchars($q['DB_USER']).'"></td></tr>
            <tr '.$attr['DB_PASS'].' ><td align=right><font face=verdana, arial size=2>Password:</td><td align=left> <input name=DB_PASS value="'.htmlspecialchars($q['DB_PASS']).'"></td></tr>
            <tr '.$attr['DB_DATABASE'].' ><td align=right><font face=verdana, arial size=2>Database:</td><td align=left> <input name=DB_DATABASE value="'.htmlspecialchars($q['DB_DATABASE']).'"></td></tr>
            <tr><td colspan=2 align=center> <font face=verdana, arial size=2><br>
            Click <b>Setup</b> when you have entered all information above:
            </td></tr>
            <tr><td colspan=2 align=center><input type="submit" name="go" value="Setup" class="cssvsc"></td></tr>
            </form>
            </center>
            		</td></tr>
		</table>
    ';

    }
}

function run_queries($db,$SQL) {
    foreach (preg_split('/;\s+/', $SQL, -1, PREG_SPLIT_NO_EMPTY) as $query) {
        if (trim($query) == '') continue;
        echo(nl2br("$query\n"));
        $res = $db->query($query);
        if (DB::isError($res)) {
            $err = $res->getUserInfo();
            $matches = array();
            if (preg_match('/.*\[nativecode=((\d+).*)\]\s*/s', $err, $matches)) {
                $err = $matches[1];
                # skip duplicate column name error
                if ($matches[2] == '1060')
                    echo("<span class=''>$err</span><br>\n");
                else
                    echo("<span class=error>$err</span><br>\n");
            }
        } else {
            echo("<span class=ok>OK</span><br>\n");
        }
    }
}

?>



	</td></tr>
	</table>
</td>
</tr>

      </td>
    </tr>
<?php
if(strtoupper(substr(PHP_OS, 0, 3)) != "WIN") {
?>    
<tr><td align="center" style="color: #FFFFFF; font-size: 14px; background-image:url(images/bottom_bg.jpg);" height="49">Copyright 2007-2009 <a target=_new href="http://www.WPManagerDX.com/" style="color: #FFFFFF;">WPManagerDX</a>. All rights reserved worldwide.</td></tr>
<?php
}
?>

  </table>

  </center>
</body>
</html>