<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: 			*/
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004-2011 ARMIA INC                                    |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Easyindex                     |
// +----------------------------------------------------------------------+
// | Authors: Aswin<aswin.j@armiasystems.com>             		  |
// +----------------------------------------------------------------------+
?>
<?php
error_reporting(0);
session_start();


function checkAndValidateEntityAlias($table_name, $alias_text, $id_column="id",$id = "", $alias_column="alias") {
            
        //format alias 
        $alias = str_replace("&amp;", "and", $alias_text);
        $alias = htmlspecialchars_decode($alias, ENT_QUOTES);
        $alias = str_replace("-", " ", $alias);
        $alias = preg_replace("/[^a-zA-Z0-9\s]/", "", $alias);
        $alias = preg_replace('/[\r\n\s]+/xms', ' ', trim($alias));
        $alias = strtolower(str_replace(" ", "-", $alias));

        //$dbh = new ModelCommon();
        //check for duplicates
        $sql = "select count(*) as total from $table_name where $alias_column = '".$alias."'";
        if ($id) $sql .= " and $id_column <> $id";
        $duplicates = fetchRow($sql);

        //if duplicates exist recursively create a new alias and try
        if ($duplicates->total > 0) {
                $rand_str = rand_str(4);
                return checkAndValidateEntityAlias($table_name, $alias."-".$rand_str,$id_column, $id,$alias_column);
        }

        return strtolower($alias);
}


	//creates a random string
function rand_str($length = 32, $chars = 'abcdefghijklmnopqrstuvwxyz1234567890')
{
        // Length of character list
        $chars_length = (strlen($chars) - 1);

        // Start our string
        $string = $chars{rand(0, $chars_length)};

        // Generate random string
        for ($i = 1; $i < $length; $i = strlen($string))
        {
                // Grab a random character from our list
                $r = $chars{rand(0, $chars_length)};

                // Make sure the same two characters don't appear next to each other
                if ($r != $string{$i - 1}) $string .=  $r;
        }

        // Return the string
        return $string;
}
function fetchRow($resultSet)
	{
		$resultArray = array();
		while($obj = mysqli_fetch_object($resultSet))
		{
			$resultArray[] = $obj;
		}
        if(isset($resultArray[0])) {
            return $resultArray[0];
        }
		return $resultArray;
	}


$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);
}

$installed = false;
$txtDBServerName        =       "localhost";
$txtTablePrefix		=	"EasyIndex_";

$settingsfile           =       "config/settings.php";
$globalfile             =       "config/globals.php";

$txtSiteURL             =       "http://".$fullurl;
$txtSecureSiteURL       =       "https://" . $fullurl;
$txtSiteURLt            =       "http://".$fullurl;
$txtSecureSiteURLt      =       "https://" . $fullurl;

/* *********************************check server configuration *****************************************************/

  

//include_once('../config.php');
include_once($settingsfile);
$database = MYSQL_USERNAME;
$databasePassword = MYSQL_PASSWORD;
$server =  MYSQL_HOST;
$databaseName = MYSQL_DB;
$sqlUser    = $database;
$sqlPass    = $databasePassword;
$sqlHost    = $server;
$sqlDB      = $databaseName;

$db_error = false;

$connection = @mysqli_connect($sqlHost, $sqlUser, $sqlPass);
if ($connection === false) {
    $error = true;
    $db_error = true;
    $message .= " * Connection Not Successful! Please verify your database details!<br>";
    $serverconfiguration    = "FAILURE";
} else {
    $dbselected = @mysqli_select_db($connection,$sqlDB);
    if (!$dbselected) {
        $error = true;
        $db_error = true;
        $message .= " * Database could not be selected! Please verify your database details!<br>";
        $serverconfiguration    = "FAILURE";
    }
}


        //---------------------------------------------------------------------------------------------------------------------------------------------------------------//
        
        $qry = mysqli_query($connection,"SELECT * FROM ".$txtTablePrefix."product WHERE alias='' and nStatus='1'") or die(mysqli_error($connection));
        
        if($qry){            
            while($res = mysqli_fetch_array($qry)){
                  $product_alias  =   checkAndValidateEntityAlias('product', $res['Title'],'nBusId' ,$id = "", $alias_column="alias");
                   mysqli_query($connection,"UPDATE `".$txtTablePrefix."product` SET `alias` = '".$product_alias."' WHERE `nBusId` =".$res['nBusId']) or die(mysqli_error($connection)); 
               }
         }

        
       