<?php

define("_sys", "HZ");
define("_version", "6.0.0");
define("_syspath", __DIR__);
define("_surfow_path", __DIR__);

error_reporting(0);
ini_set('display_errors', 0);

if(!extension_loaded('mcrypt')){
	exit("<div style='color:484848;padding:20px 30px;'><b>mcrypt is not loaded, This process require mcrypt to decrypt all passwords, please try to use your old server/configuration or switch to another server with mcrypt loaded</b></div>");
}

require_once("config/config.php");
require_once("system/required/Log.class.php");
require_once("system/required/Request.class.php");
require_once("system/required/Sys.class.php");
require_once("system/required/Db.class.php");

class OldEncryption {

	private static $syskey = '';

    public static function randomstring($length = 8)
	{
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return trim($randomString);
    }

    public static function direct($sysk)
    {
        $s_count = strlen($sysk);
        if(!empty($sysk) && $s_count >= 8)
        {
            self::$syskey = substr($sysk, 0, 8);
        }
        else
        {
            self::$syskey = "systemky";
        }
    }

    protected static function safe_b64encode($string)
	{
        $data = base64_encode($string);
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
        return $data;
    }

    protected static function safe_b64decode($string)
	{
        $data = str_replace(array('-','_'),array('+','/'),$string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }

    public static function encode($value)
	{
		try
		{
			if(!$value){return false;}
	        if(!empty(self::$syskey))
	        {
	            $s_key = self::$syskey;
	        }
	        else
	        {
	            $s_key = self::randomstring();
	        }
	        $text      = $value;
	        $iv_size   = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
	        $iv        = mcrypt_create_iv($iv_size, MCRYPT_RAND);
	        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $s_key.substr($GLOBALS["_SETTINGS"]["KEY"], 0, 24), $text, MCRYPT_MODE_ECB, $iv);
	        return trim($s_key.self::safe_b64encode($crypttext));
		} catch(Exception $e){
			return false;
		}
		return false;
    }

    public static function decode($value)
	{
		try
		{
			if(empty(ltrim(rtrim($value, " "), " "))){return false;}
			$custom_key  = substr($value, 0, 8);
			$value       = str_replace($custom_key, "", $value);

			$xdata = str_replace(array('-','_'),array('+','/'),$value);
	        $mod4 = strlen($xdata) % 4;
	        if ($mod4) {
	            $xdata .= substr('====', $mod4);
	        }

			if(base64_encode(base64_decode($xdata)) === $xdata)
			{
				$crypttext   = self::safe_b64decode($value);
		        $iv_size     = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
		        $iv          = mcrypt_create_iv($iv_size, MCRYPT_RAND);
		        $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $custom_key.substr($GLOBALS["_SETTINGS"]["KEY"], 0, 24), $crypttext, MCRYPT_MODE_ECB, $iv);
		        return $decrypttext;
			}
		} catch(Exception $e){
			return false;
		}
		return false;
    }

    public static function generate($length = 10)
	{
        $generated = self::randomstring($length);
		$encode    = self::encode($generated);
		return $encode;
    }
}

function count_items($op)
{
	$query = "SELECT COUNT(id) FROM ".$op;
	$get = Db::query($query);
	return $get[0]["COUNT(id)"];
}

function get_items($table, $start=0, $limit=50)
{
	Db::bind("start", $start);
	Db::bind("limit", $limit);
	$data = Db::query("SELECT * FROM ".$table." LIMIT :start, :limit");
	return $data;
}

$all_users = count_items("users");

if(isset($_GET["page"]))
{
	$page = $_GET["page"];
} else {
	$page = 1;
}

if(is_numeric($page) && $page > 0)
{
	$start = floor(50*($page - 1));
	$progress = 50*$page;
	if($progress > $all_users)
	{
		$progress = floor($progress-($progress-$all_users));
	}
	$limit = 50;
	$keep  = ($all_users == $progress) ? false : true;
	$nextpage = "before.php?page=".floor($page+1);
}

ob_start();

$items = get_items("users", $start, $limit);
if(!empty($items) && is_array($items))
{
	foreach($items as $item)
	{
		$password = false;
		$password = OldEncryption::decode($item["password"]);
		if($password)
		{
			Db::bind("id", $item["id"]);
			Db::bind("password", $password);
			Db::query("UPDATE users SET `password` = :password WHERE id = :id");
		}
	}
}

if(!$keep)
{
	$aditems = get_items("users", 0, count_items("admins"));
	if(!empty($aditems) && is_array($aditems))
	{
		foreach($aditems as $item)
		{
			$password = false;
			$password = OldEncryption::decode($item["password"]);
			if($password)
			{
				Db::bind("id", $item["id"]);
				Db::bind("password", $password);
				Db::query("UPDATE admins SET `password` = :password WHERE id = :id");
			}
		}
	}
}

ob_flush();

echo "<center style='border: solid 2px #808080; border-radius:10px;padding:40px;margin: 80px 60px;' >";
echo "<p>we're going to decrypt passwords from mcrypt to normal plain/text</p><br>";
echo "<b>USERS: $progress/$all_users</b><br>";

if($keep) {
	echo "<meta http-equiv='refresh' content='4; url=$nextpage'/>please wait...<br><h2 style='color:red;' >(DO NOT CLOSE THIS PAGE)</h2>";
} else {
	echo "<br><h2 style='color:green;' >DECRYPTION COMPLETE</h2>";
	@unlink("before.php");
}

echo "</center>";


ob_end_flush();

?>
