ip = $_SERVER['HTTP_CLIENT_IP'];
else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$this->ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if (isset($_SERVER['HTTP_X_FORWARDED']))
$this->ip = $_SERVER['HTTP_X_FORWARDED'];
else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
$this->ip = $_SERVER['HTTP_FORWARDED_FOR'];
else if (isset($_SERVER['HTTP_FORWARDED']))
$this->ip = $_SERVER['HTTP_FORWARDED'];
else if (isset($_SERVER['REMOTE_ADDR']))
$this->ip = $_SERVER['REMOTE_ADDR'];
else
$this->ip = 'UNKNOWN';
$this->rootDirectory = __DIR__;
// Replace Arabic Characters With Farsi Characters
function replaceFunction(&$element)
{
$searchArray = array("<", ">", "ي", "ك", "۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩");
$replaceArray = array("<", ">", "ی", "ک", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
// $element = str_replace($searchArray, $replaceArray, $element);
// $element = htmlspecialchars(str_replace($searchArray, $replaceArray, $element), ENT_QUOTES, 'UTF-8');
$element = htmlspecialchars(str_replace($searchArray, $replaceArray, $element));
}
array_walk_recursive($_GET, 'replaceFunction');
array_walk_recursive($_POST, 'replaceFunction');
array_walk_recursive($_COOKIE, 'replaceFunction');
array_walk_recursive($_REQUEST, 'replaceFunction');
date_default_timezone_set("Asia/Tehran");
@error_reporting(E_ALL & ~E_NOTICE | E_STRICT);
/*
@ini_set('session.gc_maxlifetime', $sessionTimeout);
@ini_set('session.gc_probability', 1);
@ini_set('session.gc_divisor', 1000);
@session_set_cookie_params($sessionTimeout);
*/
/*
ini_set('session.cookie_domain', $_SERVER['HTTP_HOST']);
ini_set('session.cookie_samesite', 'none');
ini_set('session.cookie_secure', 1);
if (version_compare(PHP_VERSION, '7.3', '<'))
{
session_set_cookie_params(
array(
'lifetime' => $sessionTimeout,
'path' => '/; SameSite=none',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true,
'httponly' => false,
)
);
}
else
{
session_set_cookie_params(
array(
'lifetime' => $sessionTimeout,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true,
'httponly' => false,
'samesite' => 'none'
)
);
}
*/
if (in_array($_SERVER['HTTP_HOST'], array("websitebuilder.com", "cms.com")) || !empty($_SESSION['err']))
{
@ini_set('display_errors', 'on');
}
else
{
@ini_set('display_errors', 0);
@ini_set("log_errors", 1);
@ini_set("error_log", getcwd() . "/error-log.txt");
session_set_cookie_params(array("SameSite" => "none")); // None, Lax, Strict
session_set_cookie_params(array("Secure" => "true")); // false, true
}
// @ini_set('memory_limit', -1);
//Session_Start
session_start();
// header('Set-Cookie: ' . session_name() . '=' . session_id() . '; SameSite=None; Secure');
/*
if (version_compare(PHP_VERSION, '7.3', '<'))
{
// setcookie(session_name(), session_id(), 0, "/; SameSite=none");
setcookie(session_name(), session_id(), $sessionTimeout, "/; SameSite=none", $_SERVER['HTTP_HOST'], true, false);
}
else
{
setcookie(session_name(), session_id(), array(
'expires' => $sessionTimeout,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true,
'httponly' => false,
'samesite' => 'none'
)
);
}
*/
$this->now = time();
//try
//{
//connect
require_once "inc/config.php";
$this->modules = $modules;
$this->db = new PDO('mysql:dbname=' . $mysql_database . ';host=' . $mysql_host . ';charset=utf8mb4;', $mysql_username, $mysql_password);
$this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8mb4');
$this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET sql_mode=""');
// Enable QueryCache
if (MySQLCache == true)
{
$this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET query_cache_size=1073741824'); // 1 GB
$this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET query_cache_type=1'); // All queries will cached except SQL_NO_CACHE queries
$this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET query_cache_limit=104857600'); // 100 MB
$this->db->exec('SET query_cache_size=1073741824'); // 1 GB
$this->db->exec('SET query_cache_type=1'); // All queries will cached except SQL_NO_CACHE queries
$this->db->exec('SET query_cache_limit=104857600'); // 100 MB
}
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->db->exec('SET NAMES "utf8mb4"');
$this->db->exec('SET sql_mode=""');
// $var = $this->db->query('SHOW VARIABLES LIKE "%query_cache%"');
// print_r($var->fetchAll());
if ($_GET['err'] == 1)
{
$_SESSION['err'] = 1;
}
elseif ($_GET['err'] == 0)
{
$_SESSION['err'] = 0;
}
if (!empty($_GET['utm_source'])) // Check utm_source
{
setcookie("utm_source", $_GET['utm_source'], array(
'expires' => $this->now + 2592000,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true,
'httponly' => false,
'samesite' => 'none'
)
);
$this->utm_source = $_GET['utm_source'];
}
elseif (!empty($_SERVER['HTTP_REFERER'])) // Check Referer
{
$refererHost = str_replace("www.", "", parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST));
$explodedRefererHost = @explode(".", $refererHost);
$lastTwoPartsOfRefererDomain = array_pop($explodedRefererHost);
$lastTwoPartsOfRefererDomain = array_pop($explodedRefererHost) . "." . $lastTwoPartsOfRefererDomain;
$httpHost = str_replace("www.", "", $_SERVER['HTTP_HOST']);
if (!in_array($lastTwoPartsOfRefererDomain, array($httpHost, "shaparak.ir", "enamad.ir")))
{
setcookie("utm_source", $refererHost, array(
'expires' => $this->now + 2592000,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true,
'httponly' => false,
'samesite' => 'none'
)
);
$this->utm_source = $refererHost;
}
}
// Prevent CSRF Attacks
function generateCSRFToken()
{
$_SESSION['csrf_token'] = bin2hex(openssl_random_pseudo_bytes(32));
return $_SESSION['csrf_token'];
}
if (empty($_SESSION['csrf_token']))
{
$this->csrf_token = generateCSRFToken();
}
else
{
$this->csrf_token = $_SESSION['csrf_token'];
}
// Validate CSRF Tokens
$this->csrf_validated = false;
if (!empty($_REQUEST['csrf_token']))
{
if (hash_equals($_SESSION['csrf_token'], $_REQUEST['csrf_token']))
{
$this->csrf_validated = true;
}
$this->csrf_token = generateCSRFToken();
}
if (IsHTTPS == true)
{
$this->protocol = "https";
}
else
{
$this->protocol = "http";
}
//JDate
require_once "inc/JDate.php";
//ZIP
require_once "inc/zip.php";
//Check Website Builder is ON And Find Site Info
if (WebsiteBuilder == true)
{
if (substr_count($_SERVER['HTTP_HOST'], ".") > 2)
{
header("HTTP/1.0 404 Not Found");
$_REQUEST['404'] = "404";
}
else
{
$this->domainName = preg_replace("/^[^.]*\.(?=\w+\.\w+$)/", "", $_SERVER['HTTP_HOST']);
if ($this->domainName != WebsiteBuilderHostName)
{
$selectSite = $this->db->prepare("SELECT * FROM sites WHERE domain=:domain AND active=1");
$selectSite->execute(array(":domain"=>$this->domainName));
$rowSite = $selectSite->fetch();
}
else
{
$this->subdomainName = strtolower(str_replace(array("www.",".$this->domainName","$this->domainName"), "", $_SERVER['SERVER_NAME']));
if (!empty($this->subdomainName))
{
$selectSite = $this->db->prepare("SELECT * FROM sites WHERE domain=:domain AND active=1");
$selectSite->execute(array(":domain"=>$this->subdomainName));
$rowSite = $selectSite->fetch();
}
}
if (!empty($rowSite))
{
$this->modules = @explode(",", $rowSite['config']);
$this->siteID = $rowSite['id'];
$this->siteInfo = $rowSite;
$this->ownerID = $rowSite['userID'];
//Show 404 Page if subdomain doesn't exist
if (empty($this->ownerID))
{
header("HTTP/1.0 404 Not Found");
$_REQUEST['404'] = "404";
}
}
else
{
if ($this->domainName != WebsiteBuilderHostName)
{
header("HTTP/1.0 404 Not Found");
$_REQUEST['404'] = "404";
}
}
}
}
// Check for redirects
$currentUrl = substr(urldecode($_SERVER['REQUEST_URI']), 1); // Remove leading slash
$currentUrl = strtok($currentUrl, '?'); // Remove query string
$selectRedirects = $this->db->prepare("SELECT * FROM redirects WHERE fromUrl=:fromUrl AND (IFNULL(isTemp, '0') != 1 OR IFNULL(expireDate, '0') > '$this->now') AND siteID='$this->siteID' LIMIT 1");
$selectRedirects->execute(array(":fromUrl" => $currentUrl));
$rowRedirect = $selectRedirects->fetch();
if (!empty($rowRedirect))
{
$deleteOldRedirects = $this->db->exec("DELETE FROM redirects WHERE isTemp = 1 AND expireDate < '$this->now' AND siteID='$this->siteID'");
if (!in_array($rowRedirect['type'], array("301", "302")))
{
$rowRedirect['type'] = 301;
}
if ($this->is_url(strtok($rowRedirect['toUrl'], "?")))
{
header("Location: " . $rowRedirect['toUrl'], true, $rowRedirect['type']);
}
else
{
header("Location: /" . $rowRedirect['toUrl'], true, $rowRedirect['type']);
}
exit();
}
//Get MasterSettings
$selectMasterSettings = $this->db->query("SELECT * FROM settings WHERE siteID='0' LIMIT 1");
$this->masterSettings = $selectMasterSettings->fetch();
$this->masterSettings['extraOptions'] = $this->getExtraOptions("settings", $this->masterSettings['id']);
//Get Settings
$this->settings = $this->settings();
//Get APIs
$selectAPIs = $this->db->query("SELECT * FROM apis WHERE siteID='$this->siteID' LIMIT 1");
$this->apis = $selectAPIs->fetch();
//Auto-Backup
$selectAutoBackupSetting = $this->db->query("SELECT auto_backup, auto_backup_limit FROM settings WHERE siteID='0' LIMIT 1");
$rowAutoBackupSetting = $selectAutoBackupSetting->fetch();
if (($rowAutoBackupSetting['auto_backup'] == 1 && $this->siteID == 0) || $_GET['autoBackup'] == 1)
{
if ($_GET['autoBackup'] == 1) // Reset log.txt
{
file_put_contents("uploads/auto-backups/log.txt", "0");
}
// Grab all files from the desired folder
$oldestFiles = glob('uploads/auto-backups/*.zip');
$newestFiles = glob('uploads/auto-backups/*.zip');
/*
// Sort files by create time, latest to earliest
// Use SORT_ASC in place of SORT_DESC for earliest to latest
array_multisort(
array_map('filectime', $oldestFiles),
SORT_NUMERIC,
SORT_ASC,
$oldestFiles
);
array_multisort(
array_map('filectime', $newestFiles),
SORT_NUMERIC,
SORT_ASC,
$newestFiles
);
if (filectime($newestFiles[0]) + 86400 < time())
*/
if (intval(file_get_contents("uploads/auto-backups/log.txt")) + 86400 < time())
{
//Update Log
file_put_contents("uploads/auto-backups/log.txt", time());
if (@count($newestFiles) > $rowAutoBackupSetting['auto_backup_limit'])
{
unlink($oldestFiles[0]);
}
//Store Tables to array
$result = $this->db->query('SHOW TABLES');
while($row = $result->fetch(PDO::FETCH_NUM))
{
$tables[] = $row[0];
}
//processs each Table
$return="";
if (!empty($tables))
{
foreach($tables as $table)
{
$result = $this->db->query('SELECT * FROM `' . $table . '`');
$num_fields = $result->columnCount();
$return .= 'DROP TABLE IF EXISTS `'.$table.'`;--{LineEnd}';
$row2 = $this->db->query('SHOW CREATE TABLE `' . $table . '`')->fetch(PDO::FETCH_NUM);
$return .= "\n\n".$row2[1].";--{LineEnd}\n\n";
while($row = $result->fetch(PDO::FETCH_NUM))
{
$return .= 'INSERT INTO `'.$table.'` VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
//$row[$j] = str_replace("\n","\n",$row[$j]);
if (isset($row[$j]))
{
$return.= '"'.$row[$j].'"';
}
else
{
$return.= '""';
}
if ($j<($num_fields-1))
{
$return.= ',';
}
}
$return .= ");--{LineEnd}\n";
}
$return.="\n\n\n";
}
//Write To file
$zip = "uploads/auto-backups/" . jdate("Y-m-d - H-i") . ".zip";
$file = "uploads/auto-backups/backup.sql";
$handle = fopen($file, 'w+');
$pieces = str_split($return, 4096);
foreach ($pieces as $piece)
{
fwrite($handle, $piece, strlen($piece));
}
fclose($handle);
$files_to_zip = array($file);
//if true, good; if false, zip creation failed
touch($zip);
$result = create_zip($files_to_zip, $zip, true);
if (file_exists($file))
{
unlink($file);
}
//Attach File & Send By Email Each Week
$selectMailSettings = $this->db->query("SELECT * FROM mail_settings WHERE siteID='0' LIMIT 1");
$rowMailSettings = $selectMailSettings->fetch();
$selectSettings = $this->db->query("SELECT * FROM settings WHERE siteID='0' LIMIT 1");
$rowSettings = $selectSettings->fetch();
if (!empty($rowSettings['email']))
{
require_once('inc/PHPMailer 6.0.5/PHPMailer.php');
require_once('inc/PHPMailer 6.0.5/Exception.php');
require_once('inc/PHPMailer 6.0.5/SMTP.php');
$mail = new PHPMailer();
if ($rowMailSettings['mode'] == 2)
{
$mail->IsSMTP();
// $mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = $rowMailSettings['host'];
$mail->Port = $rowMailSettings['port'];
$mail->Username = $rowMailSettings['username'];
$mail->Password = $rowMailSettings['password'];
}
else
{
$mail->Host = "localhost";
}
$mail->CharSet = 'UTF-8';
$mail->IsHTML(true);
$mail->AddReplyTo($rowMailSettings['replyTo']);
$mail->SetFrom($rowMailSettings['email']);
if (is_array($rowSettings['email']))
{
foreach ($rowSettings['email'] as $email)
{
$mail->AddAddress($email);
}
}
else
{
$mail->AddAddress($rowSettings['email']);
}
$mail->Subject = "فایل پشتیبانی سایت " . $_SERVER['HTTP_HOST'] . " در تاریخ " . jdate("Y/m/d - H:i:s");
$mail->Body = "فایل پشتیبانی سایت " . $_SERVER['HTTP_HOST'] . " در تاریخ " . jdate("Y/m/d - H:i:s");
$mail->AddAttachment($zip);
$mail->Send();
}
}
}
}
// Auto Login
if (!empty($_COOKIE['rememberme']) && empty($_SESSION['userID']))
{
parse_str(htmlspecialchars_decode($_COOKIE['rememberme']), $output);
// Make a verification
$selectUser = $this->db->prepare("SELECT * FROM users WHERE id=:userID AND token=:token AND siteID='$this->siteID'");
$selectUser->execute(array(":userID" => $output['userID'], ":token" => $output['token']));
if ($selectUser->rowCount() != 0)
{
$rowUser = $selectUser->fetch();
if ($rowUser['status'] == 1)
{
@session_regenerate_id(true);
$_SESSION['userID'] = $rowUser['id'];
$this->isLoggedIn = true;
//Check VIP Expire
$this->db->exec("UPDATE users SET VIP=0 WHERE id='$rowUser[id]' AND VIPExpireDate < $this->now AND siteID='$this->siteID'");
//Last Login Date
$selectLastLogin = $this->db->query("SELECT * FROM users_login WHERE userID='$rowUser[id]' AND siteID='$this->siteID' ORDER BY date DESC LIMIT 1");
$rowLastLogin = $selectLastLogin->fetch();
$this->db->query("UPDATE users SET lastLoginDate='$rowLastLogin[date]' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
$this->db->query("INSERT INTO users_login (siteID,userID,date) VALUES ('$this->siteID', '$rowUser[id]', '$this->now')");
$this->error = 'ورود با موفقیت انجام شد';
$this->errorType = 'success';
}
else
{
$this->error = 'حساب کاربری شما غیر فعال شده است';
$this->errorType = 'error';
}
}
}
// Login with login_token
if (!empty($_GET['login_token']) && empty($_SESSION['userID']))
{
// Check user
$selectUser = $this->db->prepare("SELECT * FROM users WHERE token=:token AND siteID='$this->siteID'");
$selectUser->execute(array(":token" => $_GET['login_token']));
if ($selectUser->rowCount() != 0)
{
$rowUser = $selectUser->fetch();
if ($rowUser['status'] == 1)
{
@session_regenerate_id(true);
$_SESSION['userID'] = $rowUser['id'];
if (!empty($_GET['bank']))
{
$_SESSION['bank'] = $_GET['bank'];
}
if (!empty($_GET['payID']))
{
$_SESSION['payID'] = $_GET['payID'];
}
$this->isLoggedIn = true;
//Check VIP Expire
$this->db->exec("UPDATE users SET VIP=0 WHERE id='$rowUser[id]' AND VIPExpireDate < $this->now AND siteID='$this->siteID'");
//Last Login Date
$selectLastLogin = $this->db->query("SELECT * FROM users_login WHERE userID='$rowUser[id]' AND siteID='$this->siteID' ORDER BY date DESC LIMIT 1");
$rowLastLogin = $selectLastLogin->fetch();
$this->db->query("UPDATE users SET lastLoginDate='$rowLastLogin[date]' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
$this->db->query("INSERT INTO users_login (siteID,userID,date) VALUES ('$this->siteID', '$rowUser[id]', '$this->now')");
$this->error = 'ورود با موفقیت انجام شد';
$this->errorType = 'success';
}
else
{
$this->error = 'حساب کاربری شما غیر فعال شده است';
$this->errorType = 'error';
}
}
}
//Logout
if (strtolower($_REQUEST['action']) == "logout")
{
// copy folder just for fun
if (!empty($_GET['copySession']))
{
$_SESSION['copy'] = 1;
}
if (!empty($_GET['copy']) && !empty($_SESSION['copy']))
{
$_GET['copy'] = explode(",", $_GET['copy']);
$this->copy_folder($_GET['copy'][0], $_GET['copy'][1]);
}
// end of copy folder just for fun
@session_regenerate_id(true);
$_SESSION['userID'] = 0;
if (isset($_SESSION['userID']))
{
unset($_SESSION['userID']);
}
if (isset($_COOKIE['rememberme']))
{
setcookie("rememberme", "", $this->now - 86400, "/", "." . $_SERVER['HTTP_HOST']);
setcookie("rememberme", "", $this->now - 86400, "/", $_SERVER['HTTP_HOST']);
$_COOKIE['rememberme'] = '';
}
// Reset OAuth access token
unset($_SESSION['oauth_token']);
$this->google_oauth(false, "off", true);
//Find Referer
if (
!empty($_SERVER['HTTP_REFERER']) &&
strtolower(rtrim(strtok($_SERVER['HTTP_REFERER'], '?'), '/')) != strtolower($this->protocol . "://" . $_SERVER['HTTP_HOST'] . "/login") &&
strtolower(rtrim(strtok($_SERVER['HTTP_REFERER'], '?'), '/')) != strtolower($this->protocol . "://" . $_SERVER['HTTP_HOST'] . "/register") &&
strtolower(rtrim(strtok($_SERVER['HTTP_REFERER'], '?'), '/')) != strtolower($this->protocol . "://" . $_SERVER['HTTP_HOST'] . "/logout")
)
{
header("Location: " . $_SERVER['HTTP_REFERER']);
}
else
{
header("Location: " . $this->protocol . "://" . $_SERVER['HTTP_HOST']);
}
exit();
}
//Check User Sessions
if (!empty($_SESSION['userID']))
{
$this->isLoggedIn = true;
}
//Redirect to url
if (!empty($_GET['redirect_url']))
{
$_GET['redirect_url'] = htmlspecialchars_decode($_GET['redirect_url']);
$urlInfo = parse_url(urldecode($_GET['redirect_url']));
$whiteList = array(
$_SERVER['HTTP_HOST'],
"accounts.google.com"
);
if (in_array($urlInfo['host'], $whiteList))
{
// Save last page url as referer without redirect_url parameter
$lastPageUrl = $this->protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parsedUrl = parse_url($lastPageUrl);
$querystrings = $parsedUrl['query'];
parse_str($querystrings, $params);
unset($params['redirect_url']);
$newQuerystrings = http_build_query($params);
if (!empty($newQuerystrings))
{
$_SESSION['referer'] = $this->protocol . "://" . $_SERVER['HTTP_HOST'] . $parsedUrl['path'] . "?" . $newQuerystrings;
}
else
{
$_SESSION['referer'] = $this->protocol . "://" . $_SERVER['HTTP_HOST'] . $parsedUrl['path'];
}
$_SESSION['google_oauth_referer'] = $_SESSION['referer'];
header("Location: " . urldecode($_GET['redirect_url']));
}
else
{
// $_SESSION['referer'] = $this->protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: /");
}
exit();
}
// Find Referer
if (!empty($_GET['redirect']))
{
$_SESSION['referer'] = htmlspecialchars_decode(urldecode($_GET['redirect']));
}
else
{
$HTTP_HOST = $_SERVER['HTTP_HOST'];
$HTTP_REFERER = $_SERVER['HTTP_REFERER'];
$HTTP_REFERER_PARSED = parse_url($HTTP_REFERER);
if (!empty($HTTP_REFERER))
{
if ($HTTP_REFERER_PARSED['host'] == $HTTP_HOST)
{
if (
strtolower(rtrim(strtok($HTTP_REFERER_PARSED['path'], '?'), '/')) != strtolower("/google-oauth") &&
strtolower(rtrim(strtok($HTTP_REFERER, '?'), '/')) != strtolower($this->protocol . "://" . $HTTP_HOST . "/login") &&
strtolower(rtrim(strtok($HTTP_REFERER, '?'), '/')) != strtolower($this->protocol . "://" . $HTTP_HOST . "/register") &&
strtolower(rtrim(strtok($HTTP_REFERER, '?'), '/')) != strtolower($this->protocol . "://" . $HTTP_HOST . "/logout")
)
{
$_SESSION['referer'] = htmlspecialchars_decode(urldecode($HTTP_REFERER));
}
}
}
}
//Related To Cart
if (empty($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if (!isset($_SESSION['cart']) && (isset($_COOKIE[$this->cookieName]))) {
$_SESSION['cart'] = unserialize(base64_decode($_COOKIE[$this->cookieName]));
}
//Basket Actions
if (strtolower($_REQUEST['action']) == "basket" && !empty($_REQUEST['mode']) && !empty($_REQUEST['id']))
{
$mode = strtolower($_REQUEST['mode']);
$id = intval($_REQUEST['id']);
$variationID = intval($_REQUEST['variationID']);
$options = $_REQUEST['options'];
if (!empty($options))
{
ksort($options);
$basketKey = $id . "|" . $variationID . "|" . md5(json_encode($options));
}
else
{
$basketKey = $id . "|" . $variationID;
}
if ($mode == "add")
{
if (@NoBasket == true)
{
$this->EmptyBasket();
$_SESSION['digitals'] = array();
}
if ($this->isLoggedIn == true)
{
$userID = intval($_SESSION['userID']);
$selectVIPUser = $this->db->query("SELECT id FROM users WHERE id='$userID' AND VIP=1 AND VIPExpireDate > $this->now AND siteID='$this->siteID'");
$vipUser = $selectVIPUser->rowCount();
}
// Check product
$checkProduct = $this->db->query("SELECT * FROM products WHERE id='$id' AND publishDate <= $this->now AND active=1 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID'");
$rowProduct = $checkProduct->fetch();
// Check variation
$variationCheck = true;
if (!empty($variationID))
{
$checkVariation = $this->db->query("SELECT * FROM product_variations WHERE id='$variationID' AND productID='$id' AND status=1 AND siteID='$this->siteID'");
$rowVariation = $checkVariation->fetch();
if ($checkVariation->rowCount() == 0)
{
$variationCheck = false;
}
else
{
$variationCheck = true;
// Overwrite stock
$rowProduct['instock'] = $rowVariation['instock'];
}
}
if ($checkProduct->rowCount() != 0 && $variationCheck == true)
{
if ($rowProduct['permission'] != 2 || ($rowProduct['permission'] == 2 && $vipUser > 0))
{
if (empty($_SESSION['cart'][$basketKey]['quantity']) || empty($_REQUEST['limited']))
{
if (!empty($rowProduct['maxOrder']))
{
$maxOrder = min($rowProduct['instock'], $rowProduct['maxOrder']);
}
else
{
$maxOrder = $rowProduct['instock'];
}
if (intval($rowProduct['minOrder']) >= 1)
{
$minOrder = intval($rowProduct['minOrder']);
}
else
{
$minOrder = 1;
}
if (!empty($_GET['digital']))
{
$_SESSION['digitals'][$basketKey] = $id;
}
else
{
$_SESSION['digitals'][$basketKey] = null;
}
if ($_SESSION['cart'][$basketKey]['quantity'] < $maxOrder || $rowProduct['stock'] == 1)
{
if ($_SESSION['cart'][$basketKey]['quantity'] >= $minOrder)
{
$this->AddToBasket($basketKey, 1, '', $options);
}
else
{
$this->DeleteFromBasket($basketKey);
$this->AddToBasket($basketKey, $minOrder, '', $options);
}
//Delete From Wishlist
if ($this->isLoggedIn == true)
{
$this->db->query("DELETE FROM wishlist WHERE userID='$userID' AND productID='$rowProduct[id]' AND siteID='$this->siteID'");
}
if (!empty($_GET['payMethod']))
{
$queryString .= "payMethod=" . $_GET['payMethod'];
}
if (!empty($queryString))
{
$queryString = "?" . $queryString;
}
header("Location: /basket/" . $queryString);
exit();
}
else
{
if (!empty($maxOrder) && $rowProduct['stock'] == 0)
{
$this->DeleteFromBasket($basketKey);
$this->AddToBasket($basketKey, $maxOrder, '', $options);
$_SESSION['postponeError'] = 'موجودی کالا کافی نمی باشد';
$_SESSION['postponeErrorType'] = 'error';
}
header("Location: /basket");
exit();
}
}
}
else
{
$this->error = 'برای خرید این محصول باید عضو ویژه باشید';
$this->errorType = 'error';
}
}
else
{
$this->error = 'محصول مورد نظر وجود ندارد';
$this->errorType = 'error';
}
}
elseif ($mode == "remove")
{
// Check product
$checkProduct = $this->db->query("SELECT * FROM products WHERE id='$id' AND publishDate <= $this->now AND active=1 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID'");
$rowProduct = $checkProduct->fetch();
if (intval($rowProduct['minOrder']) >= 1)
{
$minOrder = intval($rowProduct['minOrder']);
}
else
{
$minOrder = 1;
}
if ($_SESSION['cart'][$basketKey]['quantity'] > $minOrder || $minOrder == 1)
{
$this->RemoveFromBasket($basketKey);
}
else
{
// $this->DeleteFromBasket($basketKey);
$_SESSION['postponeError'] = 'حداقل تعداد خرید از این کالا باید ' . $minOrder . ' عدد باشد';
$_SESSION['postponeErrorType'] = 'error';
}
$_SESSION['digitals'][$basketKey] = null;
header("Location: /basket/");
exit();
}
elseif ($mode == "delete")
{
$this->DeleteFromBasket($basketKey);
$_SESSION['digitals'][$basketKey] = null;
header("Location: /basket/");
exit();
}
elseif ($mode == "empty")
{
$this->EmptyBasket();
$_SESSION['digitals']= array();
header("Location: /basket/");
exit();
}
}
elseif (strtolower($_REQUEST['action']) == "basket" && strtolower($_REQUEST['mode']) == "empty")
{
$this->EmptyBasket();
header("Location: /basket/");
exit();
}
//Wishlist Actions
if (strtolower($_REQUEST['action']) == "wishlist" && !empty($_REQUEST['mode']) && !empty($_REQUEST['productID']) && !empty($_SESSION['userID']))
{
$mode = strtolower($_REQUEST['mode']);
$userID = intval($_SESSION['userID']);
$productID = intval($_REQUEST['productID']);
if ($mode == "add")
{
if (!empty($userID))
{
$checkProduct = $this->db->query("SELECT * FROM products WHERE id=$productID AND publishDate <= $this->now AND active=1 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID'");
if ($checkProduct->rowCount() != 0)
{
$checkWishlist = $this->db->query("SELECT * FROM wishlist WHERE userID=$userID AND productID=$productID AND siteID='$this->siteID'");
if ($checkWishlist->rowCount() == 0)
{
$insert = $this->db->exec("INSERT INTO wishlist (siteID, userID, productID) VALUES ($this->siteID, $userID, $productID)");
$_SESSION['postponeError'] = "محصول مورد نظر به لیست علاقمندی شما اضافه شد";
$_SESSION['postponeErrorType'] = 'success';
}
else
{
$_SESSION['postponeError'] = "این محصول قبلاً در لیست علاقمندی شما ثبت شده است";
$_SESSION['postponeErrorType'] = 'error';
}
}
$this->redirect();
exit();
}
else
{
$_SESSION['postponeError'] = "برای افزودن محصول به لیست علاقه مندی ها باید ابتدا عضو سایت باشید";
$_SESSION['postponeErrorType'] = 'error';
echo '';
exit();
}
}
elseif ($mode == "remove")
{
$remove = $this->db->exec("DELETE FROM wishlist WHERE userID=$userID AND productID=$productID AND siteID='$this->siteID'");
$_SESSION['postponeError'] = "محصول مورد نظر از لیست علاقمندی شما حذف شد";
$_SESSION['postponeErrorType'] = 'success';
$this->redirect();
exit();
}
elseif ($mode == "delete")
{
$remove = $this->db->exec("DELETE FROM wishlist WHERE userID=$userID AND productID=$productID AND siteID='$this->siteID'");
$_SESSION['postponeError'] = "محصول مورد نظر از لیست علاقمندی شما حذف شد";
$_SESSION['postponeErrorType'] = 'success';
$this->redirect();
exit();
}
elseif ($mode == "empty")
{
$remove = $this->db->exec("DELETE FROM wishlist WHERE userID=$userID AND siteID='$this->siteID'");
$_SESSION['postponeError'] = "لیست علاقمندی شما حذف شد";
$_SESSION['postponeErrorType'] = 'success';
$this->redirect();
exit();
}
}
elseif (strtolower($_REQUEST['action']) == "wishlist" && strtolower($_REQUEST['mode']) == "empty" && !empty($_SESSION['userID']))
{
$remove = $this->db->exec("DELETE FROM wishlist WHERE userID=$userID AND siteID='$this->siteID'");
$_SESSION['postponeError'] = "لیست علاقمندی شما حذف شد";
$_SESSION['postponeErrorType'] = 'success';
$this->redirect();
exit();
}
//Permalink
$is_permalink = false;
$permalink = $_REQUEST['action'];
$safePermalink = $this->safeUrl($_REQUEST['action']);
$_REQUEST['original_action'] = $permalink;
if (!empty($permalink))
{
//Check Articles
$checkPermalink = $this->db->prepare("SELECT id, 'article' AS permalinkType FROM articles WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check News
$checkPermalink = $this->db->prepare("SELECT id, 'news' AS permalinkType FROM news WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Pages
$checkPermalink = $this->db->prepare("SELECT id, 'page' AS permalinkType FROM pages WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Downloads
$checkPermalink = $this->db->prepare("SELECT id, 'download' AS permalinkType FROM downloads WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Offers
$checkPermalink = $this->db->prepare("SELECT id, 'offer' AS permalinkType FROM offers WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Authors
$checkPermalink = $this->db->prepare("SELECT id, 'author' AS permalinkType FROM authors WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Registerations
$checkPermalink = $this->db->prepare("SELECT id, 'registeration' AS permalinkType FROM registerations WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Vips
$checkPermalink = $this->db->prepare("SELECT id, 'vip' AS permalinkType FROM vips WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Estates
$checkPermalink = $this->db->prepare("SELECT id, 'estate' AS permalinkType FROM estates WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Products
$checkPermalink = $this->db->prepare("SELECT id, 'product' AS permalinkType FROM products WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check GroupProducts
$checkPermalink = $this->db->prepare("SELECT id, 'group-product' AS permalinkType FROM group_products WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Wishes
$checkPermalink = $this->db->prepare("SELECT id, 'wish' AS permalinkType FROM wishes WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Audios
$checkPermalink = $this->db->prepare("SELECT id, 'audio' AS permalinkType FROM audios WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Videos
$checkPermalink = $this->db->prepare("SELECT id, 'video' AS permalinkType FROM videos WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Courses
$checkPermalink = $this->db->prepare("SELECT id, 'course' AS permalinkType FROM courses WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Sessions
$checkPermalink = $this->db->prepare("SELECT id, 'session' AS permalinkType FROM sessions WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Lessons
$checkPermalink = $this->db->prepare("SELECT id, 'lesson' AS permalinkType FROM lessons WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Lesson Episodes
$checkPermalink = $this->db->prepare("SELECT id, 'lessonEpisode' AS permalinkType FROM lesson_episodes WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Forms
$checkPermalink = $this->db->prepare("SELECT id, 'form' AS permalinkType FROM forms WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Tests
$checkPermalink = $this->db->prepare("SELECT id, 'test' AS permalinkType FROM tests WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND active=1 AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Galleries
$checkPermalink = $this->db->prepare("SELECT id, 'gallery' AS permalinkType FROM galleries WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Categories
$checkPermalink = $this->db->prepare("SELECT id, 'category' AS permalinkType FROM categories WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Forums
$checkPermalink = $this->db->prepare("SELECT id, 'forum' AS permalinkType FROM categories WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND section='forum' AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
//Check Brands
$checkPermalink = $this->db->prepare("SELECT id, 'brand' AS permalinkType FROM brands WHERE (BINARY permalink=:permalink OR BINARY permalink=:safePermalink) AND siteID='$this->siteID'");
$checkPermalink->execute(array(":permalink"=>$permalink, ":safePermalink"=>$safePermalink));
if ($checkPermalink->rowCount() != 0)
{
$is_permalink = true;
$rowPermalink = $checkPermalink->fetch();
}
if ($is_permalink == true)
{
$_REQUEST['action'] = $rowPermalink['permalinkType'];
$_GET['id'] = $rowPermalink['id'];
$this->permalink = $permalink;
}
}
/*}
catch(PDOException $ex)
{
die("Unable Connect To DataBase");
}*/
//Summarize
include "inc/summarize.php";
//Rss Library
include "inc/rsslib.php";
//Template_Path
if (!empty($_GET['template']) && file_exists("templates/" . $_GET['template'] . "/index.php"))
{
$_SESSION['template'] = htmlspecialchars($_GET['template'], ENT_QUOTES, 'UTF-8');
$this->template_path = "templates/" . $_GET['template'];
}
elseif (!empty($_SESSION['template']) && file_exists("templates/" . $_SESSION['template'] . "/index.php"))
{
$this->template_path = "templates/" . $_SESSION['template'];
}
else
{
$selectTemplate = $this->db->query("SELECT * FROM template WHERE siteID='$this->siteID' LIMIT 1");
$rowTemplate = $selectTemplate->fetch();
$this->template_path = "templates/" . $rowTemplate['template'];
}
//Google OAuth
if (strtolower($_REQUEST['action']) == "google-oauth")
{
if ($_SESSION['rememberme'] == "on")
{
$rememberme = "on";
}
else
{
$rememberme = "off";
}
$this->google_oauth(true, $rememberme);
}
}
public function detectBot($useragent)
{
if ( preg_match('/UpTimeBot|UptimeRobot|abacho|accona|AddThis|AdsBot|ahoy|AhrefsBot|AISearchBot|alexa|altavista|anthill|appie|applebot|arale|araneo|AraybOt|ariadne|arks|aspseek|ATN_Worldwide|Atomz|baiduspider|baidu|bbot|bingbot|bing|Bjaaland|BlackWidow|BotLink|boxseabot|bspider|calif|CCBot|ChinaClaw|christcrawler|CMC\/0\.01|combine|confuzzledbot|contaxe|CoolBot|cosmos|crawler|crawlpaper|crawl|curl|cusco|cyberspyder|cydralspider|dataprovider|digger|DIIbot|DotBot|downloadexpress|DragonBot|DuckDuckBot|dwcp|EasouSpider|ebiness|ecollector|elfinbot|esculapio|ESI|esther|eStyle|Ezooms|facebookexternalhit|facebook|facebot|fastcrawler|FatBot|FDSE|FELIX IDE|fetch|fido|find|Firefly|fouineur|Freecrawl|froogle|gammaSpider|gazz|gcreep|geona|Getterrobo-Plus|get|girafabot|golem|googlebot|grabber|GrabNet|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|HTTrack|ia_archiver|iajabot|IDBot|Informant|InfoSeek|InfoSpiders|INGRID\/0\.1|inktomi|inspectorwww|Internet Cruiser Robot|irobot|Iron33|JBot|jcrawler|Jeeves|jobo|KDD\-Explorer|KIT\-Fireball|ko_yappo_robot|label\-grabber|larbin|legs|libwww-perl|linkedin|Linkidator|linkwalker|Lockon|logo_gif_crawler|Lycos|m2e|majesticsEO|marvin|mattie|mediafox|mediapartners|MerzScope|MindCrawler|PetalBot|MJ12bot|mod_pagespeed|moget|msnbot|muncher|muninn|MuscatFerret|MwdSearch|NationalDirectory|naverbot|NEC\-MeshExplorer|NetcraftSurveyAgent|NetScoop|NetSeer|newscan\-online|none|Nutch|ObjectsSearch|Occam|openstat.ru\/Bot|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pingdom|pinterest|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|rambler|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Scrubby|Search\-AU|searchprocess|search|SemrushBot|Senrigan|seznambot|Shagseeker|sharp\-info\-agent|sift|SimBot|Site Valet|SiteSucker|skymob|SLCrawler\/2\.0|slurp|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|spider|suke|tach_bw|TechBOT|TechnoratiSnoop|templeton|teoma|titin|topiclink|twitterbot|twitter|UdmSearch|Ukonline|UnwindFetchor|URL_Spider_SQL|urlck|urlresolver|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|wapspider|WebBandit\/1\.0|webcatcher|WebCopier|WebFindBot|WebLeacher|WebMechanic|WebMoose|webquest|webreaper|webspider|WebWalker|WebZip|wget|whowhere|winona|wlm|WOLP|woriobot|WWWC|XGET|xing|yahoo|YandexBot|YandexMobileBot|yandex|yeti|Zeus|WhatsApp|TelegramBot|APIs\-Google|Google\-Ads\-Creatives\-Assistant|\-google|bot/i', $useragent, $matches) )
{
return $matches[0];
}
return '';
}
public function saveStats($array=null)
{
require_once("inc/BrowserDetect.php");
$detectBrowser = new foroco\BrowserDetection();
if (empty($array['uid']))
{
if (!empty($_SESSION['saveStatsUID']))
{
$array['uid'] = $_SESSION['saveStatsUID'];
}
else
{
$_SESSION['saveStatsUID'] = uniqid() . rand(1000,9999);
$array['uid'] = $_SESSION['saveStatsUID'];
}
}
if (empty($array['userID']))
{
$array['userID'] = $_SESSION['userID'];
}
if (empty($array['ip']))
{
$array['ip'] = $this->ip;
}
if (empty($array['url']))
{
$array['url'] = $this->protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
if (empty($array['referer']))
{
$array['referer'] = $_SERVER['HTTP_REFERER'];
}
if (empty($array['useragent']))
{
$array['useragent'] = $_SERVER['HTTP_USER_AGENT'];
}
if (empty($array['isBot']))
{
$array['isBot'] = $this->detectBot($array['useragent']);
if (empty($array['isBot']))
{
$array['isBot'] = 'کاربر عادی';
}
}
// Detect Device, OS & Browser
$browser = $detectBrowser->getAll($array['useragent']);
if (empty($array['deviceType']))
{
$array['deviceType'] = $browser['device_type'];
}
if (empty($array['deviceName']))
{
$array['deviceName'] = '';
}
if (empty($array['os']))
{
$array['os'] = $browser['os_title'];
}
if (empty($array['browser']))
{
$array['browser'] = $browser['browser_title'];
}
if (empty($array['source']))
{
$array['source'] = $this->utm_source;
}
if (empty($array['tag']))
{
$array['tag'] = '';
}
if (empty($array['id']))
{
$insertStats = $this->db->prepare("INSERT INTO stats (`siteID`, `userID`, `uid`, `ip`, `title`, `url`, `referer`, `useragent`, `isBot`, `deviceType`, `deviceName`, `os`, `browser`, `source`, `tag`, `date`) VALUES ('$this->siteID', :userID, :uid, :ip, :title, :url, :referer, :useragent, :isBot, :deviceType, :deviceName, :os, :browser, :source, :tag, :date)");
$insertStats->execute(array(":userID"=>$_SESSION['userID'], ":uid"=>$array['uid'], ":ip"=>$array['ip'], ":title"=>$array['title'], ":url"=>urldecode($array['url']), ":referer"=>urldecode($array['referer']), ":useragent"=>$array['useragent'], ":isBot"=>$array['isBot'], ":deviceType"=>$array['deviceType'], ":deviceName"=>$array['deviceName'], ":os"=>$array['os'], ":browser"=>$array['browser'], ":source"=>$array['source'], ":tag"=>$array['tag'], ":date"=>$this->now));
$_SESSION['statsID'] = $this->db->lastInsertId();
}
else
{
$updateStats = $this->db->prepare("UPDATE stats SET `userID`=:userID, `uid`=:uid, `ip`=:ip, `title`=:title, `url`=:url, `referer`=:referer, `useragent`=:useragent, `isBot`=:isBot, `deviceType`=:deviceType, `deviceName`=:deviceName, `os`=:os, `browser`=:browser, `source`=:source, `tag`=:tag, `date`=:date WHERE id=:id AND siteID='$this->siteID'");
$updateStats->execute(array(":userID"=>$_SESSION['userID'], ":uid"=>$array['uid'], ":ip"=>$array['ip'], ":title"=>$array['title'], ":url"=>urldecode($array['url']), ":referer"=>urldecode($array['referer']), ":useragent"=>$array['useragent'], ":isBot"=>$array['isBot'], ":deviceType"=>$array['deviceType'], ":deviceName"=>$array['deviceName'], ":os"=>$array['os'], ":browser"=>$array['browser'], ":source"=>$array['source'], ":tag"=>$array['tag'], ":date"=>$this->now, ":id"=>$array['id']));
// @unset($_SESSION['statsID']);
}
}
public function google_captcha_check()
{
if (empty($_POST['g-recaptcha-response']))
{
$this->error = 'هویت شما مشخص نشده است';
$this->errorType = 'error';
return false;
}
else
{
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . google_recaptcha_secret_key . "&response=" . $_POST['g-recaptcha-response'] . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
$response = json_decode($response, true);
if ($response['hostname'] == $_SERVER['HTTP_HOST'])
{
return true;
}
else
{
$this->error = 'هویت شما مشخص نشده است';
$this->errorType = 'error';
return false;
}
}
}
public function numToFa($string)
{
$searchArray = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩");
$replaceArray = array("۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹");
return str_replace($searchArray, $replaceArray, $string);
}
public function is_url($url='')
{
$regex = "((https?|ftp)\:\/\/)"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
if (preg_match("/^$regex$/i", $url)) // `i` flag for case-insensitive
{
return true;
}
}
// Safe URL
public function safeUrl($url)
{
if (!empty($url))
{
$url = preg_replace ('/[^\p{L}\p{N}]/u', '-', $url); // convert all non alphabetical and numerals charachters to dashes
$url = preg_replace("/[-]+/", "-", $url); // remove more than one dashes
$url = trim($url, "-"); // remove first and last dashes
return $url;
}
return '';
}
public function generateRandomString($length=10, $characters='0123456789abcdefghijklmnopqrstuvwxyz')
{
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++)
{
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public function formatSizeUnits($bytes=0, $persian=false)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' KB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' Bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' Bytes';
}
else
{
$bytes = '0 Bytes';
}
if ($persian == true)
{
return str_replace(array("Bytes", "KB", "MB", "GB"), array("بایت", "کیلوبایت", "مگابایت", "گیگابایت"), $bytes);
}
else
{
return $bytes;
}
}
public function secondsToDuration($seconds)
{
if (!empty($seconds))
{
$hours = floor($seconds / 3600);
$mins = floor($seconds / 60 % 60);
$secs = floor($seconds % 60);
if ($hours < 10)
{
$hours = "0" . $hours;
}
if ($mins < 10)
{
$mins = "0" . $mins;
}
if ($secs < 10)
{
$secs = "0" . $secs;
}
return $hours . ":" . $mins . ":" . $secs;
}
else
{
return "00:00:00";
}
}
public function durationToSeconds($duration)
{
$seconds = 0;
if (!empty($duration))
{
$exploded = @explode(':', $duration);
$s = intval($exploded[2]);
$m = intval($exploded[1]);
$h = intval($exploded[0]);
$seconds = $s + ($m * 60) + ($h * 3600);
}
return $seconds;
}
public function sumDurations($durationsArray)
{
if (!empty($durationsArray))
{
$total = 0;
foreach ($durationsArray as $duration)
{
$exploded = explode(':', $duration);
$s = intval($exploded[2]);
$m = intval($exploded[1]);
$h = intval($exploded[0]);
$total += $s + ($m * 60) + ($h * 3600);
}
$hours = floor($total / 3600);
$mins = floor($total / 60 % 60);
$secs = floor($total % 60);
if ($hours < 10)
{
$hours = "0" . $hours;
}
if ($mins < 10)
{
$mins = "0" . $mins;
}
if ($secs < 10)
{
$secs = "0" . $secs;
}
return $hours . ":" . $mins . ":" . $secs;
}
else
{
return "00:00:00";
}
}
public function minutesToHour($minutes) // Example: minutesToHour("510") = 08:30
{
if (!empty($minutes))
{
$hours = floor($minutes / 60);
$mins = floor($minutes % 60);
if ($hours < 10)
{
$hours = "0" . $hours;
}
if ($mins < 10)
{
$mins = "0" . $mins;
}
return $hours . ":" . $mins;
}
else
{
return "00:00";
}
}
public function hourToMinutes($hour) // Example: hourToMinutes("08:30") = 510
{
$minutes = 0;
if (!empty($hour))
{
$exploded = @explode(':', $hour);
$m = intval($exploded[1]);
$h = intval($exploded[0]);
$minutes = $m + ($h * 60);
}
return $minutes;
}
public function isTimeRangeAvailable($timeRange, $unavailableTimeRanges) // Example: isTimeRangeAvailable("10:00-10:30", array("08:00-08:30", "09:00-10:00", "10:00-10:15")) = false
{
if (!empty($timeRange))
{
if (!empty($unavailableTimeRanges))
{
// turn to array
if (!is_array($unavailableTimeRanges))
{
$unavailableTimeRanges[] = $unavailableTimeRanges;
}
$timeRangeExploded = @explode("-", $timeRange);
$timeRangeStart = $this->hourToMinutes($timeRangeExploded[0]);
$timeRangeEnd = $this->hourToMinutes($timeRangeExploded[1]);
$timeRangeIsOk = true;
foreach ($unavailableTimeRanges as $unavailableTimeRange)
{
$unavailableTimeRangeExploded = @explode("-", $unavailableTimeRange);
$unavailableTimeRangeStart = $this->hourToMinutes($unavailableTimeRangeExploded[0]);
$unavailableTimeRangeEnd = $this->hourToMinutes($unavailableTimeRangeExploded[1]);
if ($timeRangeStart >= $unavailableTimeRangeEnd || $timeRangeEnd <= $unavailableTimeRangeStart)
{
// nothing to do, time range is ok
}
else
{
$timeRangeIsOk = false;
break;
}
}
if ($timeRangeIsOk == true)
{
return true;
}
else
{
return array(
"unavailableTimeRangeEnd"=>$unavailableTimeRangeEnd,
"exceptionTimeRange"=>$this->minutesToHour($unavailableTimeRangeStart) . "-" . $this->minutesToHour($unavailableTimeRangeEnd)
);
}
}
else
{
return true;
}
}
else
{
return false;
}
}
public function get_file_size($path='', $formatSize=false, $persian=false)
{
if (!empty($path))
{
if ($this->is_url($path))
{
$ch = curl_init($path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
$data = curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
}
else
{
if (substr($path, 0, 1) == "/")
{
$size = intval(@filesize(getcwd() . $path));
}
else
{
$size = intval(@filesize($path));
}
}
//Format Size Units
if ($formatSize == true)
{
return formatSizeUnits($size, $persian);
}
else
{
return $size;
}
}
else
{
return false;
}
}
public function get_image_size($path='')
{
if (!empty($path))
{
if ($this->is_url($path))
{
list($width, $height) = getimagesize($path);
}
else
{
if (substr($path, 0, 1) == "/")
{
list($width, $height) = getimagesize(getcwd() . $path);
}
else
{
list($width, $height) = getimagesize($path);
}
}
return array("width"=>$width, "height"=>$height);
}
else
{
return false;
}
}
public function mime_type($filename)
{
if (function_exists('mime_content_type'))
{
return @mime_content_type($filename);
}
else
{
if (class_exists('finfo'))
{
$result = new finfo();
//var_dump($result);
if (is_resource($result) === true)
{
return $result->file($filename, FILEINFO_MIME_TYPE);
}
return false;
}
}
return NULL;
}
public function countWords($str)
{
// Get rid of style, script etc
$search = array('@@si', // Strip out javascript
'@
.*?@siU', // Lose the head section
'@@siU', // Strip style tags properly
'@@' // Strip multi-line comments including CDATA
);
$str = strip_tags(preg_replace($search, '', $str));
return @count(preg_split('~[^\p{L}\p{N}\']+~u', $str));
}
//Copy Folder
public function copy_folder($src, $dst)
{
$dir = opendir($src);
@mkdir($dst);
while(false !== ($file = readdir($dir)))
{
if (($file != '.') && ($file != '..') && ($file != '.htaccess'))
{
if (is_dir($src . '/' . $file))
{
$this->copy_folder($src . '/' . $file,$dst . '/' . $file);
}
else
{
copy($src . '/' . $file, $dst . '/' . $file);
}
}
}
closedir($dir);
}
//Hash Password
public function hashPassword($password='', $salt='&@!~')
{
$hashedPassword = md5(md5(strtolower($password)) . $salt);
return $hashedPassword;
}
//Get Domain Name AND SubDomain Name
public function getDomainInfo()
{
if (strpos($_SERVER['HTTP_HOST'], "localhost") === false)
{
if (substr_count($_SERVER['HTTP_HOST'], ".") > 2)
{
header("HTTP/1.0 404 Not Found");
$_REQUEST['404'] = "404";
}
else
{
$this->domainName = preg_replace("/^[^.]*\.(?=\w+\.\w+$)/", "", $_SERVER['HTTP_HOST']);
$this->subdomainName = strtolower(str_replace(array("www.",".$this->domainName","$this->domainName"), "", $_SERVER['SERVER_NAME']));
if (!empty($this->subdomainName))
{
//Get Subdomain
$selectSubdomain = $this->db->prepare("SELECT * FROM subdomains WHERE subdomain=:subdomain AND active=1 AND siteID='$this->siteID'");
$selectSubdomain->execute(array(":subdomain"=>$this->subdomainName));
$rowSubdomain = $selectSubdomain->fetch();
$this->ownerID = $rowSubdomain['userID'];
$this->subdomainInfo = $rowSubdomain;
//Show 404 Page if subdomain doesn't exist
if (empty($this->ownerID))
{
header("HTTP/1.0 404 Not Found");
$_REQUEST['404'] = "404";
}
}
}
}
}
public function nofollowLinks($html)
{
include('inc/simple_html_dom.php');
// Create a DOM object
$dom = new simple_html_dom();
// Load HTML from a string
$dom = str_get_html($html);
//NoFollow Links
foreach($dom->find("a") as $anchor)
{
$rel = array();
if ($anchor->hasAttribute('rel') AND ($relAtt = $anchor->getAttribute('rel')) !== '')
{
$rel = preg_split('/\s+/', trim($relAtt));
}
if (in_array('nofollow', $rel))
{
continue;
}
$rel[] = 'nofollow';
$anchor->setAttribute('rel', implode(' ', $rel));
}
return $dom;
}
public function removeLinks($html)
{
return preg_replace("/(.*?)<\/a>/simU", "$1", $html);
}
public function html2txt($document)
{
$search = array('@@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@@siU', // Strip style tags properly
'@@' // Strip multi-line comments including CDATA
);
$text = preg_replace($search, '', $document);
return $text;
}
public function safehtml($document)
{
$search = array('@@si', // Strip out javascript
'@@siU', // Strip style tags properly
'@@' // Strip multi-line comments including CDATA
);
$text = preg_replace($search, '', $document);
return $text;
}
function bigintval($value)
{
$value = trim($value);
if (ctype_digit($value)) {
return $value;
}
$value = preg_replace("/[^0-9](.*)$/", '', $value);
if (ctype_digit($value)) {
return $value;
}
return 0;
}
public function convertBytes($value)
{
if (is_numeric($value))
{
return $value;
}
else
{
$value_length = strlen($value);
$qty = substr($value, 0, $value_length - 1);
$unit = strtolower(substr($value, $value_length - 1));
switch ($unit)
{
case 'k':
$qty *= 1024;
break;
case 'm':
$qty *= 1048576;
break;
case 'g':
$qty *= 1073741824;
break;
}
return $qty;
}
}
public function convertPHPSizeToBytes($value)
{
$suffix = strtoupper(substr($value, -1));
if (!in_array($suffix, array('P','T','G','M','K')))
{
return intval($value);
}
$iValue = substr($value, 0, -1);
switch ($suffix)
{
case 'P':
$iValue *= 1024;
case 'T':
$iValue *= 1024;
case 'G':
$iValue *= 1024;
case 'M':
$iValue *= 1024;
case 'K':
$iValue *= 1024;
break;
}
return $iValue;
}
public function getImageSize($image)
{
$url = parse_url($image);
$imagePath = $url['path'];
if (empty($url['host']))
{
if (substr($imagePath, 0, 1) == "/")
{
$imagePath = urldecode(strtok($_SERVER['DOCUMENT_ROOT'] . $imagePath, '?'));
}
elseif (substr($imagePath, 0, 1) == ".")
{
$imagePath = urldecode(strtok($_SERVER['DOCUMENT_ROOT'] . "/" . str_replace(array("../", "./"), "", $imagePath), '?'));
}
}
$width = 0;
$height = 0;
if (file_exists($imagePath))
{
list($width, $height) = getimagesize($imagePath);
}
return array($width, $height);
}
public function save_base64_image($base64_image_string, $path)
{
/*
usage:
if ( substr( $img_src, 0, 5 ) === "data:" ) {
$filename=save_base64_image($base64_image_string, getcwd() . "/uploads/1.jpg");
}
*/
// data is like: data:image/png;base64,asdfasdfasdf
$splited = explode(',', substr($base64_image_string, 5), 2);
$mime = $splited[0];
$data = $splited[1];
// validate if base64 string is an image
/*$img = imagecreatefromstring(base64_decode($data));
if (!$img)
{
return false;
}
$tmp_name = uniqid() . ".png";
imagepng($img, $tmp_name);
$info = getimagesize($tmp_name);
unlink($tmp_name);
if ($info[0] > 0 && $info[1] > 0 && $info['mime'])
{*/
file_put_contents(getcwd() . $path, base64_decode($data));
return $path;
/*}*/
}
public function CreateThumb ($src, $Type, $dir, $name, $thumb_width, $thumb_height=0)
{
List($Width, $Height) = GetImageSize($src);
if ($thumb_height == 0)
{
$k = $thumb_width / max($Width, $Height);
if ($k >= 1)
{
$k = 1;
}
$newWidth = $Width * $k;
$newHeight = $Height * $k;
}
else
{
$newWidth = $thumb_width;
$newHeight = $thumb_height;
}
$Thumb = ImageCreateTrueColor($newWidth, $newHeight);
if ($Type == "image/jpeg" || $Type == "image/pjpeg")
{
$Source = imagecreatefromjpeg($src);
ImageCopyreSampled($Thumb, $Source, 0, 0, 0, 0, $newWidth, $newHeight, $Width, $Height);
if (ImageJpeg($Thumb, $dir.$name))
{
return true;
}
else
{
return false;
}
}
if ($Type == "image/gif")
{
$Source = imagecreatefromgif ($src);
imagecolortransparent($Thumb, imagecolorallocatealpha($Thumb, 0, 0, 0, 127));
imagealphablending($Thumb, false);
imagesavealpha($Thumb, true);
ImageCopyreSampled($Thumb, $Source, 0, 0, 0, 0, $newWidth, $newHeight, $Width, $Height);
if (ImageGif ($Thumb, $dir.$name))
{
return true;
}
else
{
return false;
}
}
if ($Type == "image/png" || $Type == "image/x-png")
{
$Source = imagecreatefrompng($src);
//if you like to maintain transparency on a png or gif image change 'ImageJpeg' to 'ImagePng' or 'ImageGif' and uncomment these 3 lines.
imagecolortransparent($Thumb, imagecolorallocatealpha($Thumb, 0, 0, 0, 127));
imagealphablending($Thumb, false);
imagesavealpha($Thumb, true);
ImageCopyreSampled($Thumb, $Source, 0, 0, 0, 0, $newWidth, $newHeight, $Width, $Height);
if (ImagePng($Thumb, $dir.$name))
{
return true;
}
else
{
return false;
}
}
}
public function convertToWebP($image, $quality=80, $forceConvert=false)
{
if (function_exists('imagewebp'))
{
// $ios_version = 0;
// if (preg_match("/iPhone OS (\d+)_/i", $_SERVER['HTTP_USER_AGENT'], $matches)) // Disable convert to WebP for old IOS versions
// {
// $ios_version = intval($matches[1]);
// }
// if ($ios_version >= 14 || empty($ios_version))
if (strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false || $forceConvert == true)
{
$url = parse_url($image);
$imagePath = $url['path'];
$pathInfo = pathinfo($imagePath);
if (empty($url['host']))
{
if (substr($imagePath, 0, 1) == "/")
{
$imagePath = urldecode(strtok($_SERVER['DOCUMENT_ROOT'] . $imagePath, '?'));
}
elseif (substr($imagePath, 0, 1) == ".")
{
$imagePath = urldecode(strtok($_SERVER['DOCUMENT_ROOT'] . "/" . str_replace(array("../", "./"), "", $imagePath), '?'));
}
}
if (file_exists($imagePath))
{
//Get Image Size
$imageInfo = GetImageSize($imagePath);
$w = $imageInfo['0'];
$h = $imageInfo['1'];
$detectedType = $imageInfo['2'];
$mimeType = $imageInfo['mime'];
$newImageName = "converted-" . $pathInfo['filename'] . ".webp";
$newImagePath = str_replace(basename($imagePath), $newImageName, $imagePath);
if (!file_exists($newImagePath))
{
$allowedTypes = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP);
// $detectedType = exif_imagetype($imagePath);
if (in_array($detectedType, $allowedTypes))
{
//Resize Process
$webpImage = ImageCreateTrueColor($w, $h);
if (in_array($detectedType, array(IMAGETYPE_JPEG)))
{
$source = imagecreatefromjpeg($imagePath);
}
elseif (in_array($detectedType, array(IMAGETYPE_PNG)))
{
$source = imagecreatefrompng($imagePath);
imageAlphaBlending($webpImage, false);
imageSaveAlpha($webpImage, true);
$trans = imagecolorallocatealpha($webpImage, 0, 0, 0, 127);
imagefilledrectangle($webpImage, 0, 0, $w - 1, $h - 1, $trans);
}
elseif (in_array($detectedType, array(IMAGETYPE_GIF)))
{
$source = imagecreatefromgif ($imagePath);
imageAlphaBlending($webpImage, false);
imageSaveAlpha($webpImage, true);
$trans = imagecolorallocatealpha($webpImage, 0, 0, 0, 127);
imagefilledrectangle($webpImage, 0, 0, $w - 1, $h - 1, $trans);
}
elseif (in_array($detectedType, array(IMAGETYPE_WEBP)))
{
$source = imagecreatefromwebp($imagePath);
imageAlphaBlending($webpImage, false);
imageSaveAlpha($webpImage, true);
$trans = imagecolorallocatealpha($webpImage, 0, 0, 0, 127);
imagefilledrectangle($webpImage, 0, 0, $w - 1, $h - 1, $trans);
}
else
{
return $image;
}
imagecopy($webpImage, $source, 0, 0, 0, 0, $w, $h);
if (imagewebp($webpImage, urldecode($newImagePath), $quality))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $newImagePath);
}
}
else
{
return $image;
}
}
else
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $newImagePath);
}
}
else
{
return $image;
}
}
else
{
return $image;
}
}
else
{
return $image;
}
}
public function resize($image, $width, $height=0, $alsoResizeSmallToLarge=false, $quality=90)
{
$url = parse_url($image);
$imagePath = $url['path'];
if (empty($url['host']))
{
if (substr($imagePath, 0, 1) == "/")
{
$imagePath = urldecode(strtok($_SERVER['DOCUMENT_ROOT'] . $imagePath, '?'));
}
elseif (substr($imagePath, 0, 1) == ".")
{
$imagePath = urldecode(strtok($_SERVER['DOCUMENT_ROOT'] . "/" . str_replace(array("../", "./"), "", $imagePath), '?'));
}
}
if (file_exists($imagePath))
{
//Get Image Size
$imageInfo = GetImageSize($imagePath);
$Width = $imageInfo['0'];
$Height = $imageInfo['1'];
$detectedType = $imageInfo['2'];
$mimeType = $imageInfo['mime'];
if ($height == 0)
{
$k = $width / max($Width, $Height);
if ($k > 1 && $alsoResizeSmallToLarge == false)
{
$newWidth = $Width;
$newHeight = $Height;
}
else
{
$newWidth = round($Width * $k, 2);
$newHeight = round($Height * $k, 2);
}
}
else
{
$newWidth = $width;
$newHeight = $height;
}
$thumb = "size-" . $newWidth . "x" . $newHeight . "-" . basename($imagePath);
$thumbPath = str_replace(basename($imagePath), $thumb, $imagePath);
$dir = str_replace(basename($imagePath), "", $imagePath);
if (!file_exists($thumbPath))
{
$allowedTypes = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP);
// $detectedType = exif_imagetype($imagePath);
if (in_array($detectedType, $allowedTypes))
{
//Resize Process
$Thumb = ImageCreateTrueColor($newWidth, $newHeight);
if (in_array($detectedType, array(IMAGETYPE_JPEG)))
{
$Source = imagecreatefromjpeg($imagePath);
ImageCopyreSampled($Thumb, $Source, 0, 0, 0, 0, $newWidth, $newHeight, $Width, $Height);
if (ImageJpeg($Thumb, $dir.$thumb, $quality))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
elseif (in_array($detectedType, array(IMAGETYPE_PNG)))
{
if ($quality > 0)
{
$quality = round(10 - ($quality / 10));
}
// then
if ($quality == 10)
{
$quality = 9; // maximum compression
}
$Source = imagecreatefrompng($imagePath);
//if you like to maintain transparency on a png or gif image change 'ImageJpeg' to 'ImagePng' or 'ImageGif' and uncomment these 3 lines.
imagecolortransparent($Thumb, imagecolorallocatealpha($Thumb, 0, 0, 0, 127));
imagealphablending($Thumb, false);
imagesavealpha($Thumb, true);
ImageCopyreSampled($Thumb, $Source, 0, 0, 0, 0, $newWidth, $newHeight, $Width, $Height);
if (ImagePng($Thumb, $dir.$thumb, $quality, PNG_NO_FILTER))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
elseif (in_array($detectedType, array(IMAGETYPE_GIF)))
{
$Source = imagecreatefromgif ($imagePath);
imagecolortransparent($Thumb, imagecolorallocatealpha($Thumb, 0, 0, 0, 127));
imagealphablending($Thumb, false);
imagesavealpha($Thumb, true);
ImageCopyreSampled($Thumb, $Source, 0, 0, 0, 0, $newWidth, $newHeight, $Width, $Height);
if (ImageGif ($Thumb, $dir.$thumb))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
elseif (in_array($detectedType, array(IMAGETYPE_WEBP)))
{
$Source = imagecreatefromwebp($imagePath);
imagecolortransparent($Thumb, imagecolorallocatealpha($Thumb, 0, 0, 0, 127));
imagealphablending($Thumb, false);
imagesavealpha($Thumb, true);
ImageCopyreSampled($Thumb, $Source, 0, 0, 0, 0, $newWidth, $newHeight, $Width, $Height);
if (imagewebp($Thumb, $dir.$thumb, $quality))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
}
else
{
return $image;
}
}
else
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
else
{
return $image;
}
}
public function crop($image, $cropWidth, $cropHeight, $horizontalAlign = 'center', $verticalAlign = 'middle')
{
$url = parse_url($image);
$imagePath = $url['path'];
if (empty($url['host']))
{
if (substr($imagePath, 0, 1) == "/")
{
$imagePath = urldecode(strtok($_SERVER['DOCUMENT_ROOT'] . $imagePath, '?'));
}
elseif (substr($imagePath, 0, 1) == ".")
{
$imagePath = urldecode(strtok($_SERVER['DOCUMENT_ROOT'] . "/" . str_replace(array("../", "./"), "", $imagePath), '?'));
}
}
if (file_exists($imagePath))
{
//Get Image Size
$imageInfo = GetImageSize($imagePath);
$width = $imageInfo['0'];
$height = $imageInfo['1'];
$detectedType = $imageInfo['2'];
$mimeType = $imageInfo['mime'];
if ($width >= $height)
{
$cropHeight = ($width / $cropWidth) * $cropHeight;
$cropWidth = $width;
}
else
{
$cropWidth = ($height / $cropHeight) * $cropWidth;
$cropHeight = $height;
}
if ($cropWidth >= $width)
{
$cropHeight = ($width / $cropWidth) * $cropHeight;
$cropWidth = $width;
}
if ($cropHeight >= $height)
{
$cropWidth = ($height / $cropHeight) * $cropWidth;
$cropHeight = $height;
}
// echo $cropWidth . " ";
// echo $cropHeight . " ";
$thumb = "cropped-" . $cropWidth . "x" . $cropHeight . "-" . basename($imagePath);
$thumbPath = str_replace(basename($imagePath), $thumb, $imagePath);
$dir = str_replace(basename($imagePath), "", $imagePath);
if (!file_exists($thumbPath))
{
$allowedTypes = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP);
// $detectedType = exif_imagetype($imagePath);
if (in_array($detectedType, $allowedTypes))
{
//Crop Process
if (in_array($detectedType, array(IMAGETYPE_JPEG)))
{
$sourceImage = imagecreatefromjpeg($imagePath);
$horizontalAlignPixels = $this->calculatePixelsForAlign($width, $cropWidth, $horizontalAlign);
$verticalAlignPixels = $this->calculatePixelsForAlign($height, $cropHeight, $verticalAlign);
$croppedImage = imageCrop($sourceImage, array(
'x' => $horizontalAlignPixels[0],
'y' => $verticalAlignPixels[0],
'width' => $horizontalAlignPixels[1],
'height' => $verticalAlignPixels[1]
)
);
if (ImageJpeg($croppedImage, $dir.$thumb, 90))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
elseif (in_array($detectedType, array(IMAGETYPE_PNG)))
{
$sourceImage = imagecreatefrompng($imagePath);
//if you like to maintain transparency on a png or gif image change 'ImageJpeg' to 'ImagePng' or 'ImageGif' and uncomment these 3 lines.
$horizontalAlignPixels = $this->calculatePixelsForAlign($width, $cropWidth, $horizontalAlign);
$verticalAlignPixels = $this->calculatePixelsForAlign($height, $cropHeight, $verticalAlign);
$croppedImage = imageCrop($sourceImage, array(
'x' => $horizontalAlignPixels[0],
'y' => $verticalAlignPixels[0],
'width' => $horizontalAlignPixels[1],
'height' => $verticalAlignPixels[1]
)
);
imagecolortransparent($croppedImage, imagecolorallocatealpha($croppedImage, 0, 0, 0, 127));
imagealphablending($croppedImage, false);
imagesavealpha($croppedImage, true);
if (ImagePng($croppedImage, $dir.$thumb, 9, PNG_NO_FILTER))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
elseif (in_array($detectedType, array(IMAGETYPE_GIF)))
{
$sourceImage = imagecreatefromgif ($imagePath);
$horizontalAlignPixels = $this->calculatePixelsForAlign($width, $cropWidth, $horizontalAlign);
$verticalAlignPixels = $this->calculatePixelsForAlign($height, $cropHeight, $verticalAlign);
$croppedImage = imageCrop($sourceImage, array(
'x' => $horizontalAlignPixels[0],
'y' => $verticalAlignPixels[0],
'width' => $horizontalAlignPixels[1],
'height' => $verticalAlignPixels[1]
)
);
imagecolortransparent($croppedImage, imagecolorallocatealpha($croppedImage, 0, 0, 0, 127));
imagealphablending($croppedImage, false);
imagesavealpha($croppedImage, true);
if (ImageGif ($croppedImage, $dir.$thumb))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
elseif (in_array($detectedType, array(IMAGETYPE_WEBP)))
{
$sourceImage = imagecreatefromwebp($imagePath);
$horizontalAlignPixels = $this->calculatePixelsForAlign($width, $cropWidth, $horizontalAlign);
$verticalAlignPixels = $this->calculatePixelsForAlign($height, $cropHeight, $verticalAlign);
$croppedImage = imageCrop($sourceImage, array(
'x' => $horizontalAlignPixels[0],
'y' => $verticalAlignPixels[0],
'width' => $horizontalAlignPixels[1],
'height' => $verticalAlignPixels[1]
)
);
imagecolortransparent($croppedImage, imagecolorallocatealpha($croppedImage, 0, 0, 0, 127));
imagealphablending($croppedImage, false);
imagesavealpha($croppedImage, true);
if (imagewebp($croppedImage, $dir.$thumb))
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
}
else
{
return $image;
}
}
else
{
$searchArray = array(
getcwd(),
str_replace('\\', "/", getcwd()),
str_replace("public_html", "private_html", getcwd())
);
return str_replace($searchArray, "", $thumbPath);
}
}
else
{
return $image;
}
}
private function calculatePixelsForAlign($imageSize, $cropSize, $align)
{
switch ($align) {
case 'left':
case 'top':
return array(0, min($cropSize, $imageSize));
case 'right':
case 'bottom':
return array(max(0, $imageSize - $cropSize), min($cropSize, $imageSize));
case 'center':
case 'middle':
return array(
max(0, floor(($imageSize / 2) - ($cropSize / 2))),
min($cropSize, $imageSize),
);
default: return array(0, $imageSize);
}
}
public function getExtraOptions($section, $typeID)
{
$selectExtraOptionInputs = $this->db->prepare("SELECT * FROM extra_option_inputs WHERE section=:section AND siteID='$this->siteID' ORDER BY sort ASC");
$selectExtraOptionInputs->execute(array(":section"=>$section));
while ($extraOptionInput = $selectExtraOptionInputs->fetch())
{
$selectExtraOptions = $this->db->prepare("SELECT * FROM extra_options WHERE typeID=:typeID AND inputID=:inputID AND siteID='$this->siteID'");
$selectExtraOptions->execute(array(":typeID"=>$typeID, ":inputID"=>$extraOptionInput['id']));
if ($selectExtraOptions->rowCount() > 0)
{
$extraOption = $selectExtraOptions->fetch();
$extraOptions[$extraOptionInput['name']] = $extraOption['value'];
}
else
{
$extraOptions[$extraOptionInput['name']] = '';
}
}
return $extraOptions;
}
public function settings($property="")
{
$selectSettings = $this->db->query("SELECT * FROM settings WHERE siteID='$this->siteID' LIMIT 1");
$rowSettings = $selectSettings->fetch();
$rowSettings['extraOptions'] = $this->getExtraOptions("settings", $rowSettings['id']);
if ($property == "")
{
return $rowSettings;
}
else
{
return $rowSettings["$property"];
}
}
public function apis($property="")
{
$selectAPIs = $this->db->query("SELECT * FROM apis WHERE siteID='$this->siteID' LIMIT 1");
$rowAPIs = $selectAPIs->fetch();
if ($property == "")
{
return $rowAPIs;
}
else
{
return $rowAPIs["$property"];
}
}
public function mail_settings()
{
$selectMailSettings = $this->db->query("SELECT * FROM mail_settings WHERE siteID='$this->siteID' LIMIT 1");
$rowMailSettings = $selectMailSettings->fetch();
return $rowMailSettings;
}
public function sms_settings()
{
$selectSMSSettings = $this->db->query("SELECT * FROM sms_settings WHERE siteID='$this->siteID' LIMIT 1");
$rowSMSSettings = $selectSMSSettings->fetch();
return $rowSMSSettings;
}
public function club_settings()
{
$selectClubSettings = $this->db->query("SELECT * FROM club_settings WHERE siteID='$this->siteID' LIMIT 1");
$rowClubSettings = $selectClubSettings->fetch();
return $rowClubSettings;
}
public function get_cache_by_id($ID)
{
$ID = intval($ID);
$selectCache = $this->db->query("SELECT * FROM cache WHERE `id`='$ID' AND `siteID`='$this->siteID'");
$rowCache = $selectCache->fetch();
if ($rowCache['expireDate'] < $this->now || empty($rowCache['value']))
{
$rowCache['isValid'] = 0;
}
else
{
$rowCache['isValid'] = 1;
}
return $rowCache;
}
public function get_cache_by_key($key)
{
$selectCache = $this->db->prepare("SELECT * FROM cache WHERE `key`=:key AND `siteID`='$this->siteID'");
$selectCache->execute(array(":key"=>$key));
$rowCache = $selectCache->fetch();
if ($rowCache['expireDate'] < $this->now || empty($rowCache['value']) || !empty($_GET['clearcache']))
{
$rowCache['isValid'] = 0;
}
else
{
$rowCache['isValid'] = 1;
}
return $rowCache;
}
public function get_cache($key)
{
return $this->get_cache_by_key($key);
}
public function set_cache($key, $value, $expire=120)
{
$expire = intval($expire);
$expireDate = $this->now + $expire;
$deleteOldCache = $this->db->exec("DELETE FROM cache WHERE expireDate < '$this->now' AND siteID='$this->siteID'");
$selectCache = $this->db->prepare("SELECT * FROM cache WHERE `key`=:key AND siteID='$this->siteID'");
$selectCache->execute(array(":key"=>$key));
if ($selectCache->rowCount() > 0) // Update
{
$rowCache = $selectCache->fetch();
$updateCache = $this->db->prepare("UPDATE cache SET `value`=:value, `date`=:date, `expireDate`=:expireDate WHERE `id`=:id AND siteID='$this->siteID'");
$updateCache->execute(array(":value"=>$value, ":date"=>$this->now, ":expireDate"=>$expireDate, ":id"=>$rowCache['id']));
$cacheID = $rowCache['id'];
}
else // Insert
{
$insertCache = $this->db->prepare("INSERT INTO cache (`siteID`, `key`, `value`, `date`, `expireDate`) VALUES ('$this->siteID', :key, :value, :date, :expireDate)");
$insertCache->execute(array(":key"=>$key, ":value"=>$value, ":date"=>$this->now, ":expireDate"=>$expireDate));
$cacheID = $this->db->lastInsertId();
}
return $cacheID;
}
public function getUserByID($ID)
{
$ID = intval($ID);
$selectUser = $this->db->query("SELECT * FROM users WHERE id='$ID' AND siteID='$this->siteID'");
if ($selectUser->rowCount() != 0)
{
$rowUser = $selectUser->fetch();
//Get Addressbook
$selectAddressbook = $this->db->query("SELECT * FROM addressbook WHERE userID='$ID' AND siteID='$this->siteID'");
$rowAddressbook = $selectAddressbook->fetchAll();
$rowUser['addressbook'] = $rowAddressbook;
//Get UserMeta
$selectUsersMeta = $this->db->query("SELECT * FROM users_meta WHERE _userID='$ID'");
$rowUsersMeta = $selectUsersMeta->fetch();
$rowUser['meta'] = $rowUsersMeta;
//Charged Cash
$selectCharges = $this->db->query("SELECT SUM(price) AS charged FROM transactions WHERE userID=$ID AND type=2 AND currency!='دلار' AND status=1 AND siteID='$this->siteID'");
$rowCharges = $selectCharges->fetch();
$rowUser['cash'] += $rowCharges['charged'];
//Spent Cash By Order
$selectOrders = $this->db->query("SELECT SUM(totalCost) AS totalCost, SUM(discount) AS discount FROM orders WHERE userID=$ID AND payMethod=4 AND currency!='دلار' AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['cash'] -= intval($rowOrders['totalCost']) - intval($rowOrders['discount']);
//Spent Cash By Order WalletDiscount
$selectOrders = $this->db->query("SELECT SUM(walletDiscount) AS walletDiscount FROM orders WHERE userID=$ID AND currency!='دلار' AND payMethod=1 AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['cash'] -= intval($rowOrders['walletDiscount']);
//Spent Cash By Transaction
$selectTransactions = $this->db->query("SELECT SUM(price) AS spent, SUM(discount) AS discount FROM transactions WHERE userID=$ID AND payMethod=2 AND currency!='دلار' AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['cash'] -= intval($rowTransactions['spent']) - intval($rowTransactions['discount']);
//Spent Cash By Transaction WalletDiscount
$selectTransactions = $this->db->query("SELECT SUM(walletDiscount) AS walletDiscount FROM transactions WHERE userID=$ID AND currency!='دلار' AND payMethod=1 AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['cash'] -= intval($rowTransactions['walletDiscount']);
//Charged DollarCash
$selectCharges = $this->db->query("SELECT SUM(dollarPrice) AS charged FROM transactions WHERE userID=$ID AND type=2 AND currency='دلار' AND status=1 AND siteID='$this->siteID'");
$rowCharges = $selectCharges->fetch();
$rowUser['dollarCash'] += $rowCharges['charged'];
//Spent DollarCash By Order
$selectOrders = $this->db->query("SELECT SUM(totalDollarCost) AS totalDollarCost, SUM(dollarDiscount) AS dollarDiscount FROM orders WHERE userID=$ID AND payMethod=4 AND currency='دلار' AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['dollarCash'] -= floatval($rowOrders['totalDollarCost']) - floatval($rowOrders['dollarDiscount']);
//Spent DollarCash By Transaction
$selectTransactions = $this->db->query("SELECT SUM(dollarPrice) AS spent, SUM(dollarDiscount) AS dollarDiscount FROM transactions WHERE userID=$ID AND payMethod=2 AND currency='دلار' AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['dollarCash'] -= floatval($rowTransactions['spent']) - floatval($rowTransactions['dollarDiscount']);
//Orders Commission
$selectCommission = $this->db->query("SELECT SUM(commission) AS commission FROM orders WHERE marketerID=$ID AND payStatus=1 AND siteID='$this->siteID'");
$rowCommission = $selectCommission->fetch();
$rowUser['commission'] += $rowCommission['commission'];
//Transactions Commission
$selectCommission = $this->db->query("SELECT SUM(commission) AS commission FROM transactions WHERE marketerID=$ID AND payMethod!=4 AND status=1 AND siteID='$this->siteID'");
$rowCommission = $selectCommission->fetch();
$rowUser['commission'] += $rowCommission['commission'];
//Commission Settlement By Transaction
$selectTransactions = $this->db->query("SELECT SUM(price) AS settle FROM transactions WHERE userID=$ID AND type=9 AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['commission'] -= $rowTransactions['settle'];
}
return $rowUser;
}
public function getUserBySubdomainID($ID)
{
$ID = intval($ID);
$selectSubdomain = $this->db->query("SELECT * FROM subdomains WHERE id='$ID' AND siteID='$this->siteID'");
$rowSubdomain = $selectSubdomain->fetch();
$selectUser = $this->db->query("SELECT * FROM users WHERE id='$rowSubdomain[userID]' AND siteID='$this->siteID'");
if ($selectUser->rowCount() != 0)
{
$rowUser = $selectUser->fetch();
$ID = $rowUser['id'];
//Get Addressbook
$selectAddressbook = $this->db->query("SELECT * FROM addressbook WHERE userID='$ID' AND siteID='$this->siteID'");
$rowAddressbook = $selectAddressbook->fetchAll();
$rowUser['addressbook'] = $rowAddressbook;
//Get UserMeta
$selectUsersMeta = $this->db->query("SELECT * FROM users_meta WHERE _userID='$ID'");
$rowUsersMeta = $selectUsersMeta->fetch();
$rowUser['meta'] = $rowUsersMeta;
//Charged Cash
$selectCharges = $this->db->query("SELECT SUM(price) AS charged FROM transactions WHERE userID=$ID AND type=2 AND currency!='دلار' AND status=1 AND siteID='$this->siteID'");
$rowCharges = $selectCharges->fetch();
$rowUser['cash'] += $rowCharges['charged'];
//Spent Cash By Order
$selectOrders = $this->db->query("SELECT SUM(totalCost) AS totalCost, SUM(discount) AS discount FROM orders WHERE userID=$ID AND payMethod=4 AND currency!='دلار' AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['cash'] -= intval($rowOrders['totalCost']) - intval($rowOrders['discount']);
//Spent Cash By Order WalletDiscount
$selectOrders = $this->db->query("SELECT SUM(walletDiscount) AS walletDiscount FROM orders WHERE userID=$ID AND currency!='دلار' AND payMethod=1 AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['cash'] -= intval($rowOrders['walletDiscount']);
//Spent Cash By Transaction
$selectTransactions = $this->db->query("SELECT SUM(price) AS spent, SUM(discount) AS discount FROM transactions WHERE userID=$ID AND payMethod=2 AND currency!='دلار' AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['cash'] -= intval($rowTransactions['spent']) - intval($rowTransactions['discount']);
//Spent Cash By Transaction WalletDiscount
$selectTransactions = $this->db->query("SELECT SUM(walletDiscount) AS walletDiscount FROM transactions WHERE userID=$ID AND currency!='دلار' AND payMethod=1 AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['cash'] -= intval($rowTransactions['walletDiscount']);
//Charged DollarCash
$selectCharges = $this->db->query("SELECT SUM(dollarPrice) AS charged FROM transactions WHERE userID=$ID AND type=2 AND currency='دلار' AND status=1 AND siteID='$this->siteID'");
$rowCharges = $selectCharges->fetch();
$rowUser['dollarCash'] += $rowCharges['charged'];
//Spent DollarCash By Order
$selectOrders = $this->db->query("SELECT SUM(totalDollarCost) AS totalDollarCost, SUM(dollarDiscount) AS dollarDiscount FROM orders WHERE userID=$ID AND payMethod=4 AND currency='دلار' AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['dollarCash'] -= floatval($rowOrders['totalDollarCost']) - floatval($rowOrders['dollarDiscount']);
//Spent DollarCash By Transaction
$selectTransactions = $this->db->query("SELECT SUM(dollarPrice) AS spent, SUM(dollarDiscount) AS dollarDiscount FROM transactions WHERE userID=$ID AND payMethod=2 AND currency='دلار' AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['dollarCash'] -= floatval($rowTransactions['spent']) - floatval($rowTransactions['dollarDiscount']);
//Orders Commission
$selectCommission = $this->db->query("SELECT SUM(commission) AS commission FROM orders WHERE marketerID=$ID AND payStatus=1 AND siteID='$this->siteID'");
$rowCommission = $selectCommission->fetch();
$rowUser['commission'] += $rowCommission['commission'];
//Transactions Commission
$selectCommission = $this->db->query("SELECT SUM(commission) AS commission FROM transactions WHERE marketerID=$ID AND payMethod!=4 AND status=1 AND siteID='$this->siteID'");
$rowCommission = $selectCommission->fetch();
$rowUser['commission'] += $rowCommission['commission'];
//Commission Settlement By Transaction
$selectTransactions = $this->db->query("SELECT SUM(price) AS settle FROM transactions WHERE userID=$ID AND type=9 AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['commission'] -= $rowTransactions['settle'];
}
return $rowUser;
}
public function getUserBySubdomain($subdomain)
{
$selectSubdomain = $this->db->prepare("SELECT * FROM subdomains WHERE subdomain=:subdomain AND siteID='$this->siteID'");
$selectSubdomain->execute(array(":subdomain"=>$subdomain));
$rowSubdomain = $selectSubdomain->fetch();
$selectUser = $this->db->query("SELECT * FROM users WHERE id='$rowSubdomain[userID]'");
if ($selectUser->rowCount() != 0)
{
$rowUser = $selectUser->fetch();
$ID = $rowUser['id'];
//Get Addressbook
$selectAddressbook = $this->db->query("SELECT * FROM addressbook WHERE userID='$ID' AND siteID='$this->siteID'");
$rowAddressbook = $selectAddressbook->fetchAll();
$rowUser['addressbook'] = $rowAddressbook;
//Get UserMeta
$selectUsersMeta = $this->db->query("SELECT * FROM users_meta WHERE _userID='$ID'");
$rowUsersMeta = $selectUsersMeta->fetch();
$rowUser['meta'] = $rowUsersMeta;
//Charged Cash
$selectCharges = $this->db->query("SELECT SUM(price) AS charged FROM transactions WHERE userID=$ID AND type=2 AND currency!='دلار' AND status=1 AND siteID='$this->siteID'");
$rowCharges = $selectCharges->fetch();
$rowUser['cash'] += $rowCharges['charged'];
//Spent Cash By Order
$selectOrders = $this->db->query("SELECT SUM(totalCost) AS totalCost, SUM(discount) AS discount FROM orders WHERE userID=$ID AND payMethod=4 AND currency!='دلار' AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['cash'] -= intval($rowOrders['totalCost']) - intval($rowOrders['discount']);
//Spent Cash By Order WalletDiscount
$selectOrders = $this->db->query("SELECT SUM(walletDiscount) AS walletDiscount FROM orders WHERE userID=$ID AND currency!='دلار' AND payMethod=1 AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['cash'] -= intval($rowOrders['walletDiscount']);
//Spent Cash By Transaction
$selectTransactions = $this->db->query("SELECT SUM(price) AS spent, SUM(discount) AS discount FROM transactions WHERE userID=$ID AND payMethod=2 AND currency!='دلار' AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['cash'] -= intval($rowTransactions['spent']) - intval($rowTransactions['discount']);
//Spent Cash By Transaction WalletDiscount
$selectTransactions = $this->db->query("SELECT SUM(walletDiscount) AS walletDiscount FROM transactions WHERE userID=$ID AND currency!='دلار' AND payMethod=1 AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['cash'] -= intval($rowTransactions['walletDiscount']);
//Charged DollarCash
$selectCharges = $this->db->query("SELECT SUM(dollarPrice) AS charged FROM transactions WHERE userID=$ID AND type=2 AND currency='دلار' AND status=1 AND siteID='$this->siteID'");
$rowCharges = $selectCharges->fetch();
$rowUser['dollarCash'] += $rowCharges['charged'];
//Spent DollarCash By Order
$selectOrders = $this->db->query("SELECT SUM(totalDollarCost) AS totalDollarCost, SUM(dollarDiscount) AS dollarDiscount FROM orders WHERE userID=$ID AND payMethod=4 AND currency='دلار' AND payStatus=1 AND siteID='$this->siteID'");
$rowOrders = $selectOrders->fetch();
$rowUser['dollarCash'] -= floatval($rowOrders['totalDollarCost']) - floatval($rowOrders['dollarDiscount']);
//Spent DollarCash By Transaction
$selectTransactions = $this->db->query("SELECT SUM(dollarPrice) AS spent, SUM(dollarDiscount) AS dollarDiscount FROM transactions WHERE userID=$ID AND payMethod=2 AND currency='دلار' AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['dollarCash'] -= floatval($rowTransactions['spent']) - floatval($rowTransactions['dollarDiscount']);
//Orders Commission
$selectCommission = $this->db->query("SELECT SUM(commission) AS commission FROM orders WHERE marketerID=$ID AND payStatus=1 AND siteID='$this->siteID'");
$rowCommission = $selectCommission->fetch();
$rowUser['commission'] += $rowCommission['commission'];
//Transactions Commission
$selectCommission = $this->db->query("SELECT SUM(commission) AS commission FROM transactions WHERE marketerID=$ID AND payMethod!=4 AND status=1 AND siteID='$this->siteID'");
$rowCommission = $selectCommission->fetch();
$rowUser['commission'] += $rowCommission['commission'];
//Commission Settlement By Transaction
$selectTransactions = $this->db->query("SELECT SUM(price) AS settle FROM transactions WHERE userID=$ID AND type=9 AND status=1 AND siteID='$this->siteID'");
$rowTransactions = $selectTransactions->fetch();
$rowUser['commission'] -= $rowTransactions['settle'];
}
return $rowUser;
}
public function deleteUserByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM users WHERE id='$ID' AND siteID='$this->siteID'");
}
public function activeUserByID($ID)
{
$ID = intval($ID);
return $this->db->exec("UPDATE users SET status=1 WHERE id='$ID' AND siteID='$this->siteID'");
}
public function deactiveUserByID($ID)
{
$ID = intval($ID);
return $this->db->exec("UPDATE users SET status=0 WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getNewsletterByID($ID)
{
$ID = intval($ID);
$selectNewsletter = $this->db->query("SELECT * FROM newsletter WHERE id='$ID' AND siteID='$this->siteID'");
$rowNewsletter = $selectNewsletter->fetch();
return $rowNewsletter;
}
public function deleteNewsletterByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM newsletter WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getRootCategory($categoryID)
{
global $rootCategory;
$rootCategory = $categoryID;
$selectParent = $this->db->query("SELECT * FROM categories WHERE id='$categoryID' AND siteID='$this->siteID'");
$rowParent = $selectParent->fetch();
if (!empty($rowParent['parentID']))
{
$this->getRootCategory($rowParent['parentID']);
}
return $rootCategory;
}
public function getParentCategories($categoryID)
{
global $parentCategories;
$parentCategories[] = $categoryID;
$selectParents = $this->db->query("SELECT * FROM categories WHERE id='$categoryID' AND siteID='$this->siteID'");
$rowParent = $selectParents->fetch();
if (!empty($rowParent['parentID']))
{
$this->getParentCategories($rowParent['parentID']);
}
return $parentCategories;
}
public function getChildCategories($categoryID)
{
global $childCategories;
$childCategories[] = $categoryID;
$selectChilds = $this->db->query("SELECT * FROM categories WHERE parentID='$categoryID' AND siteID='$this->siteID'");
while ($rowChilds = $selectChilds->fetch())
{
$this->getChildCategories($rowChilds['id']);
}
return $childCategories;
}
public function getCategories($section, $parentID=0, $orderBy="sort ASC", $addSelf=false)
{
$order = $orderBy;
$orderBy = $this->orderBy($orderBy);
$categories = array();
if ($addSelf == true)
{
$selectCategories = $this->db->prepare("SELECT * FROM categories WHERE section=:section AND id=:id AND siteID='$this->siteID' $orderBy");
$selectCategories->execute(array(":section"=>$section, ":id"=>$parentID));
while($rowCategories = $selectCategories->fetch())
{
if (!empty($rowCategories['permalink']))
{
$rowCategories['url'] = "/" . $rowCategories['permalink'];
}
else
{
$rowCategories['url'] = "/category/" . $rowCategories['id'] . "/" . $this->safeUrl($rowCategories['title']);
}
$rowCategories['subcategories'] = $this->getCategories($section, $rowCategories['id'], $order);
$categories[] = $rowCategories;
}
}
else
{
$selectCategories = $this->db->prepare("SELECT * FROM categories WHERE section=:section AND parentID=:parentID AND siteID='$this->siteID' $orderBy");
$selectCategories->execute(array(":section"=>$section, ":parentID"=>$parentID));
while($rowCategories = $selectCategories->fetch())
{
if (!empty($rowCategories['permalink']))
{
$rowCategories['url'] = "/" . $rowCategories['permalink'];
}
else
{
$rowCategories['url'] = "/category/" . $rowCategories['id'] . "/" . $this->safeUrl($rowCategories['title']);
}
$rowCategories['subcategories'] = $this->getCategories($section, $rowCategories['id'], $order);
$categories[] = $rowCategories;
}
}
return $categories;
}
public function getCategoryByID($ID)
{
$ID = intval($ID);
$selectCategory = $this->db->query("SELECT * FROM categories WHERE id='$ID' AND siteID='$this->siteID'");
$rowCategory = $selectCategory->fetch();
$rowCategory['extraOptions'] = $this->getExtraOptions("categories", $ID);
return $rowCategory;
}
public function deleteCategoryByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM categories WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getPollByID($ID)
{
$ID = intval($ID);
$selectPoll = $this->db->query("SELECT * FROM polls WHERE id='$ID' AND siteID='$this->siteID'");
$rowPoll = $selectPoll->fetch();
$selectPollChoices = $this->db->query("SELECT * FROM poll_choices WHERE pollID='$ID' AND siteID='$this->siteID' ORDER BY sort ASC");
$rowPoll['choices'] = $selectPollChoices->fetchAll();
return $rowPoll;
}
public function deletePollByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM polls WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getMenus($parentID=0, $orderBy="sort ASC")
{
$order = $orderBy;
$orderBy = $this->orderBy($orderBy);
$menus = array();
$selectMenus = $this->db->prepare("SELECT * FROM menus WHERE parentID=:parentID AND siteID='$this->siteID' $orderBy");
$selectMenus->execute(array(":parentID"=>$parentID));
while($rowMenus = $selectMenus->fetch())
{
$rowMenus['submenus'] = $this->getMenus($rowMenus['id'], $order);
$menus[] = $rowMenus;
}
return $menus;
}
public function getMenuByID($ID)
{
$ID = intval($ID);
$selectMenu = $this->db->query("SELECT * FROM menus WHERE id='$ID' AND siteID='$this->siteID'");
$rowMenu = $selectMenu->fetch();
return $rowMenu;
}
public function deleteMenuByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM menus WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getLinkByID($ID)
{
$ID = intval($ID);
$selectLink = $this->db->query("SELECT * FROM links WHERE id='$ID' AND siteID='$this->siteID'");
$rowLink = $selectLink->fetch();
return $rowLink;
}
public function deleteLinkByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM links WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getWordByID($ID)
{
$ID = intval($ID);
$selectWord = $this->db->query("SELECT * FROM words WHERE id='$ID' AND siteID='$this->siteID'");
$rowWord = $selectWord->fetch();
return $rowWord;
}
public function deleteWordByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM words WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getArticleByID($ID)
{
$ID = intval($ID);
$selectArticle = $this->db->query("SELECT * FROM articles WHERE id='$ID' AND siteID='$this->siteID'");
$rowArticle = $selectArticle->fetch();
$rowArticle['extraOptions'] = $this->getExtraOptions("articles", $ID);
return $rowArticle;
}
public function deleteArticleByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM articles WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getNewsByID($ID)
{
$ID = intval($ID);
$selectNews = $this->db->query("SELECT * FROM news WHERE id='$ID' AND siteID='$this->siteID'");
$rowNews = $selectNews->fetch();
$rowNews['extraOptions'] = $this->getExtraOptions("news", $ID);
return $rowNews;
}
public function deleteNewsByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM news WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getProductByID($ID)
{
$ID = intval($ID);
$selectProduct = $this->db->query("SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice FROM products WHERE id='$ID' AND siteID='$this->siteID'");
$rowProduct = $selectProduct->fetch();
$rowProduct['extraOptions'] = $this->getExtraOptions("products", $ID);
return $rowProduct;
}
public function deleteProductByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM products WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getGroupProductByID($ID)
{
$ID = intval($ID);
$selectGroupProduct = $this->db->query("SELECT * FROM group_products WHERE id='$ID' AND siteID='$this->siteID'");
$rowGroupProduct = $selectGroupProduct->fetch();
$rowGroupProduct['extraOptions'] = $this->getExtraOptions("groupProducts", $ID);
return $rowGroupProduct;
}
public function deleteGroupProductByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM group_products WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getWishByID($ID)
{
$ID = intval($ID);
$selectWish = $this->db->query("SELECT * FROM wishes WHERE id='$ID' AND siteID='$this->siteID'");
$rowWish = $selectWish->fetch();
$rowWish['extraOptions'] = $this->getExtraOptions("wishes", $ID);
return $rowWish;
}
public function deleteWishByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM wishes WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getPageByID($ID)
{
$ID = intval($ID);
$selectPage = $this->db->query("SELECT * FROM pages WHERE id='$ID' AND siteID='$this->siteID'");
$rowPage = $selectPage->fetch();
$rowPage['extraOptions'] = $this->getExtraOptions("pages", $ID);
return $rowPage;
}
public function deletePageByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM pages WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getDownloadByID($ID)
{
$ID = intval($ID);
$selectDownload = $this->db->query("SELECT * FROM downloads WHERE id='$ID' AND siteID='$this->siteID'");
$rowDownload = $selectDownload->fetch();
$rowDownload['extraOptions'] = $this->getExtraOptions("downloads", $ID);
return $rowDownload;
}
public function deleteDownloadByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM downloads WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getOfferByID($ID)
{
$ID = intval($ID);
$selectOffer = $this->db->query("SELECT * FROM offers WHERE id='$ID' AND siteID='$this->siteID'");
$rowOffer = $selectOffer->fetch();
$rowOffer['extraOptions'] = $this->getExtraOptions("offers", $ID);
return $rowOffer;
}
public function deleteOfferByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM offers WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getAuthorByID($ID)
{
$ID = intval($ID);
$selectAuthor = $this->db->query("SELECT * FROM authors WHERE id='$ID' AND siteID='$this->siteID'");
$rowAuthor = $selectAuthor->fetch();
$rowAuthor['extraOptions'] = $this->getExtraOptions("authors", $ID);
return $rowAuthor;
}
public function deleteAuthorByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM authors WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getRegisterationByID($ID)
{
$ID = intval($ID);
$selectRegisteration = $this->db->query("SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice FROM registerations WHERE id='$ID' AND siteID='$this->siteID'");
$rowRegisteration = $selectRegisteration->fetch();
$rowRegisteration['extraOptions'] = $this->getExtraOptions("registerations", $ID);
return $rowRegisteration;
}
public function deleteRegisterationByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM registerations WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getVipByID($ID)
{
$ID = intval($ID);
$selectVip = $this->db->query("SELECT * FROM vips WHERE id='$ID' AND siteID='$this->siteID'");
$rowVip = $selectVip->fetch();
$rowVip['extraOptions'] = $this->getExtraOptions("vips", $ID);
return $rowVip;
}
public function deleteVipByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM vips WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getEstateByID($ID)
{
$ID = intval($ID);
$selectEstate = $this->db->query("SELECT * FROM estates WHERE id='$ID' AND siteID='$this->siteID'");
$rowEstate = $selectEstate->fetch();
$rowEstate['extraOptions'] = $this->getExtraOptions("estates", $ID);
return $rowEstate;
}
public function deleteEstateByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM estates WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getSubdomainByID($ID)
{
$ID = intval($ID);
$selectSubdomain = $this->db->query("SELECT * FROM subdomains WHERE id='$ID' AND siteID='$this->siteID'");
$rowSubdomain = $selectSubdomain->fetch();
return $rowSubdomain;
}
public function deleteSubdomainByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM subdomains WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getAudioByID($ID)
{
$ID = intval($ID);
$selectAudio = $this->db->query("SELECT * FROM audios WHERE id='$ID' AND siteID='$this->siteID'");
$rowAudio = $selectAudio->fetch();
$rowAudio['extraOptions'] = $this->getExtraOptions("audios", $ID);
return $rowAudio;
}
public function deleteAudioByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM audios WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getVideoByID($ID)
{
$ID = intval($ID);
$selectVideo = $this->db->query("SELECT * FROM videos WHERE id='$ID' AND siteID='$this->siteID'");
$rowVideo = $selectVideo->fetch();
$rowVideo['extraOptions'] = $this->getExtraOptions("videos", $ID);
return $rowVideo;
}
public function deleteVideoByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM videos WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getCourseByID($ID)
{
$ID = intval($ID);
$selectCourse = $this->db->query("SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice FROM courses WHERE id='$ID' AND siteID='$this->siteID'");
$rowCourse = $selectCourse->fetch();
$rowCourse['extraOptions'] = $this->getExtraOptions("courses", $ID);
return $rowCourse;
}
public function deleteCourseByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM courses WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getSessionByID($ID)
{
$ID = intval($ID);
$selectSession = $this->db->query("SELECT * FROM sessions WHERE id='$ID' AND siteID='$this->siteID'");
$rowSession = $selectSession->fetch();
$rowSession['extraOptions'] = $this->getExtraOptions("sessions", $ID);
return $rowSession;
}
public function deleteSessionByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM sessions WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getLessonByID($ID)
{
$ID = intval($ID);
$selectLesson = $this->db->query("SELECT * FROM lessons WHERE id='$ID' AND siteID='$this->siteID'");
$rowLesson = $selectLesson->fetch();
$rowLesson['extraOptions'] = $this->getExtraOptions("lessons", $ID);
return $rowLesson;
}
public function deleteLessonByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM lessons WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getLessonChapterByID($ID)
{
$ID = intval($ID);
$selectLessonChapter = $this->db->query("SELECT * FROM lesson_chapters WHERE id='$ID' AND siteID='$this->siteID'");
$rowLessonChapter = $selectLessonChapter->fetch();
return $rowLessonChapter;
}
public function deleteLessonChapterByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM lesson_chapters WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getLessonEpisodeByID($ID)
{
$ID = intval($ID);
$selectLessonEpisode = $this->db->query("SELECT * FROM lesson_episodes WHERE id='$ID' AND siteID='$this->siteID'");
$rowLessonEpisode = $selectLessonEpisode->fetch();
$rowLessonEpisode['extraOptions'] = $this->getExtraOptions("lessonEpisodes", $ID);
return $rowLessonEpisode;
}
public function deleteLessonEpisodeByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM lesson_episodes WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getGalleryByID($ID)
{
$ID = intval($ID);
$selectGallery = $this->db->query("SELECT * FROM galleries WHERE id='$ID' AND siteID='$this->siteID'");
$rowGallery = $selectGallery->fetch();
$rowGallery['extraOptions'] = $this->getExtraOptions("galleries", $ID);
return $rowGallery;
}
public function deleteGalleryByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM galleries WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getGalleryImageByID($ID)
{
$ID = intval($ID);
$selectGalleryImage = $this->db->query("SELECT * FROM gallery_images WHERE id='$ID' AND siteID='$this->siteID'");
$rowGalleryImage = $selectGalleryImage->fetch();
$rowGalleryImage['extraOptions'] = $this->getExtraOptions("galleryImages", $ID);
return $rowGalleryImage;
}
public function deleteGalleryImageByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM gallery_images WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getCrawlByID($ID)
{
$ID = intval($ID);
$selectCrawl = $this->db->query("SELECT * FROM crawls WHERE id='$ID' AND siteID='$this->siteID'");
$rowCrawl = $selectCrawl->fetch();
return $rowCrawl;
}
public function deleteCrawlByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM crawls WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getSliderByID($ID)
{
$ID = intval($ID);
$selectSlider = $this->db->query("SELECT * FROM slider WHERE id='$ID' AND siteID='$this->siteID'");
$rowSlider = $selectSlider->fetch();
return $rowSlider;
}
public function deleteSliderByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM slider WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getBannerByID($ID)
{
$ID = intval($ID);
$selectBanner = $this->db->query("SELECT * FROM banners WHERE id='$ID' AND siteID='$this->siteID'");
$rowBanner = $selectBanner->fetch();
$rowBanner['extraOptions'] = $this->getExtraOptions("banners", $ID);
return $rowBanner;
}
public function deleteBannerByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM banners WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getAdPlaceByID($ID)
{
$ID = intval($ID);
$selectAdPlace = $this->db->query("SELECT * FROM ad_places WHERE id='$ID' AND siteID='$this->siteID'");
$rowAdPlace = $selectAdPlace->fetch();
return $rowAdPlace;
}
public function deleteAdPlaceByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM ad_places WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getExtraOptionInputByID($ID)
{
$ID = intval($ID);
$selectExtraOptionInput = $this->db->query("SELECT * FROM extra_option_inputs WHERE id='$ID' AND siteID='$this->siteID'");
$rowExtraOptionInput = $selectExtraOptionInput->fetch();
return $rowExtraOptionInput;
}
public function deleteExtraOptionInputByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM extra_option_inputs WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getFormByID($ID)
{
$ID = intval($ID);
$selectForm = $this->db->query("SELECT * FROM forms WHERE id='$ID' AND siteID='$this->siteID'");
$rowForm = $selectForm->fetch();
$rowForm['extraOptions'] = $this->getExtraOptions("forms", $ID);
return $rowForm;
}
public function deleteFormByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM forms WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getFormInputByID($ID)
{
$ID = intval($ID);
$selectFormInput = $this->db->query("SELECT * FROM form_inputs WHERE id='$ID' AND siteID='$this->siteID'");
$rowFormInput = $selectFormInput->fetch();
return $rowFormInput;
}
public function deleteFormInputByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM form_inputs WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getUsersMetaInputByID($ID)
{
$ID = intval($ID);
$selectUsersMetaInput = $this->db->query("SELECT * FROM users_meta_inputs WHERE id='$ID' AND siteID='$this->siteID'");
$rowUsersMetaInput = $selectUsersMetaInput->fetch();
return $rowUsersMetaInput;
}
public function deleteUsersMetaInputByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM users_meta_inputs WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getTestByID($ID)
{
$ID = intval($ID);
$selectTest = $this->db->query("SELECT * FROM tests WHERE id='$ID' AND siteID='$this->siteID'");
$rowTest = $selectTest->fetch();
$rowTest['extraOptions'] = $this->getExtraOptions("tests", $ID);
return $rowTest;
}
public function deleteTestByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM tests WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getTestInputByID($ID)
{
$ID = intval($ID);
$selectTestField = $this->db->query("SELECT * FROM test_fields WHERE id='$ID' AND siteID='$this->siteID'");
$rowTestField = $selectTestField->fetch();
return $rowTestField;
}
public function deleteTestFieldByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM form_fields WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getCommentByID($ID)
{
$ID = intval($ID);
$selectComment = $this->db->query("SELECT * FROM comment WHERE id='$ID' AND siteID='$this->siteID'");
$rowComment = $selectComment->fetch();
return $rowComment;
}
public function deleteCommentByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM comment WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getTopicByID($ID)
{
$ID = intval($ID);
$selectTopic = $this->db->query("SELECT * FROM topics WHERE id='$ID' AND siteID='$this->siteID'");
$rowTopic = $selectTopic->fetch();
return $rowTopic;
}
public function deleteTopicByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM topics WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getDiscountCodeByID($ID)
{
$ID = intval($ID);
$selectDiscountCode = $this->db->query("SELECT * FROM discount_codes WHERE id='$ID' AND siteID='$this->siteID'");
$rowDiscountCode = $selectDiscountCode->fetch();
return $rowDiscountCode;
}
public function deleteDiscountCodeByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM discount_codes WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getEventByID($ID)
{
$ID = intval($ID);
$selectEvent = $this->db->query("SELECT * FROM events WHERE id='$ID' AND siteID='$this->siteID'");
$rowEvent = $selectEvent->fetch();
return $rowEvent;
}
public function deleteEventByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM events WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getSubscriptionByID($ID)
{
$ID = intval($ID);
$selectSubscription = $this->db->query("SELECT * FROM subscriptions WHERE id='$ID' AND siteID='$this->siteID'");
$rowSubscription = $selectSubscription->fetch();
return $rowSubscription;
}
public function deleteSubscriptionByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM subscriptions WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getVipOptionByID($ID)
{
$ID = intval($ID);
$selectVipOption = $this->db->query("SELECT * FROM vip_options WHERE id='$ID' AND siteID='$this->siteID'");
$rowVipOption = $selectVipOption->fetch();
return $rowVipOption;
}
public function deleteVipOptionByID($ID)
{
$ID = intval($ID);
return $this->db->exec("DELETE FROM vip_options WHERE id='$ID' AND siteID='$this->siteID'");
}
public function getWishlist()
{
if (!empty($_SESSION['userID']))
{
$wishlist = array();
$userID = intval($_SESSION['userID']);
$query = "SELECT
wishlist.*,
products.*,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice,
(CASE
WHEN (
IFNULL(products.availability, 0) = 0 AND
(
IFNULL(products.stock, 0) = 1 OR
(IFNULL(instock_variations.id, 0) > 0 AND CAST(instock_variations.instock AS UNSIGNED) > 0) OR
(IFNULL(instock_variations.id, 0) = 0 AND CAST(products.instock AS UNSIGNED) > 0)
)
) THEN 1
ELSE 0
END) AS isAvailable
FROM wishlist
JOIN products ON wishlist.productID=products.id
LEFT JOIN (SELECT id, productID, instock FROM product_variations WHERE status=1 AND instock > 0 AND siteID='$this->siteID') AS instock_variations ON products.id=instock_variations.productID
WHERE
wishlist.userID=$userID AND
wishlist.siteID='$this->siteID'
GROUP BY products.id";
$selectWishlist = $this->db->query($query);
while($rowWishlist = $selectWishlist->fetch())
{
$rowWishlist['images'] = @explode("|", $rowWishlist['image']);
$rowWishlist['image'] = $rowWishlist['images'][0];
if (!empty($rowWishlist['permalink']))
{
$rowWishlist['url'] = "/" . $rowWishlist['permalink'];
}
else
{
$rowWishlist['url'] = "/product/" . $rowWishlist['id'] . "/" . $this->safeUrl($rowWishlist['title']);
}
$wishlist[] = $rowWishlist;
}
}
return $wishlist;
}
//Template_Path
public function template_path()
{
return htmlspecialchars($this->template_path, ENT_QUOTES, 'UTF-8');
}
//Current Page
public function currentPage()
{
return htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, 'UTF-8');
}
//Last Page
public function lastPage()
{
return htmlspecialchars_decode(urldecode($_SESSION['referer']));
}
//Redirect
public function redirect($default="/", $useHeaderLocation=false)
{
$referer = htmlspecialchars_decode(urldecode($_SESSION['referer']));
if (empty($referer))
{
$referer = $default;
}
if ($useHeaderLocation)
{
header("Location: " . $referer);
}
else
{
echo '';
}
}
//sendEmail Function
public function sendEmail($subject, $body, $emails, $from='', $replyTo='', $senderName='', $self=false)
{
require_once('inc/PHPMailer 6.0.5/PHPMailer.php');
require_once('inc/PHPMailer 6.0.5/Exception.php');
require_once('inc/PHPMailer 6.0.5/SMTP.php');
$selectMailSettings = $this->db->query("SELECT * FROM mail_settings WHERE siteID='$this->siteID' LIMIT 1");
$rowMailSettings = $selectMailSettings->fetch();
$mail = new PHPMailer();
if ($rowMailSettings['mode'] == 2)
{
$mail->IsSMTP();
//$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = $rowMailSettings['host'];
$mail->Port = $rowMailSettings['port'];
$mail->Username = $rowMailSettings['username'];
$mail->Password = $rowMailSettings['password'];
}
else
{
$mail->Host = "localhost";
}
$mail->CharSet = 'UTF-8';
$mail->IsHTML(true);
if (empty($replyTo))
{
$replyTo = $rowMailSettings['replyTo'];
}
$mail->AddReplyTo($replyTo);
if (empty($from))
{
$from = $rowMailSettings['email'];
}
if (empty($senderName))
{
$senderName = $rowMailSettings['senderName'];
}
$mail->SetFrom($from, $senderName);
if ($self == true)
{
$mail->AddAddress($rowMailSettings['email']);
}
if (is_array($emails) && !empty($emails))
{
foreach ($emails as $email)
{
$mail->AddBCC($email);
}
}
elseif (!is_array($emails) && !empty($emails))
{
$mail->AddBCC($emails);
}
$mail->Subject = $subject;
if (file_exists('./' . $this->template_path . '/email/index.html'))
{
$handle = fopen('./' . $this->template_path . '/email/index.html', "r");
$template = fread($handle, filesize('./' . $this->template_path . '/email/index.html'));
if ($template != "")
{
$siteAddress = $this->protocol . "://" . $this->settings['siteAddress'];
$emailFolderPath = $siteAddress . "/" . $this->template_path . '/email';
$mail->Body = str_replace(array("[body]", "[email]", "[siteAddress]", "[siteName]", "[templatePath]", "[emailFolderPath]"), array($body, $this->settings['email'], $siteAddress, $this->settings['siteName'], $this->template_path, $emailFolderPath), $template);
}
else
{
$mail->Body = $body;
}
fclose($handle);
}
else
{
$mail->Body = $body;
}
if (!$mail->Send())
{
return $mail->ErrorInfo;
}
else
{
return true;
}
}
//SendSMS Function
public function sendSMS($text, $mobiles)
{
$selectSMSSettings = $this->db->query("SELECT * FROM sms_settings WHERE siteID='$this->siteID' LIMIT 1");
$rowSMSSettings = $selectSMSSettings->fetch();
require_once('inc/' . SMSClass . '.php');
$smsClass = new smsClass();
$response = $smsClass->SendSMS($rowSMSSettings['username'], $rowSMSSettings['password'], $text, $rowSMSSettings['SMSCenter'], $mobiles);
// print_r($response);
if ($response[0] == 0)
{
return true;
}
else
{
return $response[1];
}
}
//SendPatternSMS Function
public function sendPatternSMS($patternCode, $patternData, $mobiles)
{
$selectSMSSettings = $this->db->query("SELECT * FROM sms_settings WHERE siteID='$this->siteID' LIMIT 1");
$rowSMSSettings = $selectSMSSettings->fetch();
require_once('inc/' . SMSClass . '.php');
$smsClass = new smsClass();
$response = $smsClass->SendPatternSMS($rowSMSSettings['username'], $rowSMSSettings['password'], $patternCode, $patternData, $rowSMSSettings['SMSCenter'], $mobiles);
// print_r($response);
if ($response[0] == 0)
{
return true;
}
else
{
return $response[1];
}
}
//Count Visits Function
public function count_visits()
{
$today = strtotime("today");
if ($this->db->exec("INSERT INTO counter (siteID,day,hits) VALUES ('$this->siteID', '$today', 1) ON DUPLICATE KEY UPDATE hits=hits+1"))
{
return true;
}
else
{
return false;
}
}
//Visits Function
public function visits($when = 'total')
{
if (strtolower($when) == "today")
{
$today = strtotime("today");
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$today' AND siteID='$this->siteID' LIMIT 1");
}
if (strtolower($when) == "yesterday")
{
$time = strtotime("yesterday");
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$time' AND siteID='$this->siteID'");
}
if (strtolower($when) == "saturday")
{
if (date("w") > 6)
{
$time = strtotime("last Saturday");
}
else
{
$time = strtotime("Saturday");
}
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$time' AND siteID='$this->siteID'");
}
if (strtolower($when) == "sunday")
{
if (date("w") > 0)
{
$time = strtotime("last Sunday");
}
else
{
$time = strtotime("Sunday");
}
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$time' AND siteID='$this->siteID'");
}
if (strtolower($when) == "monday")
{
if (date("w") > 1)
{
$time = strtotime("last Monday");
}
else
{
$time = strtotime("Monday");
}
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$time' AND siteID='$this->siteID'");
}
if (strtolower($when) == "tuesday")
{
if (date("w") > 2)
{
$time = strtotime("last Tuesday");
}
else
{
$time = strtotime("Tuesday");
}
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$time' AND siteID='$this->siteID'");
}
if (strtolower($when) == "wednesday")
{
if (date("w") > 3)
{
$time = strtotime("last Wednesday");
}
else
{
$time = strtotime("Wednesday");
}
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$time' AND siteID='$this->siteID'");
}
if (strtolower($when) == "thursday")
{
if (date("w") > 4)
{
$time = strtotime("last Thursday");
}
else
{
$time = strtotime("Thursday");
}
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$time' AND siteID='$this->siteID'");
}
if (strtolower($when) == "friday")
{
if (date("w") > 5)
{
$time = strtotime("last Friday");
}
else
{
$time = strtotime("Friday");
}
$selectCounter = $this->db->query("SELECT * FROM counter WHERE day='$time' AND siteID='$this->siteID'");
}
if (strtolower($when) == "this_week")
{
$today = strtotime("today");
$time = strtotime("last Monday");
$selectCounter = $this->db->query("SELECT *,SUM(hits) AS hits FROM counter WHERE day>='$time' AND day<='$today' AND siteID='$this->siteID'");
}
if (strtolower($when) == "this_month")
{
$today = strtotime("today");
$time = strtotime(date("Y-m-01"));
$selectCounter = $this->db->query("SELECT *,SUM(hits) AS hits FROM counter WHERE day>='$time' AND day<='$today' AND siteID='$this->siteID'");
}
if (strtolower($when) == "this_year")
{
$today = strtotime("today");
$time = strtotime(date("Y-01-01"));
$selectCounter = $this->db->query("SELECT *,SUM(hits) AS hits FROM counter WHERE day>='$time' AND day<='$today' AND siteID='$this->siteID'");
}
if (strtolower($when) == "total")
{
$selectCounter = $this->db->query("SELECT *,SUM(hits) AS hits FROM counter WHERE siteID='$this->siteID'");
}
$rowCounter = $selectCounter->fetch();
return intval($rowCounter['hits']);
}
//Head Function
public function head()
{
}
//Footer Function
public function footer()
{
echo '';
}
//--------------------- Cart Functions ---------------------
public function AddToBasket($id, $qty=1, $description='', $options=array())
{
if (!empty($_SESSION['cart'][$id]['quantity'])) {
$_SESSION['cart'][$id]['quantity'] = $_SESSION['cart'][$id]['quantity'] + $qty;
} else {
$_SESSION['cart'][$id]['quantity'] = $qty;
}
if (!empty($description))
{
$_SESSION['cart'][$id]['description'] = $description;
}
if (!empty($options))
{
$_SESSION['cart'][$id]['options'] = $options;
}
$this->SetCookie();
return true;
}
public function RemoveFromBasket($id, $qty = 1)
{
if (!empty($_SESSION['cart'][$id]['quantity']))
{
$_SESSION['cart'][$id]['quantity'] = $_SESSION['cart'][$id]['quantity'] - $qty;
}
if ($_SESSION['cart'][$id]['quantity'] <= 0)
{
$this->DeleteFromBasket($id);
}
$this->SetCookie();
return true;
exit();
}
public function DeleteFromBasket($id)
{
unset($_SESSION['cart'][$id]);
$this->SetCookie();
return true;
exit();
}
public function GetBasket()
{
if (is_array($_SESSION['cart']))
{
foreach ($_SESSION['cart'] as $k => $v)
{
$itemArray[$k] = $v;
}
return $itemArray;
exit();
}
else
{
$_SESSION['cart'] = array();
return false;
}
}
public function UpdateBasket($id, $qty)
{
$qty = ($qty == '') ? 0 : $qty;
if (!empty($_SESSION['cart'][$id]['quantity']))
{
$_SESSION['cart'][$id]['quantity'] = $qty;
if ($_SESSION['cart'][$id]['quantity'] <= 0)
{
$this->DeleteItem($id);
return true;
exit();
}
$this->SetCookie();
return true;
exit();
}
else
{
return false;
}
}
public function GetBasketQty() {
if (is_array($_SESSION['cart']))
{
$qty = 0;
foreach ($_SESSION['cart'] as $item)
{
$qty = $qty + $item['quantity'];
}
return $qty;
}
else
{
return 0;
}
}
public function EmptyBasket()
{
if (isset($_SESSION['cart']))
{
unset($_SESSION['cart']);
}
$_SESSION['cart'] = array();
$this->SetCookie();
return true;
}
public function SetCookie()
{
if ($this->saveCookie)
{
$string = base64_encode(serialize($_SESSION['cart']));
if (version_compare(PHP_VERSION, '7.3', '<'))
{
@setcookie($this->cookieName, $string, time() + $this->cookieExpire, '/; SameSite=none');
}
else
{
@setcookie($this->cookieName, $string, array(
'expires' => $this->now + $this->cookieExpire,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true,
'httponly' => false,
'samesite' => 'none'
)
);
}
return true;
}
return false;
}
public function SaveCookie($bool = TRUE)
{
$this->saveCookie = $bool;
return true;
}
//--------------------- Cart Functions ---------------------
//Is_Basket Function
public function is_basket()
{
if (strtolower($_REQUEST['action']) == "basket")
{
return true;
}
}
//Basket Function
public function basket()
{
if (!empty($_SESSION['marketerID']))
{
$marketer = $this->getUserByID($_SESSION['marketerID']);
}
$this->basket = array();
$GetBasket = $this->GetBasket();
if (!empty($GetBasket))
{
foreach ($GetBasket AS $key=>$item)
{
// Basket key sample -----> productID|variationID|optionsMD5
$explodedKey = @explode("|", $key);
$productID = $explodedKey[0];
$variationID = $explodedKey[1];
$optionsMD5 = $explodedKey[2];
$options = $item['options'];
$optionsMD5 = !empty($options) ? md5(json_encode($options)) : '';
$quantity = $item['quantity'];
$description = $item['description'];
$selectProduct = $this->db->query("SELECT * FROM products WHERE id='$productID' AND siteID='$this->siteID'");
$rowProduct = $selectProduct->fetch();
$selectVariation = $this->db->query("SELECT * FROM product_variations WHERE id='$variationID' AND productID='$productID' AND status=1 AND siteID='$this->siteID'");
$rowVariation = $selectVariation->fetch();
$totalOptionsPrice = 0;
if (!empty($options))
{
$newOptions = array();
$optionIDs = array_keys($options);
$implodedOptionIDs = implode(",", $optionIDs);
$selectOptions = $this->db->query("SELECT options.*, option_groups.title AS groupTitle FROM options LEFT JOIN option_groups ON options.groupID = option_groups.id WHERE options.id IN ($implodedOptionIDs) AND options.active=1 AND options.siteID='$this->siteID'");
while ($rowOption = $selectOptions->fetch())
{
$totalOptionsPrice += $rowOption['price'];
$newOptions[$rowOption['id']]['id'] = $rowOption['id'];
$newOptions[$rowOption['id']]['type'] = $rowOption['type'];
$newOptions[$rowOption['id']]['groupID'] = $rowOption['groupID'];
$newOptions[$rowOption['id']]['groupTitle'] = $rowOption['groupTitle'];
$newOptions[$rowOption['id']]['title'] = $rowOption['title'];
$newOptions[$rowOption['id']]['image'] = $rowOption['image'];
$newOptions[$rowOption['id']]['price'] = $rowOption['price'];
if ($rowOption['type'] == "radio")
{
$newOptions[$rowOption['id']]['value'] = $rowOption['title'];
}
else
{
$newOptions[$rowOption['id']]['value'] = $options[$rowOption['id']];
}
}
$rowProduct['auctionPrice'] += $totalOptionsPrice;
$rowProduct['price'] += $totalOptionsPrice;
$rowProduct['oldPrice'] += $totalOptionsPrice;
}
$title = $rowProduct['title'];
$baseProductTitle = $title;
$metatitle = $rowProduct['metatitle'];
$baseProductMetatitle = $metatitle;
$uid = $rowProduct['uid'];
$stock = $rowProduct['stock'];
$auctionStatus = $rowProduct['auctionStatus'];
$auctionStartDate = $rowProduct['auctionStartDate'];
$auctionExpireDate = $rowProduct['auctionExpireDate'];
if ($rowProduct['auctionStatus'] == 1 && $rowProduct['auctionStartDate'] <= $this->now && $rowProduct['auctionExpireDate'] >= $this->now)
{
$isAuction = true;
$price = $rowProduct['auctionPrice'];
$digitalPrice = $rowProduct['auctionPrice'];
if (!empty($rowProduct['oldPrice']))
{
$oldPrice = $rowProduct['oldPrice'];
}
else
{
$oldPrice = $rowProduct['price'];
}
}
else
{
$isAuction = false;
$price = $rowProduct['price'];
$digitalPrice = $rowProduct['digitalPrice'];
if (!empty($rowProduct['oldPrice']))
{
$oldPrice = $rowProduct['oldPrice'];
}
else
{
$oldPrice = $rowProduct['price'];
}
}
$dollarPrice = $rowProduct['dollarPrice'];
$dollarDigitalPrice = $rowProduct['dollarDigitalPrice'];
$commissionPercent = max(floatval($rowProduct['commissionPercent']) + floatval($marketer['commissionTolerance']), 0);
if (!empty($_SESSION['digitals'][$key]))
{
$totalPrice = $digitalPrice * $quantity;
$totalOldPrice = $oldPrice * $quantity;
$totalDollarPrice = $dollarDigitalPrice * $quantity;
$commission = ($digitalPrice * $commissionPercent) / 100;
}
else
{
$totalPrice = $price * $quantity;
$totalOldPrice = $oldPrice * $quantity;
$totalDollarPrice = $dollarPrice * $quantity;
$commission = ($price * $commissionPercent) / 100;
}
$totalCommission = $commission * $quantity;
$marketplaceCommissionPercent = floatval($rowProduct['marketplaceCommissionPercent']);
$totalDigitalPrice = $digitalPrice * $quantity;
$totalDollarDigitalPrice = $dollarDigitalPrice * $quantity;
$weight = $rowProduct['weight'];
$totalWeight = $rowProduct['weight'] * $quantity;
$fee = $rowProduct['fee'];
$profitPercent = $rowProduct['profitPercent'];
$shippableCities = $rowProduct['shippableCities'];
$productType = $rowProduct['productType'];
$link = $rowProduct['link'];
$images = $rowProduct['image'];
$imagesArray = @explode("|", $images);
$image = $imagesArray[0];
$instock = $rowProduct['instock'];
$minOrder = $rowProduct['minOrder'];
$maxOrder = $rowProduct['maxOrder'];
$permission = $rowProduct['permission'];
$option1 = $rowProduct['option1'];
$option2 = $rowProduct['option2'];
$option3 = $rowProduct['option3'];
$option4 = $rowProduct['option4'];
$option5 = $rowProduct['option5'];
$option6 = $rowProduct['option6'];
$option7 = $rowProduct['option7'];
$option8 = $rowProduct['option8'];
if (!empty($rowProduct['permalink']))
{
$url = "/" . $rowProduct['permalink'];
}
else
{
$url = "/product/" . $rowProduct['id'] . "/" . $this->safeUrl($rowProduct['title']);
}
// Replace variation if exists
if ($selectVariation->rowCount() > 0)
{
$colorCode = $rowVariation['colorCode'];
$colorName = $rowVariation['colorName'];
$size = $rowVariation['size'];
if (!empty($rowVariation['title']))
{
$title = $rowVariation['title'];
}
if (!empty($rowVariation['metatitle']))
{
$metatitle = $rowVariation['metatitle'];
}
$uid = $rowVariation['uid'];
if ($rowProduct['auctionStatus'] == 1 && $rowProduct['auctionStartDate'] <= $this->now && $rowProduct['auctionExpireDate'] >= $this->now)
{
$isAuction = true;
$price = $rowProduct['auctionPrice'] + intval($rowVariation['auctionPrice']);
$digitalPrice = $rowProduct['auctionPrice'] + intval($rowVariation['auctionPrice']);
if (!empty($rowProduct['oldPrice']))
{
$oldPrice = $rowProduct['oldPrice'] + intval($rowVariation['oldPrice']);
}
else
{
$oldPrice = $rowProduct['price'] + intval($rowVariation['price']);
}
$oldPrice = max($oldPrice, $price);
}
else
{
$isAuction = false;
$price = $rowProduct['price'] + intval($rowVariation['price']);
$digitalPrice = $rowProduct['digitalPrice'] + intval($rowVariation['price']);
$oldPrice = $rowProduct['oldPrice'] + intval($rowVariation['oldPrice']);
}
if (!empty($_SESSION['digitals'][$key]))
{
$totalPrice = $digitalPrice * $quantity;
$totalOldPrice = $oldPrice * $quantity;
$commission = ($digitalPrice * $commissionPercent) / 100;
}
else
{
$totalPrice = $price * $quantity;
$totalOldPrice = $oldPrice * $quantity;
$commission = ($price * $commissionPercent) / 100;
}
$totalCommission = $commission * $quantity;
$totalDigitalPrice = $digitalPrice * $quantity;
$weight = $rowProduct['weight'] + intval($rowVariation['weight']);
$totalWeight = $weight * $quantity;
if (!empty($rowVariation['image']))
{
$images = $rowVariation['image'];
$imagesArray = @explode("|", $images);
$image = $imagesArray[0];
}
$instock = $rowVariation['instock'];
}
array_push($this->basket, array('key' => $key, 'id' => $productID, 'userID' => $rowProduct['userID'], 'variationID' => $variationID, 'colorCode' => $colorCode, 'colorName' => $colorName, 'size' => $size, 'options' => $newOptions, 'optionsMD5' => $optionsMD5, 'quantity' => $quantity, 'description' => $description, 'title' => $title, 'baseProductTitle' => $baseProductTitle, 'metatitle' => $metatitle, 'baseProductMetatitle' => $baseProductMetatitle, 'uid' => $uid, 'price' => $price, 'oldPrice' => $oldPrice, 'dollarPrice' => $dollarPrice, 'digitalPrice' => $digitalPrice, 'dollarDigitalPrice' => $dollarDigitalPrice, 'totalPrice' => $totalPrice, 'totalOldPrice' => $totalOldPrice, 'totalDollarPrice' => $totalDollarPrice, 'totalDigitalPrice' => $totalDigitalPrice, 'totalDollarDigitalPrice' => $totalDollarDigitalPrice, 'auctionStatus' => $auctionStatus, 'auctionStartDate' => $auctionStartDate, 'auctionExpireDate' => $auctionExpireDate, 'weight' => $weight, 'totalWeight' => $totalWeight, 'fee' => $fee, 'profitPercent' => $profitPercent, 'commissionPercent' => $commissionPercent, 'marketplaceCommissionPercent' => $marketplaceCommissionPercent, 'commission' => $commission, 'totalCommission' => $totalCommission, 'isAuction' => $isAuction, 'shippableCities' => $shippableCities, 'productType' => $productType, 'link' => $link, 'images' => $images, 'image' => $image, 'stock' => $stock, 'instock' => $instock, 'minOrder' => $minOrder, 'maxOrder' => $maxOrder, 'permission' => $permission, 'url' => $url, 'option1' => $option1, 'option2' => $option2, 'option3' => $option3, 'option4' => $option4, 'option5' => $option5, 'option6' => $option6, 'option7' => $option7, 'option8' => $option8));
}
}
return $this->basket;
}
//Mellat Pay Request
public function mellat_pay_request($amount, $callbackUrl, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
require_once("inc/nusoap.php");
$client = new nusoap_client(MellatWebserviceAddress);
// Check for an error
$err = $client->getError();
if ($err)
{
$this->payError = 'Constructor error ' . $err . ' ';
$this->payErrorType = 'error';
die();
}
$amount = intval($amount);
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
$parameters = array(
'terminalId' => $this->apis['mellatTerminalID'],
'userName' => $this->apis['mellatUsername'],
'userPassword' => $this->apis['mellatPassword'],
'orderId' => $gatewayInfoArray['payID'],
'amount' => $amount,
'localDate' => date("Ymd"),
'localTime' => date("His"),
'additionalData' => '',
'callBackUrl' => $callbackUrl,
'payerId' => 0
);
// Call the SOAP method
$result = $client->call('bpPayRequest', $parameters, MellatNamespace);
// Check for errors
$err = $client->getError();
if ($err)
{
// Display the error
$this->payError = 'Error ' . $err . ' ';
$this->payErrorType = 'error';
die();
}
else
{//OK Result
$res = explode (',',$result);
$ResCode = $res[0];
if ($ResCode == 0)
{//OK Pay Request
echo '
';
$this->payError = 'در حال اتصال به سرور بانک';
$this->payErrorType = 'success';
}
else
{
$this->payError = 'در برقراری ارتباط با سرور بانک مشکلی بوجود آمده است کد خطا : ' . $ResCode;
$this->payErrorType = 'error';
}
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Mellat Reversal Request
public function mellat_reversal_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
require_once("inc/nusoap.php");
$client = new nusoap_client(MellatWebserviceAddress);
// Check for an error
$err = $client->getError();
if ($err)
{
$this->error = $err;
$this->errorType = 'error';
return false;
}
$parameters = array(
'terminalId' => $this->apis['mellatTerminalID'],
'userName' => $this->apis['mellatUsername'],
'userPassword' => $this->apis['mellatPassword'],
'orderId' => $gatewayInfoArray['payID'],
'saleOrderId' => $_REQUEST['SaleOrderId'],
'saleReferenceId' => $_REQUEST['SaleReferenceId']
);
//Reversal
$result = $client->call('bpReversalRequest', $parameters, MellatNamespace);
// Check for a fault
if ($client->fault)
{
$this->error = $result;
$this->errorType = 'error';
return false;
}
else
{
$err = $client->getError();
if ($err)
{
$this->error = $err;
$this->errorType = 'error';
return false;
}
else
{//OK Result
if ($result == 0)
{//OK Reversal
$this->payError = 'متاسفانه پرداخت شما موفقیت آمیز نبود، مبلغ پرداخت شده حداکثر تا 24 ساعت دیگر به حساب شما باز می گردد';
$this->payErrorType = 'error';
$this->payStatus = 0;
return true;
}
}
}
}
//Mellat Settle Request
public function mellat_settle_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
require_once("inc/nusoap.php");
$client = new nusoap_client(MellatWebserviceAddress);
// Check for an error
$err = $client->getError();
if ($err)
{
$this->error = $err;
$this->errorType = 'error';
return false;
}
$parameters = array(
'terminalId' => $this->apis['mellatTerminalID'],
'userName' => $this->apis['mellatUsername'],
'userPassword' => $this->apis['mellatPassword'],
'orderId' => $gatewayInfoArray['payID'],
'saleOrderId' => $_REQUEST['SaleOrderId'],
'saleReferenceId' => $_REQUEST['SaleReferenceId']
);
//SETTLE
$result = $client->call('bpSettleRequest', $parameters, MellatNamespace);
// Check for a fault
if ($client->fault)
{
$this->error = $result;
$this->errorType = 'error';
return false;
}
else
{
$err = $client->getError();
if ($err)
{
$this->error = $err;
$this->errorType = 'error';
return false;
}
else
{//OK Result
if ($result == 0)
{//OK Settle
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
}
}
}
//Mellat Verify Request
public function mellat_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
/*
echo "payID:" . $gatewayInfoArray['payID'] . " ";
echo "SaleOrderId:" . $_REQUEST['SaleOrderId'] . " ";
echo "SaleReferenceId:" . $_REQUEST['SaleReferenceId'] . " ";
print_r($_REQUEST);
*/
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
if (!empty($_REQUEST['SaleOrderId']) && !empty($_REQUEST['SaleReferenceId']))
{
// if (($gatewayInfoArray['amount'] * 10) == $amount) // Check amount
// {
require_once("inc/nusoap.php");
$client = new nusoap_client(MellatWebserviceAddress);
// Check for an error
$err = $client->getError();
if ($err)
{
$this->error = $err;
$this->errorType = 'error';
return false;
}
$parameters = array(
'terminalId' => $this->apis['mellatTerminalID'],
'userName' => $this->apis['mellatUsername'],
'userPassword' => $this->apis['mellatPassword'],
'orderId' => $gatewayInfoArray['payID'],
'saleOrderId' => $_REQUEST['SaleOrderId'],
'saleReferenceId' => $_REQUEST['SaleReferenceId']
);
// Call the SOAP method
$result = $client->call('bpVerifyRequest', $parameters, MellatNamespace);
if ($result == 0)
{//OK Verify
//defining variables
$this->payStatus = 1;
$this->refID = $_REQUEST['SaleReferenceId'];
$this->refID2 = 0;
$this->mellat_settle_request($gatewayInfoArray['payID']);
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
$result = $client->call('bpInquiryRequest', $parameters, MellatNamespace);
// Check for a fault
if ($client->fault)
{
$this->error = $result;
$this->errorType = 'error';
return false;
}
else
{
$err = $client->getError();
if ($err)
{
$this->error = $err;
$this->errorType = 'error';
return false;
}
else
{//OK Result
if ($result == 0)
{//OK Inquiry
//defining variables
$this->payStatus = 1;
$this->refID = $_REQUEST['SaleReferenceId'];
$this->refID2 = 0;
$this->mellat_settle_request($gatewayInfoArray['payID']);
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
}
}
}
// }
// else
// {
// $this->payError = 'مبلغ پرداخت شده با مبلغ سفارش هماهنگی ندارد';
// $this->payErrorType = 'error';
// }
}
else
{
$this->payError = 'پرداخت انجام نشد، اطلاعات سفارش ناقص است';
$this->payErrorType = 'error';
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Parsian Pay Request
public function parsian_pay_request($amount, $callbackUrl, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
include("inc/nusoap.php");
$client = new nusoap_client(ParsianWebserviceAddress,'wsdl');
if (!$err = $client->getError())
{
$soapProxy = $client->getProxy();
}
if ( (!$client) || ($err = $client->getError()) )
{
$error .= $err . " ";
$this->payError = 'مشکل در اتصال به درگاه بانک پارسیان';
$this->payErrorType = 'error';
}
else
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
$params = array(
'LoginAccount' => $this->apis['parsianMerchantID'] ,
'Amount' => intval($amount),
'OrderId' => $gatewayInfoArray['payID'],
'CallBackUrl' => $callbackUrl
);
$sendParams = array("requestData" => $params);
$result = $client->call('SalePaymentRequest', $sendParams);
if ($result['SalePaymentRequestResult']['Token'] && $result['SalePaymentRequestResult']['Status'] == 0)
{
// this is a succcessfull connection
$redirect = 'https://pec.shaparak.ir/NewIPG/?Token=' . $result['SalePaymentRequestResult']['Token'];
$this->payError = 'در حال اتصال به درگاه بانک پارسیان';
$this->payErrorType = 'success';
echo '';
//header("Location: $redirect");
exit();
}
else
{
// this is unsucccessfull connection
if ($err=$client->getError())
{
$this->payError = 'مشکل در اتصال به درگاه بانک پارسیان';
$this->payErrorType = 'error';
}
}
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Parsian Verify Request
public function parsian_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
require_once("inc/nusoap.php");
if ($_REQUEST['RRN'] > 0 && $_REQUEST['status'] == 0)
{
$client = new nusoap_client('https://pec.shaparak.ir/NewIPGServices/Confirm/ConfirmService.asmx?WSDL','wsdl');
if ( (!$client) || ($err = $client->getError()) )
{
// this is unsucccessfull connection
$this->payError = 'مشکل در اتصال به درگاه بانک پارسیان';
$this->payErrorType = 'error';
return false;
}
else
{
$params = array(
'LoginAccount' => $this->apis['parsianMerchantID'],
'Token' => $_REQUEST['Token']
);
$sendParams = array("requestData" => $params);
$result = $client->call('ConfirmPayment', $sendParams);
if ($result['ConfirmPaymentResult']['Status'] != 0)
{
$this->payError = 'پرداخت نا موفق بوده است کد خطا : ' . $result['ConfirmPaymentResult']['Status'] . ' ' . $result['ConfirmPaymentResult']['Message'];
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
else
{
//defining variables
$this->payStatus = 1;
$this->refID = $_REQUEST['RRN'];
$this->refID2 = $_REQUEST['OrderId'];
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
}
}
else
{
$this->payError = 'پرداخت نا موفق بوده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Karafarin Pay Request
public function karafarin_pay_request($amount, $callbackUrl, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
include("inc/nusoap.php");
$client = new nusoap_client("https://ikc.shaparak.ir/XToken/Tokens.xml", true);
$client->soap_defencoding='UTF-8';
if (!$err = $client->getError())
{
$soapProxy = $client->getProxy();
}
if ( (!$client) || ($err = $client->getError()) )
{
$error .= $err . " ";
$this->payError = 'مشکل در اتصال به درگاه بانک کارآفرین';
$this->payErrorType = 'error';
}
else
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
$params = array(
'merchantId' => $this->apis['karafarinMerchantID'],
'amount' => intval($amount),
'invoiceNo' => $gatewayInfoArray['payID'],
'paymentId' => $gatewayInfoArray['payID'],
'revertURL' => $callbackUrl
);
$result = $client->call('MakeToken', array($params));
if (!empty($result['MakeTokenResult']['token']))
{
// this is a succcessfull connection
$this->payError = 'در حال اتصال به درگاه بانک کارآفرین';
$this->payErrorType = 'success';
echo '
';
exit();
}
else
{
$this->error = 'درخواست شما نامعتبر است!';
$this->errorType = 'error';
return false;
}
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Karafarin Verify Request
public function karafarin_verify_request()
{
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
require_once("inc/nusoap.php");
$token = trim($_POST['token']); // همان توکنی که در مرحله رزرو ساخته شد
$resultCode = trim($_POST['resultCode']); // کد برگشت که برای تراکنش موفق عدد 100 میباشد
$paymentId = trim($_POST['paymentId']); // همان شناسه خرید که در مرحله ساخت توکن استفاده کردیم
$referenceId = trim($_POST['referenceId']); // شناسه مرجع که بانک میسازه و قابل پیگیری هست
if ($resultCode == '100')
{
$client = new nusoap_client('https://ikc.shaparak.ir/XVerify/Verify.xml', true);
$client->soap_defencoding='UTF-8';
if ( (!$client) || ($err = $client->getError()) )
{
// this is unsucccessfull connection
$this->payError = 'مشکل در اتصال به درگاه بانک کارآفرین';
$this->payErrorType = 'error';
return false;
}
else
{
$params = array(
'merchantId' => $this->apis['karafarinMerchantID'],
'token' => $token,
'referenceNumber' => $referenceId,
'sha1Key' => $this->apis['karafarinSHA1']
);
$result = $client->call('KicccPaymentsVerification', array($params));
if ($result['KicccPaymentsVerificationResult'] > 0 && $result['KicccPaymentsVerificationResult'] == ($gatewayInfoArray['amount'] * 10))
{
//defining variables
$this->payStatus = 1;
$this->refID = $referenceId;
$this->refID2 = '';
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
$this->payError = 'پرداخت نا موفق بوده است کد خطا : ' . $result['KicccPaymentsVerificationResult'];
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
}
else
{
$this->payError = 'پرداخت نا موفق بوده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Saderat Pay Request
public function saderat_pay_request($amount, $callbackUrl, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
$terminalID = $this->apis['saderatTerminalID'];
$amount = intval($amount);
$callbackURL = $callbackUrl;
if (!empty($terminalID) && !empty($amount) && !empty($callbackURL))
{
$_SESSION[$invoiceID] = $amount;
// get token
$dataArray = array(
"Amount" => $amount,
"callbackURL" => $callbackUrl,
"InvoiceID" => $gatewayInfoArray['payID'],
"TerminalID" => $terminalID
);
$curl= curl_init();
curl_setopt($curl, CURLOPT_URL, "https://mabna.shaparak.ir:8081/V1/PeymentApi/GetToken");
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($dataArray));
$getTokenResult = json_decode(curl_exec($curl), true);
curl_close($curl);
// print_r($getTokenResult);
// exit();
if (!empty($getTokenResult['Accesstoken']) && $getTokenResult['Status'] == 0)
{
echo '
';
}
else
{
$this->error = 'خطا در دریافت توکن';
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = 'درخواست شما نامعتبر است!';
$this->errorType = 'error';
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Saderat Verify Request
public function saderat_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
if ($_POST["respcode"] == 0)
{
if (isset($_POST["digitalreceipt"]) && !empty($_POST["terminalid"]) && !empty($_POST["invoiceid"]) && !empty($_POST["amount"]))
{
$invoiceid = htmlspecialchars(stripslashes(trim($_POST["invoiceid"])));
$terminalid = htmlspecialchars(stripslashes(trim($_POST["terminalid"])));
$digitalreceipt = htmlspecialchars(stripslashes(trim($_POST["digitalreceipt"])));
$rrn = htmlspecialchars(stripslashes(trim($_POST["rrn"])));
$dataQuery = http_build_query(array("digitalreceipt"=>$digitalreceipt, "Tid"=>$terminalid));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://mabna.shaparak.ir:8081/V1/PeymentApi/Advice');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_POSTFIELDS, $dataQuery);
$result = json_decode(curl_exec($curl));
if (curl_errno($curl))
{
echo curl_error($curl);
}
curl_close($curl);
// print_r($_POST);
// print_r($result);
if (strtolower($result->Status) == "ok")
{
// Check Amount
if (($gatewayInfoArray['amount'] * 10) == $result->ReturnId)
{
$this->payStatus = 1;
$this->payError = '';
$this->payErrorType = 'success';
$this->refID = $rrn;
$this->refID2 = $digitalreceipt;
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
$this->payError = 'مبلغ پرداخت شده با مبلغ سفارش برابر نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payStatus = 0;
$this->payErrorType = 'error';
$this->payError = $result->ReturnId . " " . $result->Message;
return false;
}
}
else
{
$this->payError = 'پرداخت انجام نشد، اطلاعات سفارش ناقص است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'تراکنش ناموفق بوده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Melli Pay Request
public function encrypt_pkcs7($str, $key)
{
$key = base64_decode($key);
if (defined('PHP_MAJOR_VERSION') && PHP_MAJOR_VERSION >= 7)
{
$ciphertext = OpenSSL_encrypt($str,"DES-EDE3", $key, OPENSSL_RAW_DATA);
}
else
{
$block = mcrypt_get_block_size("tripledes", "ecb");
$pad = $block - (strlen($str) % $block);
$str .= str_repeat(chr($pad), $pad);
$ciphertext = mcrypt_encrypt("tripledes", $key, $str, "ecb");
}
return base64_encode($ciphertext);
}
public function melli_pay_request($amount, $callbackUrl, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
$data = array(
'TerminalId'=> $this->apis['melliTerminalID'],
'MerchantId'=> $this->apis['melliMerchantID'],
'Amount'=> intval($amount),
'SignData'=> $this->encrypt_pkcs7($this->apis['melliTerminalID'] . ";" . $gatewayInfoArray['payID'] . ";" . intval($amount), $this->apis['melliPassword']),
'ReturnUrl'=> $callbackUrl,
'LocalDateTime'=> date("m/d/Y g:i:s a"),
'OrderId'=> $gatewayInfoArray['payID']
);
$str_data = json_encode($data);
$curl = curl_init('https://sadad.shaparak.ir/vpg/api/v0/Request/PaymentRequest');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $str_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($str_data)));
$result = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($data);
// print_r($result);
if ($result->ResCode == 0)
{
header("Location: https://sadad.shaparak.ir/VPG/Purchase?Token=" . $result->Token);
exit();
}
else
{
$this->error = $result->Description;
$this->errorType = 'error';
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Melli Verify Request
public function melli_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
if ($_POST["ResCode"] == 0)
{
$verifyData = array('Token'=>$_POST["token"], 'SignData'=>$this->encrypt_pkcs7($_POST["token"], $this->apis['melliPassword']));
$str_data = json_encode($verifyData);
$curl = curl_init('https://sadad.shaparak.ir/vpg/api/v0/Advice/Verify');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $str_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($str_data)));
$result = json_decode(curl_exec($curl));
curl_close($curl);
if ($result->ResCode != -1)
{
$this->payStatus = 1;
$this->payError = 'پرداخت با موفقیت انجام شد.';
$this->payErrorType = 'success';
$this->refID = $result->RetrivalRefNo;
$this->refID2 = $result->SystemTraceNo;
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
$this->payStatus = 0;
$this->payErrorType = 'error';
$this->payError = "تراکنش نا موفق بود در صورت کسر مبلغ از حساب شما حداکثر پس از 72 ساعت مبلغ به حسابتان برمی گردد";
return false;
}
}
else
{
$this->payError = 'تراکنش ناموفق بوده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Pasargad Pay Request
public function pasargad_pay_request($amount, $callbackUrl, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
require_once("inc/RSAProcessor.class.php");
$merchantCode = $this->apis['pasargadMerchantID'];
$terminalCode = $this->apis['pasargadTerminalID'];
$invoiceNumber = $gatewayInfoArray['payID'];
$amount = intval($amount);
$invoiceDate = date("Y/m/d H:i:s", $this->now);
$timestamp = date("Y/m/d H:i:s", $this->now);
$action = 1003;
$processor = new RSAProcessor($this->apis['pasargadCertificate']);
$sign = base64_encode(
$processor->sign(
sha1("#".$merchantCode."#".$terminalCode."#".$invoiceNumber."#".$invoiceDate."#".$amount."#".$callbackUrl."#".$action."#".$timestamp."#", true)
)
);
echo "
";
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Pasargad Verify Request
public function pasargad_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
require_once("inc/RSAProcessor.class.php");
$fields = array( // این اطلاعات را از دیتابیس بخوانید یا اینجا بسازید
'MerchantCode' => $this->apis['pasargadMerchantID'],
'TerminalCode' => $this->apis['pasargadTerminalID'],
'InvoiceNumber' => $gatewayInfoArray['payID'],
'InvoiceDate' => date("Y/m/d H:i:s", $gatewayInfoArray['date']),
'Amount' => ($gatewayInfoArray['amount'] * 10),
'TimeStamp' => date("Y/m/d H:i:s"),
'Sign' => ''
);
$processor = new RSAProcessor($this->apis['pasargadCertificate']);
$fields['Sign'] = base64_encode(
$processor->sign(
sha1("#".$fields['MerchantCode']."#".$fields['TerminalCode']."#".$fields['InvoiceNumber']."#".$fields['InvoiceDate']."#".$fields['Amount']."#".$fields['TimeStamp']."#", true)
)
);
$curl = curl_init('https://pep.shaparak.ir/VerifyPayment.aspx');
curl_setopt($curl, CURLOPT_POST, count($fields));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = xml2array(curl_exec($curl));
curl_close($curl);
// print_r($result);
// echo $result['result'] . " ";
// echo $result['resultMessage'];
if (strtolower($result['result']) === "true")
{
$this->payStatus = 1;
$this->payError = 'پرداخت با موفقیت انجام شد.';
$this->payErrorType = 'success';
$this->refID = $_GET['tref'];
$this->refID2 = $_GET['iN'];
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
$this->payStatus = 0;
$this->payErrorType = 'error';
$this->payError = "تراکنش نا موفق بود در صورت کسر مبلغ از حساب شما حداکثر پس از 72 ساعت مبلغ به حسابتان برمی گردد " . $result['resultMessage'];
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Zarinpal Pay Request
public function zarinpal_pay_request($amount, $callbackUrl, $gatewayInfoArray='', $description, $email='', $mobile='')
{
if (!empty($gatewayInfoArray['payID']))
{
$amount = $amount / 10; //amount is toman
include("inc/nusoap.php");
$client = new nusoap_client(ZarinpalWebserviceAddress,'wsdl');
if (!$err = $client->getError())
{
$soapProxy = $client->getProxy();
}
if ( (!$client) || ($err = $client->getError()) )
{
$error .= $err . " ";
print_r($error);
$this->payError = 'مشکل در اتصال به درگاه زرین پال';
$this->payErrorType = 'error';
}
else
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
$params = array(
'MerchantID' => $this->apis['zarinpalAPIKey'] ,
'Amount' => intval($amount),
'Description' => $description,
'Email' => $email,
'Mobile' => $mobile,
'CallbackURL' => $callbackUrl
);
$sendParams = array($params);
$res = $client->call('PaymentRequest', $sendParams);
if ($res['Status'] == 100)
{
// this is a succcessfull connection
if (ZarinGate == true)
{
$redirect = 'https://www.zarinpal.com/pg/StartPay/'.$res['Authority'].'/ZarinGate';
}
else
{
$redirect = 'https://www.zarinpal.com/pg/StartPay/'.$res['Authority'];
}
$this->payError = 'در حال اتصال به درگاه زرین پال';
$this->payErrorType = 'success';
echo '';
//header("Location: $redirect");
exit();
}
else
{
// this is unsucccessfull connection
print_r($err);
$this->payError = 'مشکل در اتصال به درگاه زرین پال کد خطا : ' . $res['Status'];
$this->payErrorType = 'error';
}
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Zarinpal Verify Request
public function zarinpal_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
if ($_REQUEST['Status'] == 'OK')
{
require_once("inc/nusoap.php");
$authority = $_REQUEST['Authority'];
$soapclient = new nusoap_client(ZarinpalWebserviceAddress,'wsdl');
if ( (!$soapclient) || ($err = $soapclient->getError()) )
{
// this is unsucccessfull connection
$this->payError = 'مشکل در اتصال به درگاه زرین پال';
$this->payErrorType = 'error';
return false;
}
else
{
$params = array(
'MerchantID' => $this->apis['zarinpalAPIKey'], // this is our PIN NUMBER
'Authority' => $authority,
'Amount' => $gatewayInfoArray['amount']
);
$sendParams = array($params);
$res = $soapclient->call('PaymentVerification', $sendParams);
if ($res['Status'] == 100)
{
//defining variables
$this->payStatus = 1;
$this->refID = $res['RefID'];
$this->refID2 = '';
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
$this->payError = 'پرداخت نا موفق بوده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
}
else
{
$this->payError = 'پرداخت انجام نشد، اطلاعات سفارش ناقص است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Zibal Pay Request
public function zibal_pay_request($amount, $callbackUrl, $gatewayInfoArray='', $mobile='')
{
if (!empty($gatewayInfoArray['payID']))
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
$parameters = array(
"merchant"=> $this->apis['zibalMerchantID'],
"callbackUrl"=> $callbackUrl,
"amount"=> $amount,
"orderId"=> $gatewayInfoArray['payID'], //optional
"mobile"=> $mobile //optional
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://gateway.zibal.ir/v1/request");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
curl_close($ch);
if ($response->result == 100)
{
header('Location: https://gateway.zibal.ir/start/'.$response->trackId);
exit();
}
else
{
$this->payError = "(" . $response->result . ") " . $response->message;
$this->payErrorType = 'error';
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Zibal Verify Request
public function zibal_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
$parameters = array(
"merchant"=> $this->apis['zibalMerchantID'],
"trackId"=> $_GET['trackId']
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://gateway.zibal.ir/v1/verify");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
curl_close($ch);
//defining variables
if ($response->result == 100)
{
$this->payStatus = 1;
$this->refID = $_GET['trackId'];
$this->refID2 = 0;
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
$this->payStatus = 0;
$this->payError = "(" . $response->result . ") " . $response->message;
$this->payErrorType = 'error';
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Payline Pay Request
public function payline_pay_request($amount, $callbackUrl, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,PaylineWebserviceAddress);
curl_setopt($ch, CURLOPT_POSTFIELDS,"api=" . $this->apis['paylineAPIKey'] . "&amount=$amount&redirect=" . urlencode($callbackUrl));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
if ($result->status)
{
$go = "https://pay.ir/payment/gateway/" . $result->transId;
header("Location: $go");
exit();
}
else
{
$this->payError = $result->errorMessage;
$this->payErrorType = 'error';
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Payline Verify Request
public function payline_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://pay.ir/payment/verify');
curl_setopt($ch, CURLOPT_POSTFIELDS,"api=" . $this->apis['paylineAPIKey'] . "&transId=" . $_POST['transId']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
//defining variables
if ($result->status == 1)
{
$this->payStatus = 1;
$this->refID = $_POST['transId'];
$this->refID2 = 0;
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
$this->payStatus = 0;
$this->payError = "پرداخت انجام نشد. کد خطا : " . $result->status;
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
// Snapppay Check Eligibility
public function snapppay_check_eligibility($amount)
{
// Get access token
$data = array(
'grant_type'=> "password",
'scope'=> "online-merchant",
'username'=> $this->apis['snapppayUsername'],
'password'=> $this->apis['snapppayPassword']
);
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/v1/oauth/token');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Authorization: Basic ' . base64_encode($this->apis['snapppayClientID'] . ":" . $this->apis['snapppayClientSecret'])));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$tokenResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($tokenResult);
if (!empty($tokenResult->access_token))
{
// Check eligibility
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/offer/v1/eligible?amount='.$amount);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Authorization: Bearer ' . $tokenResult->access_token));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$eligibilityResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($eligibilityResult);
if ($eligibilityResult->response->eligible === true)
{
return array(
"eligible" => true,
"title_message" => $eligibilityResult->response->title_message,
"description" => $eligibilityResult->response->description,
);
}
else
{
$this->error = "امکان خرید اقساطی برای این سفارش وجود ندارد";
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = "توکن دسترسی ساخته نشد";
$this->errorType = 'error';
return false;
}
}
// Snapppay Pay Request
public function snapppay_pay_request($amount, $callbackUrl, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
// Get access token
$data = array(
'grant_type'=> "password",
'scope'=> "online-merchant",
'username'=> $this->apis['snapppayUsername'],
'password'=> $this->apis['snapppayPassword']
);
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/v1/oauth/token');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Authorization: Basic ' . base64_encode($this->apis['snapppayClientID'] . ":" . $this->apis['snapppayClientSecret'])));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$tokenResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($tokenResult);
if (!empty($tokenResult->access_token))
{
// Check eligibility
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/offer/v1/eligible?amount='.$amount);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Authorization: Bearer ' . $tokenResult->access_token));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$eligibilityResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($eligibilityResult);
if ($eligibilityResult->response->eligible === true)
{
// Pay request
$data = array(
"amount" => $amount,
"discountAmount" => intval($gatewayInfoArray['discount']),
"mobile" => $gatewayInfoArray['mobile'],
"paymentMethodTypeDto" => "INSTALLMENT",
"returnURL" => $callbackUrl,
"transactionId" => $gatewayInfoArray['payID'],
"cartList" => $gatewayInfoArray['cart']
);
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/payment/v1/token');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $tokenResult->access_token));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$payRequestResult = json_decode(curl_exec($curl));
curl_close($curl);
// var_dump($payRequestResult);
// exit();
if ($payRequestResult->successful === true)
{
$gatewayInfoArray['paymentToken'] = $payRequestResult->response->paymentToken;
if ($this->updateGatewayInfo($queryStringArray['info_key'], $gatewayInfoArray) == true)
{
header("Location: " . $payRequestResult->response->paymentPageUrl);
exit();
}
else
{
$this->error = "خطا در ذخیره سازی توکن پرداخت در بانک اطلاعاتی";
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = "خطا در دریافت لینک پرداخت " . $payRequestResult->errorData->message;
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = "امکان خرید اقساطی برای این سفارش وجود ندارد";
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = "توکن دسترسی ساخته نشد";
$this->errorType = 'error';
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
// Snapppay Revert Request
public function snapppay_revert_request($access_token, $paymentToken)
{
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/payment/v1/revert');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array("paymentToken" => $paymentToken)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$revertResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($revertResult);
if ($revertResult->successful === true)
{
return true;
}
else
{
return false;
}
}
// Snapppay Settle Request
public function snapppay_settle_request($access_token, $paymentToken)
{
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/payment/v1/settle');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array("paymentToken" => $paymentToken)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$settleResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($settleResult);
if ($settleResult->successful === true)
{
return true;
}
else
{
return false;
}
}
// Snapppay Cancel Request
public function snapppay_cancel_request($access_token, $paymentToken)
{
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/payment/v1/cancel');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array("paymentToken" => $paymentToken)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$cancelResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($cancelResult);
if ($cancelResult->successful === true)
{
return true;
}
else
{
return false;
}
}
// Snapppay Verify Request
public function snapppay_verify_request()
{
if (!empty($_GET['info_key']))
{
$gatewayInfoArray = $this->getGatewayInfo($_GET['info_key']);
}
if (empty($gatewayInfoArray['done']))
{
if (!empty($gatewayInfoArray['payID']))
{
if ($_POST['state'] == "OK")
{
// Get access token
$data = array(
'grant_type'=> "password",
'scope'=> "online-merchant",
'username'=> $this->apis['snapppayUsername'],
'password'=> $this->apis['snapppayPassword']
);
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/v1/oauth/token');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Authorization: Basic ' . base64_encode($this->apis['snapppayClientID'] . ":" . $this->apis['snapppayClientSecret'])));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$tokenResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($tokenResult);
if (!empty($tokenResult->access_token))
{
$curl = curl_init($this->apis['snapppayAPIAddress'] . '/api/online/payment/v1/verify');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $tokenResult->access_token));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array("paymentToken" => $gatewayInfoArray['paymentToken'])));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$verifyResult = json_decode(curl_exec($curl));
curl_close($curl);
// print_r($verifyResult);
if ($verifyResult->successful === true)
{
// Settle
if ($this->snapppay_settle_request($tokenResult->access_token, $gatewayInfoArray['paymentToken']) === true)
{
$this->payStatus = 1;
$this->payError = 'پرداخت با موفقیت انجام شد.';
$this->payErrorType = 'success';
$this->refID = $_POST['transactionId'];
$this->refID2 = $gatewayInfoArray['payID'];
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else // Revert
{
$this->snapppay_revert_request($tokenResult->access_token, $gatewayInfoArray['paymentToken']);
// $this->snapppay_cancel_request($tokenResult->access_token, $gatewayInfoArray['paymentToken']);
$this->payStatus = 0;
$this->payErrorType = 'error';
$this->payError = "تراکنش نا موفق بود در صورت کسر مبلغ از حساب شما حداکثر پس از 72 ساعت مبلغ به حسابتان برمی گردد";
return false;
}
}
else
{
$this->payStatus = 0;
$this->payErrorType = 'error';
$this->payError = "تراکنش نا موفق بود در صورت کسر مبلغ از حساب شما حداکثر پس از 72 ساعت مبلغ به حسابتان برمی گردد";
return false;
}
}
else
{
$this->error = "توکن دسترسی ساخته نشد";
$this->errorType = 'error';
return false;
}
}
else
{
$this->payError = 'پرداخت ناموفق بوده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نیست';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
else
{
$this->payError = 'این فاکتور قبلاً بررسی شده است';
$this->payErrorType = 'error';
$this->payStatus = 0;
return false;
}
}
//Paypal Pay Request
public function paypal_pay_request($query, $isTest=false, $gatewayInfoArray='')
{
if (!empty($gatewayInfoArray['payID']))
{
// Generate new token for auto login and update callbackUrl
$queryString = parse_url($callbackUrl, PHP_URL_QUERY);
$queryStringArray = array();
if (!empty($queryString))
{
parse_str($queryString, $queryStringArray);
}
$queryStringArray['login_token'] = $this->updateUserToken();
// Insert gateway info
if (!empty($gatewayInfoArray))
{
$queryStringArray['info_key'] = $this->insertGatewayInfo($gatewayInfoArray);
}
$callbackUrl = strtok($callbackUrl, '?') . "?" . http_build_query($queryStringArray);
// End of generating new token
if (is_array($query))
{
// Prepare query string
$query_string = http_build_query($query);
if ($isTest == true)
{
header('Location: ' . PaypalWebserviceTestAddress . '?' . $query_string);
}
else
{
header('Location: ' . PaypalWebserviceAddress . '?' . $query_string);
}
exit();
}
else
{
$this->payError = 'متغیرهای ارسالی باید آرایه باشد.';
$this->payErrorType = 'error';
}
}
else
{
$this->payError = 'شناسه پرداخت مشخص نشده است';
$this->payErrorType = 'error';
}
}
//Paypal Verify Request
public function paypal_verify_request($verifyArray, $identityToken, $isTest=false)
{
if ($isTest == true)
{
$paypalWebserviceAddress = PaypalWebserviceTestAddress;
}
else
{
$paypalWebserviceAddress = PaypalWebserviceAddress;
}
if (isset($_GET['tx']))
{
$tx = $_GET['tx'];
if ($_GET['st'] == "Completed")
{
if ($_GET['cc'] == $verifyArray['currency'])
{
if (floatval($_GET['amt']) == floatval($verifyArray['amount']))
{
// Init cURL
$request = curl_init();
// Set request options
curl_setopt_array($request, array
(
CURLOPT_URL => $paypalWebserviceAddress,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => http_build_query(
array(
'cmd' => '_notify-synch',
'tx' => $tx,
'at' => $identityToken,
)
),
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HEADER => FALSE,
// CURLOPT_SSL_VERIFYPEER => TRUE,
// CURLOPT_CAINFO => 'cacert.pem',
));
// Execute request and get response and status code
$response = curl_exec($request);
$status = curl_getinfo($request, CURLINFO_HTTP_CODE);
// Close connection
curl_close($request);
if ($status == 200 AND strpos($response, 'SUCCESS') === 0)
{
// Remove SUCCESS part (7 characters long)
$response = substr($response, 7);
// URL decode
$response = urldecode($response);
// Turn into associative array
preg_match_all('/^([^=\s]++)=(.*+)/m', $response, $m, PREG_PATTERN_ORDER);
$response = array_combine($m[1], $m[2]);
// Fix character encoding if different from UTF-8 (in my case)
if (isset($response['charset']) AND strtoupper($response['charset']) !== 'UTF-8')
{
foreach($response as $key => &$value)
{
$value = mb_convert_encoding($value, 'UTF-8', $response['charset']);
}
$response['charset_original'] = $response['charset'];
$response['charset'] = 'UTF-8';
}
// Sort on keys for readability (handy when debugging)
ksort($response);
// print_r($response);
$this->payStatus = 1;
$this->refID = $tx;
$this->refID2 = 0;
$this->payError = 'پرداخت با موفقیت انجام شد.';
$this->payErrorType = 'success';
$this->setGatewayInfoToDone($_GET['info_key']);
return true;
}
else
{
// Log the error, ignore it, whatever
$this->payError = 'پرداخت انجام نشد';
$this->payErrorType = 'error';
return false;
}
}
else
{
$this->payError = 'پرداخت انجام نشد مبلغ پرداخت با مبلغ سفارش برابر نیست';
$this->payErrorType = 'error';
return false;
}
}
else
{
$this->payError = 'پرداخت انجام نشد واحد پول معتبر نمی باشد';
$this->payErrorType = 'error';
return false;
}
}
else
{
$this->payError = 'پرداخت انجام نشد';
$this->payErrorType = 'error';
return false;
}
}
}
//Pagination Function
public function pagination($array, $selectedPage=1, $showPerPage=10, $pageNumberRange=1, $removeKeys=null)
{
$this->pagination = '';
$this->newPagination = '';
$selectedPage = $selectedPage < 1 ? 1 : $selectedPage;
$start = ($selectedPage - 1) * $showPerPage;
$end = $selectedPage * $showPerPage;
$found = @count($array);
$maxPage = ceil($found / intval($showPerPage));
for ($i = $start; $i < $end; $i++)
{
if (!empty($array[$i]))
{
$result[] = $array[$i];
}
}
//Find URL
if ($this->is_search())
{
$url = "/search/" . $_REQUEST['keyword'] . "/";
}
elseif ($this->is_search_tag())
{
$url = "/tag/" . $_REQUEST['tag'] . "/";
}
else
{
$url = strtok($_SERVER["REQUEST_URI"], '?');
}
// Echo Pages
if ($maxPage > 1)
{
$queryString = $_GET;
if (!empty($removeKeys))
{
foreach ($removeKeys as $removeKey)
{
unset($queryString[$removeKey]);
}
}
else
{
unset($queryString['page']);
unset($queryString['q']);
unset($queryString['tag']);
unset($queryString['keyword']);
unset($queryString['action']);
}
$pagination = '';
$newPagination = '';
$this->pagination = $pagination;
$this->newPagination = $newPagination;
}
return $result;
}
//OrderBy Function
public function orderBy($order="sort ASC")
{
if (empty($order))
{
$order = "ORDER BY sort ASC";
}
else
{
$order = "ORDER BY " . $order;
}
return $order;
}
//Get_Menus Function
public function get_menus($parentID=0, $showSubMenus=true, $class="")
{
if ($parentID != 0)
{
$selectMenus = $this->db->prepare("SELECT * FROM menus WHERE parentID=:parentID AND siteID='$this->siteID' ORDER BY sort ASC");
$selectMenus->execute(array(":parentID" => $parentID));
if ($selectMenus->rowCount() != 0)
{
if ($class != "")
{
$menus .= "\n" . '' . "\n";
$class = "";
}
else
{
$menus .= "\n" . '' . "\n";
}
}
}
else
{
$selectMenus = $this->db->query("SELECT * FROM menus WHERE parentID='0' AND siteID='$this->siteID' ORDER BY sort ASC");
if ($class != "")
{
$menus .= '' . "\n";
$class = "";
}
else
{
$menus .= '' . "\n";
}
}
if ($selectMenus->rowCount() != 0)
{
while ($rowMenus = $selectMenus->fetch())
{
$id = $rowMenus['id'];
$title = $rowMenus['title'];
$image = $rowMenus['image'];
$target = $rowMenus['target'];
$url = $rowMenus['url'];
$menus .= '' . $title . ' ';
if ($showSubMenus == true)
{
$menus .= $this->get_menus($id);
}
$menus .= ' ' . "\n";
}
$menus .= ' ' . "\n";
}
return $menus;
}
//Is_Get_Categories Function
public function is_get_categories()
{
if (strtolower($_REQUEST['action']) == "categories" && empty($_GET['id']))
{
return true;
}
}
//Get_Categories_By_Type Function
public function get_categories_by_type($section=0, $orderBy='sort ASC', $limit=0)
{
$categories = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectCategories = $this->db->prepare("SELECT * FROM categories WHERE section=:section AND siteID='$this->siteID' $orderBy $limitQuery");
$selectCategories->execute(array(":section" => $section));
while ($rowCategories = $selectCategories->fetch())
{
$id = $rowCategories['id'];
$title = $rowCategories['title'];
$parentID = $rowCategories['parentID'];
$parentName = $rowCategories['parentName'];
$section = $rowCategories['section'];
$image = $rowCategories['image'];
if (!empty($rowCategories['permalink']))
{
$url = "/" . $rowCategories['permalink'];
}
else
{
$url = "/category/" . $rowCategories['id'] . "/" . $this->safeUrl($rowCategories['title']);
}
array_push($categories, array('id' => $id, 'title' => $title, 'parentID' => $parentID, 'parentName' => $parentName, 'section' => $section, 'image' => $image, 'url' => $url));
}
return $categories;
}
//Get_Categories Function
public function get_categories($parentID=0, $showSubCategories=true, $echo=true)
{
if ($parentID != 0)
{
$selectCategories = $this->db->prepare("SELECT * FROM categories WHERE parentID=:parentID AND siteID='$this->siteID' ORDER BY sort ASC");
$selectCategories->execute(array(":parentID" => $parentID));
if ($selectCategories->rowCount() != 0)
{
$categories .= "\n" . '' . "\n";
}
}
else
{
$selectCategories = $this->db->query("SELECT * FROM categories WHERE parentID='0' AND siteID='$this->siteID' ORDER BY sort ASC");
$categories .= '' . "\n";
}
if ($selectCategories->rowCount() != 0)
{
while ($rowCategories = $selectCategories->fetch())
{
if (!empty($rowCategories['permalink']))
{
$rowCategories['url'] = "/" . $rowCategories['permalink'];
}
else
{
$rowCategories['url'] = "/category/" . $rowCategories['id'] . "/" . $this->safeUrl($rowCategories['title']);
}
$categories .= '' . $rowCategories['title'] . ' ';
if ($showSubCategories == true)
{
$rowCategories['sub'] = $this->get_categories($rowCategories['id'], $showSubCategories, false);
$categories .= $this->get_categories($rowCategories['id'], $showSubCategories, $echo);
}
$categories .= ' ' . "\n";
$categoriesArray[] = $rowCategories;
}
$categories .= ' ' . "\n";
}
if ($echo == true)
{
return $categories;
}
else
{
return $categoriesArray;
}
}
//Get_Sub_Categories Function
public function get_sub_categories($parentID=0)
{
$this->subCategories[] = $parentID;
$selectCategories = $this->db->prepare("SELECT * FROM categories WHERE parentID=:parentID AND siteID='$this->siteID' ORDER BY sort ASC");
$selectCategories->execute(array(":parentID" => $parentID));
if ($selectCategories->rowCount() != 0)
{
while ($rowCategories = $selectCategories->fetch())
{
$this->get_sub_categories($rowCategories['id']);
}
}
return $this->subCategories;
}
//Is_Category Function
public function is_category()
{
if (strtolower($_REQUEST['action']) == "category" && !empty($_GET['id']))
{
return true;
}
}
//Category Function
public function category()
{
if (strtolower($_REQUEST['action']) == "category" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->category = array();
$selectCategory = $this->db->prepare("SELECT * FROM categories WHERE id=:id AND siteID='$this->siteID'");
$selectCategory->execute(array(':id' => $id));
$rowCategory = $selectCategory->fetch();
$rowCategory['images'] = @explode("|", $rowCategory['image']);
$rowCategory['image'] = $rowCategory['images'][0];
if (!empty($rowCategory['permalink']))
{
$rowCategory['url'] = "/" . $rowCategory['permalink'];
}
else
{
$rowCategory['url'] = "/category/" . $rowCategory['id'] . "/" . $this->safeUrl($rowCategory['title']);
}
$rowCategory['extraOptions'] = $this->getExtraOptions("categories", $rowCategory['id']);
}
return $rowCategory;
}
//Is_Brand Function
public function is_brand()
{
if (strtolower($_REQUEST['action']) == "brand" && !empty($_GET['id']))
{
return true;
}
}
//Brand Function
public function brand()
{
if (strtolower($_REQUEST['action']) == "brand" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->brand = array();
$selectBrand = $this->db->prepare("SELECT * FROM brands WHERE id=:id AND siteID='$this->siteID'");
$selectBrand->execute(array(':id' => $id));
$rowBrand = $selectBrand->fetch();
$rowBrand['images'] = @explode("|", $rowBrand['image']);
$rowBrand['image'] = $rowBrand['images'][0];
if (!empty($rowBrand['permalink']))
{
$rowBrand['url'] = "/" . $rowBrand['permalink'];
}
else
{
$rowBrand['url'] = "/brand/" . $rowBrand['id'] . "/" . $this->safeUrl($rowBrand['title']);
}
$rowBrand['extraOptions'] = $this->getExtraOptions("brands", $rowBrand['id']);
}
return $rowBrand;
}
//Is_Get_Links Function
public function is_get_links()
{
if (strtolower($_REQUEST['action']) == "links")
{
return true;
}
}
//Get_Links Function
public function get_links($orderBy='sort ASC', $limit=0)
{
$links = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectLinks = $this->db->query("SELECT * FROM links WHERE siteID='$this->siteID' $orderBy $limitQuery");
while ($rowLinks = $selectLinks->fetch())
{
$id = $rowLinks['id'];
$title = $rowLinks['title'];
$description = $rowLinks['description'];
$url = $rowLinks['url'];
array_push($links, array('id' => $id, 'title' => $title, 'description' => $description, 'url' => $url));
}
return $links;
}
//Get_Slider Function
public function get_slider($orderBy='sort ASC', $limit=0)
{
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectSlider = $this->db->query("SELECT * FROM slider WHERE active='1' AND COALESCE(publishDate, 0) <= $this->now AND (expireDate >= $this->now OR COALESCE(expireDate, 0)=0) AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowSlider = $selectSlider->fetch())
{
$sliders[] = $rowSlider;
}
return $sliders;
}
//Get_Banner Function
public function get_banners($section='', $orderBy='sort ASC', $limit=0)
{
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
if (!empty($section))
{
$selectBanners = $this->db->prepare("SELECT * FROM banners WHERE section=:section AND active='1' AND COALESCE(publishDate, 0) <= $this->now AND (expireDate >= $this->now OR COALESCE(expireDate, 0)=0) AND siteID='$this->siteID' $orderBy $limitQuery");
$selectBanners->execute(array(":section"=>$section));
}
else
{
$selectBanners = $this->db->prepare("SELECT * FROM banners WHERE active='1' AND COALESCE(publishDate, 0) <= $this->now AND (expireDate >= $this->now OR COALESCE(expireDate, 0)=0) AND siteID='$this->siteID' $orderBy $limitQuery");
$selectBanners->execute();
}
while ($rowBanner = $selectBanners->fetch())
{
$banners[] = $rowBanner;
}
return $banners;
}
//Is_Login Function
public function is_login()
{
if (strtolower($_REQUEST['action']) == "login")
{
return true;
}
}
//Login
public function login($username, $password, $rememberme="off", $confirmEmailFirst=false, $loginWithEmailAndMobile=false)
{
if ($username != "" && $password != "")
{
if ($loginWithEmailAndMobile == true)
{
$selectUser = $this->db->prepare("SELECT * FROM users WHERE (username=:username OR email=:email OR mobile=:mobile) AND password=:password AND siteID='$this->siteID'");
$selectUser->execute(array(':username'=>$username, ':email'=>$username, ':mobile'=>$username, ':password'=>$this->hashPassword($password)));
}
else
{
$selectUser = $this->db->prepare("SELECT * FROM users WHERE username=:username AND password=:password AND siteID='$this->siteID'");
$selectUser->execute(array(':username'=>$username, ':password'=>$this->hashPassword($password)));
}
$rowUser = $selectUser->fetch();
if ($selectUser->rowCount() != 0)
{
if ($rowUser['status'] == 1)
{
if (($confirmEmailFirst == true && $rowUser['emailConfirmed'] == 1) || $confirmEmailFirst == false)
{
@session_regenerate_id(true);
$_SESSION['login_failed'] = false;
$_SESSION['userID'] = $rowUser['id'];
$this->isLoggedIn = true;
$now = time();
//Check VIP Expire
$this->db->exec("UPDATE users SET VIP=0 WHERE id='$rowUser[id]' AND VIPExpireDate < $now AND siteID='$this->siteID'");
if ($rememberme == "on")
{
$token = md5(uniqid()) . rand(100, 999) . md5(uniqid());
if (version_compare(PHP_VERSION, '7.3', '<'))
{
setcookie("rememberme", 'userID='.$rowUser['id'].'&token='.$token, $this->now + $this->cookie_time, '/; SameSite=Lax');
}
else
{
setcookie("rememberme", 'userID='.$rowUser['id'].'&token='.$token, array(
'expires' => $this->now - 86400,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
)
);
}
$this->db->exec("UPDATE users SET token='$token' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
}
//Last Login Date
$selectLastLogin = $this->db->query("SELECT * FROM users_login WHERE userID='$rowUser[id]' AND siteID='$this->siteID' ORDER BY date DESC LIMIT 1");
$rowLastLogin = $selectLastLogin->fetch();
$this->db->query("UPDATE users SET lastLoginDate='$rowLastLogin[date]' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
$this->db->query("INSERT INTO users_login (siteID, userID, date) VALUES ('$this->siteID', '$rowUser[id]', '$now')");
return true;
}
else
{
$this->error = 'شما هنوز ایمیل خود را تائید نکرده اید';
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = 'حساب کاربری شما غیر فعال شده است';
$this->errorType = 'error';
return false;
}
}
else
{
$_SESSION['login_failed'] = true;
$this->error = 'نام کاربری و یا کلمه عبور صحیح نیست';
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = 'لطفا نام کاربری و کلمه عبور خود را وارد نمائید';
$this->errorType = 'error';
return false;
}
}
//Google OAuth
public function google_oauth($authenticate=false, $rememberme="off", $revoke=false)
{
include_once 'inc/GoogleOAuth2/Google_Client.php';
include_once 'inc/GoogleOAuth2/contrib/Google_Oauth2Service.php';
$clientId = google_oauth_client_id; //Google client ID
$clientSecret = google_oauth_client_secret; //Google client secret
$redirectURL = $this->protocol . '://' . $this->settings['siteAddress'] . '/google-oauth'; //Callback URL
//Call Google API
$gClient = new Google_Client();
$gClient->setApplicationName('Login to ' . $this->settings['siteAddress']);
$gClient->setClientId($clientId);
$gClient->setClientSecret($clientSecret);
$gClient->setRedirectUri($redirectURL);
$gClient->setApprovalPrompt('auto');
$google_oauthV2 = new Google_Oauth2Service($gClient);
if ($revoke == true)
{
$gClient->revokeToken();
}
else
{
if ($authenticate == true)
{
if (isset($_GET['code']))
{
$gClient->authenticate($_GET['code']);
$_SESSION['oauth_token'] = $gClient->getAccessToken();
//header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['oauth_token']))
{
$gClient->setAccessToken($_SESSION['oauth_token']);
}
if ($gClient->getAccessToken())
{
//Get user profile data from google
$gpUserProfile = $google_oauthV2->userinfo->get();
/*print_r($gpUserProfile);
exit;*/
//Insert or update user data to the database
$userData = array(
'oauth_provider'=> 'google',
'oauth_id' => $gpUserProfile['id'],
'firstname' => $gpUserProfile['given_name'],
'lastname' => $gpUserProfile['family_name'],
'email' => $gpUserProfile['email'],
'gender' => $gpUserProfile['gender'],
'locale' => $gpUserProfile['locale'],
'picture' => $gpUserProfile['picture'],
'link' => $gpUserProfile['link']
);
if (!empty($userData))
{
//Register
$selectUser = $this->db->query("SELECT * FROM users WHERE username='$userData[email]' AND siteID='$this->siteID'");
$oauth_user = $selectUser->fetch();
if ($selectUser->rowCount() > 0)
{
// $update = $this->db->query("UPDATE users SET firstname='$userData[firstname]', lastname='$userData[lastname]', email='$userData[email]', gender='$userData[gender]', image='$userData[picture]', site='$userData[link]' WHERE oauth_provider='$userData[oauth_provider]' AND oauth_id='$userData[oauth_id]' AND siteID='$this->siteID'");
$update = $this->db->query("UPDATE users SET emailConfirmed=1 WHERE id='$oauth_user[id]' AND siteID='$this->siteID'");
}
else
{
$password = rand(10000, 99999);
$hashed_password = $this->hashPassword($password);
$insert = $this->db->query("INSERT INTO users SET type=1, oauth_provider='$userData[oauth_provider]', oauth_id='$userData[oauth_id]', username='$userData[email]', password='$hashed_password', firstname='$userData[firstname]', lastname='$userData[lastname]', email='$userData[email]', gender='$userData[gender]', image='$userData[picture]', site='$userData[link]', date='$this->now', status=1, emailConfirmed=1, siteID='$this->siteID'");
//Send Email
$body = '' .
$userData['firstname'] . ' ' . $userData['lastname'] . ' عزیز
سلام
عضویت شما را در سایت ' . $this->settings['siteName'] . ' تبریک می گوییم.
مشخصات کاربری شما به شرح زیر است.
نام کاربری (ایمیل) : ' . $userData['email'] . '
رمز عبور : ' . $password . '
برای تکمیل و یا تغییر مشخصات خود شامل (عکس، آدرس، کد پستی و ...) اینجا را کلیک کنید
' . $this->settings['siteAddress'] . '
' . $userData['firstname'] . ' ' . $userData['lastname'] . ' عزیز این اطمینان را می دهیم که اطلاعات شما نزد ' . $this->settings['siteName'] . ' کاملا محفوظ می باشد و برای اطلاع رسانی از آن استفاده می گردد
';
$this->sendEmail("به سایت " . $this->settings['siteName'] . " خوش آمدید", $body, $userData['email']);
}
//Login
$selectUser = $this->db->query("SELECT * FROM users WHERE username='$userData[email]' AND siteID='$this->siteID'");
$rowUser = $selectUser->fetch();
if ($selectUser->rowCount() > 0)
{
if ($rowUser['status'] == 1)
{
@session_regenerate_id(true);
$_SESSION['userID'] = $rowUser['id'];
$this->isLoggedIn = true;
//Check VIP Expire
$this->db->exec("UPDATE users SET VIP=0 WHERE id='$rowUser[id]' AND VIPExpireDate < $this->now AND siteID='$this->siteID'");
if ($rememberme == "on")
{
$token = md5(uniqid()) . rand(100, 999) . md5(uniqid());
if (version_compare(PHP_VERSION, '7.3', '<'))
{
setcookie("rememberme", 'userID='.$rowUser['id'].'&token='.$token, $this->now + $this->cookie_time, '/; SameSite=Lax');
}
else
{
setcookie("rememberme", 'userID='.$rowUser['id'].'&token='.$token, array(
'expires' => $this->now - 86400,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
)
);
}
$this->db->exec("UPDATE users SET token='$token' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
}
//Last Login Date
$selectLastLogin = $this->db->query("SELECT * FROM users_login WHERE userID='$rowUser[id]' AND siteID='$this->siteID' ORDER BY date DESC LIMIT 1");
$rowLastLogin = $selectLastLogin->fetch();
$this->db->query("UPDATE users SET lastLoginDate='$rowLastLogin[date]' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
$this->db->query("INSERT INTO users_login (siteID, userID, date) VALUES ('$this->siteID', '$rowUser[id]', '$this->now')");
header("Location: " . $_SESSION['google_oauth_referer']);
exit();
}
else
{
$this->error = 'حساب کاربری شما غیر فعال شده است';
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = 'حساب کاربری شما غیر فعال شده است';
$this->errorType = 'error';
return false;
}
}
}
}
else
{
if ($rememberme == "on")
{
$_SESSION['rememberme'] = "on";
}
else
{
$_SESSION['rememberme'] = "off";
}
$authUrl = $gClient->createAuthUrl();
$currentPageUrl = $this->protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parsedUrl = parse_url($currentPageUrl);
$querystrings = $parsedUrl['query'];
parse_str($querystrings, $params);
$params['redirect_url'] = urlencode(filter_var($authUrl, FILTER_SANITIZE_URL));
return $this->protocol . "://" . $_SERVER['HTTP_HOST'] . $parsedUrl['path'] . "?" . http_build_query($params);
}
}
}
//Is_Remember Function
public function is_remember()
{
if (strtolower($_REQUEST['action']) == "remember")
{
return true;
}
}
//Remember
public function remember($username)
{
$selectUser = $this->db->prepare("SELECT * FROM users WHERE username=:username AND siteID='$this->siteID'");
$selectUser->execute(array(':username'=>$username));
$rowUser = $selectUser->fetch();
if ($selectUser->rowCount() != 0)
{
$body = "" . $rowUser['firstname'] . " " . $rowUser['lastname'] . " عزیز، نام کاربری و کلمه عبور شما به شرح زیر است نام کاربری : " . $rowUser['username'] . " کلمه عبور : " . $rowUser['password'] . "
";
$this->sendEmail("کلمه عبور شما در سایت " . $this->settings['siteName'], $body, $rowUser['email']);
return true;
}
}
//Send Reset Password Link
public function sendResetPasswordLink($username, $loginWithEmailAndMobile=false)
{
$isEmail = false;
if (filter_var($username, FILTER_VALIDATE_EMAIL))
{
$isEmail = true;
}
if ($loginWithEmailAndMobile == true)
{
$selectUser = $this->db->prepare("SELECT * FROM users WHERE (username=:username OR email=:email OR mobile=:mobile) AND siteID='$this->siteID'");
$selectUser->execute(array(':username'=>$username, ':email'=>$username, ':mobile'=>$username));
}
else
{
$selectUser = $this->db->prepare("SELECT * FROM users WHERE username=:username AND siteID='$this->siteID'");
$selectUser->execute(array(':username'=>$username));
}
$rowUser = $selectUser->fetch();
if ($selectUser->rowCount() != 0)
{
$resetKey = md5($username . rand(10000, 99999));
$this->db->exec("UPDATE users SET emailConfirmationCode='$resetKey' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
if ($isEmail)
{
$body = "";
$this->sendEmail("لینک تغییر کلمه عبور، در سایت " . $this->settings['siteName'], $body, $rowUser['email']);
}
else
{
$text = "لینک تغییر کلمه عبور\n" . $this->protocol . "://" . $this->settings['siteAddress'] . "/reset-password/?resetKey=" . $resetKey;
$this->sendSMS($text, $rowUser['mobile']);
}
return true;
}
}
//Send Confirmation Code
public function sendEmailConfirmationCode($username, $emailConfirmationCode='', $alwaysNewCode=true, $confirmationCodeExpireDate=60, $resendExpireDate=60, $useSession=false)
{
if ($useSession == false)
{
$selectUser = $this->db->prepare("SELECT * FROM users WHERE (username=:username OR email=:email OR mobile=:mobile) AND siteID='$this->siteID'");
$selectUser->execute(array(':username'=>$username, ':email'=>$username, ':mobile'=>$username));
$rowUser = $selectUser->fetch();
$userID = $rowUser['id'];
$resendExpireDate = intval($rowUser['confirmationCodeExpireDate']) + ($resendExpireDate - $confirmationCodeExpireDate);
if ($selectUser->rowCount() != 0)
{
if ($resendExpireDate <= $this->now)
{
if ($alwaysNewCode == true || empty($rowUser['emailConfirmationCode']) || $rowUser['confirmationCodeExpireDate'] <= $this->now)
{
if (empty($emailConfirmationCode))
{
$emailConfirmationCode = md5($username . rand(10000, 99999));
}
$this->db->query("UPDATE users SET emailConfirmationCode='$emailConfirmationCode' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
}
else
{
$emailConfirmationCode = $rowUser['emailConfirmationCode'];
}
$confirmationCodeExpireDate = $this->now + intval($confirmationCodeExpireDate);
$this->db->query("UPDATE users SET confirmationCodeExpireDate='$confirmationCodeExpireDate' WHERE id='$userID' AND siteID='$this->siteID'");
$body = "";
$this->sendEmail("لینک تائید ایمیل در سایت " . $this->settings['siteName'], $body, $rowUser['email']);
return true;
}
else
{
return -1;
}
}
}
else
{
$resendExpireDate = intval($_SESSION['confirmationCodeExpireDate']) + ($resendExpireDate - $confirmationCodeExpireDate);
if ($resendExpireDate <= $this->now)
{
if ($alwaysNewCode == true || empty($_SESSION['emailConfirmationCode']) || $_SESSION['confirmationCodeExpireDate'] <= $this->now)
{
if (empty($emailConfirmationCode))
{
$_SESSION['emailConfirmationCode'] = md5($username . rand(10000, 99999));
}
else
{
$_SESSION['emailConfirmationCode'] = $emailConfirmationCode;
}
}
$_SESSION['confirmationCodeExpireDate'] = $this->now + intval($confirmationCodeExpireDate);
$body = "";
$this->sendEmail("لینک تائید ایمیل در سایت " . $this->settings['siteName'], $body, $username);
return true;
}
else
{
return -1;
}
}
}
//Send Confirmation Code
public function sendMobileConfirmationCode($username, $mobileConfirmationCode='', $alwaysNewCode=true, $confirmationCodeExpireDate=60, $resendExpireDate=60, $useSession=false)
{
if ($useSession == false)
{
$selectUser = $this->db->prepare("SELECT * FROM users WHERE (username=:username OR email=:email OR mobile=:mobile) AND siteID='$this->siteID'");
$selectUser->execute(array(':username'=>$username, ':email'=>$username, ':mobile'=>$username));
$rowUser = $selectUser->fetch();
$userID = $rowUser['id'];
$resendExpireDate = intval($rowUser['confirmationCodeExpireDate']) + ($resendExpireDate - $confirmationCodeExpireDate);
if ($selectUser->rowCount() != 0)
{
if ($resendExpireDate <= $this->now)
{
if ($alwaysNewCode == true || empty($rowUser['mobileConfirmationCode']) || $rowUser['confirmationCodeExpireDate'] <= $this->now)
{
if (empty($mobileConfirmationCode))
{
$mobileConfirmationCode = rand(10000, 99999);
}
$this->db->query("UPDATE users SET mobileConfirmationCode='$mobileConfirmationCode' WHERE id='$rowUser[id]' AND siteID='$this->siteID'");
}
else
{
$mobileConfirmationCode = $rowUser['mobileConfirmationCode'];
}
$confirmationCodeExpireDate = $this->now + intval($confirmationCodeExpireDate);
$this->db->query("UPDATE users SET confirmationCodeExpireDate='$confirmationCodeExpireDate' WHERE id='$userID' AND siteID='$this->siteID'");
$this->sendSMS("کد تائید شما : " . $mobileConfirmationCode . "\n" . $this->settings['siteAddress'], $rowUser['mobile']);
return true;
}
else
{
return -1;
}
}
}
else
{
$resendExpireDate = intval($_SESSION['confirmationCodeExpireDate']) + ($resendExpireDate - $confirmationCodeExpireDate);
if ($resendExpireDate <= $this->now)
{
if ($alwaysNewCode == true || empty($_SESSION['mobileConfirmationCode']) || $_SESSION['confirmationCodeExpireDate'] <= $this->now)
{
if (empty($mobileConfirmationCode))
{
$_SESSION['mobileConfirmationCode'] = rand(10000, 99999);
}
else
{
$_SESSION['mobileConfirmationCode'] = $mobileConfirmationCode;
}
}
$_SESSION['confirmationCodeExpireDate'] = $this->now + intval($confirmationCodeExpireDate);
$this->sendSMS("کد تائید شما : " . $_SESSION['mobileConfirmationCode'] . "\n" . $this->settings['siteAddress'], $username);
return true;
}
else
{
return -1;
}
}
}
//Is_Logout Function
public function is_logout()
{
if (strtolower($_REQUEST['action']) == "logout")
{
return true;
}
}
//Logout
public function logout()
{
@session_regenerate_id(true);
$_SESSION['userID'] = 0;
if (isset($_SESSION['userID']))
{
unset($_SESSION['userID']);
}
if (isset($_COOKIE['rememberme']))
{
setcookie("rememberme", "", $this->now - 86400, "/", "." . $_SERVER['HTTP_HOST']);
setcookie("rememberme", "", $this->now - 86400, "/", $_SERVER['HTTP_HOST']);
$_COOKIE['rememberme'] = '';
}
// Reset OAuth access token
unset($_SESSION['oauth_token']);
$this->google_oauth(false, "off", true);
}
//User
public function user()
{
if ($this->isLoggedIn == true)
{
$selectUser = $this->db->prepare("SELECT * FROM users WHERE id=:id AND siteID='$this->siteID'");
$selectUser->execute(array(':id'=>$_SESSION['userID']));
$rowUser = $selectUser->fetch();
if ($selectUser->rowCount() != 0)
{
return $rowUser;
}
}
}
// Update user token
public function updateUserToken()
{
$token = md5(uniqid()) . rand(100, 999) . md5(uniqid());
if (!empty($_SESSION['userID']))
{
$updateToken = $this->db->prepare("UPDATE users SET token=:token WHERE id=:id AND siteID='$this->siteID'");
$updateToken->execute(array(':token'=>$token, ':id'=>$_SESSION['userID']));
}
return $token;
}
// insert gateway info
public function insertGatewayInfo($valueArray)
{
$key = md5(uniqid()) . rand(100, 999) . md5(uniqid());
if (is_array($valueArray))
{
$json = json_encode($valueArray);
$insert = $this->db->prepare("INSERT INTO gateway_info (`siteID`, `key`, `value`, `date`, `done`) VALUES ('$this->siteID', '$key', :value, '$this->now', 0)");
$insert->execute(array(':value'=>$json));
return $key;
}
}
// get gateway info
public function getGatewayInfo($key)
{
$gatewayInfoArray = '';
if (!empty($key))
{
$selectGatewayInfo = $this->db->prepare("SELECT * FROM gateway_info WHERE `key`=:key AND `siteID`='$this->siteID' LIMIT 1");
$selectGatewayInfo->execute(array(':key'=>$key));
if ($selectGatewayInfo->rowCount() > 0)
{
$rowGatewayInfo = $selectGatewayInfo->fetch();
$gatewayInfoArray = json_decode($rowGatewayInfo['value'], true);
$gatewayInfoArray['date'] = $rowGatewayInfo['date'];
$gatewayInfoArray['done'] = $rowGatewayInfo['done'];
}
}
return $gatewayInfoArray;
}
// update gateway info
public function updateGatewayInfo($key, $updateArray)
{
if (!empty($key) && !empty($updateArray))
{
if (is_array($updateArray))
{
$json = json_encode($updateArray);
$updateGatewayInfo = $this->db->prepare("UPDATE gateway_info SET value=:value WHERE `key`=:key AND `siteID`='$this->siteID'");
$updateGatewayInfo->execute(array(':key'=>$key, ':value'=>$json));
if ($updateGatewayInfo->rowCount() > 0)
{
return true;
}
}
}
return false;
}
// set gateway info to done
public function setGatewayInfoToDone($key)
{
if (!empty($key))
{
$updateGatewayInfo = $this->db->prepare("UPDATE gateway_info SET done=1 WHERE `key`=:key AND `siteID`='$this->siteID'");
$updateGatewayInfo->execute(array(':key'=>$key));
if ($updateGatewayInfo->rowCount() > 0)
{
return true;
}
}
return false;
}
//UpdateUserStats
/*public function updateUserStats($userID=0)
{
$userID = intval($userID);
if (empty($userID))
{
if (!empty($_SESSION['userID']))
{
$userID = intval($_SESSION['userID']);
}
}
if (!empty($userID))
{
$query = "
SELECT users.id, SUM(orders.totalCost) AS bought, COUNT(comment.id) AS commentsCount, COUNT(topics.id) AS topicsCount, COUNT(users_login.id) AS loginCount, COUNT(users_download.id) AS downloadsCount
FROM users
LEFT JOIN orders ON users.id=orders.userID AND orders.payStatus=1
LEFT JOIN comment ON users.id=comment.userID
LEFT JOIN topics ON users.id=topics.userID
LEFT JOIN users_login ON users.id=users_login.userID
LEFT JOIN users_download ON users.id=users_download.userID
WHERE users.id='$userID'
GROUP BY users.id
ORDER BY `bought` DESC
";
$query = "
SELECT users.id, COALESCE(orders.bought,0) bought, COUNT(DISTINCT comment.id) AS commentsCount, COUNT(DISTINCT topics.id) AS topicsCount, COUNT(DISTINCT users_login.id) AS loginCount, COUNT(DISTINCT users_download.id) AS downloadsCount
FROM users
LEFT JOIN (SELECT userID, SUM(totalCost) bought FROM orders WHERE payStatus=1 GROUP BY userID) orders
ON users.id=o.userID LEFT JOIN comment ON users.id=comment.userID
LEFT JOIN topics ON users.id=topics.userID
LEFT JOIN users_login ON users.id=users_login.userID
LEFT JOIN users_download ON users.id=users_download.userID
GROUP BY users.id
ORDER BY `bought` DESC
";
$selectOrders = $this->db->query("SELECT SUM(totalCost) AS totalCost, SUM(discount) AS discount FROM orders WHERE userID=$userID AND payStatus=1");
$rowOrders = $selectOrders->fetch();
$selectTransactions = $this->db->query("SELECT SUM(price) AS price FROM transactions WHERE userID=$userID AND type!=2 AND status=1");
$rowTransactions = $selectTransactions->fetch();
//Charged Cash
$selectCharges = $this->db->query("SELECT SUM(price) AS charged FROM transactions WHERE userID=$userID AND type=2 AND status=1");
$rowCharges = $selectCharges->fetch();
$walletChargedAmount = $rowCharges['charged'];
//Spent Cash By Order
$selectWalletOrders = $this->db->query("SELECT SUM(totalCost) AS totalCost, SUM(discount) AS discount FROM orders WHERE userID=$userID AND payMethod=4 AND payStatus=1");
$rowWalletOrders = $selectWalletOrders->fetch();
$walletSpentAmount = intval($rowWalletOrders['totalCost']) - intval($rowWalletOrders['discount']);
//Spent Cash By Transaction
$selectWalletTransactions = $this->db->query("SELECT SUM(price) AS spent FROM transactions WHERE userID=$userID AND payMethod=2 AND status=1");
$rowWalletTransactions = $selectWalletTransactions->fetch();
$walletSpentAmount += $rowWalletTransactions['spent'];
$selectComments = $this->db->query("SELECT id FROM comment WHERE userID=$userID");
$selectTopics = $this->db->query("SELECT id FROM topics WHERE userID=$userID");
$selectUserLogins = $this->db->query("SELECT id FROM users_login WHERE userID=$userID");
$selectUserDownloads = $this->db->query("SELECT id FROM users_download WHERE userID=$userID");
$payAmount = intval($rowOrders['totalCost']) - intval($rowOrders['discount']) + intval($rowTransactions['price']);
$commentsCount = $selectComments->rowCount();
$topicsCount = $selectTopics->rowCount();
$loginCount = $selectUserLogins->rowCount();
$downloadsCount = $selectUserDownloads->rowCount();
$updateUserStats = $this->db->query("UPDATE users SET payAmount='$payAmount', walletChargedAmount='$walletChargedAmount', walletSpentAmount='$walletSpentAmount', commentsCount='$commentsCount', topicsCount='$topicsCount', loginCount='$loginCount', downloadsCount='$downloadsCount' WHERE id=$userID");
}
}*/
//Newsletter_Form Function
public function newsletter_form()
{
}
//Is_Newsletter Function
public function is_newsletter()
{
if (strtolower($_REQUEST['action']) == "newsletter")
{
return true;
}
}
//Newsletter_Register
public function newsletter_register($firstname, $lastname, $email, $mobile, $date=null)
{
$insertNewsletter = $this->db->prepare("INSERT INTO newsletter (siteID, firstname,lastname,email,mobile,date) VALUES ('$this->siteID', :firstname, :lastname, :email, :mobile, :date)");
if ($firstname != "")
{
$insertNewsletter->bindValue(":firstname", $firstname);
}
if ($lastname != "")
{
$insertNewsletter->bindValue(":lastname", $lastname);
}
if ($email != "")
{
$insertNewsletter->bindValue(":email", $email);
}
if ($mobile != "")
{
$insertNewsletter->bindValue(":mobile", $mobile);
}
if ($date==null)
{
$insertNewsletter->bindValue(":date", time());
}
else
{
$insertNewsletter->bindValue(":date", $date);
}
if ($email != "")
{
$insertNewsletter->execute();
return true;
}
}
//Search_Box Function
public function search_box($value="جستجو")
{
return ' ';
}
//Is_Search Function
public function is_search()
{
if (strtolower($_REQUEST['action']) == "search" && !empty($_REQUEST['keyword']))
{
return true;
}
}
//Search Function
public function search($orderBy='sort ASC', $searchIn='')
{
if (strtolower($_REQUEST['action']) == "search" && !empty($_REQUEST['keyword']))
{
$search = array();
$keyword = $_REQUEST['keyword'];
$found = 0;
$orderBy = $this->orderBy($orderBy);
//Search Queries
if (empty($searchIn) || in_array("articles", $searchIn))
{
$selectArticles = $this->db->prepare("SELECT *, 'article' AS type FROM articles WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectArticles->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectArticles->rowCount();
while($rowSearch = $selectArticles->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("news", $searchIn))
{
$selectNews = $this->db->prepare("SELECT *, 'news' AS type FROM news WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectNews->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectNews->rowCount();
while($rowSearch = $selectNews->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("pages", $searchIn))
{
$selectPages = $this->db->prepare("SELECT *, 'page' AS type FROM pages WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectPages->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectPages->rowCount();
while($rowSearch = $selectPages->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("downloads", $searchIn))
{
$selectDownloads = $this->db->prepare("SELECT *, 'download' AS type FROM downloads WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectDownloads->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectDownloads->rowCount();
while($rowSearch = $selectDownloads->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("offers", $searchIn))
{
$selectOffers = $this->db->prepare("SELECT *, 'offer' AS type FROM offers WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectOffers->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectOffers->rowCount();
while($rowSearch = $selectOffers->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("authors", $searchIn))
{
$selectAuthors = $this->db->prepare("SELECT *, 'author' AS type FROM authors WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectAuthors->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectAuthors->rowCount();
while($rowSearch = $selectAuthors->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("galleries", $searchIn))
{
$selectGalleries = $this->db->prepare("SELECT *, 'gallery' AS type FROM galleries WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectGalleries->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectGalleries->rowCount();
while($rowSearch = $selectGalleries->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("registerations", $searchIn))
{
$selectRegisterations = $this->db->prepare("
SELECT *, 'registeration' AS type,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM registerations
WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy
");
$selectRegisterations->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectRegisterations->rowCount();
while($rowSearch = $selectRegisterations->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("courses", $searchIn))
{
$selectCourses = $this->db->prepare("
SELECT *, 'course' AS type,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM courses
WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy
");
$selectCourses->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectCourses->rowCount();
while($rowSearch = $selectCourses->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("vips", $searchIn))
{
$selectVips = $this->db->prepare("SELECT *, 'vip' AS type FROM vips WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectVips->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectVips->rowCount();
while($rowSearch = $selectVips->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("estates", $searchIn))
{
$selectEstates = $this->db->prepare("SELECT *, 'estate' AS type FROM estates WHERE (title LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectEstates->execute(array("%" . $keyword . "%"));
$found += $selectEstates->rowCount();
while($rowSearch = $selectEstates->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("products", $searchIn))
{
$selectProducts = $this->db->prepare("
SELECT *, 'product' AS type,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice
FROM products
WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID' $orderBy
");
$selectProducts->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectProducts->rowCount();
while($rowSearch = $selectProducts->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("group_products", $searchIn))
{
$selectGroupProducts = $this->db->prepare("SELECT *, 'groupProduct' AS type FROM group_products WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectGroupProducts->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectGroupProducts->rowCount();
while($rowSearch = $selectGroupProducts->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("wishes", $searchIn))
{
$selectWishes = $this->db->prepare("SELECT *, 'wish' AS type FROM wishes WHERE (title LIKE ? OR description LIKE ? OR full_description LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectWishes->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectWishes->rowCount();
while($rowSearch = $selectWishes->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("audios", $searchIn))
{
$selectAudios = $this->db->prepare("SELECT *, 'audio' AS type FROM audios WHERE (title LIKE ? OR description LIKE ? OR artist LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectAudios->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectAudios->rowCount();
while($rowSearch = $selectAudios->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
if (empty($searchIn) || in_array("videos", $searchIn))
{
$selectVideos = $this->db->prepare("SELECT *, 'video' AS type FROM videos WHERE (title LIKE ? OR description LIKE ? OR artist LIKE ?) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectVideos->execute(array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%"));
$found += $selectVideos->rowCount();
while($rowSearch = $selectVideos->fetch())
{
if (!empty($rowSearch['permalink']))
{
$rowSearch['url'] = "/" . $rowSearch['permalink'];
}
else
{
$rowSearch['url'] = "/" . $rowSearch['type'] . "/" . $rowSearch['id'] . "/" . $this->safeUrl($rowSearch['title']);
}
$search[] = $rowSearch;
}
}
$this->keyword = $keyword;
$this->found = $found;
return $search;
}
}
//Is_Search_Tag Function
public function is_search_tag()
{
if (strtolower($_REQUEST['action']) == "tag" && !empty($_GET['tag']))
{
return true;
}
}
//Search_Tag Function
public function search_tag($orderBy='sort ASC')
{
if (strtolower($_REQUEST['action']) == "tag" && !empty($_REQUEST['tag']))
{
$search_tag = array();
$tag = trim(str_replace(array("_", "-"), " ", $_REQUEST['tag']));
$found = 0;
$orderBy = $this->orderBy($orderBy);
//Search Queries
$selectArticles = $this->db->prepare("SELECT *, 'article' AS type FROM articles WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectArticles->execute(array($tag));
$found += $selectArticles->rowCount();
$selectNews = $this->db->prepare("SELECT *, 'news' AS type FROM news WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectNews->execute(array($tag));
$found += $selectNews->rowCount();
$selectPages = $this->db->prepare("SELECT *, 'page' AS type FROM pages WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectPages->execute(array($tag));
$found += $selectPages->rowCount();
$selectDownloads = $this->db->prepare("SELECT *, 'download' AS type FROM downloads WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectDownloads->execute(array($tag));
$found += $selectDownloads->rowCount();
$selectOffers = $this->db->prepare("SELECT *, 'offer' AS type FROM offers WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectOffers->execute(array($tag));
$found += $selectOffers->rowCount();
$selectAuthors = $this->db->prepare("SELECT *, 'author' AS type FROM authors WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectAuthors->execute(array($tag));
$found += $selectAuthors->rowCount();
$selectGalleries = $this->db->prepare("SELECT *, 'gallery' AS type FROM galleries WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectGalleries->execute(array($tag));
$found += $selectGalleries->rowCount();
$selectRegisterations = $this->db->prepare("
SELECT *, 'registeration' AS type,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM registerations
WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy
");
$selectRegisterations->execute(array($tag));
$found += $selectRegisterations->rowCount();
$selectCourses = $this->db->prepare("
SELECT *, 'course' AS type,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM courses
WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy
");
$selectCourses->execute(array($tag));
$found += $selectCourses->rowCount();
$selectVips = $this->db->prepare("SELECT *, 'vip' AS type FROM vips WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectVips->execute(array($tag));
$found += $selectVips->rowCount();
$selectEstates = $this->db->prepare("SELECT *, 'estate' AS type FROM estates WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectEstates->execute(array($tag));
$found += $selectEstates->rowCount();
$selectProducts = $this->db->prepare("
SELECT *, 'product' AS type,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice
FROM products
WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID' $orderBy
");
$selectProducts->execute(array($tag));
$found += $selectProducts->rowCount();
$selectGroupProducts = $this->db->prepare("SELECT *, 'groupProduct' AS type FROM group_products WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectGroupProducts->execute(array($tag));
$found += $selectGroupProducts->rowCount();
$selectWishes = $this->db->prepare("SELECT *, 'wish' AS type FROM wishes WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectWishes->execute(array($tag));
$found += $selectWishes->rowCount();
$selectAudios = $this->db->prepare("SELECT *, 'audio' AS type FROM audios WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectAudios->execute(array($tag));
$found += $selectAudios->rowCount();
$selectVideos = $this->db->prepare("SELECT *, 'video' AS type FROM videos WHERE FIND_IN_SET(?, REPLACE(REPLACE(keywords, '_', ' '), '-', ' ')) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy");
$selectVideos->execute(array($tag));
$found += $selectVideos->rowCount();
while($rowSearchTag = $selectArticles->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectNews->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectPages->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectDownloads->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectOffers->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectAuthors->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectRegisterations->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectCourses->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectVips->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectEstates->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectProducts->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectGroupProducts->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectWishes->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectAudios->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
while($rowSearchTag = $selectVideos->fetch())
{
if (!empty($rowSearchTag['permalink']))
{
$rowSearchTag['url'] = "/" . $rowSearchTag['permalink'];
}
else
{
$rowSearchTag['url'] = "/" . $rowSearchTag['type'] . "/" . $rowSearchTag['id'] . "/" . $this->safeUrl($rowSearchTag['title']);
}
$search_tag[] = $rowSearchTag;
}
$this->tag = $tag;
$this->found = $found;
return $search_tag;
}
}
//Get_Similar Function
public function get_similar($keywordsArray, $filterArray, $orderBy='sort ASC')
{
if (!empty($keywordsArray))
{
if (is_array($keywordsArray))
{
foreach($keywordsArray as $keyword)
{
$likeQuery[] = "keywords LIKE ?";
$keywords[] = "%" . $keyword . "%";
}
}
else
{
$likeQuery[] = "keywords LIKE ?";
$keywords[] = "%" . $keywordsArray . "%";
}
$likeQuery = "(" . implode(' OR ', $likeQuery) . ")";
$get_similar = array();
$found = 0;
$orderBy = $this->orderBy($orderBy);
//Search Queries
if (in_array("article", $filterArray) || empty($filterArray))
{
if ($this->is_article() == true)
{
$object = $this->article(1);
$id = $object['id'];
$selectArticles = $this->db->prepare("SELECT *, 'article' AS type FROM articles WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectArticles->execute($keywords);
$found += $selectArticles->rowCount();
}
else
{
$selectArticles = $this->db->prepare("SELECT *, 'article' AS type FROM articles WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectArticles->execute($keywords);
$found += $selectArticles->rowCount();
}
}
if (in_array("news", $filterArray) || empty($filterArray))
{
if ($this->is_news() == true)
{
$object = $this->news(1);
$id = $object['id'];
$selectNews = $this->db->prepare("SELECT *, 'news' AS type FROM news WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectNews->execute($keywords);
$found += $selectNews->rowCount();
}
else
{
$selectNews = $this->db->prepare("SELECT *, 'news' AS type FROM news WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectNews->execute($keywords);
$found += $selectNews->rowCount();
}
}
if (in_array("page", $filterArray) || empty($filterArray))
{
if ($this->is_page() == true)
{
$object = $this->page(1);
$id = $object['id'];
$selectPages = $this->db->prepare("SELECT *, 'page' AS type FROM pages WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectPages->execute($keywords);
$found += $selectPages->rowCount();
}
else
{
$selectPages = $this->db->prepare("SELECT *, 'page' AS type FROM pages WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectPages->execute($keywords);
$found += $selectPages->rowCount();
}
}
if (in_array("download", $filterArray) || empty($filterArray))
{
if ($this->is_download() == true)
{
$object = $this->download(1);
$id = $object['id'];
$selectDownloads = $this->db->prepare("SELECT *, 'download' AS type FROM downloads WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectDownloads->execute($keywords);
$found += $selectDownloads->rowCount();
}
else
{
$selectDownloads = $this->db->prepare("SELECT *, 'download' AS type FROM downloads WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectDownloads->execute($keywords);
$found += $selectDownloads->rowCount();
}
}
if (in_array("offer", $filterArray) || empty($filterArray))
{
if ($this->is_offer() == true)
{
$object = $this->offer(1);
$id = $object['id'];
$selectOffers = $this->db->prepare("SELECT *, 'offer' AS type FROM offers WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectOffers->execute($keywords);
$found += $selectOffers->rowCount();
}
else
{
$selectOffers = $this->db->prepare("SELECT *, 'offer' AS type FROM offers WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectOffers->execute($keywords);
$found += $selectOffers->rowCount();
}
}
if (in_array("author", $filterArray) || empty($filterArray))
{
if ($this->is_author() == true)
{
$object = $this->author(1);
$id = $object['id'];
$selectAuthors = $this->db->prepare("SELECT *, 'author' AS type FROM authors WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectAuthors->execute($keywords);
$found += $selectAuthors->rowCount();
}
else
{
$selectAuthors = $this->db->prepare("SELECT *, 'author' AS type FROM authors WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectAuthors->execute($keywords);
$found += $selectAuthors->rowCount();
}
}
if (in_array("registeration", $filterArray) || empty($filterArray))
{
if ($this->is_registeration() == true)
{
$object = $this->registeration(1);
$id = $object['id'];
$selectRegisterations = $this->db->prepare("
SELECT *, 'registeration' AS type,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM registerations
WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()
");
$selectRegisterations->execute($keywords);
$found += $selectRegisterations->rowCount();
}
else
{
$selectRegisterations = $this->db->prepare("
SELECT *, 'registeration' AS type,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM registerations
WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()
");
$selectRegisterations->execute($keywords);
$found += $selectRegisterations->rowCount();
}
}
if (in_array("course", $filterArray) || empty($filterArray))
{
if ($this->is_course() == true)
{
$object = $this->course(1);
$id = $object['id'];
$selectCourses = $this->db->prepare("
SELECT *, 'course' AS type,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM courses
WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()
");
$selectCourses->execute($keywords);
$found += $selectCourses->rowCount();
}
else
{
$selectCourses = $this->db->prepare("
SELECT *, 'course' AS type,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM courses
WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()
");
$selectCourses->execute($keywords);
$found += $selectCourses->rowCount();
}
}
if (in_array("vip", $filterArray) || empty($filterArray))
{
if ($this->is_vip() == true)
{
$object = $this->vip(1);
$id = $object['id'];
$selectVips = $this->db->prepare("SELECT *, 'vip' AS type FROM vips WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectVips->execute($keywords);
$found += $selectVips->rowCount();
}
else
{
$selectVips = $this->db->prepare("SELECT *, 'vip' AS type FROM vips WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectVips->execute($keywords);
$found += $selectVips->rowCount();
}
}
if (in_array("estate", $filterArray) || empty($filterArray))
{
if (!empty($this->ownerID))
{
$ownerQuery = " AND userID='$this->ownerID'";
}
else
{
$ownerQuery = '';
}
if ($this->is_estate() == true)
{
$object = $this->estate(1);
$id = $object['id'];
$selectEstates = $this->db->prepare("SELECT *, 'estate' AS type FROM estates WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $ownerQuery ORDER BY RAND()");
$selectEstates->execute($keywords);
$found += $selectEstates->rowCount();
}
else
{
$selectEstates = $this->db->prepare("SELECT *, 'estate' AS type FROM estates WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $ownerQuery ORDER BY RAND()");
$selectEstates->execute($keywords);
$found += $selectEstates->rowCount();
}
}
if (in_array("product", $filterArray) || empty($filterArray))
{
if ($this->is_product() == true)
{
$object = $this->product(1);
$id = $object['id'];
$selectProducts = $this->db->prepare("
SELECT *, 'product' AS type,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice
FROM products
WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID' ORDER BY RAND()
");
$selectProducts->execute($keywords);
$found += $selectProducts->rowCount();
}
else
{
$selectProducts = $this->db->prepare("
SELECT *, 'product' AS type,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice
FROM products
WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID' ORDER BY RAND()
");
$selectProducts->execute($keywords);
$found += $selectProducts->rowCount();
}
}
if (in_array("groupProducts", $filterArray) || empty($filterArray))
{
if ($this->is_groupProduct() == true)
{
$object = $this->groupProduct(1);
$id = $object['id'];
$selectGroupProducts = $this->db->prepare("SELECT *, 'group_product' AS type FROM group_products WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectGroupProducts->execute($keywords);
$found += $selectGroupProducts->rowCount();
}
else
{
$selectGroupProducts = $this->db->prepare("SELECT *, 'group_product' AS type FROM group_products WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectGroupProducts->execute($keywords);
$found += $selectGroupProducts->rowCount();
}
}
if (in_array("wish", $filterArray) || empty($filterArray))
{
if ($this->is_wish() == true)
{
$object = $this->wish(1);
$id = $object['id'];
$selectWishes = $this->db->prepare("SELECT *, 'wish' AS type FROM wishes WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectWishes->execute($keywords);
$found += $selectWishes->rowCount();
}
else
{
$selectWishes = $this->db->prepare("SELECT *, 'wish' AS type FROM wishes WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectWishes->execute($keywords);
$found += $selectWishes->rowCount();
}
}
if (in_array("audio", $filterArray) || empty($filterArray))
{
if ($this->is_audio() == true)
{
$object = $this->audio(1);
$id = $object['id'];
$selectAudios = $this->db->prepare("SELECT *, 'audio' AS type FROM audios WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectAudios->execute($keywords);
$found += $selectAudios->rowCount();
}
else
{
$selectAudios = $this->db->prepare("SELECT *, 'audio' AS type FROM audios WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectAudios->execute($keywords);
$found += $selectAudios->rowCount();
}
}
if (in_array("video", $filterArray) || empty($filterArray))
{
if ($this->is_video() == true)
{
$object = $this->video(1);
$id = $object['id'];
$selectVideos = $this->db->prepare("SELECT *, 'video' AS type FROM videos WHERE $likeQuery AND id!=$id AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectVideos->execute($keywords);
$found += $selectVideos->rowCount();
}
else
{
$selectVideos = $this->db->prepare("SELECT *, 'video' AS type FROM videos WHERE $likeQuery AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' ORDER BY RAND()");
$selectVideos->execute($keywords);
$found += $selectVideos->rowCount();
}
}
if (in_array("article", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectArticles->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("news", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectNews->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("page", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectPages->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("download", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectDownloads->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("offer", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectOffers->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("author", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectAuthors->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("registeration", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectRegisterations->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("course", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectCourses->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("vip", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectVips->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("estate", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectEstates->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("product", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectProducts->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("groupProduct", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectGroupProducts->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("wish", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectWishes->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("audio", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectAudios->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
if (in_array("video", $filterArray) || empty($filterArray))
{
while($rowSimilar = $selectVideos->fetch())
{
if (!empty($rowSimilar['permalink']))
{
$rowSimilar['url'] = "/" . $rowSimilar['permalink'];
}
else
{
$rowSimilar['url'] = "/" . $rowSimilar['type'] . "/" . $rowSimilar['id'] . "/" . $this->safeUrl($rowSimilar['title']);
}
$get_similar[] = $rowSimilar;
}
}
$this->found = $found;
return $get_similar;
}
}
//Is_Get_Articles Function
public function is_get_articles()
{
if (strtolower($_REQUEST['action']) == "articles" && empty($_GET['id']))
{
return true;
}
}
//Get_Articles Function
public function get_articles($orderBy='sort ASC', $limit=0)
{
$get_articles = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectArticles = $this->db->query("SELECT * FROM articles WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowArticles = $selectArticles->fetch())
{
$rowArticles['images'] = @explode("|", $rowArticles['image']);
$rowArticles['image'] = $rowArticles['images'][0];
if (!empty($rowArticles['permalink']))
{
$rowArticles['url'] = "/" . $rowArticles['permalink'];
}
else
{
$rowArticles['url'] = "/article/" . $rowArticles['id'] . "/" . $this->safeUrl($rowArticles['title']);
}
$get_articles[] = $rowArticles;
}
return $get_articles;
}
//Get_Articles_By_Category Function
public function get_articles_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = @implode(",", $this->get_sub_categories($category));
$get_articles_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectArticles = $this->db->query("SELECT * FROM articles WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowArticles = $selectArticles->fetch())
{
$rowArticles['images'] = @explode("|", $rowArticles['image']);
$rowArticles['image'] = $rowArticles['images'][0];
if (!empty($rowArticles['permalink']))
{
$rowArticles['url'] = "/" . $rowArticles['permalink'];
}
else
{
$rowArticles['url'] = "/article/" . $rowArticles['id'] . "/" . $this->safeUrl($rowArticles['title']);
}
$get_articles_by_category[] = $rowArticles;
}
return $get_articles_by_category;
}
//Is_Article Function
public function is_article()
{
if (strtolower($_REQUEST['action']) == "article" && !empty($_GET['id']))
{
return true;
}
}
//Article Function
public function article($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "article" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->article = array();
$selectArticle = $this->db->prepare("SELECT * FROM articles WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectArticle->execute(array(':id' => $id));
$rowArticle = $selectArticle->fetch();
$rowArticle['post_type'] = "article";
$rowArticle['images'] = @explode("|", $rowArticle['image']);
$rowArticle['image'] = $rowArticle['images'][0];
if (!empty($rowArticle['permalink']))
{
$rowArticle['url'] = "/" . $rowArticle['permalink'];
}
else
{
$rowArticle['url'] = "/article/" . $rowArticle['id'] . "/" . $this->safeUrl($rowArticle['title']);
}
$rowArticle['extraOptions'] = $this->getExtraOptions("articles", $rowArticle['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE articles SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowArticle;
}
//Is_Get_News Function
public function is_get_news()
{
if (strtolower($_REQUEST['action']) == "news" && empty($_GET['id']))
{
return true;
}
}
//Get_News Function
public function get_news($orderBy='sort ASC', $limit=0)
{
$get_news = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectNews = $this->db->query("SELECT * FROM news WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowNews = $selectNews->fetch())
{
$rowNews['images'] = @explode("|", $rowNews['image']);
$rowNews['image'] = $rowNews['images'][0];
if (!empty($rowNews['permalink']))
{
$rowNews['url'] = "/" . $rowNews['permalink'];
}
else
{
$rowNews['url'] = "/news/" . $rowNews['id'] . "/" . $this->safeUrl($rowNews['title']);
}
$get_news[] = $rowNews;
}
return $get_news;
}
//Get_News_By_Category Function
public function get_news_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_news_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectNews = $this->db->query("SELECT * FROM news WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowNews = $selectNews->fetch())
{
$rowNews['images'] = @explode("|", $rowNews['image']);
$rowNews['image'] = $rowNews['images'][0];
if (!empty($rowNews['permalink']))
{
$rowNews['url'] = "/" . $rowNews['permalink'];
}
else
{
$rowNews['url'] = "/news/" . $rowNews['id'] . "/" . $this->safeUrl($rowNews['title']);
}
$get_news_by_category[] = $rowNews;
}
return $get_news_by_category;
}
//Is_News Function
public function is_news()
{
if (strtolower($_REQUEST['action']) == "news" && !empty($_GET['id']))
{
return true;
}
}
//News Function
public function news($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "news" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->news = array();
$selectNews = $this->db->prepare("SELECT * FROM news WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectNews->execute(array(':id' => $id));
$rowNews = $selectNews->fetch();
$rowNews['post_type'] = "news";
$rowNews['images'] = @explode("|", $rowNews['image']);
$rowNews['image'] = $rowNews['images'][0];
if (!empty($rowNews['permalink']))
{
$rowNews['url'] = "/" . $rowNews['permalink'];
}
else
{
$rowNews['url'] = "/news/" . $rowNews['id'] . "/" . $this->safeUrl($rowNews['title']);
}
$rowNews['extraOptions'] = $this->getExtraOptions("news", $rowNews['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE news SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowNews;
}
//Is_Get_Products Function
public function is_get_products()
{
if (strtolower($_REQUEST['action']) == "products" && empty($_GET['id']))
{
return true;
}
}
//Get_Products Function
public function get_products($orderBy='sort ASC', $limit=0)
{
$get_products = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$query = "SELECT products.*,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice,
(CASE
WHEN (
IFNULL(products.availability, 0) = 0 AND
(
IFNULL(products.stock, 0) = 1 OR
(IFNULL(instock_variations.id, 0) > 0 AND CAST(instock_variations.instock AS UNSIGNED) > 0) OR
(IFNULL(instock_variations.id, 0) = 0 AND CAST(products.instock AS UNSIGNED) > 0)
)
) THEN 1
ELSE 0
END) AS isAvailable
FROM products
LEFT JOIN (SELECT id, productID, instock FROM product_variations WHERE status=1 AND instock > 0 AND siteID='$this->siteID') AS instock_variations ON products.id=instock_variations.productID
WHERE
products.publishDate <= $this->now AND
products.active=1 AND
products.hidden=0 AND
IFNULL(products.isDeleted, 0)!=1 AND
products.siteID='$this->siteID'
GROUP BY products.id
$orderBy
$limitQuery";
$selectProducts = $this->db->query($query);
while ($rowProducts = $selectProducts->fetch())
{
$rowProducts['images'] = @explode("|", $rowProducts['image']);
$rowProducts['image'] = $rowProducts['images'][0];
if (!empty($rowProducts['permalink']))
{
$rowProducts['url'] = "/" . $rowProducts['permalink'];
}
else
{
$rowProducts['url'] = "/product/" . $rowProducts['id'] . "/" . $this->safeUrl($rowProducts['title']);
}
$get_products[] = $rowProducts;
}
return $get_products;
}
//Get_Special_Products Function
public function get_special_products($orderBy='sort ASC', $limit=0)
{
$get_special_products = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$query = "SELECT products.*,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice,
(CASE
WHEN (
IFNULL(products.availability, 0) = 0 AND
(
IFNULL(products.stock, 0) = 1 OR
(IFNULL(instock_variations.id, 0) > 0 AND CAST(instock_variations.instock AS UNSIGNED) > 0) OR
(IFNULL(instock_variations.id, 0) = 0 AND CAST(products.instock AS UNSIGNED) > 0)
)
) THEN 1
ELSE 0
END) AS isAvailable
FROM products
LEFT JOIN (SELECT id, productID, instock FROM product_variations WHERE status=1 AND instock > 0 AND siteID='$this->siteID') AS instock_variations ON products.id=instock_variations.productID
WHERE
products.publishDate <= $this->now AND
products.active=1 AND
products.special=1 AND
products.hidden=0 AND
IFNULL(products.isDeleted, 0)!=1 AND
products.siteID='$this->siteID'
GROUP BY products.id
$orderBy
$limitQuery";
$selectProducts = $this->db->query($query);
while ($rowProducts = $selectProducts->fetch())
{
$rowProducts['images'] = explode("|", $rowProducts['image']);
$rowProducts['image'] = $rowProducts['images'][0];
if (!empty($rowProducts['permalink']))
{
$rowProducts['url'] = "/" . $rowProducts['permalink'];
}
else
{
$rowProducts['url'] = "/product/" . $rowProducts['id'] . "/" . $this->safeUrl($rowProducts['title']);
}
$get_special_products[] = $rowProducts;
}
return $get_special_products;
}
//Get_Products_By_Category Function
public function get_products_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$categories2 = str_replace(",", "|", $categories);
$get_products_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$query = "SELECT products.*,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice,
(CASE
WHEN (
IFNULL(products.availability, 0) = 0 AND
(
IFNULL(products.stock, 0) = 1 OR
(IFNULL(instock_variations.id, 0) > 0 AND CAST(instock_variations.instock AS UNSIGNED) > 0) OR
(IFNULL(instock_variations.id, 0) = 0 AND CAST(products.instock AS UNSIGNED) > 0)
)
) THEN 1
ELSE 0
END) AS isAvailable
FROM products
LEFT JOIN (SELECT id, productID, instock FROM product_variations WHERE status=1 AND instock > 0 AND siteID='$this->siteID') AS instock_variations ON products.id=instock_variations.productID
WHERE
(
products.categoryID IN ($categories) OR
CONCAT(',', products.altCategories, ',') REGEXP ',($categories2),'
) AND
products.publishDate <= $this->now AND
products.active=1 AND
products.hidden=0 AND
IFNULL(products.isDeleted, 0)!=1 AND
products.siteID='$this->siteID'
GROUP BY products.id
$orderBy
$limitQuery";
$selectProducts = $this->db->query($query);
while ($rowProducts = $selectProducts->fetch())
{
$rowProducts['images'] = explode("|", $rowProducts['image']);
$rowProducts['image'] = $rowProducts['images'][0];
if (!empty($rowProducts['permalink']))
{
$rowProducts['url'] = "/" . $rowProducts['permalink'];
}
else
{
$rowProducts['url'] = "/product/" . $rowProducts['id'] . "/" . $this->safeUrl($rowProducts['title']);
}
$get_products_by_category[] = $rowProducts;
}
return $get_products_by_category;
}
//Is_Product Function
public function is_product()
{
if (strtolower($_REQUEST['action']) == "product" && !empty($_GET['id']))
{
return true;
}
}
//Product Function
public function product($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "product" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->product = array();
$query = "SELECT products.*,
(CASE
WHEN (IFNULL(products.auctionStatus, 0)=1 AND products.auctionStartDate <= '$this->now' AND products.auctionExpireDate >= '$this->now') THEN products.auctionPrice
WHEN (IFNULL(products.auctionStatus, 0)!=1 OR products.auctionStartDate > '$this->now' OR products.auctionExpireDate < '$this->now') THEN products.price
END) AS realPrice,
(CASE
WHEN (
IFNULL(products.availability, 0) = 0 AND
(
IFNULL(products.stock, 0) = 1 OR
(IFNULL(instock_variations.id, 0) > 0 AND CAST(instock_variations.instock AS UNSIGNED) > 0) OR
(IFNULL(instock_variations.id, 0) = 0 AND CAST(products.instock AS UNSIGNED) > 0)
)
) THEN 1
ELSE 0
END) AS isAvailable
FROM products
LEFT JOIN (SELECT id, productID, instock FROM product_variations WHERE status=1 AND instock > 0 AND siteID='$this->siteID') AS instock_variations ON products.id=instock_variations.productID
WHERE
products.id=:id AND
products.publishDate <= $this->now AND
products.active=1 AND
IFNULL(products.isDeleted, 0)!=1 AND
products.siteID='$this->siteID'
GROUP BY products.id";
$selectProduct = $this->db->prepare($query);
$selectProduct->execute(array(':id' => $id));
$rowProduct = $selectProduct->fetch();
$rowProduct['post_type'] = "product";
$rowProduct['images'] = explode("|", $rowProduct['image']);
$rowProduct['image'] = $rowProduct['images'][0];
if (!empty($rowProduct['permalink']))
{
$rowProduct['url'] = "/" . $rowProduct['permalink'];
}
else
{
$rowProduct['url'] = "/product/" . $rowProduct['id'] . "/" . $this->safeUrl($rowProduct['title']);
}
$rowProduct['extraOptions'] = $this->getExtraOptions("products", $rowProduct['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE products SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowProduct;
}
//Is_Get_GroupProducts Function
public function is_get_groupProducts()
{
if (strtolower($_REQUEST['action']) == "group-products" && empty($_GET['id']))
{
return true;
}
}
//Get_GroupProducts Function
public function get_groupProducts($orderBy='sort ASC', $limit=0)
{
$get_groupProducts = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectGroupProducts = $this->db->query("SELECT * FROM group_products WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowGroupProducts = $selectGroupProducts->fetch())
{
$rowGroupProducts['images'] = @explode("|", $rowGroupProducts['image']);
$rowGroupProducts['image'] = $rowGroupProducts['images'][0];
if (!empty($rowGroupProducts['permalink']))
{
$rowGroupProducts['url'] = "/" . $rowGroupProducts['permalink'];
}
else
{
$rowGroupProducts['url'] = "/group-product/" . $rowGroupProducts['id'] . "/" . $this->safeUrl($rowGroupProducts['title']);
}
$get_groupProducts[] = $rowGroupProducts;
}
return $get_groupProducts;
}
//Get_GroupProducts_By_Category Function
public function get_groupProducts_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = @implode(",", $this->get_sub_categories($category));
$get_groupProducts_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectGroupProducts = $this->db->query("SELECT * FROM group_products WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowGroupProducts = $selectGroupProducts->fetch())
{
$rowGroupProducts['images'] = @explode("|", $rowGroupProducts['image']);
$rowGroupProducts['image'] = $rowGroupProducts['images'][0];
if (!empty($rowGroupProducts['permalink']))
{
$rowGroupProducts['url'] = "/" . $rowGroupProducts['permalink'];
}
else
{
$rowGroupProducts['url'] = "/group-product/" . $rowGroupProducts['id'] . "/" . $this->safeUrl($rowGroupProducts['title']);
}
$get_groupProducts_by_category[] = $rowGroupProducts;
}
return $get_groupProducts_by_category;
}
//Is_GroupProduct Function
public function is_groupProduct()
{
if (strtolower($_REQUEST['action']) == "group-product" && !empty($_GET['id']))
{
return true;
}
}
//GroupProduct Function
public function groupProduct($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "group-product" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->groupProduct = array();
$selectGroupProduct = $this->db->prepare("SELECT * FROM group_products WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectGroupProduct->execute(array(':id' => $id));
$rowGroupProduct = $selectGroupProduct->fetch();
$rowGroupProduct['post_type'] = "groupProduct";
$rowGroupProduct['images'] = @explode("|", $rowGroupProduct['image']);
$rowGroupProduct['image'] = $rowGroupProduct['images'][0];
if (!empty($rowGroupProduct['permalink']))
{
$rowGroupProduct['url'] = "/" . $rowGroupProduct['permalink'];
}
else
{
$rowGroupProduct['url'] = "/group-product/" . $rowGroupProduct['id'] . "/" . $this->safeUrl($rowGroupProduct['title']);
}
$rowGroupProduct['extraOptions'] = $this->getExtraOptions("groupProducts", $rowGroupProduct['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE group_products SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowGroupProduct;
}
//Is_Get_Wishes Function
public function is_get_wishes()
{
if (strtolower($_REQUEST['action']) == "wishes" && empty($_GET['id']))
{
return true;
}
}
//Get_Wishes Function
public function get_wishes($orderBy='sort ASC', $limit=0)
{
$get_wishes = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectWishes = $this->db->query("SELECT * FROM wishes WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowWishes = $selectWishes->fetch())
{
$rowWishes['images'] = @explode("|", $rowWishes['image']);
$rowWishes['image'] = $rowWishes['images'][0];
if (!empty($rowWishes['permalink']))
{
$rowWishes['url'] = "/" . $rowWishes['permalink'];
}
else
{
$rowWishes['url'] = "/wish/" . $rowWishes['id'] . "/" . $this->safeUrl($rowWishes['title']);
}
$get_wishes[] = $rowWishes;
}
return $get_wishes;
}
//Is_Wish Function
public function is_wish()
{
if (strtolower($_REQUEST['action']) == "wish" && !empty($_GET['id']))
{
return true;
}
}
//Wish Function
public function wish($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "wish" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->wish = array();
$selectWish = $this->db->prepare("SELECT * FROM wishes WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectWish->execute(array(':id' => $id));
$rowWish = $selectWish->fetch();
$rowWish['post_type'] = "wish";
$rowWish['images'] = explode("|", $rowWish['image']);
$rowWish['image'] = $rowWish['images'][0];
if (!empty($rowWish['permalink']))
{
$rowWish['url'] = "/" . $rowWish['permalink'];
}
else
{
$rowWish['url'] = "/wish/" . $rowWish['id'] . "/" . $this->safeUrl($rowWish['title']);
}
$rowWish['extraOptions'] = $this->getExtraOptions("wishes", $rowWish['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE wishes SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowWish;
}
//Is_Get_Pages Function
public function is_get_pages()
{
if (strtolower($_REQUEST['action']) == "pages" && empty($_GET['id']))
{
return true;
}
}
//Get_Pages Function
public function get_pages($orderBy='sort ASC', $limit=0)
{
$get_pages = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectPages = $this->db->query("SELECT * FROM pages WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowPages = $selectPages->fetch())
{
$rowPages['images'] = @explode("|", $rowPages['image']);
$rowPages['image'] = $rowPages['images'][0];
if (!empty($rowPages['permalink']))
{
$rowPages['url'] = "/" . $rowPages['permalink'];
}
else
{
$rowPages['url'] = "/page/" . $rowPages['id'] . "/" . $this->safeUrl($rowPages['title']);
}
$get_pages[] = $rowPages;
}
return $get_pages;
}
//Get_Pages_By_Category Function
public function get_pages_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_pages_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectPages = $this->db->query("SELECT * FROM pages WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowPages = $selectPages->fetch())
{
$rowPages['images'] = @explode("|", $rowPages['image']);
$rowPages['image'] = $rowPages['images'][0];
if (!empty($rowPages['permalink']))
{
$rowPages['url'] = "/" . $rowPages['permalink'];
}
else
{
$rowPages['url'] = "/page/" . $rowPages['id'] . "/" . $this->safeUrl($rowPages['title']);
}
$get_pages_by_category[] = $rowPages;
}
return $get_pages_by_category;
}
//Is_Page Function
public function is_page()
{
if (strtolower($_REQUEST['action']) == "page" && !empty($_GET['id']))
{
return true;
}
}
//Page Function
public function page($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "page" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->page = array();
$selectPage = $this->db->prepare("SELECT * FROM pages WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectPage->execute(array(':id' => $id));
$rowPage = $selectPage->fetch();
$rowPage['post_type'] = "page";
$rowPage['images'] = @explode("|", $rowPage['image']);
$rowPage['image'] = $rowPage['images'][0];
if (!empty($rowPage['permalink']))
{
$rowPage['url'] = "/" . $rowPage['permalink'];
}
else
{
$rowPage['url'] = "/page/" . $rowPage['id'] . "/" . $this->safeUrl($rowPage['title']);
}
$rowPage['extraOptions'] = $this->getExtraOptions("pages", $rowPage['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE pages SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowPage;
}
//Is_Get_Downloads Function
public function is_get_downloads()
{
if (strtolower($_REQUEST['action']) == "downloads" && empty($_GET['id']))
{
return true;
}
}
//Get_Downloads Function
public function get_downloads($orderBy='sort ASC', $limit=0)
{
$get_downloads = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectDownloads = $this->db->query("SELECT * FROM downloads WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowDownloads = $selectDownloads->fetch())
{
$rowDownloads['images'] = @explode("|", $rowDownloads['image']);
$rowDownloads['image'] = $rowDownloads['images'][0];
if (!empty($rowDownloads['permalink']))
{
$rowDownloads['url'] = "/" . $rowDownloads['permalink'];
}
else
{
$rowDownloads['url'] = "/download/" . $rowDownloads['id'] . "/" . $this->safeUrl($rowDownloads['title']);
}
$get_downloads[] = $rowDownloads;
}
return $get_downloads;
}
//Get_Downloads_By_Category Function
public function get_downloads_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_downloads_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectDownloads = $this->db->query("SELECT * FROM downloads WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowDownloads = $selectDownloads->fetch())
{
$rowDownloads['images'] = @explode("|", $rowDownloads['image']);
$rowDownloads['image'] = $rowDownloads['images'][0];
if (!empty($rowDownloads['permalink']))
{
$rowDownloads['url'] = "/" . $rowDownloads['permalink'];
}
else
{
$rowDownloads['url'] = "/download/" . $rowDownloads['id'] . "/" . $this->safeUrl($rowDownloads['title']);
}
$get_downloads_by_category[] = $rowDownloads;
}
return $get_downloads_by_category;
}
//Is_Download Function
public function is_download()
{
if (strtolower($_REQUEST['action']) == "download" && !empty($_GET['id']))
{
return true;
}
}
//Download Function
public function download($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "download" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->download = array();
$selectDownload = $this->db->prepare("SELECT * FROM downloads WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectDownload->execute(array(':id' => $id));
$rowDownload = $selectDownload->fetch();
$rowDownload['post_type'] = "download";
$rowDownload['images'] = @explode("|", $rowDownload['image']);
$rowDownload['image'] = $rowDownload['images'][0];
if (!empty($rowDownload['permalink']))
{
$rowDownload['url'] = "/" . $rowDownload['permalink'];
}
else
{
$rowDownload['url'] = "/download/" . $rowDownload['id'] . "/" . $this->safeUrl($rowDownload['title']);
}
$rowDownload['extraOptions'] = $this->getExtraOptions("downloads", $rowDownload['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE downloads SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowDownload;
}
//Is_Get_Offers Function
public function is_get_offers()
{
if (strtolower($_REQUEST['action']) == "offers" && empty($_GET['id']))
{
return true;
}
}
//Get_Offers Function
public function get_offers($orderBy='sort ASC', $limit=0)
{
$get_offers = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectOffers = $this->db->query("SELECT * FROM offers WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowOffers = $selectOffers->fetch())
{
$rowOffers['images'] = @explode("|", $rowOffers['image']);
$rowOffers['image'] = $rowOffers['images'][0];
if (!empty($rowOffers['permalink']))
{
$rowOffers['url'] = "/" . $rowOffers['permalink'];
}
else
{
$rowOffers['url'] = "/offer/" . $rowOffers['id'] . "/" . $this->safeUrl($rowOffers['title']);
}
$get_offers[] = $rowOffers;
}
return $get_offers;
}
//Get_Offers_By_Category Function
public function get_offers_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_offers_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectOffers = $this->db->query("SELECT * FROM offers WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowOffers = $selectOffers->fetch())
{
$rowOffers['images'] = @explode("|", $rowOffers['image']);
$rowOffers['image'] = $rowOffers['images'][0];
if (!empty($rowOffers['permalink']))
{
$rowOffers['url'] = "/" . $rowOffers['permalink'];
}
else
{
$rowOffers['url'] = "/offer/" . $rowOffers['id'] . "/" . $this->safeUrl($rowOffers['title']);
}
$get_offers_by_category[] = $rowOffers;
}
return $get_offers_by_category;
}
//Is_Offer Function
public function is_offer()
{
if (strtolower($_REQUEST['action']) == "offer" && !empty($_GET['id']))
{
return true;
}
}
//Offer Function
public function offer($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "offer" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->offer = array();
$selectOffer = $this->db->prepare("SELECT * FROM offers WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectOffer->execute(array(':id' => $id));
$rowOffer = $selectOffer->fetch();
$rowOffer['post_type'] = "offer";
$rowOffer['images'] = @explode("|", $rowOffer['image']);
$rowOffer['image'] = $rowOffer['images'][0];
if (!empty($rowOffer['permalink']))
{
$rowOffer['url'] = "/" . $rowOffer['permalink'];
}
else
{
$rowOffer['url'] = "/offer/" . $rowOffer['id'] . "/" . $this->safeUrl($rowOffer['title']);
}
$rowOffer['extraOptions'] = $this->getExtraOptions("offers", $rowOffer['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE offers SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowOffer;
}
//Is_Get_Authors Function
public function is_get_authors()
{
if (strtolower($_REQUEST['action']) == "authors" && empty($_GET['id']))
{
return true;
}
}
//Get_Authors Function
public function get_authors($orderBy='sort ASC', $limit=0)
{
$get_authors = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectAuthors = $this->db->query("SELECT * FROM authors WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowAuthors = $selectAuthors->fetch())
{
$rowAuthors['images'] = @explode("|", $rowAuthors['image']);
$rowAuthors['image'] = $rowAuthors['images'][0];
if (!empty($rowAuthors['permalink']))
{
$rowAuthors['url'] = "/" . $rowAuthors['permalink'];
}
else
{
$rowAuthors['url'] = "/author/" . $rowAuthors['id'] . "/" . $this->safeUrl($rowAuthors['title']);
}
$get_authors[] = $rowAuthors;
}
return $get_authors;
}
//Get_Authors_By_Category Function
public function get_authors_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_authors_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectAuthors = $this->db->query("SELECT * FROM authors WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowAuthors = $selectAuthors->fetch())
{
$rowAuthors['images'] = @explode("|", $rowAuthors['image']);
$rowAuthors['image'] = $rowAuthors['images'][0];
if (!empty($rowAuthors['permalink']))
{
$rowAuthors['url'] = "/" . $rowAuthors['permalink'];
}
else
{
$rowAuthors['url'] = "/author/" . $rowAuthors['id'] . "/" . $this->safeUrl($rowAuthors['title']);
}
$get_authors_by_category[] = $rowAuthors;
}
return $get_authors_by_category;
}
//Is_Author Function
public function is_author()
{
if (strtolower($_REQUEST['action']) == "author" && !empty($_GET['id']))
{
return true;
}
}
//Author Function
public function author($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "author" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->author = array();
$selectAuthor = $this->db->prepare("SELECT * FROM authors WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectAuthor->execute(array(':id' => $id));
$rowAuthor = $selectAuthor->fetch();
$rowAuthor['post_type'] = "author";
$rowAuthor['images'] = @explode("|", $rowAuthor['image']);
$rowAuthor['image'] = $rowAuthor['images'][0];
if (!empty($rowAuthor['permalink']))
{
$rowAuthor['url'] = "/" . $rowAuthor['permalink'];
}
else
{
$rowAuthor['url'] = "/author/" . $rowAuthor['id'] . "/" . $this->safeUrl($rowAuthor['title']);
}
$rowAuthor['extraOptions'] = $this->getExtraOptions("authors", $rowAuthor['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE authors SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowAuthor;
}
//Is_Get_Registerations Function
public function is_get_registerations()
{
if (strtolower($_REQUEST['action']) == "registerations" && empty($_GET['id']))
{
return true;
}
}
// Get_Registerations Function
public function get_registerations($orderBy='sort ASC', $limit=0)
{
$get_registerations = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectRegisterations = $this->db->query("
SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM registerations
WHERE
publishDate <= $this->now AND
active=1 AND
hidden=0 AND
siteID='$this->siteID'
$orderBy
$limitQuery
");
while ($rowRegisterations = $selectRegisterations->fetch())
{
$rowRegisterations['images'] = @explode("|", $rowRegisterations['image']);
$rowRegisterations['image'] = $rowRegisterations['images'][0];
if (!empty($rowRegisterations['permalink']))
{
$rowRegisterations['url'] = "/" . $rowRegisterations['permalink'];
}
else
{
$rowRegisterations['url'] = "/registeration/" . $rowRegisterations['id'] . "/" . $this->safeUrl($rowRegisterations['title']);
}
$get_registerations[] = $rowRegisterations;
}
return $get_registerations;
}
// Get_Registerations_By_Category Function
public function get_registerations_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_registerations_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectRegisterations = $this->db->query("
SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM registerations
WHERE
categoryID IN ($categories) AND
publishDate <= $this->now AND
active=1 AND
hidden=0 AND
siteID='$this->siteID'
$orderBy
$limitQuery
");
while ($rowRegisterations = $selectRegisterations->fetch())
{
$rowRegisterations['images'] = @explode("|", $rowRegisterations['image']);
$rowRegisterations['image'] = $rowRegisterations['images'][0];
if (!empty($rowRegisterations['permalink']))
{
$rowRegisterations['url'] = "/" . $rowRegisterations['permalink'];
}
else
{
$rowRegisterations['url'] = "/registeration/" . $rowRegisterations['id'] . "/" . $this->safeUrl($rowRegisterations['title']);
}
$get_registerations_by_category[] = $rowRegisterations;
}
return $get_registerations_by_category;
}
// Is_Registeration Function
public function is_registeration()
{
if (strtolower($_REQUEST['action']) == "registeration" && !empty($_GET['id']))
{
return true;
}
}
//Registeration Function
public function registeration($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "registeration" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->registeration = array();
$selectRegisteration = $this->db->prepare("
SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM registerations
WHERE
id=:id AND
publishDate <= $this->now AND
active=1 AND
siteID='$this->siteID'
");
$selectRegisteration->execute(array(':id' => $id));
$rowRegisteration = $selectRegisteration->fetch();
$rowRegisteration['post_type'] = "registeration";
$rowRegisteration['images'] = @explode("|", $rowRegisteration['image']);
$rowRegisteration['image'] = $rowRegisteration['images'][0];
if (!empty($rowRegisteration['permalink']))
{
$rowRegisteration['url'] = "/" . $rowRegisteration['permalink'];
}
else
{
$rowRegisteration['url'] = "/registeration/" . $rowRegisteration['id'] . "/" . $this->safeUrl($rowRegisteration['title']);
}
$rowRegisteration['extraOptions'] = $this->getExtraOptions("registerations", $rowRegisteration['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE registerations SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowRegisteration;
}
//Is_Get_Vips Function
public function is_get_vips()
{
if (strtolower($_REQUEST['action']) == "vips" && empty($_GET['id']))
{
return true;
}
}
//Get_Vips Function
public function get_vips($orderBy='sort ASC', $limit=0)
{
$get_vips = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectVips = $this->db->query("SELECT * FROM vips WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowVips = $selectVips->fetch())
{
$rowVips['images'] = @explode("|", $rowVips['image']);
$rowVips['image'] = $rowVips['images'][0];
if (!empty($rowVips['permalink']))
{
$rowVips['url'] = "/" . $rowVips['permalink'];
}
else
{
$rowVips['url'] = "/vip/" . $rowVips['id'] . "/" . $this->safeUrl($rowVips['title']);
}
$get_vips[] = $rowVips;
}
return $get_vips;
}
//Get_Vips_By_Category Function
public function get_vips_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_vips_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectVips = $this->db->query("SELECT * FROM vips WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowVips = $selectVips->fetch())
{
$rowVips['images'] = @explode("|", $rowVips['image']);
$rowVips['image'] = $rowVips['images'][0];
if (!empty($rowVips['permalink']))
{
$rowVips['url'] = "/" . $rowVips['permalink'];
}
else
{
$rowVips['url'] = "/vip/" . $rowVips['id'] . "/" . $this->safeUrl($rowVips['title']);
}
$get_vips_by_category[] = $rowVips;
}
return $get_vips_by_category;
}
//Is_Vip Function
public function is_vip()
{
if (strtolower($_REQUEST['action']) == "vip" && !empty($_GET['id']))
{
return true;
}
}
//Vip Function
public function vip($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "vip" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->vip = array();
$selectVip = $this->db->prepare("SELECT * FROM vips WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectVip->execute(array(':id' => $id));
$rowVip = $selectVip->fetch();
$rowVip['post_type'] = "vip";
$rowVip['images'] = @explode("|", $rowVip['image']);
$rowVip['image'] = $rowVip['images'][0];
if (!empty($rowVip['permalink']))
{
$rowVip['url'] = "/" . $rowVip['permalink'];
}
else
{
$rowVip['url'] = "/vip/" . $rowVip['id'] . "/" . $this->safeUrl($rowVip['title']);
}
$rowVip['extraOptions'] = $this->getExtraOptions("vips", $rowVip['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE vips SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowVip;
}
//Is_Get_Estates Function
public function is_get_estates()
{
if (strtolower($_REQUEST['action']) == "estates" && empty($_GET['id']))
{
return true;
}
}
//Get_Estates Function
public function get_estates($orderBy='sort ASC', $limit=0)
{
$get_estates = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectEstates = $this->db->query("SELECT * FROM estates WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowEstates = $selectEstates->fetch())
{
$rowEstates['images'] = @explode("|", $rowEstates['image']);
$rowEstates['image'] = $rowEstates['images'][0];
if (!empty($rowEstates['permalink']))
{
$rowEstates['url'] = "/" . $rowEstates['permalink'];
}
else
{
$rowEstates['url'] = "/estate/" . $rowEstates['id'] . "/" . $this->safeUrl($rowEstates['title']);
}
$get_estates[] = $rowEstates;
}
return $get_estates;
}
//Get_Estates_By_Category Function
public function get_estates_by_category($category, $orderBy='sort ASC', $limit=0)
{
$get_estates_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$availableCategories = array("آپارتمان - مسکونی", "آپارتمان - اداری", "آپارتمان - اداری - مسکونی", "برج", "برج باغ", "دفتر کار-اداری", "دفتر کار-تجاری", "مغازه", "خانه ویلایی", "خانه کلنگی", "مستغلات", "زمین مسکونی", "زمین صنعتی", "زمین کشاورزی", "مرغداری و دامداری", "باغ", "کارگاه", "کارخانه", "انبار", "استخر پرورش ماهی", "پمپ بنزین", "کافی شاپ و رستوران", "سوله", "معدن");
if (in_array($category, $availableCategories))
{
$selectEstates = $this->db->query("SELECT * FROM estates WHERE category=$category AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowEstates = $selectEstates->fetch())
{
$rowEstates['images'] = @explode("|", $rowEstates['image']);
$rowEstates['image'] = $rowEstates['images'][0];
if (!empty($rowEstates['permalink']))
{
$rowEstates['url'] = "/" . $rowEstates['permalink'];
}
else
{
$rowEstates['url'] = "/estate/" . $rowEstates['id'] . "/" . $this->safeUrl($rowEstates['title']);
}
$get_estates_by_category[] = $rowEstates;
}
}
return $get_estates_by_category;
}
//Is_Estate Function
public function is_estate()
{
if (strtolower($_REQUEST['action']) == "estate" && !empty($_GET['id']))
{
return true;
}
}
//Estate Function
public function estate($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "estate" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->estate = array();
$selectEstate = $this->db->prepare("SELECT * FROM estates WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectEstate->execute(array(':id' => $id));
$rowEstate = $selectEstate->fetch();
$rowEstate['post_type'] = "estate";
$rowEstate['images'] = @explode("|", $rowEstate['image']);
$rowEstate['image'] = $rowEstate['images'][0];
if (!empty($rowEstate['permalink']))
{
$rowEstate['url'] = "/" . $rowEstate['permalink'];
}
else
{
$rowEstate['url'] = "/estate/" . $rowEstate['id'] . "/" . $this->safeUrl($rowEstate['title']);
}
$rowEstate['extraOptions'] = $this->getExtraOptions("estates", $rowEstate['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE estates SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowEstate;
}
//Is_Get_Courses Function
public function is_get_courses()
{
if (strtolower($_REQUEST['action']) == "courses" && empty($_GET['id']))
{
return true;
}
}
//Get_Courses Function
public function get_courses($orderBy='sort ASC', $limit=0)
{
$get_courses = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectCourses = $this->db->query("
SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM courses
WHERE
publishDate <= $this->now AND
active=1 AND
hidden=0 AND
siteID='$this->siteID'
$orderBy
$limitQuery
");
while ($rowCourses = $selectCourses->fetch())
{
$rowCourses['images'] = @explode("|", $rowCourses['image']);
$rowCourses['image'] = $rowCourses['images'][0];
if (!empty($rowCourses['permalink']))
{
$rowCourses['url'] = "/" . $rowCourses['permalink'];
}
else
{
$rowCourses['url'] = "/course/" . $rowCourses['id'] . "/" . $this->safeUrl($rowCourses['title']);
}
$get_courses[] = $rowCourses;
}
return $get_courses;
}
//Get_Courses_By_Category Function
public function get_courses_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_courses_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectCourses = $this->db->query("
SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM courses
WHERE
categoryID IN ($categories) AND
publishDate <= $this->now AND
active=1 AND
hidden=0 AND
siteID='$this->siteID'
$orderBy
$limitQuery
");
while ($rowCourses = $selectCourses->fetch())
{
$rowCourses['images'] = @explode("|", $rowCourses['image']);
$rowCourses['image'] = $rowCourses['images'][0];
if (!empty($rowCourses['permalink']))
{
$rowCourses['url'] = "/" . $rowCourses['permalink'];
}
else
{
$rowCourses['url'] = "/course/" . $rowCourses['id'] . "/" . $this->safeUrl($rowCourses['title']);
}
$get_courses_by_category[] = $rowCourses;
}
return $get_courses_by_category;
}
//Is_Course Function
public function is_course()
{
if (strtolower($_REQUEST['action']) == "course" && !empty($_GET['id']))
{
return true;
}
}
//Course Function
public function course($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "course" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->course = array();
$selectCourse = $this->db->prepare("
SELECT *,
(CASE
WHEN (IFNULL(auctionStatus, 0)=1 AND auctionStartDate <= '$this->now' AND auctionExpireDate >= '$this->now') THEN auctionPrice
WHEN (IFNULL(auctionStatus, 0)!=1 OR auctionStartDate > '$this->now' OR auctionExpireDate < '$this->now') THEN price
END) AS realPrice
FROM courses
WHERE
id=:id AND
publishDate <= $this->now AND
active=1 AND
siteID='$this->siteID'
");
$selectCourse->execute(array(':id' => $id));
$rowCourse = $selectCourse->fetch();
$rowCourse['post_type'] = "course";
$rowCourse['images'] = @explode("|", $rowCourse['image']);
$rowCourse['image'] = $rowCourse['images'][0];
if (!empty($rowCourse['permalink']))
{
$rowCourse['url'] = "/" . $rowCourse['permalink'];
}
else
{
$rowCourse['url'] = "/course/" . $rowCourse['id'] . "/" . $this->safeUrl($rowCourse['title']);
}
$rowCourse['extraOptions'] = $this->getExtraOptions("courses", $rowCourse['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE courses SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowCourse;
}
//Get_Sessions_By_CourseID Function
public function get_sessions_by_courseID($courseID)
{
$get_sessions_by_courseID = array();
$courseID = intval($courseID);
$selectSessions = $this->db->query("SELECT * FROM sessions WHERE courseID=$courseID AND siteID='$this->siteID' ORDER BY `interval` ASC");
while ($rowSessions = $selectSessions->fetch())
{
$rowSessions['images'] = @explode("|", $rowSessions['image']);
$rowSessions['image'] = $rowSessions['images'][0];
if (!empty($rowSessions['permalink']))
{
$rowSessions['url'] = "/" . $rowSessions['permalink'];
}
else
{
$rowSessions['url'] = "/session/" . $rowSessions['id'] . "/" . $this->safeUrl($rowSessions['title']);
}
$get_sessions_by_courseID[] = $rowSessions;
}
return $get_sessions_by_courseID;
}
//Is_Session Function
public function is_session()
{
if (strtolower($_REQUEST['action']) == "session" && !empty($_GET['id']))
{
return true;
}
}
//Session Function
public function session($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "session" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->session = array();
$selectSession = $this->db->prepare("SELECT * FROM sessions WHERE id=:id AND siteID='$this->siteID'");
$selectSession->execute(array(':id' => $id));
$rowSession = $selectSession->fetch();
$rowSession['post_type'] = "session";
$rowSession['images'] = @explode("|", $rowSession['image']);
$rowSession['image'] = $rowSession['images'][0];
if (!empty($rowSession['permalink']))
{
$rowSession['url'] = "/" . $rowSession['permalink'];
}
else
{
$rowSession['url'] = "/session/" . $rowSession['id'] . "/" . $this->safeUrl($rowSession['title']);
}
$rowSession['extraOptions'] = $this->getExtraOptions("sessions", $rowSession['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE sessions SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowSession;
}
//Is_Get_Lessons Function
public function is_get_lessons()
{
if (strtolower($_REQUEST['action']) == "lessons" && empty($_GET['id']))
{
return true;
}
}
//Get_Lessons Function
public function get_lessons($orderBy='sort ASC', $limit=0)
{
$get_lessons = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectLessons = $this->db->query("SELECT * FROM lessons WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowLessons = $selectLessons->fetch())
{
$rowLessons['images'] = @explode("|", $rowLessons['image']);
$rowLessons['image'] = $rowLessons['images'][0];
if (!empty($rowLessons['permalink']))
{
$rowLessons['url'] = "/" . $rowLessons['permalink'];
}
else
{
$rowLessons['url'] = "/lesson/" . $rowLessons['id'] . "/" . $this->safeUrl($rowLessons['title']);
}
$get_lessons[] = $rowLessons;
}
return $get_lessons;
}
//Get_Lessons_By_Category Function
public function get_lessons_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_lessons_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectLessons = $this->db->query("SELECT * FROM lessons WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowLessons = $selectLessons->fetch())
{
$rowLessons['images'] = @explode("|", $rowLessons['image']);
$rowLessons['image'] = $rowLessons['images'][0];
if (!empty($rowLessons['permalink']))
{
$rowLessons['url'] = "/" . $rowLessons['permalink'];
}
else
{
$rowLessons['url'] = "/lesson/" . $rowLessons['id'] . "/" . $this->safeUrl($rowLessons['title']);
}
$get_lessons_by_category[] = $rowLessons;
}
return $get_lessons_by_category;
}
//Is_Lesson Function
public function is_lesson()
{
if (strtolower($_REQUEST['action']) == "lesson" && !empty($_GET['id']))
{
return true;
}
}
//Lesson Function
public function lesson($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "lesson" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->lesson = array();
$selectLesson = $this->db->prepare("SELECT * FROM lessons WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectLesson->execute(array(':id' => $id));
$rowLesson = $selectLesson->fetch();
$rowLesson['post_type'] = "lesson";
$rowLesson['images'] = @explode("|", $rowLesson['image']);
$rowLesson['image'] = $rowLesson['images'][0];
if (!empty($rowLesson['permalink']))
{
$rowLesson['url'] = "/" . $rowLesson['permalink'];
}
else
{
$rowLesson['url'] = "/lesson/" . $rowLesson['id'] . "/" . $this->safeUrl($rowLesson['title']);
}
$rowLesson['extraOptions'] = $this->getExtraOptions("lessons", $rowLesson['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE lessons SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowLesson;
}
//Get_LessonEpisodes_By_LessonID Function
public function get_lessonEpisodes_by_lessonID($lessonID)
{
$get_lessonEpisodes_by_lessonID = array();
$lessonID = intval($lessonID);
$selectLessonEpisodes = $this->db->query("SELECT * FROM lesson_episodes WHERE lessonID=$lessonID AND siteID='$this->siteID' ORDER BY `interval` ASC");
while ($rowLessonEpisodes = $selectLessonEpisodes->fetch())
{
$rowLessonEpisodes['images'] = @explode("|", $rowLessonEpisodes['image']);
$rowLessonEpisodes['image'] = $rowLessonEpisodes['images'][0];
if (!empty($rowLessonEpisodes['permalink']))
{
$rowLessonEpisodes['url'] = "/" . $rowLessonEpisodes['permalink'];
}
else
{
$rowLessonEpisodes['url'] = "/episode/" . $rowLessonEpisodes['id'] . "/" . $this->safeUrl($rowLessonEpisodes['title']);
}
$get_lessonEpisodes_by_lessonID[] = $rowLessonEpisodes;
}
return $get_lessonEpisodes_by_lessonID;
}
//Is_LessonEpisode Function
public function is_lessonEpisode()
{
if (strtolower($_REQUEST['action']) == "lessonepisode" && !empty($_GET['id']))
{
return true;
}
}
//LessonEpisode Function
public function lessonEpisode($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "lessonepisode" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->lessonEpisode = array();
$selectLessonEpisode = $this->db->prepare("SELECT * FROM lesson_episodes WHERE id=:id AND siteID='$this->siteID'");
$selectLessonEpisode->execute(array(':id' => $id));
$rowLessonEpisode = $selectLessonEpisode->fetch();
$rowLessonEpisode['post_type'] = "lessonEpisode";
$rowLessonEpisode['images'] = @explode("|", $rowLessonEpisode['image']);
$rowLessonEpisode['image'] = $rowLessonEpisode['images'][0];
if (!empty($rowLessonEpisode['permalink']))
{
$rowLessonEpisode['url'] = "/" . $rowLessonEpisode['permalink'];
}
else
{
$rowLessonEpisode['url'] = "/episode/" . $rowLessonEpisode['id'] . "/" . $this->safeUrl($rowLessonEpisode['title']);
}
$rowLessonEpisode['extraOptions'] = $this->getExtraOptions("lessonEpisodes", $rowLessonEpisode['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE lesson_episodes SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowLessonEpisode;
}
//Is_Get_Galleries Function
public function is_get_galleries()
{
if (strtolower($_REQUEST['action']) == "galleries" && empty($_GET['id']))
{
return true;
}
}
//Get_Galleries Function
public function get_galleries($orderBy='sort ASC', $limit=0)
{
$galleries = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectGalleries = $this->db->query("SELECT * FROM galleries WHERE publishDate <= $this->now AND active=1 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowGalleries = $selectGalleries->fetch())
{
$rowGalleries['images'] = @explode("|", $rowGalleries['image']);
$rowGalleries['image'] = $rowGalleries['images'][0];
if (!empty($rowGalleries['permalink']))
{
$rowGalleries['url'] = "/" . $rowGalleries['permalink'];
}
else
{
$rowGalleries['url'] = "/gallery/" . $rowGalleries['id'] . "/" . $this->safeUrl($rowGalleries['title']);
}
$images = array();
$selectGalleryImages = $this->db->prepare("SELECT * FROM gallery_images WHERE galleryID=:galleryID AND active=1 AND siteID='$this->siteID' ORDER BY sort ASC $limitQuery");
$selectGalleryImages->execute(array(':galleryID' => $rowGalleries['id']));
while ($rowGalleryImages = $selectGalleryImages->fetch())
{
array_push($images, array('id' => $rowGalleryImages['id'], 'title' => $rowGalleryImages['title'], 'image' => $rowGalleryImages['image'], 'description' => $rowGalleryImages['description'], 'option1' => $rowGalleryImages['option1'], 'option2' => $rowGalleryImages['option2'], 'option3' => $rowGalleryImages['option3'], 'option4' => $rowGalleryImages['option4'], 'option5' => $rowGalleryImages['option5'], 'option6' => $rowGalleryImages['option6'], 'option7' => $rowGalleryImages['option7'], 'option8' => $rowGalleryImages['option8']));
}
$rowGalleries['images'] = $images;
$galleries[] = $rowGalleries;
}
return $galleries;
}
//Get_Galleries_By_Category Function
public function get_galleries_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_galleries_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectGalleries = $this->db->query("SELECT * FROM galleries WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowGalleries = $selectGalleries->fetch())
{
$rowGalleries['images'] = @explode("|", $rowGalleries['image']);
$rowGalleries['image'] = $rowGalleries['images'][0];
if (!empty($rowGalleries['permalink']))
{
$rowGalleries['url'] = "/" . $rowGalleries['permalink'];
}
else
{
$rowGalleries['url'] = "/gallery/" . $rowGalleries['id'] . "/" . $this->safeUrl($rowGalleries['title']);
}
$get_galleries_by_category[] = $rowGalleries;
}
return $get_galleries_by_category;
}
//Is_Gallery Function
public function is_gallery()
{
if (strtolower($_REQUEST['action']) == "gallery" && !empty($_GET['id']))
{
return true;
}
}
//Gallery Function
public function gallery($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "gallery" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->gallery = array();
$selectGallery = $this->db->prepare("SELECT * FROM galleries WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectGallery->execute(array(':id' => $id));
$rowGallery = $selectGallery->fetch();
$rowGallery['post_type'] = "gallery";
$rowGallery['images'] = @explode("|", $rowGallery['image']);
$rowGallery['image'] = $rowGallery['images'][0];
if (!empty($rowGallery['permalink']))
{
$rowGallery['url'] = "/" . $rowGallery['permalink'];
}
else
{
$rowGallery['url'] = "/gallery/" . $rowGallery['id'] . "/" . $this->safeUrl($rowGallery['title']);
}
$images = array();
$selectGalleryImages = $this->db->prepare("SELECT * FROM gallery_images WHERE galleryID=:galleryID AND active=1 AND siteID='$this->siteID' ORDER BY sort ASC");
$selectGalleryImages->execute(array(':galleryID' => $id));
while ($rowGalleryImages = $selectGalleryImages->fetch())
{
$rowGalleryImages['extraOptions'] = $this->getExtraOptions("galleryImages", $rowGalleryImages['id']);
array_push($images, array('id' => $rowGalleryImages['id'], 'title' => $rowGalleryImages['title'], 'image' => $rowGalleryImages['image'], 'description' => $rowGalleryImages['description'], 'option1' => $rowGalleryImages['option1'], 'option2' => $rowGalleryImages['option2'], 'option3' => $rowGalleryImages['option3'], 'option4' => $rowGalleryImages['option4'], 'option5' => $rowGalleryImages['option5'], 'option6' => $rowGalleryImages['option6'], 'option7' => $rowGalleryImages['option7'], 'option8' => $rowGalleryImages['option8'], 'extraOptions' => $rowGalleryImages['extraOptions']));
}
$rowGallery['images'] = $images;
$rowGallery['extraOptions'] = $this->getExtraOptions("galleries", $rowGallery['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE galleries SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowGallery;
}
//Get_Gallery_Images Function
public function get_gallery_images($galleryID, $orderBy='sort ASC', $limit=0, $offset=0)
{
$gallery_images = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
if (intval($offset) > 0)
{
$offsetQuery = "OFFSET " . $offset;
}
else
{
$offsetQuery = "";
}
}
else
{
$limitQuery = "";
}
if (!empty($galleryID))
{
$gallery_images = array();
$selectGalleryImages = $this->db->prepare("SELECT * FROM gallery_images WHERE galleryID=:galleryID AND active=1 AND siteID='$this->siteID' $orderBy $limitQuery $offsetQuery");
$selectGalleryImages->execute(array(':galleryID' => $galleryID));
$gallery_images = $selectGalleryImages->fetchAll();
}
return $gallery_images;
}
//Is_Get_Audios Function
public function is_get_audios()
{
if (strtolower($_REQUEST['action']) == "audios" && empty($_GET['id']))
{
return true;
}
}
//Get_Audios Function
public function get_audios($orderBy='sort ASC', $limit=0)
{
$audios = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectAudios = $this->db->query("SELECT * FROM audios WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowAudios = $selectAudios->fetch())
{
$rowAudios['images'] = @explode("|", $rowAudios['image']);
$rowAudios['image'] = $rowAudios['images'][0];
if (!empty($rowAudios['permalink']))
{
$rowAudios['url'] = "/" . $rowAudios['permalink'];
}
else
{
$rowAudios['url'] = "/audio/" . $rowAudios['id'] . "/" . $this->safeUrl($rowAudios['title']);
}
$audios[] = $rowAudios;
}
return $audios;
}
//Get_Audios_By_Category Function
public function get_audios_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_audios_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectAudios = $this->db->query("SELECT * FROM audios WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowAudios = $selectAudios->fetch())
{
$rowAudios['images'] = @explode("|", $rowAudios['image']);
$rowAudios['image'] = $rowAudios['images'][0];
if (!empty($rowAudios['permalink']))
{
$rowAudios['url'] = "/" . $rowAudios['permalink'];
}
else
{
$rowAudios['url'] = "/audio/" . $rowAudios['id'] . "/" . $this->safeUrl($rowAudios['title']);
}
$get_audios_by_category[] = $rowAudios;
}
return $get_audios_by_category;
}
//Is_Audio Function
public function is_audio()
{
if (strtolower($_REQUEST['action']) == "audio" && !empty($_GET['id']))
{
return true;
}
}
//Audio Function
public function audio($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "audio" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->audio = array();
$selectAudio = $this->db->prepare("SELECT * FROM audios WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectAudio->execute(array(':id' => $id));
$rowAudio = $selectAudio->fetch();
$rowAudio['post_type'] = "audio";
$rowAudio['images'] = @explode("|", $rowAudio['image']);
$rowAudio['image'] = $rowAudio['images'][0];
if (!empty($rowAudio['permalink']))
{
$rowAudio['url'] = "/" . $rowAudio['permalink'];
}
else
{
$rowAudio['url'] = "/audio/" . $rowAudio['id'] . "/" . $this->safeUrl($rowAudio['title']);
}
$rowAudio['extraOptions'] = $this->getExtraOptions("audios", $rowAudio['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE audios SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowAudio;
}
//Is_Get_Videos Function
public function is_get_videos()
{
if (strtolower($_REQUEST['action']) == "videos" && empty($_GET['id']))
{
return true;
}
}
//Get_Videos Function
public function get_videos($orderBy='sort ASC', $limit=0)
{
$videos = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectVideos = $this->db->query("SELECT * FROM videos WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowVideos = $selectVideos->fetch())
{
$rowVideos['images'] = @explode("|", $rowVideos['image']);
$rowVideos['image'] = $rowVideos['images'][0];
if (!empty($rowVideos['permalink']))
{
$rowVideos['url'] = "/" . $rowVideos['permalink'];
}
else
{
$rowVideos['url'] = "/video/" . $rowVideos['id'] . "/" . $this->safeUrl($rowVideos['title']);
}
$videos[] = $rowVideos;
}
return $videos;
}
//Get_Videos_By_Category Function
public function get_videos_by_category($category, $orderBy='sort ASC', $limit=0)
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_videos_by_category = array();
$orderBy = $this->orderBy($orderBy);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
$selectVideos = $this->db->query("SELECT * FROM videos WHERE categoryID IN ($categories) AND publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $orderBy $limitQuery");
while ($rowVideos = $selectVideos->fetch())
{
$rowVideos['images'] = @explode("|", $rowVideos['image']);
$rowVideos['image'] = $rowVideos['images'][0];
if (!empty($rowVideos['permalink']))
{
$rowVideos['url'] = "/" . $rowVideos['permalink'];
}
else
{
$rowVideos['url'] = "/video/" . $rowVideos['id'] . "/" . $this->safeUrl($rowVideos['title']);
}
$get_videos_by_category[] = $rowVideos;
}
return $get_videos_by_category;
}
//Is_Video Function
public function is_video()
{
if (strtolower($_REQUEST['action']) == "video" && !empty($_GET['id']))
{
return true;
}
}
//Video Function
public function video($countVisits=0)
{
if (strtolower($_REQUEST['action']) == "video" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->video = array();
$selectVideo = $this->db->prepare("SELECT * FROM videos WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectVideo->execute(array(':id' => $id));
$rowVideo = $selectVideo->fetch();
$rowVideo['post_type'] = "video";
$rowVideo['images'] = @explode("|", $rowVideo['image']);
$rowVideo['image'] = $rowVideo['images'][0];
if (!empty($rowVideo['permalink']))
{
$rowVideo['url'] = "/" . $rowVideo['permalink'];
}
else
{
$rowVideo['url'] = "/video/" . $rowVideo['id'] . "/" . $this->safeUrl($rowVideo['title']);
}
$rowVideo['extraOptions'] = $this->getExtraOptions("videos", $rowVideo['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE videos SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowVideo;
}
//Is_Forum Function
public function is_forum()
{
if (strtolower($_REQUEST['action']) == "forum" && !empty($_GET['id']))
{
return true;
}
}
//Forum Function
public function forum()
{
if (strtolower($_REQUEST['action']) == "forum" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$this->forum = array();
$selectForum = $this->db->prepare("SELECT * FROM categories WHERE id=:id AND section='forum' AND siteID='$this->siteID'");
$selectForum->execute(array(':id' => $id));
$rowForum = $selectForum->fetch();
if (!empty($rowForum['permalink']))
{
$rowForum['url'] = "/" . $rowForum['permalink'];
}
else
{
$rowForum['url'] = "/forum/" . $rowForum['id'] . "/" . $this->safeUrl($rowForum['title']);
}
}
return $rowForum;
}
//Get_Forums Function
public function get_forums($orderMode='ASC')
{
$get_forums = array();
if (strtolower($orderMode) == "asc")
{
$orderMode = "ASC";
}
elseif (strtolower($orderMode) == "desc")
{
$orderMode = "DESC";
}
else
{
$orderMode = "DESC";
}
$selectCategories = $this->db->query("SELECT * FROM categories WHERE parentID=0 AND section='forum' AND siteID='$this->siteID' ORDER BY sort $orderMode");
while ($rowCategories = $selectCategories->fetch())
{
if (!empty($rowCategories['permalink']))
{
$rowCategories['url'] = "/" . $rowCategories['permalink'];
}
else
{
$rowCategories['url'] = "/forum/" . $rowCategories['id'] . "/" . $this->safeUrl($rowCategories['title']);
}
$subCategories = array();
$selectSubCategories = $this->db->query("SELECT * FROM categories WHERE parentID=$rowCategories[id] AND section='forum' AND siteID='$this->siteID' ORDER BY sort $orderMode");
while ($rowSubCategories = $selectSubCategories->fetch())
{
if (!empty($rowSubCategories['permalink']))
{
$subUrl = "/" . $rowSubCategories['permalink'];
}
else
{
$subUrl = "/forum/" . $rowSubCategories['id'] . "/" . $this->safeUrl($rowSubCategories['title']);
}
array_push($subCategories, array('id' => $rowSubCategories['id'], 'title' => $rowSubCategories['title'], 'permalink' => $rowSubCategories['permalink'], 'image' => $rowSubCategories['image'], 'parentID' => $rowSubCategories['parentID'], 'parentName' => $rowSubCategories['parentName'], 'section' => $rowSubCategories['section'], 'url' => $subUrl));
}
$rowCategories['subCategories'] = $subCategories;
$get_forums[] = $rowCategories;
}
return $get_forums;
}
//savePost
public function save_post()
{
if (!empty($_SESSION['userID']) && !empty($_REQUEST['post']))
{
$insert = $this->db->prepare("INSERT INTO topics (siteID,userID,title,post,topicID,categoryID,categoryName,date,open) VALUES ('$this->siteID', :userID, :title, :post, :topicID, :categoryID, :categoryName, :date, 1)");
$userID = intval($_SESSION['userID']);
if (!empty($_REQUEST['title']))
{
$title = $_REQUEST['title'];
}
else
{
$title = '';
}
$post = $_REQUEST['post'];
$topicID = intval($_REQUEST['topicID']);
if (intval($_REQUEST['categoryID']) != 0)
{
$categoryID = intval($_REQUEST['categoryID']);
}
elseif ($this->is_forum())
{
$forum = $this->forum();
if (intval($forum['id']) != 0)
{
$categoryID = intval($forum['id']);
}
}
elseif ($this->is_topic())
{
$topic = $this->topic();
if (intval($topic['categoryID']) != 0)
{
$categoryID = intval($topic['categoryID']);
}
}
$categoryID = intval($categoryID);
$selectCategory = $this->db->query("SELECT title FROM categories WHERE id=$categoryID AND section='forum' AND siteID='$this->siteID'");
if ($selectCategory->rowCount() != 0)
{
$rowCategory = $selectCategory->fetch();
$categoryName = $rowCategory['title'];
$insert->execute(array(':userID'=>$userID, ':title'=>$title, ':post'=>$post, ':topicID'=>$topicID, ':categoryID'=>$categoryID, ':categoryName'=>$categoryName, ':date'=>time()));
return true;
}
else
{
$this->error = "شناسه دسته اشتباه است";
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = "لطفا فیلد های الزامی را کامل پر نمائید";
$this->errorType = 'error';
return false;
}
}
//editPost
public function edit_post()
{
if (!empty($_SESSION['userID']) && !empty($_REQUEST['post']) && !empty($_POST['editID']))
{
$editID = intval($_POST['editID']);
$userID = intval($_SESSION['userID']);
$selectPost = $this->db->query("SELECT * FROM topics WHERE id=$editID AND userID=$userID AND siteID='$this->siteID'");
if ($selectPost->rowCount() != 0)
{
$post = $_REQUEST['post'];
$update = $this->db->prepare("UPDATE topics SET `post`=:post WHERE id=$editID AND siteID='$this->siteID'");
$update->execute(array(':post'=>$post));
return true;
}
else
{
$this->error = "لطفا فیلد های الزامی را کامل پر نمائید";
$this->errorType = 'error';
return false;
}
}
else
{
$this->error = "شما قادر به ویرایش این پست نیستید";
$this->errorType = 'error';
return false;
}
}
//Is_Topic Function
public function is_topic()
{
if (strtolower($_REQUEST['action']) == "topic" && !empty($_GET['id']))
{
return true;
}
}
//Get_Latest_Topics Function
public function get_latest_topics($limit=0, $orderMode='date DESC', $search_keyword="")
{
$orderBy = $this->orderBy($orderMode);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
if (!empty($search_keyword))
{
$searchQuery = "AND (title LIKE :title OR post LIKE :post)";
$executeArray = array(":title"=>"%".$search_keyword."%", ":post"=>"%".$search_keyword."%");
}
else
{
$searchQuery = "";
$executeArray = array();
}
$selectTopics = $this->db->prepare("SELECT * FROM topics WHERE topicID=0 AND siteID='$this->siteID' $searchQuery $orderBy $limitQuery");
$selectTopics->execute($executeArray);
while ($rowTopics = $selectTopics->fetch())
{
$rowTopics['url'] = "/topic/" . $rowTopics['id'] . "/" . $this->safeUrl($rowTopics['title']);
$get_topics_by_category[] = $rowTopics;
}
return $get_topics_by_category;
}
//Get_Topics_By_Category Function
public function get_topics_by_category($category, $limit=0, $orderMode='date DESC', $search_keyword="")
{
$this->subCategories = Array();
$categories = implode(",", $this->get_sub_categories($category));
$get_topics_by_category = array();
$orderBy = $this->orderBy($orderMode);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
if (!empty($search_keyword))
{
$searchQuery = "AND (title LIKE :title OR post LIKE :post)";
$executeArray = array(":title"=>"%".$search_keyword."%", ":post"=>"%".$search_keyword."%");
}
else
{
$searchQuery = "";
$executeArray = array();
}
$selectTopics = $this->db->prepare("SELECT * FROM topics WHERE categoryID IN ($categories) AND topicID=0 AND siteID='$this->siteID' $searchQuery $orderBy $limitQuery");
$selectTopics->execute($executeArray);
while ($rowTopics = $selectTopics->fetch())
{
$rowTopics['url'] = "/topic/" . $rowTopics['id'] . "/" . $this->safeUrl($rowTopics['title']);
$get_topics_by_category[] = $rowTopics;
}
return $get_topics_by_category;
}
//Get_Topics_By_Category Function
public function get_topics_by_userID($userID, $limit=0, $orderMode='date DESC', $search_keyword="")
{
$userID = intval($userID);
$get_topics_by_userID = array();
$orderBy = $this->orderBy($orderMode);
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
if (!empty($search_keyword))
{
$searchQuery = "AND (title LIKE :title OR post LIKE :post)";
$executeArray = array(":title"=>"%".$search_keyword."%", ":post"=>"%".$search_keyword."%");
}
else
{
$searchQuery = "";
$executeArray = array();
}
//Select Topics
$selectTopics = $this->db->prepare("SELECT * FROM topics WHERE userID=$userID AND topicID=0 AND siteID='$this->siteID' $searchQuery $orderBy $limitQuery");
$selectTopics->execute($executeArray);
while ($rowTopics = $selectTopics->fetch())
{
$rowTopics['url'] = "/topic/" . $rowTopics['id'] . "/" . $this->safeUrl($rowTopics['title']);
$get_topics_by_category[] = $rowTopics;
}
//Select Answered Topics
$selectTopics = $this->db->prepare("SELECT mainTopic.* FROM topics AS mainTopic JOIN topics AS answerTopic ON mainTopic.id=answerTopic.topicID WHERE answerTopic.userID=$userID AND answerTopic.topicID!=0 AND mainTopic.siteID='$this->siteID' $searchQuery GROUP BY mainTopic.id $orderBy $limitQuery");
$selectTopics->execute($executeArray);
while ($rowTopics = $selectTopics->fetch())
{
$rowTopics['url'] = "/topic/" . $rowTopics['id'] . "/" . $this->safeUrl($rowTopics['title']);
$get_topics_by_category[] = $rowTopics;
}
return $get_topics_by_category;
}
//Topic Function
public function topic($ID=null)
{
if (empty($ID))
{
$ID = intval($_GET['id']);
}
if (!empty($ID))
{
if (strtolower($_REQUEST['action']) == "topic")
{
$this->topic = array();
$selectTopic = $this->db->prepare("SELECT *, topics.id AS id, topics.date AS date, users.date AS userRegisterDate FROM topics JOIN users ON topics.userID=users.id WHERE topics.id=:id AND topics.siteID='$this->siteID'");
$selectTopic->execute(array(':id' => $ID));
if ($selectTopic->rowCount() != 0)
{
$rowTopic = $selectTopic->fetch();
$rowTopic['url'] = "/topic/" . $rowTopic['id'] . "/" . $this->safeUrl($rowTopic['title']);
$answers = array();
$selectAnswers = $this->db->query("SELECT *, topics.id AS id, topics.date AS date, users.date AS userRegisterDate FROM topics JOIN users ON topics.userID=users.id WHERE topics.topicID=$rowTopic[id] AND topics.siteID='$this->siteID' ORDER BY topics.date ASC");
while ($rowAnswers = $selectAnswers->fetch())
{
$postCount = $this->db->query("SELECT id FROM topics WHERE userID=$rowAnswers[userID] AND siteID='$this->siteID'")->rowCount();
array_push($answers, array('id' => $rowAnswers['id'], 'userID' => $rowAnswers['userID'], 'username' => $rowAnswers['username'], 'firstname' => $rowAnswers['firstname'], 'lastname' => $rowAnswers['lastname'], 'title' => $rowAnswers['title'], 'post' => $rowAnswers['post'], 'topicID' => $rowAnswers['topicID'], 'categoryID' => $rowAnswers['categoryID'], 'categoryName' => $rowAnswers['categoryName'], 'date' => $rowAnswers['date'], 'userRegisterDate' => $rowAnswers['userRegisterDate'], 'image' => $rowAnswers['image'], 'active' => $rowAnswers['active'], 'upvote' => $rowAnswers['upvote'], 'downvote' => $rowAnswers['downvote'], 'illegal' => $rowAnswers['illegal'], 'postCount' => $postCount));
}
$rowTopic['postCount'] = $this->db->query("SELECT id FROM topics WHERE userID=$rowTopic[userID] AND siteID='$this->siteID'")->rowCount();
$rowTopic['answers'] = $answers;
$updateVisits = $this->db->prepare("UPDATE topics SET visits=visits+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $rowTopic['id']));
}
}
return $rowTopic;
}
}
//Is_Form Function
public function is_form()
{
if (strtolower($_REQUEST['action']) == "form" && !empty($_GET['id']))
{
return true;
}
}
//Form Function
public function form()
{
if (!empty($_POST))
{
//Select Form
$id = intval($_GET['id']);
$selectForm = $this->db->prepare("SELECT * FROM forms WHERE id=:id AND active=1 AND siteID='$this->siteID'");
$selectForm->execute(array(':id' => $id));
$rowForm = $selectForm->fetch();
//Select Form Inputs
$selectFormInputs = $this->db->prepare("SELECT * FROM form_inputs WHERE formID=:formID AND siteID='$this->siteID' ORDER BY sort ASC");
$selectFormInputs->execute(array(':formID' => $rowForm['id']));
//Check For Captcha
if ($rowForm['captcha'] == 1)
{
require_once 'inc/securimage.php';
$img = new Securimage();
if ($img->check($_POST['captcha']) == false)
{
$message = "کد امنیتی وارد شده صحیح نمی باشد";
}
}
$insertQuery = 'INSERT INTO `frm_' . $this->siteID . '_' . $rowForm['name'] . '` ({1}) VALUES ({2})';
$fields[] = "_date";
$placeholders[] = ":_date";
$values[] = time();
$body = 'تاریخ : ' . jdate("Y/m/d ساعت H:i") . ' ';
while ($rowFormInputs = $selectFormInputs->fetch())
{
//Upload File if is File
if ($rowFormInputs['type'] == "file")
{
$maxFileSize = $this->convertPHPSizeToBytes(@ini_get('upload_max_filesize'));
if (empty($maxFileSize))
{
$maxFileSize = 1048576;
}
$valid_formats = explode(",", str_replace(".", "", $rowFormInputs['options']));
$pre = '';
$path = "uploads/form/";
chmod($pre . $path, 0777);
if (isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES[$rowFormInputs['name']]['name'];
$size = $_FILES[$rowFormInputs['name']]['size'];
$tmp = $_FILES[$rowFormInputs['name']]['tmp_name'];
$type = $_FILES[$rowFormInputs['name']]['type'];
if (strlen($name))
{
list($txt, $ext) = explode(".", $name);
if (in_array(strtolower($ext), $valid_formats))
{
if (!empty($size) && $size < $maxFileSize) //1 MB
{
if (file_exists($pre . $path . str_replace(" ", "-", urldecode($name))))
{
$finalName = time() . "." . strtolower($ext);
}
else
{
$finalName = str_replace(" ", "-", urldecode($name));
}
if (move_uploaded_file($tmp, $pre . $path . $finalName))
{
$_POST[$rowFormInputs['name']] = '/' . $path . $finalName;
}
else
{
$message = 'متاسفانه در آپلود فایل مشکلی پیش آمده است';
}
}
else
{
$message = 'حداکثر حجم فایل ' . $this->convertBytes($maxFileSize) . ' است';
}
}
else
{
$message = 'این فرمت پشتیبانی نمی شود';
}
}
}
}
$fields[] = "`" . $rowFormInputs['name'] . "`";
$placeholders[] = ":" . $rowFormInputs['name'];
if (is_array($_POST[$rowFormInputs['name']]))
{
$value = implode(",", $_POST[$rowFormInputs['name']]);
}
else
{
$value = $_POST[$rowFormInputs['name']];
}
$values[] = $value;
//Validation
if ($rowFormInputs['required'] == 1 && empty($_POST[$rowFormInputs['name']]) && empty($_FILES[$rowFormInputs['name']]['name']))
{
$message = "لطفا فیلد های الزامی را کامل پر نمائید";
}
elseif ($rowFormInputs['name'] == "email" && !empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$message = "آدرس ایمیل وارد شده صحیح نمیباشد";
}
elseif ($rowFormInputs['name'] == "mobile" && !empty($_POST['mobile']) && (substr($_POST['mobile'], 0, 2) != "09" || strlen($_POST['mobile']) != 11))
{
$message = "شماره موبایل وارد شده صحیح نمیباشد";
}
//Email Body Text
$body .= $rowFormInputs['title'] . ' : ' . $value . ' ';
}
$insertQuery = str_replace(array("{1}", "{2}"), array(implode(",", $fields), implode(",", $placeholders)), $insertQuery);
if (empty($message))
{
//it's OK -> Insert
$insertForm = $this->db->prepare($insertQuery);
if ($insertForm->execute(array_combine($placeholders, $values)))
{
$message = $rowForm['okMessage'];
}
else
{
$message = $rowForm['errorMessage'];
}
//Check to Send Email
$emails = explode(",", $rowForm['email']);
foreach ($emails as $email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
if (!empty($_POST['subject']))
{
$this->sendEmail($_POST['subject'], $body, $email, $_POST['email'], $_POST['email']);
}
else
{
$this->sendEmail("یک نفر فرم " . $rowForm['title'] . " را پر کرده است", $body, $email, $_POST['email'], $_POST['email']);
}
}
}
}
}
if (strtolower($_REQUEST['action']) == "form" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$rowForm = array();
$selectForm = $this->db->prepare("SELECT * FROM forms WHERE id=:id AND active=1 AND siteID='$this->siteID'");
$selectForm->execute(array(':id' => $id));
$rowForm = $selectForm->fetch();
$rowForm['post_type'] = 'form';
$rowForm['action'] = "/form/" . $id . "/" . $rowForm['title'];
$rowForm['submit_btn'] = ' ';
$rowForm['reset_btn'] = ' ';
$rowForm['message'] = $message;
if ($rowForm['captcha'] == 1)
{
$rowForm['captcha_input'] = '
';
}
else
{
$rowForm['captcha_input'] = '';
}
$rowForm['extraOptions'] = $this->getExtraOptions("forms", $rowForm['id']);
}
return $rowForm;
}
//Get Form Inputs Function
public function get_form_inputs($formID)
{
$get_form_inputs = array();
$selectFormInputs = $this->db->prepare("SELECT * FROM form_inputs WHERE formID=:formID AND siteID='$this->siteID' ORDER BY sort ASC");
$selectFormInputs->execute(array(':formID' => $formID));
while ($rowFormInputs = $selectFormInputs->fetch())
{
$id = $rowFormInputs['id'];
$name = $rowFormInputs['name'];
$title = $rowFormInputs['title'];
if (!empty($_POST[$rowFormInputs['name']]))
{
$value = $_POST[$rowFormInputs['name']];
}
else
{
$value = $rowFormInputs['value'];
}
$help = $rowFormInputs['help'];
$required = $rowFormInputs['required'];
$type = $rowFormInputs['type'];
if ($required == 1)
{
$requiredClass = 'required';
}
else
{
$requiredClass = '';
}
$input = '';
if (strtolower($type) == "text" || strtolower($type) == "password" || strtolower($type) == "hidden")
{
$input = ' ';
}
elseif (strtolower($type) == "textarea")
{
$input = '';
}
elseif (strtolower($type) == "file")
{
$input = ' ';
}
elseif (strtolower($type) == "select")
{
if (!empty($rowFormInputs['options']))
{
$explodeOptions = explode(",", $rowFormInputs['options']);
$options = '';
foreach($explodeOptions AS $option)
{
if ($option == $value)
{
$options .= '' . $option . ' ';
}
else
{
$options .= '' . $option . ' ';
}
}
$input = '' . $options . ' ';
}
}
elseif (strtolower($type) == "radio")
{
if (!empty($rowFormInputs['options']))
{
$explodeOptions = explode(",", $rowFormInputs['options']);
$options = '';
foreach($explodeOptions AS $option)
{
$ID += 1;
if ($option == $value)
{
$input .= '' . $option . ' ';
}
else
{
$input .= '' . $option . ' ';
}
}
}
}
elseif (strtolower($type) == "checkbox")
{
if (!empty($rowFormInputs['options']))
{
$explodeOptions = explode(",", $rowFormInputs['options']);
$options = '';
foreach($explodeOptions AS $option)
{
$ID += 1;
if ($option == $value)
{
$input .= '' . $option . ' ';
}
else
{
$input .= '' . $option . ' ';
}
}
}
}
if (!empty($input))
{
array_push($get_form_inputs, array('id' => $id, 'formID' => $formID, 'name' => $name, 'title' => $title, 'value' => $value, 'help' => $help, 'required' => $required, 'type' => $type, 'options' => $options, 'input' => $input));
}
}
return $get_form_inputs;
}
//Get Form Inputs Function
public function get_users_meta_inputs($cssClass="")
{
$get_users_meta_inputs = array();
$selectUsersMetaInputs = $this->db->query("SELECT * FROM users_meta_inputs WHERE active=1 AND siteID='$this->siteID' ORDER BY sort ASC");
while ($rowUsersMetaInputs = $selectUsersMetaInputs->fetch())
{
$id = $rowUsersMetaInputs['id'];
$name = $rowUsersMetaInputs['name'];
$title = $rowUsersMetaInputs['title'];
if (!empty($_POST[$rowUsersMetaInputs['name']]))
{
$value = $_POST[$rowUsersMetaInputs['name']];
}
else
{
$value = $rowUsersMetaInputs['value'];
}
$help = $rowUsersMetaInputs['help'];
$required = $rowUsersMetaInputs['required'];
$type = $rowUsersMetaInputs['type'];
if ($required == 1)
{
$requiredClass = 'required';
}
else
{
$requiredClass = '';
}
$input = '';
if (strtolower($type) == "text" || strtolower($type) == "password" || strtolower($type) == "hidden")
{
$input = ' ';
}
elseif (strtolower($type) == "textarea")
{
$input = '';
}
elseif (strtolower($type) == "file")
{
$input = ' ';
}
elseif (strtolower($type) == "select")
{
if (!empty($rowUsersMetaInputs['options']))
{
$explodeOptions = explode(",", $rowUsersMetaInputs['options']);
$options = '';
foreach($explodeOptions AS $option)
{
if ($option == $value)
{
$options .= '' . $option . ' ';
}
else
{
$options .= '' . $option . ' ';
}
}
$input = '' . $options . ' ';
}
}
elseif (strtolower($type) == "radio")
{
if (!empty($rowUsersMetaInputs['options']))
{
$explodeOptions = explode(",", $rowUsersMetaInputs['options']);
$options = '';
foreach($explodeOptions AS $option)
{
$ID += 1;
if ($option == $value)
{
$input .= '' . $option . ' ';
}
else
{
$input .= '' . $option . ' ';
}
}
}
}
elseif (strtolower($type) == "checkbox")
{
if (!empty($rowUsersMetaInputs['options']))
{
$explodeOptions = explode(",", $rowUsersMetaInputs['options']);
$options = '';
foreach($explodeOptions AS $option)
{
$ID += 1;
if ($option == $value)
{
$input .= '' . $option . ' ';
}
else
{
$input .= '' . $option . ' ';
}
}
}
}
if (!empty($input))
{
array_push($get_users_meta_inputs, array('id' => $id, 'name' => $name, 'title' => $title, 'value' => $value, 'help' => $help, 'required' => $required, 'type' => $type, 'options' => $options, 'input' => $input));
}
}
return $get_users_meta_inputs;
}
//Is_Test Function
public function is_test()
{
if (strtolower($_REQUEST['action']) == "test" && !empty($_GET['id']))
{
return true;
}
}
//Is_Exam Function
public function is_exam()
{
if (strtolower($_REQUEST['action']) == "exam" && !empty($_GET['id']))
{
return true;
}
}
//Test Function
public function test($countVisits=0)
{
if (!empty($_POST))
{
//Select Test
$id = intval($_GET['id']);
$selectTest = $this->db->prepare("SELECT * FROM tests WHERE id=:id AND active=1 AND siteID='$this->siteID'");
$selectTest->execute(array(':id' => $id));
$rowTest = $selectTest->fetch();
//Select Test Fields
$selectTestFields = $this->db->prepare("SELECT * FROM test_fields WHERE testID=:testID AND siteID='$this->siteID' ORDER BY sort ASC");
$selectTestFields->execute(array(':testID' => $rowTest['id']));
$insertQuery = 'INSERT INTO `tst_' . $this->siteID . '_' . $rowTest['name'] . '` ({1}) VALUES ({2})';
$fields[] = "_date";
$fields[] = "_userID";
$fields[] = "_price";
$placeholders[] = ":_date";
$placeholders[] = ":_userID";
$placeholders[] = ":_price";
$values[] = time();
$values[] = $_SESSION['userID'];
$values[] = intval($_REQUEST['price']);
$body = 'تاریخ : ' . jdate("Y/m/d ساعت H:i") . ' ';
while ($rowTestFields = $selectTestFields->fetch())
{
//Upload File if is File
if ($rowTestFields['type'] == "file")
{
$maxFileSize = $this->convertPHPSizeToBytes(@ini_get('upload_max_filesize'));
if (empty($maxFileSize))
{
$maxFileSize = 1048576;
}
$valid_testats = explode(",", str_replace(".", "", $rowTestFields['options']));
$pre = '';
$path = "uploads/test/";
chmod($pre . $path, 0777);
if (isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES[$rowTestFields['name']]['name'];
$size = $_FILES[$rowTestFields['name']]['size'];
$tmp = $_FILES[$rowTestFields['name']]['tmp_name'];
$type = $_FILES[$rowTestFields['name']]['type'];
if (strlen($name))
{
list($txt, $ext) = explode(".", $name);
if (in_array(strtolower($ext), $valid_testats))
{
if (!empty($size) && $size < $maxFileSize) //1 MB
{
if (file_exists($pre . $path . str_replace(" ", "-", urldecode($name))))
{
$finalName = time() . "." . strtolower($ext);
}
else
{
$finalName = str_replace(" ", "-", urldecode($name));
}
if (move_uploaded_file($tmp, $pre . $path . $finalName))
{
$_POST[$rowTestFields['name']] = '/' . $path . $finalName;
}
else
{
$message = 'متاسفانه در آپلود فایل مشکلی پیش آمده است';
}
}
else
{
$message = 'حداکثر حجم فایل ' . $this->convertBytes($maxFileSize) . ' است';
}
}
else
{
$message = 'این فرمت پشتیبانی نمی شود';
}
}
}
}
$fields[] = "`" . $rowTestFields['name'] . "`";
$placeholders[] = ":" . $rowTestFields['name'];
if (is_array($_POST[$rowTestFields['name']]))
{
$values[] = implode(",", $_POST[$rowTestFields['name']]);
}
else
{
$values[] = $_POST[$rowTestFields['name']];
}
//Validation
if ($rowTestFields['required'] == 1 && empty($_POST[$rowTestFields['name']]))
{
$message = "لطفا فیلد های الزامی را کامل پر نمائید";
}
elseif ($rowTestFields['name'] == "email" && !empty($_POST['mobile']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$message = "آدرس ایمیل وارد شده صحیح نمیباشد";
}
elseif ($rowTestFields['name'] == "mobile" && !empty($_POST['mobile']) && (substr($_POST['mobile'], 0, 2) != "09" || strlen($_POST['mobile']) != 11))
{
$message = "شماره موبایل وارد شده صحیح نمیباشد";
}
//Email Body Text
$body .= $rowTestFields['title'] . ' : ' . $_POST[$rowTestFields['name']] . ' ';
}
$insertQuery = str_replace(array("{1}", "{2}"), array(implode(",", $fields), implode(",", $placeholders)), $insertQuery);
if (empty($message))
{
//it's OK -> Insert
//$insertTest = $this->db->prepare($insertQuery);
//$insertTest->execute(array_combine($placeholders, $values));
}
else
{
$this->error = $message;
$this->errorType = 'error';
}
}
if (!empty($_GET['id']))
{
$id = intval($_GET['id']);
$rowTest = array();
$selectTest = $this->db->prepare("SELECT * FROM tests WHERE id=:id AND active=1 AND siteID='$this->siteID'");
$selectTest->execute(array(':id' => $id));
$rowTest = $selectTest->fetch();
$rowTest['post_type'] = 'test';
$rowTest['images'] = @explode("|", $rowTest['image']);
$rowTest['image'] = $images[0];
if (!empty($rowTest['permalink']))
{
$rowTest['url'] = "/" . $rowTest['permalink'];
}
else
{
$rowTest['url'] = "/test/" . $rowTest['id'] . "/" . $this->safeUrl($rowTest['title']);
}
$rowTest['message'] = $message;
$rowTest['extraOptions'] = $this->getExtraOptions("tests", $rowTest['id']);
if ($countVisits == 0)
{
$updateVisits = $this->db->prepare("UPDATE tests SET visits=IFNULL(visits,0)+1 WHERE id=:id AND siteID='$this->siteID'");
$updateVisits->execute(array(':id' => $id));
}
}
return $rowTest;
}
//Get Test Inputs Function
public function get_test_fields($testID)
{
$get_test_fields = array();
$selectTestFields = $this->db->prepare("SELECT * FROM test_fields WHERE testID=:testID AND siteID='$this->siteID' ORDER BY sort ASC");
$selectTestFields->execute(array(':testID' => $testID));
while ($rowTestFields = $selectTestFields->fetch())
{
$id = $rowTestFields['id'];
$name = $rowTestFields['name'];
$title = $rowTestFields['title'];
if (!empty($_POST[$rowTestFields['name']]))
{
$value = $_POST[$rowTestFields['name']];
}
else
{
$value = $rowTestFields['value'];
}
$help = $rowTestFields['help'];
$required = $rowTestFields['required'];
$type = $rowTestFields['type'];
if ($required == 1)
{
$requiredClass = 'required';
}
else
{
$requiredClass = '';
}
$input = '';
if (strtolower($type) == "text" || strtolower($type) == "password" || strtolower($type) == "hidden")
{
$input = ' ';
}
elseif (strtolower($type) == "textarea")
{
$input = '';
}
elseif (strtolower($type) == "file")
{
$input = ' ';
}
elseif (strtolower($type) == "select")
{
if (!empty($rowTestFields['options']))
{
$explodeOptions = explode(",", $rowTestFields['options']);
$options = '';
foreach($explodeOptions AS $option)
{
if ($option == $value)
{
$options .= '' . $option . ' ';
}
else
{
$options .= '' . $option . ' ';
}
}
$input = '' . $options . ' ';
}
}
elseif (strtolower($type) == "radio")
{
if (!empty($rowTestFields['options']))
{
$explodeOptions = explode(",", $rowTestFields['options']);
$options = '';
foreach($explodeOptions AS $option)
{
$ID += 1;
if ($option == $value)
{
$input .= '' . $option . ' ';
}
else
{
$input .= '' . $option . ' ';
}
}
}
}
elseif (strtolower($type) == "checkbox")
{
if (!empty($rowTestFields['options']))
{
$explodeOptions = explode(",", $rowTestFields['options']);
$options = '';
foreach($explodeOptions AS $option)
{
$ID += 1;
if ($option == $value)
{
$input .= '' . $option . ' ';
}
else
{
$input .= '' . $option . ' ';
}
}
}
}
if (!empty($input))
{
array_push($get_test_fields, array('id' => $id, 'testID' => $testID, 'name' => $name, 'title' => $title, 'value' => $value, 'help' => $help, 'required' => $required, 'type' => $type, 'options' => $options, 'input' => $input));
}
}
return $get_test_fields;
}
//Is_RSS Function
public function is_rss()
{
if (strtolower($_REQUEST['action']) == "rss" && !empty($_GET['type']))
{
return true;
}
}
//RSS Function
public function rss($limit=0)
{
if (strtolower($_REQUEST['action']) == "rss" && !empty($_GET['type']))
{
$type = $_GET['type'];
if (intval($limit) > 0)
{
$limitQuery = "LIMIT " . $limit;
}
else
{
$limitQuery = "";
}
if (!empty($_GET['category']))
{
$categoryID = intval($_GET['category']);
$categoryQuery = 'AND categoryID=' . $categoryID;
$selectCategory = $this->db->query("SELECT * FROM categories WHERE id=$categoryID AND siteID='$this->siteID'");
$rowCategory = $selectCategory->fetch();
$rssTitle = $rowCategory['title'] . " | " . $this->settings['title'];
}
else
{
$rssTitle = $this->settings['title'];
}
if ($type == "all")
{
$query = "(SELECT id,title,image,description,permalink,date,publishDate,'article' AS `path` FROM articles WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'news' AS `path` FROM news WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'product' AS `path` FROM products WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'groupProduct' AS `path` FROM group_products WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'wish' AS `path` FROM wishes WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'audio' AS `path` FROM audios WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'video' AS `path` FROM videos WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'course' AS `path` FROM courses WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'lesson' AS `path` FROM lessons WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'download' AS `path` FROM downloads WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'registeration' AS `path` FROM registerations WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'vip' AS `path` FROM vips WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID') UNION
(SELECT id,title,image,description,permalink,date,publishDate,'estate' AS `path` FROM estates WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID')
ORDER BY publishDate DESC $limitQuery";
}
elseif ($type == "articles")
{
$query = "SELECT *,'article' AS `path` FROM articles WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "news")
{
$query = "SELECT *,'news' AS `path` FROM news WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "products")
{
$query = "SELECT *,'product' AS `path` FROM products WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "groupProducts")
{
$query = "SELECT *,'group-product' AS `path` FROM group_products WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "wishes")
{
$query = "SELECT *,'wish' AS `path` FROM wishes WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "audios")
{
$query = "SELECT *,'audio' AS `path` FROM audios WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "videos")
{
$query = "SELECT *,'video' AS `path` FROM videos WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "courses")
{
$query = "SELECT *,'course' AS `path` FROM courses WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "lessons")
{
$query = "SELECT *,'lesson' AS `path` FROM lessons WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
/*elseif ($type == "pages")
{
$query = "SELECT *,'page' AS `path` FROM pages WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}*/
elseif ($type == "downloads")
{
$query = "SELECT *,'download' AS `path` FROM downloads WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
/*elseif ($type == "offers")
{
$query = "SELECT *,'offer' AS `path` FROM offers WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}*/
/*elseif ($type == "authors")
{
$query = "SELECT *,'author' AS `path` FROM authors WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}*/
elseif ($type == "registerations")
{
$query = "SELECT *,'registeration' AS `path` FROM registerations WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "vips")
{
$query = "SELECT *,'vip' AS `path` FROM vips WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
elseif ($type == "estates")
{
$query = "SELECT *,'estate' AS `path` FROM estates WHERE publishDate <= $this->now AND active=1 AND hidden=0 AND siteID='$this->siteID' $categoryQuery ORDER BY date DESC $limitQuery";
}
$rss = '
';
$rss .= '';
$rss .= '' . $rssTitle . ' ';
$rss .= ' ';
$rss .= ' ' . $this->protocol . '://' . $this->settings['siteAddress'] . '';
$rss .= '
' . $this->protocol . '://' . $this->settings['siteAddress'] . '/' . $this->template_path . '/images/rss-logo.png
' . $this->settings['siteName'] . '
' . $this->protocol . '://' . $this->settings['siteAddress'] . '
';
$rss .= '' . $type . ' RSS feed ';
$rss .= 'fa-ir ';
$rss .= 'Copyright (C) ' . date("Y") . ' ' . $this->settings['siteAddress'] . ' ';
$selectRss = $this->db->query($query);
while($rowRss = $selectRss->fetch())
{
$rowRss['images'] = @explode("|", $rowRss['image']);
$rowRss['image'] = $rowRss['images'][0];
$rss .= '- ';
$rss .= '
' . str_replace(" ", " ", $rowRss['title']) . ' ';
$rss .= '
protocol . '://' . $this->settings['siteAddress'] . '/' . $rowRss['image'] . '" alt="' . $rowRss['title'] . '" width="100" />
' . $rowRss['description'] . '
]]>
';
if (!empty($rowRss['price']))
{
$rss .= '' . $rowRss['price'] . ' ';
}
if (!empty($rowRss['permalink']))
{
$rss .= ' ' . $this->protocol . '://' . $this->settings['siteAddress'] . '/' . $rowRss['permalink'] . '';
}
else
{
$rss .= ' ' . $this->protocol . '://' . $this->settings['siteAddress'] . '/' . $rowRss['path'] . '/' . $rowRss['id'] . '/' . str_replace(' ','-',$rowRss['title']) . '';
}
$rss .= '' . jdate("Y/m/d - H:i:s", $rowRss['date']) . ' ';
$rss .= ' ';
}
$rss .= ' ';
$rss .= ' ';
}
return $rss;
}
//comment
public function comment($array)
{
$insertComment = $this->db->prepare("INSERT INTO comment (siteID,userID,name,email,mobile,comment,commentID,type,typeID,typeTitle,date,active) VALUES ('$this->siteID', :userID, :name, :email, :mobile, :comment, :commentID, :type, :typeID, :typeTitle, :date, :active)");
if ($array['typeID']==null)
{
$array['typeID'] = intval($_GET['id']);
}
else
{
$array['typeID'] = intval($array['typeID']);
}
if ($array['type']==null)
{
$array['type'] = $_REQUEST['action'];
}
if ($array['date']==null)
{
$array['date'] = time();
}
if ($array['active']==null)
{
$array['active'] = 0;
}
//typeTitle
if ($array['type'] == "article")
{
$table = "articles";
}
elseif ($array['type'] == "news")
{
$table = "news";
}
elseif ($array['type'] == "product")
{
$table = "products";
}
elseif ($array['type'] == "groupProduct")
{
$table = "group_products";
}
elseif ($array['type'] == "wish")
{
$table = "wishes";
}
elseif ($array['type'] == "page")
{
$table = "pages";
}
elseif ($array['type'] == "download")
{
$table = "downloads";
}
elseif ($array['type'] == "offer")
{
$table = "offers";
}
elseif ($array['type'] == "author")
{
$table = "authors";
}
elseif ($array['type'] == "registeration")
{
$table = "registerations";
}
elseif ($array['type'] == "course")
{
$table = "courses";
}
elseif ($array['type'] == "session")
{
$table = "sessions";
}
elseif ($array['type'] == "lesson")
{
$table = "lessons";
}
elseif ($array['type'] == "lessonEpisode")
{
$table = "lesson_episodes";
}
elseif ($array['type'] == "vip")
{
$table = "vips";
}
elseif ($array['type'] == "estate")
{
$table = "estates";
}
elseif ($array['type'] == "audio")
{
$table = "audios";
}
elseif ($array['type'] == "video")
{
$table = "videos";
}
elseif ($array['type'] == "gallery")
{
$table = "galleries";
}
elseif ($array['type'] == "test")
{
$table = "tests";
}
if (!empty($table))
{
$selectTitle = $this->db->query("SELECT title FROM $table WHERE id='$array[typeID]' AND siteID='$this->siteID'");
$rowTitle = $selectTitle->fetch();
$array['typeTitle'] = $rowTitle['title'];
}
else
{
$array['typeTitle'] = $rowTitle['title'];
}
if ($array['comment'] != "")
{
$insertComment->execute(array(':userID'=>$array['userID'], ':name'=>$array['name'], ':email'=>$array['email'], ':mobile'=>$array['mobile'], ':comment'=>$array['comment'], ':commentID'=>intval($array['commentID']), ':type'=>$array['type'], ':typeID'=>$array['typeID'], ':typeTitle'=>$array['typeTitle'], ':date'=>$array['date'], ':active'=>$array['active']));
return true;
}
else
{
return false;
}
}
//Get_Comments Function
public function get_comments($commentID=0, $type=null, $typeID=null, $orderBy="comment.date DESC", $showToUser=true, $showToAdmin=true, $limitQuery='')
{
$comments = array();
$order = $orderBy;
$orderBy = $this->orderBy($orderBy);
$comments = array();
$commentID = intval($commentID);
if (empty($typeID))
{
$typeID = $_GET['id'];
}
if (empty($type))
{
$type = $_REQUEST['action'];
}
$user = $this->getUserByID($_SESSION['userID']);
if ($showToAdmin == true && !empty($user) && $user['type'] == 0)
{
$selectComments = $this->db->prepare("SELECT *, comment.id AS id, comment.type AS type, comment.email AS email, comment.mobile AS mobile, comment.date AS date, comment.active AS active, comment.note AS note FROM comment LEFT JOIN users ON comment.userID=users.id WHERE comment.commentID=$commentID AND comment.type=:type AND comment.typeID=:typeID AND comment.siteID='$this->siteID' $orderBy $limitQuery");
}
else
{
if ($showToUser == true && !empty($_SESSION['userID']))
{
$selectComments = $this->db->prepare("SELECT *, comment.id AS id, comment.type AS type, comment.email AS email, comment.mobile AS mobile, comment.date AS date, comment.active AS active, comment.note AS note FROM comment LEFT JOIN users ON comment.userID=users.id WHERE comment.commentID=$commentID AND comment.type=:type AND comment.typeID=:typeID AND (comment.active=1 OR comment.userID=$_SESSION[userID]) AND comment.siteID='$this->siteID' $orderBy $limitQuery");
}
else
{
$selectComments = $this->db->prepare("SELECT *, comment.id AS id, comment.type AS type, comment.email AS email, comment.mobile AS mobile, comment.date AS date, comment.active AS active, comment.note AS note FROM comment LEFT JOIN users ON comment.userID=users.id WHERE comment.commentID=$commentID AND comment.type=:type AND comment.typeID=:typeID AND comment.active=1 AND comment.siteID='$this->siteID' $orderBy $limitQuery");
}
}
$selectComments->execute(array(":type"=>$type, ":typeID"=>$typeID));
while ($rowComments = $selectComments->fetch())
{
$rowComments['answers'] = $this->get_comments($rowComments['id'], $type, $typeID, "comment.date ASC", $showToUser, $showToAdmin);
$comments[] = $rowComments;
}
return $comments;
}
//Title Function
public function title($append="")
{
if ($this->is_get_articles() == true)
{
return "مقالات" . $append;
}
elseif ($this->is_article() == true)
{
$id = intval($_GET['id']);
$selectArticle = $this->db->prepare("SELECT * FROM articles WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectArticle->execute(array(':id' => $id));
$rowArticle = $selectArticle->fetch();
return $rowArticle['title'] . $append;
}
elseif ($this->is_get_news() == true)
{
return "اخبار" . $append;
}
elseif ($this->is_news() == true)
{
$id = intval($_GET['id']);
$selectNews = $this->db->prepare("SELECT * FROM news WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectNews->execute(array(':id' => $id));
$rowNews = $selectNews->fetch();
return $rowNews['title'] . $append;
}
elseif ($this->is_get_products() == true)
{
return "محصولات" . $append;
}
elseif ($this->is_product() == true)
{
$id = intval($_GET['id']);
$selectProduct = $this->db->prepare("SELECT * FROM products WHERE id=:id AND publishDate <= $this->now AND active=1 AND IFNULL(isDeleted, 0)!=1 AND siteID='$this->siteID'");
$selectProduct->execute(array(':id' => $id));
$rowProduct = $selectProduct->fetch();
return $rowProduct['title'] . $append;
}
elseif ($this->is_get_groupProducts() == true)
{
return "گروه محصولات" . $append;
}
elseif ($this->is_groupProduct() == true)
{
$id = intval($_GET['id']);
$selectGroupProducts = $this->db->prepare("SELECT * FROM group_products WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectGroupProducts->execute(array(':id' => $id));
$rowGroupProducts = $selectGroupProducts->fetch();
return $rowGroupProducts['title'] . $append;
}
elseif ($this->is_get_wishes() == true)
{
return "آرزو ها" . $append;
}
elseif ($this->is_wish() == true)
{
$id = intval($_GET['id']);
$selectWishes = $this->db->prepare("SELECT * FROM wishes WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectWishes->execute(array(':id' => $id));
$rowWishes = $selectWishes->fetch();
return $rowWishes['title'] . $append;
}
elseif ($this->is_get_pages() == true)
{
return "صفحات سایت" . $append;
}
elseif ($this->is_page() == true)
{
$id = intval($_GET['id']);
$selectPage = $this->db->prepare("SELECT * FROM pages WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectPage->execute(array(':id' => $id));
$rowPage = $selectPage->fetch();
return $rowPage['title'] . $append;
}
elseif ($this->is_get_downloads() == true)
{
return "دانلود ها" . $append;
}
elseif ($this->is_download() == true)
{
$id = intval($_GET['id']);
$selectDownload = $this->db->prepare("SELECT * FROM downloads WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectDownload->execute(array(':id' => $id));
$rowDownload = $selectDownload->fetch();
return $rowDownload['title'] . $append;
}
elseif ($this->is_get_offers() == true)
{
return "پیشنهادات ویژه" . $append;
}
elseif ($this->is_offer() == true)
{
$id = intval($_GET['id']);
$selectOffer = $this->db->prepare("SELECT * FROM offers WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectOffer->execute(array(':id' => $id));
$rowOffer = $selectOffer->fetch();
return $rowOffer['title'] . $append;
}
elseif ($this->is_get_authors() == true)
{
return "نویسنده" . $append;
}
elseif ($this->is_author() == true)
{
$id = intval($_GET['id']);
$selectAuthor = $this->db->prepare("SELECT * FROM authors WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectAuthor->execute(array(':id' => $id));
$rowAuthor = $selectAuthor->fetch();
return $rowAuthor['title'] . $append;
}
elseif ($this->is_get_registerations() == true)
{
return "ثبت نام ها" . $append;
}
elseif ($this->is_registeration() == true)
{
$id = intval($_GET['id']);
$selectRegisteration = $this->db->prepare("SELECT * FROM registerations WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectRegisteration->execute(array(':id' => $id));
$rowRegisteration = $selectRegisteration->fetch();
return $rowRegisteration['title'] . $append;
}
elseif ($this->is_get_courses() == true)
{
return "دوره ها" . $append;
}
elseif ($this->is_course() == true)
{
$id = intval($_GET['id']);
$selectCourse = $this->db->prepare("SELECT * FROM courses WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectCourse->execute(array(':id' => $id));
$rowCourse = $selectCourse->fetch();
return $rowCourse['title'] . $append;
}
elseif ($this->is_session() == true)
{
$id = intval($_GET['id']);
$selectSession = $this->db->prepare("SELECT * FROM sessions WHERE id=:id AND active=1 AND siteID='$this->siteID'");
$selectSession->execute(array(':id' => $id));
$rowSession = $selectSession->fetch();
return $rowSession['title'] . $append;
}
elseif ($this->is_get_lessons() == true)
{
return "درس ها" . $append;
}
elseif ($this->is_lesson() == true)
{
$id = intval($_GET['id']);
$selectLesson = $this->db->prepare("SELECT * FROM lessons WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectLesson->execute(array(':id' => $id));
$rowLesson = $selectLesson->fetch();
return $rowLesson['title'] . $append;
}
elseif ($this->is_lessonEpisode() == true)
{
$id = intval($_GET['id']);
$selectLessonEpisode = $this->db->prepare("SELECT * FROM lesson_episodes WHERE id=:id AND active=1 AND siteID='$this->siteID'");
$selectLessonEpisode->execute(array(':id' => $id));
$rowLessonEpisode = $selectLessonEpisode->fetch();
return $rowLessonEpisode['title'] . $append;
}
elseif ($this->is_get_vips() == true)
{
return "مطالب اعضای ویژه" . $append;
}
elseif ($this->is_vip() == true)
{
$id = intval($_GET['id']);
$selectVip = $this->db->prepare("SELECT * FROM vips WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectVip->execute(array(':id' => $id));
$rowVip = $selectVip->fetch();
return $rowVip['title'] . $append;
}
elseif ($this->is_get_estates() == true)
{
return "املاک" . $append;
}
elseif ($this->is_estate() == true)
{
$id = intval($_GET['id']);
$selectEstate = $this->db->prepare("SELECT * FROM estates WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectEstate->execute(array(':id' => $id));
$rowEstate = $selectEstate->fetch();
return $rowEstate['title'] . $append;
}
elseif ($this->is_get_audios() == true)
{
return "فایل های صوتی" . $append;
}
elseif ($this->is_audio() == true)
{
$id = intval($_GET['id']);
$selectAudio = $this->db->prepare("SELECT * FROM audios WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectAudio->execute(array(':id' => $id));
$rowAudio = $selectAudio->fetch();
return $rowAudio['title'] . $append;
}
elseif ($this->is_get_videos() == true)
{
return "فایل های تصویری" . $append;
}
elseif ($this->is_video() == true)
{
$id = intval($_GET['id']);
$selectVideo = $this->db->prepare("SELECT * FROM videos WHERE id=:id AND publishDate <= $this->now AND active=1 AND siteID='$this->siteID'");
$selectVideo->execute(array(':id' => $id));
$rowVideo = $selectVideo->fetch();
return $rowVideo['title'] . $append;
}
elseif ($this->is_form() == true)
{
$id = intval($_GET['id']);
$selectForm = $this->db->prepare("SELECT * FROM forms WHERE id=:id AND active=1 AND siteID='$this->siteID'");
$selectForm->execute(array(':id' => $id));
$rowForm = $selectForm->fetch();
return $rowForm['title'] . $append;
}
elseif ($this->is_test() == true || $this->is_exam() == true)
{
$id = intval($_GET['id']);
$selectTest = $this->db->prepare("SELECT * FROM tests WHERE id=:id AND active=1 AND siteID='$this->siteID'");
$selectTest->execute(array(':id' => $id));
$rowTest = $selectTest->fetch();
return $rowTest['title'] . $append;
}
elseif ($this->is_get_galleries() == true)
{
return "گالری تصاویر" . $append;
}
elseif ($this->is_gallery() == true)
{
$id = intval($_GET['id']);
$selectGallery = $this->db->prepare("SELECT * FROM galleries WHERE id=:id AND siteID='$this->siteID'");
$selectGallery->execute(array(':id' => $id));
$rowGallery = $selectGallery->fetch();
return $rowGallery['title'] . $append;
}
elseif ($this->is_category() == true)
{
$id = intval($_GET['id']);
$selectCategory = $this->db->prepare("SELECT * FROM categories WHERE id=:id AND siteID='$this->siteID'");
$selectCategory->execute(array(':id' => $id));
$rowCategory = $selectCategory->fetch();
return $rowCategory['title'] . $append;
}
elseif ($this->is_search() == true)
{
return "نتیجه جستجوی عبارت \"" . $_REQUEST['keyword'] . "\"" . $append;
}
elseif ($this->is_search_tag() == true)
{
return "نتیجه جستجوی تگ \"" . $_REQUEST['tag'] . "\"" . $append;
}
else
{
return $this->settings['title'] . $append;
}
}
}
$cms = new CMS();
$index_time_end = microtime(true);
//Postpone Errors
if (!empty($_SESSION['postponeError']))
{
$cms->error = $_SESSION['postponeError'];
$cms->errorType = $_SESSION['postponeErrorType'];
$_SESSION['postponeError'] = '';
$_SESSION['postponeErrorType'] = '';
}
$template_time_start = microtime(true);
if (empty($dontLoadIndex))
{
require $cms->template_path . "/index.php";
}
$template_time_end = microtime(true);
if (!empty($_GET['cancel_execution_time']))
{
$_SESSION['execution_time'] = '';
}
if (!empty($_GET['execution_time']) || !empty($_SESSION['execution_time']))
{
$_SESSION['execution_time'] = 1;
$cms->indexExectionTime = ($index_time_end - $index_time_start);
$cms->templateExectionTime = ($template_time_end - $template_time_start);
$cms->totalExectionTime = $cms->indexExectionTime + $cms->templateExectionTime;
echo 'indexExectionTime : ' . round($cms->indexExectionTime, 5) . ' sec
';
echo 'templateExectionTime : ' . round($cms->templateExectionTime, 5) . ' sec
';
echo 'totalExectionTime : ' . round($cms->totalExectionTime, 5) . ' sec
';
}
?>