<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:             */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004-2008 Armia Systems, Inc                           |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Cybermatch                    |
// +----------------------------------------------------------------------+
// | Authors: simi<simi@armia.com>                                        |
// |                                                                      |
// +----------------------------------------------------------------------+

session_start();
error_reporting(0);
function isValidUsername($str) {
    if (trim($str) != "") {
        //if (eregi("[^0-9a-zA-Z+_]", $str)) {
        if (preg_match("/[^0-9a-zA-Z+_]/i", $str)) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function splitsqlfile($sql, $delimiter) {
    // Split up our string into "possible" SQL statements.
    $tokens = explode($delimiter, $sql);
    // try to save mem.
    $sql = "";
    $output = array();
    // we don't actually care about the matches preg gives us.
    $matches = array();
    // this is faster than calling count($oktens) every time thru the loop.
    $token_count = count($tokens);
    for ($i = 0; $i < $token_count; $i++) {
        // Don't wanna add an empty string as the last thing in the array.
        if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0))) {
            // This is the total number of single quotes in the token.
            $total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
            // Counts single quotes that are preceded by an odd number of backslashes,
            // which means they're escaped quotes.
            $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

            $unescaped_quotes = $total_quotes - $escaped_quotes;
            // If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
            if (($unescaped_quotes % 2) == 0) {
                // It's a complete sql statement.
                $output[] = $tokens[$i];
                // save memory.
                $tokens[$i] = "";
            } else {
                // incomplete sql statement. keep adding tokens until we have a complete one.
                // $temp will hold what we have so far.
                $temp = $tokens[$i] . $delimiter;
                // save memory..
                $tokens[$i] = "";
                // Do we have a complete statement yet?
                $complete_stmt = false;

                for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++) {
                    // This is the total number of single quotes in the token.
                    $total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
                    // Counts single quotes that are preceded by an odd number of backslashes,
                    // which means they're escaped quotes.
                    $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

                    $unescaped_quotes = $total_quotes - $escaped_quotes;

                    if (($unescaped_quotes % 2) == 1) {
                        // odd number of unescaped quotes. In combination with the previous incomplete
                        // statement(s), we now have a complete statement. (2 odds always make an even)
                        $output[] = $temp . $tokens[$j];
                        // save memory.
                        $tokens[$j] = "";
                        $temp = "";
                        // exit the loop.
                        $complete_stmt = true;
                        // make sure the outer loop continues at the right point.
                        $i = $j;
                    } else {
                        // even number of unescaped quotes. We still don't have a complete statement.
                        // (1 odd and 1 even always make an odd)
                        $temp .= $tokens[$j] . $delimiter;
                        // save memory.
                        $tokens[$j] = "";
                    }
                } // for..
            } // else
        }
    }
    return $output;
}

function isValidTableName($str) {
    if (trim($str) != "") {
        //if (eregi("[^a-zA-Z+_]", $str)) {
        if (preg_match("/[^a-zA-Z+_]/i", $str)) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function isValidEmail($email) {
    $email = trim($email);
    if ($email == "")
        return false;
//    if (!eregi("^" . "[a-z0-9]+([_\\.-][a-z0-9]+)*" . // user
//    "@" . "([a-z0-9]+([\.-][a-z0-9]+)*)+" . // domain
//    "\\.[a-z]{2,}" . // sld, tld
//    "$", $email, $regs)
//    ) {
     if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
        return false;
    } else {
        return true;
    }
}

function isNotNull($value) {
    if (is_array($value)) {
        if (sizeof($value) > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) {
            return true;
        } else {
            return false;
        }
    }
}

function isValidWebImageType($mimetype, $filename, $tempname) {
    $blacklist = array("php", "phtml", "php3", "php4", "js", "shtml", "pl", "py", "exe");
    foreach ($blacklist as $file) {
        if (preg_match("/\.$file\$/i", "$filename")) {
            return false;
        }
    }
    //check if its image file
    if (!getimagesize($tempname)) {
        return false;
    }

    if (($mimetype == "image/pjpeg") || ($mimetype == "image/jpeg") || ($mimetype == "image/x-png") || ($mimetype == "image/png") || ($mimetype == "image/gif") ||
            ($mimetype == "image/x-windows-bmp") || ($mimetype == "image/bmp")) {
        return true;
    } else {
        return false;
    }
}

function isValidWMImageType($mimetype, $filename, $tempname) {
    /* if (($mimetype == "image/pjpeg") || ($mimetype == "image/jpeg") || ($mimetype == "image/gif")) {
      return true;
      } else {
      return false;
      } */
    $blacklist = array("php", "phtml", "php3", "php4", "js", "shtml", "pl", "py", "exe");
    foreach ($blacklist as $file) {
        if (preg_match("/\.$file\$/i", "$filename")) {
            return false;
        }
    }
    //check if its image file
    if (!getimagesize($tempname)) {
        return false;
    }
    if ($mimetype == "image/gif") {
        return true;
    } else {
        return false;
    }
}

function getFilePermission($file) {
    $perm = fileperms($file);
    if ($perm === false) {
        return "0000";
    } else {
        return substr(sprintf('%o', $perm), -4);
    }
}

function stripslashes_deep($value) {
    $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    return $value;
}

function getServerOS() {
    return strtoupper(substr(PHP_OS, 0, 3));
}

//deprecated in php 5.3
//@set_magic_quotes_runtime(0);

if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}

function file_writable($file,$userDisplaypath) 
    {
        
        if(is_writable($file))
        {
            $file_status['status'] = true;
            $file_status['message'] = " * '" . $userDisplaypath . "' is writable";
        }
        else
        {
            $file_status['status'] = false;
            $file_status['message'] = " * Change the permission of '" . $userDisplaypath . "' to 777 <br/>";
        }
            
        return $file_status;
        
        
}


$schemafile = "schema.sql";
$datafile = "data.sql";
$configfile = "../config.inc.php";

