<?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('openssl')){
	exit("<div style='color:484848;padding:20px 30px;'><b>openssl is not loaded, This process require openssl to encrypt all passwords, please try to fix that or switch to another server with openssl loaded</b></div>");
}

require_once("config/config.php");
require_once("vendor/autoload.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");
require_once("system/required/Encryption.class.php");

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 = "after.php?page=".floor($page+1);
}

ob_start();

$items = get_items("users", $start, $limit);
if(!empty($items) && is_array($items))
{
	foreach($items as $item)
	{
		$password = "";
		$password = Encryption::encode(urldecode(str_replace("%00", "", urlencode($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 = "";
			$password = Encryption::encode(urldecode(str_replace("%00", "", urlencode($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 encrypt passwords using openssl</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;' >ENCRYPTION COMPLETE</h2>";
	@unlink("after.php");
}

echo "</center>";


ob_end_flush();

?>