$configcontents = @fread(@fopen($configfile, 'r'), @filesize($configfile));
$pos = strpos($configcontents, "INSTALLED");
if ($pos === false) {
    ;
} else {
    header("location:../index.php");
}

$fullurl = $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
if($_SERVER['HTTPS']=='on') {
    $http = "https://";
}else {
    $http = "http://";
}
$pos = strrpos($fullurl, "/");
if ($pos === false) { // note: three equal signs
    // not found...
} else {
    $fullurl = substr($fullurl, 0, $pos);
}

$txtSiteSecureURL   = "https://".$fullurl;
//$fullurl            = $http . $fullurl;

$installed = false;
$txtDBServerName = "localhost";
$txtTablePrefix = "tbl_";
$txtSiteURL = "http://" . $fullurl;
$txtSecureSiteURL = "https://" . $fullurl;


if($_POST['cldpack']!=1)
{
/* * ********************************check server configuration **************************************************** */

$server_flag = true;

$val1 = ini_get("safe_mode");
$val3 = ini_get("file_uploads");

$gd = function_exists('gd_info');
$curl = function_exists('curl_init');
$mysql = function_exists('mysqli_connect');

if (!empty($val1) || $val1 == 1) {
    $server_flag = false;
} elseif (empty($val3) || $val3 != 1) {
    $server_flag = false;
} elseif (!$gd) {
    $server_flag = false;
} elseif (!$curl) {
    $server_flag = false;
} elseif (!$mysql) {
    $server_flag = false;
}

$mysqlsupport = true;
if (!function_exists('mysqli_connect')) {

    $mysqlsupport = false;
}

if (!$server_flag) {
    $serverconfiguration = "FAILURE";
} else {
    $serverconfiguration = "OK";
}

/* --------------------Check server PHP configuration--------------------------- */
$sapi_type = php_sapi_name();
$chmodstatus = '000';
if (substr($sapi_type, 0, 3) == 'cgi') {
    $chmodstatus = '755';
    $write = 'WRITABLE';
} else {
    if (substr(@php_uname(s), 0, 7) == "Windows") {
        $chmodstatus = '000';
    } else {
        $chmodstatus = '777';
    }
    $write = 'UNWRITABLE';
}

$directories = array(
        "images/",
        "images/profiles/",
        "images/success_stories/",
        "userfiles/",
        "help/",
        "images/spam/",
        "banners/",
        "pem/",
        "pemfile/",
        "config.inc.php");

$perm_msg = '';
$perm_flag = true;
$host_name = parse_url($_SERVER['HTTP_HOST']);
$error=false;
$serverPermission=false;
$error_message="";
foreach ($directories as $dir) {
        $permission = file_writable("../".$dir, $dir);
        if (!$permission['status'] && $error == false) {
                $error = true; 
                $serverPermission=true;
        
        }
         if (!$permission['status'] ) {
                $error_message=$error_message.$permission['message'];
        }
}



if ($error) {
    if (isset($_POST["btnContinue"]) && !isset($_POST["auto_set"])) {
        $txtFTPusername = $_POST['FTPusername'];
        $txtFTPpassword = $_POST['FTPpassword'];

        if (trim($txtFTPusername) == '') {
            $perm_msg .= '* Please enter FTP username <br/>';
        }
        if (trim($txtFTPpassword) == '') {
            $perm_msg .= '* Please enter FTP password <br/>';
        } else {
            $conn_id = @ftp_connect($host_name["path"]);
            $login_result = @ftp_login($conn_id, $txtFTPusername, $txtFTPpassword);
            if ($login_result) {
                $mode = 777;
                $np = '0' . $mode;

                $user_install = str_replace('/install', '', getcwd());

                //get the path staring from public_html
                $path_parts = explode('/public_html', $user_install);
                $user_install = '/public_html' . $path_parts[1];

                foreach ($directories as $directory) {
                    $edited_path = str_replace('..', '', "../".$directory);
                    $directory = $user_install . $edited_path;
                    if ($directory[strlen($directory) - 1] == '/') {
                        $directory = substr($directory, 0, strlen($directory) - 1);
                    }
                    if (!@ftp_chmod($conn_id, eval("return({$np});"), $directory)) {
                        $perm_flag = false;
                    }
                }

                if (!$perm_flag) {
                    $perm_msg .= '* Sorry, an error occurred. Please try again or set the permissions manually <br/>';
                } else {
                    $perm_msg = '<b>* File permissions successfuly set </b><br/>';
                }
            } else {
                $perm_msg .= '* Sorry, could not connect to the server. Please check the credentials <br/>';
            }
        }
    }
} 
/* ----------------------------------------------------------------------------- */
$error_message="";
$serverPermission=false;
$error=false;
foreach ($directories as $dir) {
    $permission = file_writable("../".$dir, $dir);
    if (!$permission['status'] && $error == false) {
        $error = true;
        $serverPermission=true;
      
    }
    if (!$permission['status'] ) {
        $error_message=$error_message.$permission['message'];
    }
}

//show alert only for non-cgi servers


/* ---------------------------------------------------------------------------------------------------------------- */
$post_flag = false;
}

if ($_POST["btnContinue"] == "Continue" || $_POST['cldpack'] ==1) {
    
    if($_POST['cldpack']==1)
    {
        $txtDBServerName = "localhost";
        $txtDBName = $_POST["db_name"];
        $txtDBUserName = $_POST["db_user"];
        $txtDBPassword = $_POST["db_password"];
        $txtSiteName = $_POST["store_name"];
                $regmode = $_POST["regmode"];
        $txtAdminName = "admin";
        $txtAdminPassword = "q1w2e3";
        $txtLicenseKey = "1234456789";
        $txtConfirmAdminPassword =  "q1w2e3";
        $txtAdminEmail = $_POST["user_email"];
        $txtTablePrefix = "cbl_";
        $documentrootforcloud=$_POST['installPath'];
    }
    else 
    {
    $txtDBServerName = $_POST["txtDBServerName"];
    $txtDBName = $_POST["txtDBName"];
    $txtDBUserName = $_POST["txtDBUserName"];
    $txtDBPassword = $_POST["txtDBPassword"];
    $txtSiteName = $_POST["txtSiteName"];
    $regmode = $_POST["regmode"];
    $txtPopulateDummy = $_POST["txtPopulateDummy"];    
    $txtAdminName = $_POST["txtAdminName"];
    $txtAdminPassword = $_POST["txtAdminPassword"];
    $txtConfirmAdminPassword = $_POST["txtConfirmAdminPassword"];
    $txtLicenseKey = $_POST["txtLicenseKey"];
    $txtAdminEmail = $_POST["txtAdminEmail"];
    $txtTablePrefix = $_POST["txtTablePrefix"];
    }

    $post_flag = true;
    $message = "";

    if (!isNotNull($txtDBServerName)) {
        $message .= " * Database Server Name is empty!" . "<br>";
        $error = true;
    }
    if (!isNotNull($txtDBName)) {
        $message .= " * Database Name is empty!" . "<br>";
        $error = true;
    }
    if (!isNotNull($txtDBUserName)) {
        $message .= " * Database User Name is empty!" . "<br>";
        $error = true;
    }
    if (!isNotNull($txtSiteName)) {
        $message .= " * Site Name is empty!" . "<br>";
        $error = true;
    }
    /*if (!isNotNull($regmode)) {
        $message .= " * Registration mode is empty!" . "<br>";
        $error = true;
    }*/
    if (!isNotNull($txtLicenseKey)) {
        $message .= " * Licensekey is empty!" . "<br>";
        $error = true;
    }
    if (!isNotNull($txtAdminEmail)) {
        $message .= " * Admin Email is empty!" . "<br>";
        $error = true;
    } else {
        if (!isValidEmail($txtAdminEmail)) {
            $message .= " * Invalid Admin Email!" . "<br>";
            $error = true;
        }
    }

    $connection = @mysqli_connect($txtDBServerName, $txtDBUserName, $txtDBPassword);
    if ($connection === false) {
        $error = true;
        $message .= " * Connection Not Successful! Please verify your database details!<br>";
    } else {
        $dbselected = @mysqli_select_db($connection,$txtDBName );
        if (!$dbselected) {
            $error = true;
            $message .= " * Database could not be selected! Please verify your database details!<br>";
        }
    }

    //exit;

    //if ($error) {
        //$message = "<u><b>Please correct the following errors to continue:</b></u>" . "<br><br>" . $message;
        // echo $message;
    //}
    $version = '1.3';
    if (!$error) {

        //-------------------------UPDATE CONFIG FILE---------------------------//
        $uniqueid = time() . mt_rand() . session_id();
        if (strlen($uniqueid) > 15) {
            $uniqueid = substr($uniqueid, 0, 15);
            $uniqueid = md5($uniqueid);
        }//end if

        //retreving directory name
        $documentroot=str_replace("/install","",dirname($_SERVER['PHP_SELF']));
        $fp = fopen($configfile, "w+");
        $configcontent = "<?php\n";
        $configcontent .="ob_start();"."\n";
        $configcontent .="session_start();"."\n\n\n";
        $configcontent .= "define('INSTALLED', true);"."\n";
        if($_POST['cldpack']==1)
        {
            $configcontent .= "define('ISCRIPTSCLOUD', true);"."\n";
        }
        else
        {
            $configcontent .= "define('ISCRIPTSCLOUD', false);"."\n";
        }    
        $configcontent .= "include_once('mysql2i.class.php');";
        $configcontent .= "define('ENCSEED', '".$uniqueid."');"." \n\n\n";
        $configcontent .= "define('VERSION', $version); \n\n";
        $configcontent .= "ini_set('display_errors', '0'); \n\n";
        $configcontent .= "error_reporting(0); \n\n";
        if($_POST['cldpack']==1)
        {
            $configcontent .="$"."real_root='".$documentrootforcloud."';"."\n\n";
        }
        else
        {
            $configcontent.="$"."real_root='".$_SERVER['DOCUMENT_ROOT'].$documentroot."/';"."\n\n";
        }
        $configcontent .="ini_set('include_path',ini_get('include_path').':'."."$"."real_root.'classes/:'."."$"."real_root.'includes');"."\n";
        $configcontent .="define('STORY_IMAGE_PATH',"."$"."real_root.'images/success_stories');"."\n";
        $configcontent .="define('PROFILE_IMAGE_PATH',"."$"."real_root.'images/profiles');"."\n";
        $configcontent .="define('IMG_PATH',"."$"."real_root.'images/');"."\n\n\n";
        $configcontent .="define('BASE_PATH',"."$"."real_root);"."\n";
        $configcontent .="define('IMG_URL','/images/');"."\n";
        $configcontent .="define('STORY_IMAGE_URL','/images/success_stories');"."\n";
        $configcontent .="define('PROFILE_IMAGE_URL','images/profiles');"."\n\n";
        $configcontent .= "define('TABLEPREFIX','".$txtTablePrefix."');"."\n";
        $configcontent .="define('DB_HOST','".$txtDBServerName."');"."\n";
        $configcontent .="define('DB_USER','".$txtDBUserName."');"."\n";
        $configcontent .="define('DB_PASSWORD','".$txtDBPassword."');"."\n";
        $configcontent .="define('DB_DATABASE','".$txtDBName."');"."\n";        
        $configcontent .="define('REGISTRATION_FREE_MODE','Free');"."\n";
        $configcontent .="define('REGISTRATION_PAID_MODE','Paid');"."\n";
        $configcontent .="define('REGISTRATION_FREEMIUM_MODE','Freemium');"."\n";      
        $configcontent .="$"."arrAllowedPages       = array('user_photo_popup.php','manage_user_photos.php','profile.php');"."\n";
        $configcontent .="$"."arrUserAllowedPages   = array('profile.php');"."\n";
        $configcontent .= "\n?>";
        fwrite($fp, $configcontent);

        $sqlquery = @fread(@fopen($schemafile, 'r'), @filesize($schemafile));
        $sqlquery = preg_replace('/cyber_/', $txtTablePrefix, $sqlquery);
        $sqlquery = splitsqlfile($sqlquery, ";");

        // creating the tables......................................
        for($i = 0; $i < sizeof($sqlquery); $i++) {
            mysqli_query($connection,$sqlquery[$i]);
        }//end for loop

        $dataquery = @fread(@fopen($datafile, 'r'), @filesize($datafile));
        $dataquery = preg_replace('/cyber_/', $txtTablePrefix, $dataquery);
        $dataquery = splitsqlfile($dataquery, ";");

        // populating the tables with initial data......................................
        for($i = 0; $i < sizeof($dataquery); $i++) {
            mysqli_query($connection,$dataquery[$i]);
        }//end for loop

        // inserting the admin details in to the admin_users table.............

        
        if(!empty($_POST['txtPopulateDummy'])){
        /************************ Dummy Data ****************************/
        
        $string = file_get_contents("../dummydatas.json");
        $json_a = json_decode($string, true);

        
        
          for($i=0;$i<5;$i++)
    {
        
        $datauser = $json_a['data']['profiles'][1];
        $k1 = array_rand($json_a['data']['maleNames']);
        $username1 = $json_a['data']['maleNames'][$i].$json_a['data']['maleNames'][$k1];
        $datauser['vLogin'] = strtolower($username1);
        $datauser['vPass'] = md5(strtolower($username1));
        $datauser['vEmail'] = $json_a['data']['emailList'][$i];
        $datauser['vFirstName'] = $json_a['data']['maleNames'][$i];
        $datauser['vLastName'] = $json_a['data']['maleNames'][$k1];
        unset($datauser['photo']);
//      echo "<pre>";
//       print_r($datauser);
         $fields = array_keys($datauser);
         $datauser = array_map('addSlashes', $datauser);
            // build the query
            $sql = "INSERT INTO " . $txtTablePrefix ."user
    (`" . implode('`,`', $fields) . "`)
    VALUES('" . implode("','", $datauser) . "')";

            // run and return the query result resource
            mysqli_query($connection,$sql);
            $user_id =  @mysqli_insert_id($connection);
       // echo $id.'<br>';
          $data = array();
          $data['nUser_Id'] = $user_id;
          $data['vTitle'] = $username1;
          $data['vUrl'] = $json_a['data']['malePhots'][$i];
          $data['dDate'] = date('Y-m-d');
          
          
          $fields = array_keys($data);

            // build the query
            $sql = "INSERT INTO " . $txtTablePrefix ."photos
    (`" . implode('`,`', $fields) . "`)
    VALUES('" . implode("','", $data) . "')";

            // run and return the query result resource
            mysqli_query($connection,$sql);
             $fid =  @mysqli_insert_id($connection);
          if($fid)
          {
              copy('../dummyphoto/'.$data['vUrl'],'../images/profiles/'.$data['vUrl']);
              chmod('../images/profiles/'.$data['vUrl'], 0777);
              copy('../dummyphoto/'.'pthumb_'.$data['vUrl'],'../images/profiles/'.'pthumb_'.$data['vUrl']);
              chmod('../images/profiles/'.'pthumb_'.$data['vUrl'], 0777);
              copy('../dummyphoto/'.'sthumb_'.$data['vUrl'],'../images/profiles/'.'sthumb_'.$data['vUrl']);
              chmod('../images/profiles/'.'sthumb_'.$data['vUrl'], 0777);
              
              
              }
      
    }
        
        
    for($i=0;$i<5;$i++)
    {
        
        $datauser = $json_a['data']['profiles'][0];
        $k1 = array_rand($json_a['data']['femaleNames']);
        $username1 = $json_a['data']['femaleNames'][$i].$json_a['data']['femaleNames'][$k1];
        $datauser['vLogin'] = strtolower($username1);
        $datauser['vPass'] = md5(strtolower($username1));
        $datauser['vEmail'] = $json_a['data']['emailList'][$i];
        $datauser['vFirstName'] = $json_a['data']['femaleNames'][$i];
        $datauser['vLastName'] = $json_a['data']['femaleNames'][$k1];
        unset($datauser['photo']);
//      echo "<pre>";
//       print_r($datauser);
       $fields = array_keys($datauser);
       $datauser = array_map('addSlashes', $datauser);
            // build the query
            $sql = "INSERT INTO " . $txtTablePrefix ."user
    (`" . implode('`,`', $fields) . "`)
    VALUES('" . implode("','", $datauser) . "')";

            // run and return the query result resource
            mysqli_query($connection, $sql );
            $user_id =  @mysqli_insert_id($connection);
       // echo $id.'<br>';
          $data = array();
          $data['nUser_Id'] = $user_id;
          $data['vTitle'] = $username1;
          $data['vUrl'] = $json_a['data']['femalePhots'][$i];
          $data['dDate'] = date('Y-m-d');
           $fields = array_keys($data);

            // build the query
            $sql = "INSERT INTO " . $txtTablePrefix ."photos
    (`" . implode('`,`', $fields) . "`)
    VALUES('" . implode("','", $data) . "')";

            // run and return the query result resource
            mysqli_query($connection,$sql);
             $fid =  @mysqli_insert_id($connection);
          if($fid)
          {
              copy('../dummyphoto/'.$data['vUrl'],'../images/profiles/'.$data['vUrl']);
              chmod('../images/profiles/'.$data['vUrl'], 0777);
              copy('../dummyphoto/'.'pthumb_'.$data['vUrl'],'../images/profiles/'.'pthumb_'.$data['vUrl']);
              chmod('../images/profiles/'.'pthumb_'.$data['vUrl'], 0777);
              copy('../dummyphoto/'.'sthumb_'.$data['vUrl'],'../images/profiles/'.'sthumb_'.$data['vUrl']);
              chmod('../images/profiles/'.'sthumb_'.$data['vUrl'], 0777);
          }
    }
    
    /************** Gender Preference search ***************/
    
    mysqli_query( $connection, "UPDATE  " . $txtTablePrefix ."user SET vDate_Preference = 'Male' WHERE vGender='Female'");
    mysqli_query( $connection, "UPDATE  " . $txtTablePrefix ."user SET vDate_Preference = 'Female' WHERE vGender='Male'");
       
    /************** Gender Preference search ***************/

//        foreach ($json_a['data']['profiles'] as $key => $val) {
//
//            $photos = $val['photos'];
//
//            unset($val['photos']);
//
//            $fields = array_keys($val);
//
//            // build the query
//            $sql = "INSERT INTO " . $txtTablePrefix ."user
//    (`" . implode('`,`', $fields) . "`)
//    VALUES('" . implode("','", $val) . "')";
//
//            // run and return the query result resource
//            mysqli_query($sql, $connection);
//            $user_id =  @mysqli_insert_id($connection);
//
//            foreach ($photos as $k => $v) {
//                $data = array();
//
//                $data['nUser_Id'] = $user_id;
//                $data['vTitle'] = $v;
//                $data['vUrl'] = $v;
//                $data['dDate'] = date('Y-m-d');
//                $fields = array_keys($data);
//
//            // build the query
//            $sql = "INSERT INTO " . $txtTablePrefix ."photos
//    (`" . implode('`,`', $fields) . "`)
//    VALUES('" . implode("','", $data) . "')";
//
//            // run and return the query result resource
//            mysqli_query($sql, $connection);
//          
//            }
//        }
        
        
        
        /************************* Dummy data End ************************/
        
        }
        
        
        $adminusername = $txtAdminName;
        $adminusername = $adminusername == '' ? 'admin' : $adminusername ;
        $adminpassword = $txtAdminPassword;
        $adminpassword = $adminpassword == '' ? 'admin' : $adminpassword ;
        $logofilename = "logo-new.png";
        $logofilename_mobile = "mobile_logo_default.gif";
        $sqlsettings = "INSERT INTO ". $txtTablePrefix."lookup ( vName,vValue)
                                VALUES ('adminuser','".mysqli_real_escape_string($connection,$adminusername)."'),
                                        ('adminpassword','".md5(mysqli_real_escape_string($connection,$adminpassword))."'),
                                        ('site_normal_url','".$txtSiteURL."'),
                                        ('site_secure_url','".$txtSiteURL."'),
                                        ('adminmail','".mysqli_real_escape_string($connection,$txtAdminEmail)."'),
                                        ('sitelogo','".mysqli_real_escape_string($connection,$logofilename)."'),
                                        ('MobileLogo','".mysqli_real_escape_string($connection,$logofilename_mobile)."'),
                                        ('vLicenceKey','".mysqli_real_escape_string($connection,$txtLicenseKey)."'),
                                        ('regmode','".mysqli_real_escape_string($connection,$regmode)."'),
                                        ('sitename','".mysqli_real_escape_string($connection,$txtSiteName)."')";
        mysqli_query( $connection, $sqlsettings) or die(mysqli_error());
        
        $installed = true;

        /* -------------- /
        New code for install tracker
        /------------------*/
        $documentroot   = $_SERVER['DOCUMENT_ROOT'];
        $realpath       = realpath("../");
        $replacedpath   = str_replace($documentroot,"",$realpath);
        $rootserver     = "http://".$_SERVER['SERVER_NAME'].$replacedpath;

        $string     = "";
        $pro        = urlencode("Cybermatch 1.0");
        $dom        = urlencode($rootserver);
        $ipv        = urlencode($_SERVER['REMOTE_ADDR']);
        $mai        = urlencode($txtAdminEmail);
        $string     = "pro=$pro&dom=$dom&ipv=$ipv&mai=$mai";
        $contents   = "no";
        $file       = @fopen("http://www.iscripts.com/installtracker.php?$string", 'r');
        if ($file) {
            $contents = @fread($file, 8192);
        }
        /* -------------- /
        New code for install tracker
        /------------------*/

        if($_POST['cldpack']!=1)
        {
        $subject = "Script Installed at " . $txtSiteName;
        $headers = "From: " . $txtSiteName . "<" . $txtAdminEmail . ">\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
        $path = "installer_logo.png";
        $mcont = "<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>
                    <tr><td><a href='" . $txtSiteURL . "' target='_blank'><img src='" . $txtSiteURL . "/images/" . $path . "' border='0'></a></td></tr></table>";
        $mailcontent = $mcont . "Hello , <br>";
        $mailcontent .= "Your Site is successfully installed.<br> <a href='" . $txtSiteURL . "' target='_blank'>Click Here to Access your Site</a>";
        $mailcontent .= "<br><a href='" . $txtSiteURL.'/admin/' . "' target='_blank'>Click Here to Access your Store Administration Control Panel</a> <br>";
        $mailcontent .= "Your Admin Username   :  " . $adminusername;
        $mailcontent .= "<br>Your Admin Password   :  " . $adminmailpword;
        $mailcontent .= "<br> Thanks and regards,<br> " . $txtSiteName . " Team";
        $mailsent = mail(addslashes($txtAdminEmail), $subject, $mailcontent, $headers);
        }
        // section to send details to admin...............................
    }
}

$productTitle = 'Cybermatch';
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>iScripts <?php echo $productTitle; ?> Installation</title>
        <link href="../styles/installer.css" rel="stylesheet" type="text/css">
    </head>
    <script type="text/javascript" src="../js/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){ 
            if($('#auto_set').attr('checked')){
                $('#err_div').slideDown('slow');
            }
        });
        function divToggle(elem){
            if($(elem).attr('checked')){
                $('#err_div').slideDown('slow');
            }
            else{
                $('#err_div').slideUp('slow');
            }
        }
    </script>
    <style type="text/css">
        .install_option {  font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; color: #333333}
        .install_value_ok { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-weight: bold; color: #009900 }
        .install_value_fail { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 7pt; font-weight: bold; color: #CC0000}
        .block_class{
            color:#F4700E;
            font-family: Verdana, Arial, Helvetica, sans-serif;
            font-weight: bold;}

    </style>
    <body class="bodyinstaller">
        <div class="header_row" >
            <div class="header_container  sitewidth">
                <table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
                    <tr>
                        <td width="23%" align="left" ><img src="../images/installer_logo.png" alt="Logo"></td>
                        <td width="77%" align="right">
                            <h4>iScripts <?php echo $productTitle; ?> Installer</h4>
                            <div align="center" id="items_top_area">
                                &nbsp;&nbsp;
                                <a title="OnlineInstallationManual" href="#" onClick="window.open('<?php echo htmlentities($txtSiteURL);?>/docs/Insatallation_Manual.pdf','OnlineInstallationManual','top=100,left=100,width=820,height=550,scrollbars=yes,toolbar=no,status=yrd');"><strong>Installation Manual</strong></a> |
                                <a title="Readme" href="#" onClick="window.open('<?php echo htmlentities($txtSiteURL);?>/docs/Readme.txt','Readme','top=100,left=100,width=820,height=550,scrollbars=yes,toolbar=no,status=yrd');"><strong>Readme</strong></a> |
                                <a title="If you have any difficulty, submit a ticket to the support department" href="#" onClick="window.open('http://www.iscripts.com/support/postticketbeforeregister.php','','top=100,left=100,width=820,height=550,scrollbars=yes,toolbar=no,status=yrd,resizable=yes');">
                                <strong>Get Support</strong></a>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <table width="100%"  border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td><img src="../img/spacer.gif" width="1" height="5"></td>
            </tr>
        </table>
        
        <table width="100%"  border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td width="76%" valign="top" height ="400">
                    <!-- Here's where I want my views to be displayed -->
                    <table width="80%" border="0" cellpadding="0" cellspacing="0" align="center">
                        <tr>
                            <td>
                                <!--------Installer starts------------------------->

                                <!--items display area start -->
                                <?php
                                if ($serverconfiguration == "FAILURE") {
                                ?>
                                <table width="80%" border=0 align="center">
                                        <?php
                                        $ivo = "<span class='install_value_ok'>";
                                        $ivf = "<span class='install_value_fail'>";
                                        $sc = "</span>";
                                        echo "<tr><td class=maintext><b></b><br><br></td></tr>";
                                        echo "<tr><td class=maintext>Checking PHP Version... " . $ivo . PHP_VERSION . $sc . " ";
                                        if (version_compare(PHP_VERSION, "4.2.0") >= 0)
                                            echo $ivo . "" . $sc; else {
                                            echo $ivf . "(4.2.0 or higher required)" . $sc;
                                            $fatal = true;
                                        }
                                        echo "</td></tr>";
                                        echo "<tr><td class=maintext>Checking System Information... " . $ivo . PHP_OS . $sc . "</td></tr>";
                                        echo "<tr><td class=maintext>Checking PHP Server API... " . $ivo . php_sapi_name() . $sc . "</td></tr>";
                                        echo "<tr><td class=maintext>Checking Path to 'php.ini'... " . $ivo . PHP_CONFIG_FILE_PATH . $sc . "</td></tr>";
                                        $mysqlsupport = true;
                                        if (!function_exists('mysqli_connect')) {
                                            $mysqlsupport = false;
                                        }
                                        echo "<tr><td class=maintext>Checking Mysql support... ";
                                        echo $ivo . (( $mysqlsupport) ? "On" : " $ivf This program requires MYSQL support. Please recompile your PHP with MYSQL Support.") . $sc;
                                        echo "</td></tr>";
                                        echo "<tr><td class=maintext>Checking safe_mode... ";
                                        $val1 = ini_get("safe_mode");
                                        echo ((!empty($val1) || $val1 == 1) ? $ivf . "On-Please turn off safe_mode in the php.ini" : $ivo . "Off") . $sc;
                                        echo "</td></tr>";

                                        echo "<tr><td class=maintext>Checking file_uploads...";
                                        $val3 = ini_get("file_uploads");
                                        echo ((!empty($val3) || $val3 == 1) ? $ivo . "On" : $ivf . "Off - Please turn on file_uplaods in the php.ini file") . $sc;
                                        echo "</td></tr>";

                                        echo "<tr><td class=maintext>Checking CURL support... ";
                                        $val5 = function_exists('curl_init');
                                        if ($val5) {
                                            echo $ivo . "On";
                                        } else {
                                            echo $ivf . "Off-Please re-compile php with CURL support" . $sc;
                                        }
                                        echo "</td></tr>";
                                        echo "<tr><td class=maintext>Checking GD support... ";
                                        $val6 = function_exists('gd_info');
                                        if ($val6) {
                                            echo $ivo . "On";
                                        } else {
                                            echo $ivf . "Off-Please re-compile php with GD support" . $sc;
                                        }
                                        echo "</td></tr>";

                                        echo "<tr><td class=maintext>" . $ivf . "Fatal errors detected.  Please correct the above red items and reload.</td></tr>";
                                        ?>
                                </table>

                                    <?php
                                } else if (!$installed) {
                                    ?>
                                <table width="80%" border="0" align="center">
                                    <tr>
                                        <td align="center" ><b><font size="1">
                                                    <div align="justify" >
                                                        <br>
                                                        <font color="#F4700E" size="+1">Thank you for choosing iScripts <?php echo $productTitle; ?>&nbsp;</font> <br><br>
                                                        <font color="#000000" size="2">To complete this installation please enter the details below.</font>
                                                    </div>

                                                </font></b>
                                        </td>
                                    </tr>
                                        <?php if ($post_flag) { ?>
                                    <tr>
                                        <td align=center class="message" >
                                            <div align="left" class="text_information">
                                                <br>
                                                <?php if($error){?><u><b><font color="#FF0000">Please correct the following errors to continue:</font></b></u><p/><?php }?>
                                                <font color="#FF0000"><?php echo $perm_msg; ?></font><br>
                                                <font color="#FF0000"><?php echo $error_message . '<br/>' . $message; ?></font><br>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                    <tr>
                                        <td class=maintext align="left" >
                                            Note: All Fields Are Mandatory.
                                            <br>
                                            <form name="frmInstall" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data">
                                                <br>

                                                <FIELDSET>
                                                    <LEGEND class='block_class'>File Permissions</LEGEND>
                                                    <table width=85% border="0" cellpadding="2" cellspacing="2" class=maintext>
                                                        <tr>
                                                            <td colspan="2" align="left">
                                                                <b>
                                                                        <?php if ($serverPermission) { ?>
                                                                    iScripts <?php echo $productTitle; ?> requires that some of the folders have write permission. You can provide an FTP login so that this process is done automatically.<br/><br/>
                                                                    For security reasons, it is best to create a separate FTP user account with access to the iScripts <?php echo $productTitle; ?> installation only and not the entire web server. Your host can assist you with this.
                                                                    If you have difficulties completing installation without these credentials, please click "I would provide permissions manually" to do it yourself.<br/><br/>
                                                                            <?php }  ?>
                                                                </b>
                                                            </td>
                                                        </tr>
                                                            <?php if ($serverPermission) { ?>
                                                        <tr>
                                                            <td class=maintext align="left">FTP username</td>
                                                            <td width="61%" align=left>
                                                                <input name="FTPusername"  id="FTPusername" type="text" size="50" value="<?php echo htmlentities($txtFTPusername); ?>">
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td class=maintext align="left">FTP password</td>
                                                            <td width="61%" align=left>
                                                                <input name="FTPpassword"  id="FTPpassword" type="password" size="50" value="<?php echo htmlentities($txtFTPpassword); ?>">
                                                            </td>
                                                        </tr>
                                                                <?php if ($serverPermission) { ?>
                                                        <tr>
                                                            <td colspan="2" align="left">
                                                                <input type="checkbox" name="auto_set" id="auto_set" <?php echo ($_POST['auto_set'])?'checked':'';?> onclick="divToggle(this)" /> &nbsp; I would provide permissions manually
                                                            </td>
                                                        </tr>
                                                                    <?php
                                                                }
                                                            } else {
                                                                ?>
                                                        <tr>
                                                            <td colspan="2" align="left">
                                                                <b>File permissions are OK.</b>
                                                            </td>
                                                        </tr>
                                                                <?php } ?>
                                                    </table>
                                                        <?php if ($serverPermission) { ?>
                                                    <div id="err_div" style="<?php if ($serverPermission) { ?>display:none<?php } ?>">
                                                        <fieldset>
                                                            <legend>Directories/Files List</legend>
                                                                    <?php echo $error_message; ?>
                                                        </fieldset>
                                                    </div>
                                                            <?php } ?>
                                                </FIELDSET>
                                                <br>
                                                <br>

                                                <FIELDSET>
                                                    <LEGEND class='block_class'>Database Details</LEGEND>
                                                    <table width=85% border=0 cellpadding="2" cellspacing="2" class=maintext>
                                                        <tr>
                                                            <td colspan="2" class=maintext align="left">Database Server</td>
                                                            <td width="61%" align=left>
                                                                <input type="text" name="txtDBServerName" id="txtDBServerName" value="<?php echo htmlentities($txtDBServerName); ?>">
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td colspan="2" class=maintext align="left">Database Name</td>
                                                            <td width="61%" align=left>
                                                                <input name="txtDBName"  id="txtDBName" type="text"   class="textbox"  maxlength="100" size="50" value="<?php echo htmlentities($txtDBName); ?>" >
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td colspan="2" class=maintext align="left">Database User Name</td>
                                                            <td width="61%" align=left>
                                                                <input name="txtDBUserName"  id="txtDBUserName" type="text" maxlength="100" size="50" value="<?php echo htmlentities($txtDBUserName); ?>">
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td colspan="2" class=maintext align="left">Database Password</td>
                                                            <td width="61%" align=left>
                                                                <input name="txtDBPassword"  id="txtDBPassword" type="text"  maxlength="100" size="50" value="<?php echo htmlentities($txtDBPassword); ?>">
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td colspan="2" class=maintext align="left">Table Prefix</td>
                                                            <td width="61%" align=left>
                                                                <input name="txtTablePrefix"  id="txtTablePrefix" type="text"  maxlength="100" size="50" value="<?php echo htmlentities($txtTablePrefix); ?>">
                                                            </td>
                                                        </tr>

                                                    </table>
                                                </FIELDSET><br><br>
                                                <FIELDSET>
                                                    <LEGEND class='block_class'>Site Details</LEGEND>
                                                    <table width=85% border=0 cellpadding="2" cellspacing="2" class=maintext>
                                                        <tr>
                                                            <td colspan="2" class=maintext align="left">Site Name</td>
                                                            <td width="61%" align=left>
                                                                <input name="txtSiteName"  id="txtSiteName" type="text" maxlength="100" size="50" value="<?php echo htmlentities($txtSiteName); ?>">
                                                                <input name="txtSiteURL"  id="txtSiteURL" type="hidden" maxlength="100" value="<?php echo htmlentities($txtSiteURL); ?>" readonly >
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td colspan="2" class=maintext align="left">License Key</td>
                                                            <td width="61%" align=left>
                                                                <input name="txtLicenseKey"  id="txtLicenseKey" type="text" maxlength="100" size="50" value="<?php echo htmlentities($txtLicenseKey); ?>">
                                                            </td>
                                                        </tr>
                                                         <tr>
                                                            <td colspan="2" class=maintext align="left">Populate some dummy user informations</td>
                                                            <td width="61%" align=left>
                                                                
                                                                <input name="txtPopulateDummy"  id="txtPopulateDummy" type="checkbox" value="1" >
                                                               
                                                            </td>
                                                        </tr>
                                                         <tr>
                                                            <td colspan="2" class=maintext align="left">Subscription Mode</td>
                                                            <td width="61%" align=left>                                                                
                                                                <input name="regmode"  id="txtregmode" type="radio" value="Free" checked="checked"> Free
                                                                <input name="regmode"  id="txtregmode" type="radio" value="Paid" >Paid
                                                                <input name="regmode"  id="txtregmode" type="radio" value="Freemium" >Freemium                                                               
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </FIELDSET>
                                                <br>
                                                <br>
                                                <FIELDSET>
                                                    <LEGEND class="block_class">Administration Details</LEGEND>
                                                    <table width=85% border=0 cellpadding="2" cellspacing="2" class=maintext>
                                                        <tr>
                                                            <td colspan="2" class=maintext  align="left">Admin Email</td>
                                                            <td width="61%" align=left>
                                                                <input name="txtAdminName"  id="txtAdminName" type="hidden" maxlength="100" size="50" value="admin">
                                                                <input name="txtAdminPassword"  id="txtAdminPassword" type="hidden" maxlength="100" size="50" value="admin">
                                                                <input name="txtConfirmAdminPassword"  id="txtConfirmAdminPassword" type="hidden" maxlength="100" size="50" value="admin">
                                                                <input name="txtAdminEmail"  id="txtAdminEmail" type="text"  maxlength="100" size="50" value="<?php echo htmlentities($txtAdminEmail); ?>">
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </FIELDSET>
                                                <br>
                                                <table width=100% border=0 cellpadding="2" cellspacing="2" class=maintext>

                                                    <tr>
                                                        <td align="center">
                                                            <input type="submit" name="btnContinue" value="Continue" class="buttn_admin">
                                                        </td>
                                                    </tr>
                                                </table>
                                            </form>
                                        </td>
                                    </tr>
                                </table>
                                    <?php
                                } else { 
                                    ?>
                                <table width="80%" border="0" align="center">
                                    <tr>
                                        <td>
                                            <table width=85% border=0 cellpadding="2" cellspacing="2" class=maintext align="center">
                                                <br>
                                                <tr>
                                                    <td align="center" class="maintext" >
                                                        <font color="#F4700E" size="+1">Congratulations! The Installation Process was completed successfully!</font>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td align="center" class="maintext" height="20" >&nbsp;</td>
                                                </tr>
                                                <br>
                                                <br>
                                                <br>
                                                <tr>
                                                    <td align="center"><span class="required">*</span><b>
                                                            All Payment Gateways are disabled by default,Please enable at least one payment gateway !!</b>
                                                    </td>
                                                </tr>
                                                <br>
                                                    <?php
                                                    $request_uri = explode('/', $_SERVER['REQUEST_URI']);

                                                    $script_filename = explode('/', $_SERVER['SCRIPT_FILENAME']);
                                                    $build_path = "http://" . $_SERVER['HTTP_HOST'] . "/" . $request_uri[1] . "/admin/login.php";
                                                    $build_path_home = "http://" . $_SERVER['HTTP_HOST'] . "/" . $request_uri[1] . "/index.php";
                                                    ?>
                                                <tr>
                                                    <td align="center">
                                                        <br>
                                                        <fieldset>
                                                            <legend class="block_class">Site Login Details</legend>
                                                            <table cellpadding="0" cellspacing="0" width="95%" class="maintext" align="center">
                                                                <tr>
                                                                    <td colspan="2">&nbsp;</td>
                                                                </tr>
                                                                <tr>
                                                                    <td width="26%"><b><font size="-1">Admin URL&nbsp;:</font></b></td>
                                                                    <td width="74%"><a style="cursor:pointer; text-decoration: none; font-weight: bold;" href="<?php echo $txtSiteURL . "/admin/" ?>"><img src="admin_login_install.jpg" border="0" height="25" align="absmiddle">&nbsp; &nbsp; <?php echo $txtSiteURL . "/admin/"; ?></a></td>
                                                                </tr>
                                                                <tr>
                                                                    <td colspan="2">&nbsp;</td>
                                                                </tr>
                                                                <tr>
                                                                    <td  valign="top"><b><font size="-1">Admin Credentials&nbsp;:</font></b></td>
                                                                    <td  valign="top">
                                                                        <div class="adm_cred">
                                                                            <font size="-1">Username&nbsp;:&nbsp;admin</font><br/><br/>
                                                                            <font size="-1">Password&nbsp;:&nbsp;admin</font>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td colspan="2">&nbsp;</td>
                                                                </tr>
                                                                <tr>
                                                                    <td ><b><font size="-1">Home URL&nbsp;:</font></b></td>
                                                                    <td ><a style="cursor:pointer; text-decoration: none;font-weight: bold;" href="<?php echo $txtSiteURL; ?>/"><img src="home_page.jpg" border="0" height="25" align="absmiddle">&nbsp; &nbsp;<?php echo $txtSiteURL; ?>/</a></td>
                                                                </tr>
                                                            </table>
                                                        </fieldset>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td align="center" class="maintext" height="20" >&nbsp;</td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                </table>
                                    <?php
                                }
                                ?>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        <div class="installr_footer"></div>
    </body>
</html>