<?php



/***

	Website Motor v3.0
	Copyright (C) Website Motor https://www.websitemotor.com/

	This program is free; you can redistribute it and/or modify it under the terms of the
	GNU General Public License as published by the Free Software Foundation.

***/





//================================  CONFIG ===========================================

date_default_timezone_set('Asia/Tehran');
define('DATA_FOLDER','data');
define('STORE_CURRENCY','تومان');

//================================  REQUESTS =========================================

$request= stripslashes($_SERVER['REQUEST_URI']);
$t=strpos($request,'?');
if($t!==false){$request=substr($request,0,$t);}
$request= urldecode($request);
$request= trim($request,'/');

if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
	$_SERVER['REMOTE_ADDR']=$_SERVER['HTTP_X_FORWARDED_FOR'];
}

//================================  SESSION ==========================================

session_name('wotor3sn');
session_start();

$_SESSION['user_id']= $_SESSION['user_id'] ?? 0;
$_SESSION['captchano']= $_SESSION['captchano'] ?? 0;

//================================  CAPTCHA ==========================================

if($request=='captcha'){
	$s='';
	$im = ImageCreate(200,50);
	ImageColorAllocate($im,255,255,255);
	$fg = ImageColorAllocate($im,0,0,255);
	$x=-20;
	for($i = 0;$i<4;$i++){
		$c=rand(0,9);
		$s.=$c;
		$x+=rand(25,55);
		imagefilter($im, IMG_FILTER_PIXELATE,$c%2+1,true);
		@imagettftext($im , rand(32,48) ,rand(-30,30),$x,rand(35,45),$fg,DATA_FOLDER.'/captcha.0-9.ttf',$c);
	}
	$_SESSION['captcha'] = $s;
	header('Cache-Control: no-store, no-cache, must-revalidate');
	header('Content-type: image/gif');
	imagegif($im);
	imagedestroy($im);
	exit;
}

if(isset($_POST['captcha'])){
	$_POST['captcha']=str_replace(['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'],['0','1','2','3','4','5','6','7','8','9'],$_POST['captcha']);
	if($_SESSION['captcha']!=$_POST['captcha']){
		$_SESSION['captchano']=0;
		die('ERROR|کد تصویری نادرست است.');
	}
	$_SESSION['captchano']=20;
}

//================================  THUMB ============================================

if($_SESSION['user_id'] and preg_match('/.-thumb\.jpg$/',$request)){
	$f=save_resize_image(mb_substr($request,0,-10));
	$f?header('Location: /'.$request):http_response_code(404);
	exit;
}

//================================  STORE FILE =======================================

if(preg_match('/^get_store_file\/(\d+)$/',$request,$m) and isset($_SESSION['store_file'][$m[1]])){
	header('Content-Type: application/octet-stream');
	header('Content-Transfer-Encoding: Binary');
	header('Content-disposition: attachment; filename="download.'. end(explode('.',$_SESSION['store_file'][$m[1]])) . '"');
	readfile($_SESSION['store_file'][$m[1]]);
	exit;
}

//================================  SIGNOUT ==========================================

if(isset($_GET['signout'])){
	$_SESSION['user_id']=0;
	unset($_SESSION['user_name'],$_SESSION['user_role']);
	setcookie('wotor3lc','',time()-1000,'/');
	header('Location: /'.$request.'/');
	exit;
}

//================================  SDB ==============================================

$s=@file_get_contents(DATA_FOLDER.'/setting.json');
if($s===false and !file_exists(DATA_FOLDER.'/setting.json')){
	if(empty($_POST)){
		$required_php_exts=[];
		foreach(['dom','session','xml','json','PDO','mbstring','filter','ctype','pdo_sqlite','fileinfo'] as $ext){
			if(!extension_loaded($ext)){$required_php_exts[]=$ext;}
		}
		if($required_php_exts){
			die_html('خطای ماژول','امکان اجرای وب‌سایت موتور وجود ندارد.<br>ماژول'.(isset($required_php_exts[1])?'‌های':'').' ضروری '.implode(' و ',$required_php_exts).' در دسترس نیست.','خطای-ماژول');
		}
		if(!file_exists('.htaccess')){
			file_put_contents('.htaccess',"\n# BEGIN WebsiteMotor\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WebsiteMotor\n");
		}
		foreach([DATA_FOLDER,'themes','images'] as $df){
			if(!file_exists($df)){mkdir($df,0777,true);}
		}
		file_put_contents(DATA_FOLDER.'/.htaccess',"## No access to this folder\nRequire all denied\n");
		$b=base64_decode('eJzdVUuLHFUU/s69Vbe6q3omk9jVncSJNF3JNJhFavppzAhZ6kIDozAuIpNKZ5wGZ+ym7cCICCKCCAouRPAfuBDciG78F27cG1y5cJOFgrbfvX3nkRnID/DAvfc8vvOocx8FARDjI2g07rx+o715+Z05Nd9x3BvuF5PlzUtvAFLhuL+79/7bn33x/U+AmnBsjHaKB9d+Hn8LBBbfH1GBS7hI+RHlq6P92QEjrwBhiXJ3bzws1O/6gPIG5dX94mCC+9im/CblxrvF/s6DT766QJkYuTEZvzfDx/gUMMyBDQQoy5cIUULCmlmCXyMIbSQ3OcptWks2M7ZebTRwm8xNJPN/6FeHoSQ4poabtR+r3naXkjg5cP4VxlMuTRlLuIKb87nPYqWcksz/mj+eP5r/8kR0m8wcJxTlqj8FwBnSQWiiUjlOKmdt/2NiZ9hJw53W7Cv67WpzkEd5vd9bW89hjBKlJDQhZ7FdEyjiNU9DCNTzrJd3NC2uaQtbRBsjDdovSSetXpc063XSQImFGaW1NpXwEBtzl8+fxlohIj4Q+hgVBNoscTn0KTP+s/TpdvJOel2aaTWt3ZJBWm220oyuVyQP6Cq2YGFeiYIFT1WUMCa/WVzuMs7xtGFQzfIsb5ms2ev2B+20Tj4yabU9YBti56q1co1QWtwkWjGFMQxpSU7WVmPEqDVoZmvdvi/RVGu3dNlI6PByREEogStRy3H/YsYo2RhZq9epDzpxQLPWEieJxPFZXJq1oqxHnAUxEEGS+G+0e5HgGe5U1ouy5lp38KKkUa8Z5dVaJ5JFl2x8Lsb6C1unFBY3hOOHu+rP7XMbjxllxab+7ZVvXj5e/Q7C3dQFWb/6/G/OKyc0J2npyGJX+zaE9C5zVDhi99IIEi8nziYOWcEFPI8X8BpG+Bw/4lf8gX/lOWe1b4LyJ7rE98M26vZRzgq+9nUIlo9qUuzPsuft25N6PqC25vmQ61XPG+qvWWRgK1pFx/OK+juet6frLc8HxGx73n7jB5431H+4NZ5Nx9PtYTGZDUfF5s7uw71iuv6k9pSILYwxw5TzlIGHKDChPGQ7CmxiB7t4iD3yU6w/Fft06+Fe+vf2NC3Z223PIM9VlT2r8YW/yH/RZd7K1f8AIvapUA==');
		file_put_contents(DATA_FOLDER.'/captcha.0-9.ttf',gzuncompress($b));
		die_html('راه‌اندازی سایت','<style>input{border:1px solid #ccc;border-radius:3px;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;display:block;width:100%;padding:10px;margin:2px 0 10px;box-sizing:border-box;direction:ltr}input:focus{border-color:#28f;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}label{display:block;margin-top:25px;color:#000}label a{font-size:14px;float:left;font-size:14px;padding:0 5px;color:#fff;background:teal;border-radius:2px;line-height:1.25;margin-top:5px;user-select:none;line-height:1}label a:active{transform:translateY(1px)}form{margin:25px 0;max-width:400px;margin:10px auto}form p{color:#555;font-size:14px}input{margin-bottom:0}button{background:#08f;color:#fff;border:none;width:100px;border-radius:3px;cursor:pointer}</style><h1>به راه‌اندازی وب‌سایت موتور خوش آمدید.</h1><form method="POST" onsubmit="document.getElementById(\'inp-pass\').type=\'password\'"><label>نام سایت</label><input type="text" style="direction:rtl" name="sitename" required><label>نشانی ایمیل</label><input type="email" autocomplete="email" style="direction:ltr;font-family:sans-serif;text-transform:lowercase" name="email" required ><label>رمز عبور<a onclick="for(var a=\'\',n=0;n<6;n++)a+=\'!@_ABDEFGHLMNQRTabdefghijmnpqrt23456789\'.charAt(Math.floor(39*Math.random()));document.getElementById(\'inp-pass\').value=a" style="cursor:pointer">رمز تصادفی</a></label><input type="text" id="inp-pass" style="direction:ltr;font-family:sans-serif" name="pass" minlength="4" autocomplete="off" spellcheck="false" required><p style="margin:0 0 25px">رمز عبور، به حروف بزرگ و کوچک حساس است.</p><div style="text-align:center"><button type="submit">تأیید</button></div></form>');
	}
	@set_time_limit(120);
	if(!file_exists(DATA_FOLDER.'/posts.sqlite')){
		sql('CREATE TABLE posts ("post_id" INTEGER,"post_url" TEXT,"post_title" TEXT,"post_type" TEXT,"post_category" TEXT,"post_tags" TEXT,"post_img" TEXT,"post_excerpt" TEXT,"post_template" TEXT,"post_author" INTEGER,"post_price" INTEGER,"post_commenting" TEXT,"post_created" TEXT,"post_modified" TEXT,"post_data" TEXT,"post_content" TEXT,PRIMARY KEY("post_id"));');
		$dt=date('Y-m-d H:i');
		$s='INSERT INTO posts VALUES ';
		for($i=1; $i<4;$i++){
			$s.="($i,'نمونه-مطلب-$i','نمونه مطلب $i','P','4','5','images/sample$i.gif','این متن، چکیدۀ اختصاص یافته به مطلب «نمونه مطلب {$i}» است. متن خلاصه یا چکیده، یک متن کوتاه است که می‌تواند برای معرفی و توضیح مختصر مطلب، مورد استفاده قرار گیرد.','',1,0,'','$dt','$dt','','این متن، محتوای کامل اختصاص یافته به مطلب «نمونه مطلب {$i}» است. محتوا می‌تواند شامل تصاویر و پرونده‌های رسانه‌ای دیگر شود.<br> این خطوط برای نمونه در اینجا تنظیم شده است. <br>از طریق بخش مدیریت سایت، امکان ویرایش، حذف و یا ایجاد یک مطلب تازه برای مدیر یا نویسنده سایت فراهم است. <br> سطر اول <br> سطر دوم <br> سطر سوم<br> سطر چهارم <br> سطر پنجم<br> سطر ششم<br> سطر هفتم<br> سطر هشتم<br> سطر نهم <br> سطر دهم <br> ...<br><br><br>'),\n";
			$im =imagecreate(600,400);
			imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
			imagefilledellipse($im,285,175,150,150,imagecolorallocate($im,255,255,255));
			imagefilledellipse($im,270,150+rand(-15,15),10,10,imagecolorallocate($im,0,0,0));
			imagefilledellipse($im,300,150+rand(-15,15),10,10,imagecolorallocate($im,0,0,0));
			imagearc($im,285,160,rand(30,150),rand(30,150),30,120,imagecolorallocate($im,0,0,0));
			imagegif($im,'images/sample'.$i.'.gif');
		}
		sql($s."(4,'دسته-نمونه','دسته نمونه','C','','','','این متن، چکیدۀ اختصاص یافته به دسته نمونه است.','',1,0,'','$dt','$dt','',''),(5,'برچسب-نمونه','برچسب نمونه','T','','','','این متن، چکیدۀ اختصاص یافته به برچسب نمونه است.','',1,0,'','$dt','$dt','','');");
	}
	if(!file_exists(DATA_FOLDER.'/comments.sqlite')){
		sql('CREATE TABLE comments ("comment_id" INTEGER,"comment_pid" INTEGER,"comment_parent" INTEGER,"comment_status" INTEGER,"comment_name" TEXT,"comment_text" TEXT,"comment_date" TEXT,PRIMARY KEY("comment_id"));');
		sql('INSERT INTO comments VALUES (1,1,0,1,"موتور","این یک دیدگاه نمونه است.","'.date('Y-m-d H:i').'");');
	}
	if(!file_exists(DATA_FOLDER.'/post_rates.sqlite')){
		sql('CREATE TABLE post_rates ("post_id" INTEGER,"post_visit" INTEGER,"post_votes" TEXT,PRIMARY KEY("post_id"));');
	}
	if(!file_exists(DATA_FOLDER.'/comment_rates.sqlite')){
		sql('CREATE TABLE comment_rates ("comment_id" INTEGER,"comment_plus" INTEGER,"comment_minus" INTEGER,PRIMARY KEY("comment_id"));');
	}
	if(file_exists(DATA_FOLDER.'/users.sqlite')){
		rename(DATA_FOLDER.'/users.sqlite',DATA_FOLDER.'/users-deleted-'.time().'.sqlite');
	}
	sql('CREATE TABLE users ("user_id" INTEGER,"user_email" TEXT,"user_pass" TEXT,"user_name" TEXT,"user_role" TEXT,"user_url" TEXT,"user_login" TEXT,"user_cookie" TEXT,PRIMARY KEY("user_id"));');
	sql('INSERT INTO users VALUES (1,?,?,"مدیر سایت","admin","","","")',[trim(strtolower($_POST['email'])),md5($_POST['pass'])]);

	$sdb=array('sitename'=>$_POST['sitename'],'setup'=>date('Y-m-d H:i'));
	write_sdb();
	$_SESSION['user_id']=1;
	$_SESSION['user_role']='admin';
	$_SESSION['user_name']='مدیر سایت';
	$_SESSION['captchano']=20;
	logmsg('سایت راه‌اندازی شد.');
	header('Location: /ctrl/');
	exit;
}
$sdb=(array) json_decode($s,true);
$sdb or die_html('خطا در پردازش پرونده تنظیمات','پرونده setting.json خراب است.','خطای-پردازش-پرونده-تنظیمات');

if(empty($sdb['login_url'])){$sdb['login_url']='ctrl';}
foreach(['sitename','mtitle','mdescription','mkeywords','theme'] as $s){
	$sdb[$s]=$sdb[$s] ?? '';
}
if($request==$sdb['login_url'] and empty($_GET) and substr($_SERVER['REQUEST_URI'],-1)!='/'){
	header('Location: /'.$request.'/');
	exit;
}

//================================  DEFINES ==========================================

define('SITE_URL',((isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] === 'on') ? 'https' : 'http') . '://' .$_SERVER['HTTP_HOST'].'/');
define('SITE_STORE',isset($sdb['site_store']) and $sdb['site_store']=='yes');

//================================  PLUGINS ==========================================

if(isset($sdb['plugins'])){
	foreach(explode(',',$sdb['plugins']) as $p){
		if($p){@include('plugins/'.$p.'/index.php');}
	}
}

//================================  RSS ==============================================

if($request=='rss'){
	$posts=sql('SELECT post_url,post_title,post_excerpt,post_modified,post_img FROM posts WHERE post_type="P" ORDER BY post_id DESC LIMIT 20;');
	$text="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">\n <channel>\n\t<title>".$sdb['sitename']."</title>\n\t<link>".SITE_URL."</link>\n\t<description>".$sdb['mdescription']."</description>\n";
	if(isset($posts[0])){$text.="\t<lastBuildDate>".date( "D, d M Y H:i:s",strtotime($posts[0]['post_modified']) )." </lastBuildDate>\n";}
	for($i=0;$i<count($posts);$i++){
		$text .="\t<item>\n\t <pubDate>".date("D, d M Y H:i:s",strtotime($posts[$i]['post_modified']))." </pubDate>\n\t <title>".$posts[$i]['post_title']."</title>\n\t <link>".rtrim(SITE_URL,'/')."/</link>\n\t <description><![CDATA[".$posts[$i]['post_excerpt']."]]></description>\n";
		$enclosure=ltrim($posts[$i]['post_img']);
		$text .="\t ".'<enclosure url="'.SITE_URL.$enclosure.'" length="'.@filesize($enclosure).'" type="image/jpeg"/>'."\n\t</item>\n";
	}
	header('Content-type: text/xml; charset=utf-8');
	die($text ." </channel>\n</rss>");
}

//================================  ROBOTS ===========================================

if(strtolower($request)=='robots.txt'){
	header('Content-type: text/plain');
	die("User-agent: *\r\nDisallow: /\r\nUser-agent: Googlebot\r\nAllow: /\r\nUser-agent: Slurp\r\nAllow: /\r\nUser-Agent: msnbot\r\nAllow: /\r\n\r\nsitemap: ".SITE_URL."sitemap.xml\r\n");
}

//================================  SITEMAP ==========================================

if($request=='sitemap.xml'){
	$posts=sql('SELECT post_url,post_modified FROM posts WHERE post_type="P" ORDER BY post_created DESC;');
	$s="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n<url><loc>".SITE_URL."</loc><lastmod>".date('Y-m-d',filemtime(DATA_FOLDER.'/posts.sqlite'))."</lastmod></url>\n";
	for($i=0;$i<count($posts);$i++){
		$s.="<url><loc>".SITE_URL.($posts[$i]['post_url']).'/</loc><lastmod>'.substr($posts[$i]['post_modified'],0,10)."</lastmod></url>\n";
	}
	header('Content-type: text/xml; charset=utf-8');
	die($s.'</urlset>');
}

//================================  STORE ============================================

if(SITE_STORE and preg_match('/^receipt\/\d+$/',$request)){
	$order_id=substr($request,8,-6);
	$receipt_no=substr($request,8);
	(store_receipt_no($order_id)==$receipt_no) or die_html('خطا در پردازش شماره رسید','شماره رسید معتبر نیست یا حذف شده است.');

	$order=sql('SELECT * FROM orders WHERE order_id=?;',$order_id);
	$order or die_html('خطا در پردازش شماره سفارش','شماره سفارش معتبر نیست یا حذف شده است.');

	$order=$order[0];
	$order['order_data']=(array) json_decode($order['order_data'],true);
	$c=(array) json_decode($order['order_customer'],true);

	$inf='<style>ul{list-style:none;padding:15px 5px;}li{padding:10px 0;}li i{display:inline-block;width:150px;color:#555;font-style:normal}</style>';

	$inf.='<ul><li><i>فروشگاه</i>'.$sdb['sitename'].' <a style="float:left;font-family:sans-serif" href="/">'.$_SERVER['HTTP_HOST'].'</a></li><li><i>شماره سفارش </i>'.$order_id.' <a style="float:left;font-family:sans-serif" href="/receipt/'.$receipt_no.'/">'.$_SERVER['HTTP_HOST'].'/receipt/'.$receipt_no.'</a></li><li><i> مبلغ </i>'.number_format($order['order_amount'],0,',').' '.STORE_CURRENCY.' </li><li><i>تاریخ</i> <span dir="ltr" title="'.$order['order_date'].'">'.pdate($order['order_date']).'</span></li>';

	if(isset($order['order_data']['method_name'])){
		$inf.='<li><i>روش پرداخت</i>'.$order['order_data']['method_name'].'</li>';
	}
	if(isset($order['order_data']['transaction_id'])){
		$inf.='<li><i>شناسه تراکنش</i><span dir="ltr" style="font-family:sans-serif">'.$order['order_data']['transaction_id'].'</span></li>';
	}

	$ca=json_decode($order['order_cart']);
	if($ca){
		$inf.='<li><i>سبد خرید</i><p style="margin-right:150px;">';
		foreach($ca as $cai){//0id,1url,2title,3price,4ord
			$inf.=($cai[4]==1?'':($cai[4].' واحد ')).'«'.$cai[2].'» به مبلغ ' . number_format($cai[3],0, '.', ',') . ' '.STORE_CURRENCY.'<br>';
		}
		$inf.='</p></li>';
	}

	$inf.='<li><i>مشخصات</i><p style="margin-right:150px;overflow-wrap:anywhere">'.implode('<br>',$c).'</p></li></ul>';

	if(isset($order['order_data']['note'])){
		$inf.='<div style="padding:10px;background:#eee;margin:10px 0">' . str_replace("\n",'<br>',trim($order['order_data']['note'])) .'</div>';
	}

	if($order['order_status']=='P'){
		if((time()-strtotime($order['order_date']))<20*60){//store_file can be available for up to 20 minutes.
			$pids=[];
			for($i=0;$i<count($ca);$i++){$pids[]=$ca[$i][0];}
			if($pids){
				$a=sql('SELECT post_title,post_data FROM posts WHERE post_id IN ('.implode(',',$pids).') AND post_data LIKE \'%"store_file":"%\';');
				if($a){
					$_SESSION['store_file']=[];
					for($i=0;$i<count($a);$i++){
						$p=json_decode($a[$i]['post_data'],true);
						$_SESSION['store_file'][$i]=$p['store_file'];
						$inf.='<p><a target="_blank" href="/get_store_file/'.$i.'/">دریافت ضمیمه ('.$a[$i]['post_title'].')</a></p>';
					}
				}
			}
		}

		die_html('رسید تراکنش موفق','<h1 style="padding:10px;background:green;color:#fff">پرداخت با موفقیت انجام شده است.</h1>'.$inf);
	}

	if(empty($_GET) and empty($_POST)){
		die_html($order['order_status']=='E'?'رسید تراکنش ناموفق':'رسید تراکنش  ناتمام','<h1 style="padding:10px;background:'.($order['order_status']=='E'?'crimson':'gray').';color:#fff;padding:10px;">'.(isset($order['order_data']['exception'])?$order['order_data']['exception']:($order['order_status']=='E'?'تراکنش ناموفق':'وضعیت تراکنش پرداخت سفارش نامشخص است.')).'</h1>'.$inf);
	}

	$i=intval($order['order_data']['method_index']);
	$p=[];
	$a=array();

	foreach(explode(';',trim($sdb['payment_methods'][$i][2],';')) as $ai){
		$ai3=explode(',',$ai.',,');
		if($ai3[0]){$p[$ai3[0]]=$ai3[1];}
	}

	$amount=intval($order['order_amount']);

	//اسکریپت برگشت
	eval($sdb['payment_methods'][$i][4]);

	$a['exception']=empty($a['exception'])?'پرداخت انجام نشد.':$a['exception'];
	logmsg('پرداخت انجام نشد.');
	store_order_error($order_id,$a);
	exit;
}

if(SITE_STORE and $request=='checkout' and isset($_POST['cart'])){
	$_SESSION['POST']=$_POST;
	header('Location: /checkout/');
	exit;
}

if(SITE_STORE and $request=='checkout' and isset($_SESSION['POST'])){
	$POST=$_SESSION['POST'];
	unset($_SESSION['POST']);
	$pay_method=isset($POST['pay_method'])?intval($POST['pay_method']):0;
	$cart=array();
	$a=explode(';',$POST['cart']);
	$pids=[];
	$ords=[];
	foreach($a as $ai){
		$p=explode(',',trim(trim($ai),',').',1');
		$pids[]=intval($p[0]);
		$ords[intval($p[0])]=intval($p[1]);
	}
	$amount=0;
	if($pids){
		$a=sql('SELECT post_id,post_url,post_title,post_price FROM posts WHERE post_price>0 and post_id IN('.implode(',',$pids).');');
		if($a){
			foreach($a as $ai){//0id,1url,2title,3price,4ord
				$amount+=intval($ai['post_price']);
				$cart[]=[$ai['post_id'],$ai['post_url'],$ai['post_title'],$ai['post_price'],$ords[$ai['post_id']]];
			}
		}
	}
	if($amount>0 and isset($sdb['payment_methods'][$pay_method])){
		$p=[];		// Parameters in selected payment_methods
		$a=array(); // Empty array ready to store paygate data
		$c=isset($POST['customer'])?$POST['customer']:array(); // Customer array in checkout form

		foreach(explode(';',trim($sdb['payment_methods'][$pay_method][2],';')) as $ai){
			$ai3=explode(',',$ai.',,');
			if($ai3[0]){$p[$ai3[0]]=$ai3[1];}
		}

		$order_id=sql('INSERT INTO orders VALUES(null,"",?,?,?,?,?)',[$amount,date('Y-m-d H:i:s'),json_encode($cart,JSON_UNESCAPED_UNICODE),json_encode($c,JSON_UNESCAPED_UNICODE),json_encode(['method_index'=>$pay_method,'method_name'=>$sdb['payment_methods'][$pay_method][0]],JSON_UNESCAPED_UNICODE)]);

		logmsg('سفارش جدید، شماره '.$order_id.'، مبلغ '.$amount.' '.STORE_CURRENCY.'.');

		$receipt_no= store_receipt_no($order_id);
		$callback_url=SITE_URL.'receipt/'.$receipt_no.'/';

		if(!isset($_SESSION['receipts'])){$_SESSION['receipts']='';}
		$_SESSION['receipts'].=$receipt_no.',';

		$description='سفارش شماره '.$order_id.' با شماره رسید '.$receipt_no;
		if(isset($c['name'])){$description.=' به نام «'.$c['name'].'»';}
		if(isset($c['phone'])){$description.=' و تلفن «'.$c['phone'].'»';}

		//اسکریپت ارجاع
		eval($sdb['payment_methods'][$pay_method][3]); //go to pay gate or fall in error

		logmsg('خطا در اتصال به درگاه پرداخت، سفارش '.$order_id);
		$a['exception']=empty($a['exception'])?'خطا در اتصال به درگاه پرداخت':$a['exception'];
		store_order_error($order_id,$a);
		exit;
	}
}

//================================  USER SESSION ============================================

if(!$_SESSION['user_id'] and isset($_COOKIE['wotor3lc'])){
	$a=sql('SELECT user_id,user_role,user_name,user_url FROM users WHERE user_cookie=? LIMIT 1;',$_COOKIE['wotor3lc']);
	if($a){
		$_SESSION['user_id']=$a[0]['user_id'];
		$_SESSION['user_role']=$a[0]['user_role'];
		$_SESSION['user_name']=$a[0]['user_name'];
		sql('UPDATE users SET user_login=? WHERE user_id=?;',[date('Y-m-d H:i'),$a[0]['user_id']]);
	}else{
		setcookie('wotor3lc','',time()-1000,'/');
	}
}

//================================  VISIT COUNTOR ============================================

if(isset($_SERVER['HTTP_USER_AGENT']) and !isset($_SESSION['visit']) and !preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT'])){
	$os='';
	foreach(['Android','Linux','Windows','iPhone','Mac OS','NetBSD','SunOS'] as $k){
		if(strpos($_SERVER['HTTP_USER_AGENT'],$k)!==false){$os=$k;break;}
	}
	if(!$os and preg_match('/\((\w+)/',str_replace(['compatible; ','(X11;'],'',$_SERVER['HTTP_USER_AGENT']),$m)){
		$os=$m[1];
	}
	$b='';
	foreach(['GoogleApp','Firefox','SamsungBrowser','MiuiBrowser','HuaweiBrowser','OPR','Opera','Maxthon','Chrome','Safari','Vivaldi','Edge','IE','Dalvik','Android WebView','Google','PaleMoon','Edg','UBrowser','YaBrowser','Trident','MSIE'] as $k){
		if(strpos($_SERVER['HTTP_USER_AGENT'],$k)!==false){$b=$k;break;}
	}
	$_SESSION['visit']=$_SERVER['REMOTE_ADDR'].','.$os.','.$b.','.((isset($_SERVER['HTTP_REFERER']) and strpos($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST'])===false)?$_SERVER['HTTP_REFERER']:'');

	$s=@file_get_contents(DATA_FOLDER.'/countor.json');
	$countor=(array) json_decode($s,true);
	if($countor or !file_exists(DATA_FOLDER.'/countor.json')){
		$now=time();
		$onlines=array([$_SERVER['REMOTE_ADDR'],$now]);
		if(isset($countor['onlines'])){
			for($i=0;$i<count($countor['onlines']);$i++){
				if(($now-$countor['onlines'][$i][1])<180){
					if($countor['onlines'][$i][0]==$_SERVER['REMOTE_ADDR']){
						$now=0;
						break;
					}else{
						$onlines[]=$countor['onlines'][$i];
					}
				}
			}
		}
		if($now){
			list($y,$m,$d) = explode('-', date('y-m-d'));
			$rf=(isset($_SERVER['HTTP_REFERER']) and (stripos($_SERVER['HTTP_REFERER'],'google')!==false or  strpos($_SERVER['HTTP_REFERER'],'bing')!==false))?1:0;
			$countor['onlines']=$onlines;
			$countor['years'][$y]  =    isset($countor['years'][$y])     ? [$countor['years'][$y][0]+1,$countor['years'][$y][1]+$rf]:[1,$rf];
			$countor['months'][$y.$m] = isset($countor['months'][$y.$m]) ? [$countor['months'][$y.$m][0]+1,$countor['months'][$y.$m][1]+$rf]:[1,$rf];
			$countor['days'][$y.$m.$d]= isset($countor['days'][$y.$m.$d])? [$countor['days'][$y.$m.$d][0]+1,$countor['days'][$y.$m.$d][1]+$rf]:[1,$rf];

			krsort($countor['days']);
			$countor['days']=array_slice($countor['days'],0,30,true);
			krsort($countor['months']);
			$countor['months']=array_slice($countor['months'],0,6,true);

			$s=json_encode($countor,JSON_NUMERIC_CHECK);
			$r=@file_put_contents(DATA_FOLDER.'/countor.json',$s,LOCK_EX);
			if($r!==strlen($s)){
				logmsg('خطادر ذخیره پرونده countor.json');
				@file_put_contents(DATA_FOLDER."/countor.backup.$y-$m-$d.json",$s);
			}
		}
	}
	unset($countor);
}

$s=$sdb['theme']?@file_get_contents('themes/'.$sdb['theme'].'/pages/theme.json'):'';
$tdb=(array) json_decode($s,true);

//================================  TDB THEME_PHP ==========================================

if(isset($tdb['theme_php'])){eval($tdb['theme_php']);}

//================================= CTRL AREA =======================================

if($request==$sdb['login_url']){
	if(!$_SESSION['user_id']){
		if(isset($_POST['login'])){
			if($_POST['login']=='reset' and isset($_GET['resetpass'])){
				isset($_SESSION['reset_pass']) or die('ERROR|شناسه بازنشانی منقضی شده یا روی این مرورگر معتبر نیست.');
				($_SESSION['reset_pass']==$_GET['resetpass']) or die('ERROR|شناسه بازنشانی معتبر نیست یا منقضی شده است.');
				(strlen($_POST['pass'])>4) or die('ERROR|رمز انتخابی شما بیش از حد کوتاه است.');
				sql('UPDATE users SET user_pass=? WHERE user_id=?;',[md5($_POST['pass']),$_SESSION['reset_uid']]);
				$_POST['email']=$_SESSION['reset_email'];
				$_POST['login']='login';
			}

			if($_POST['login']=='login'){
				$a=sql('SELECT user_id,user_role,user_name,user_url FROM users WHERE user_email=? AND user_pass=? LIMIT 1;',[trim(strtolower($_POST['email'])),md5($_POST['pass'])]);
				$a or die('ERROR|اطلاعات ورود صحیح نیست.');
				$key=bin2hex(random_bytes(8));
				sql('UPDATE users SET user_cookie=?,user_login=? WHERE user_id=?;',[$key,date('Y-m-d H:i'),$a[0]['user_id']]);
				setcookie('wotor3lc',$key,time()+3600*24*15,'/');
				$_SESSION['user_id']=$a[0]['user_id'];
				$_SESSION['user_name']=$a[0]['user_name'];
				$_SESSION['user_role']=$a[0]['user_role'];
				logmsg('ورود  '.$a[0]['user_name']);
				die('OK');
			}

			if($_POST['login']=='lose'){
				$_POST['email']=strtolower($_POST['email']);
				$a=sql('SELECT user_id FROM users WHERE user_email=? LIMIT 1;',$_POST['email']);
				$a or die('ERROR|اطلاعات کاربر صحیح نیست.');
				$_SESSION['reset_pass']=bin2hex(random_bytes(8));
				$_SESSION['reset_email']=$_POST['email'];
				$_SESSION['reset_uid']=$a[0]['user_id'];
				$f=@mail($_POST['email'],'بازنشانی رمز ورود',"پیوند بازنشانی رمز ورود شما\r\n".SITE_URL.$sdb['login_url'].'/?resetpass='.$_SESSION['reset_pass'],"From: info@".$_SERVER['HTTP_HOST']."\r\nMIME-Version: 1.0\r\nContent-Type: test/plain; charset=utf-8\r\n",'-f info@'.$_SERVER['HTTP_HOST']);
				logmsg('بازنشانی ورود '.$_POST['email']);
				die($f?'SENT':'ERROR|ایمیل بازنشانی ارسال نشد.<a target="_blank" style="float:left;color:#fff;text-decoration:underline" href="//www.websitemotor.com/help/#ایمیل-بازنشانی-ارسال-نشد">راهنما</a>');
			}
			die('ERROR|موارد ارسالی معتبر نیست.');
		}
		if(!empty($_POST)){die('ERROR|ورود شما به بخش مدیریت نامعتبر یا منقضی شده است.');}
		die_html('ورود به مدیریت','<noscript><div style="background:red;color:#fff;padding:10px">عملکرد این بخش وابسته به قابلیت جاوا اسکریپت در مرورگر است. لطفاً آن را فعال کنید یا مرورگر دیگری را امتحان کنید.</div><style>#lfrm{display:none}</style></noscript><style>p{margin:10px 0}.login .ed,.login .pd{display:block}.login .pds{display:none}.login .obl{display:none}.login .fbtn:before{content:\'ورود\'}.lose .ed{display:block}.lose .pd{display:none}.lose .pds{display:none}.lose .obf{display:none}.lose .fbtn:before{content:\'بازنشانی رمز ورود\'}.reset .ed{display:none}.reset .pd{display:block}.reset .ob{display:none}.reset .fbtn:before{content:\'به روز رسانی رمز ورود\'}.ob{text-align:left;margin:25px 0 0}.ob .obl,.ob .obf{padding:0 10px;background:#888;border-radius:2px;color:#fff;cursor:pointer;}.loader{position:absolute;text-align:center;width:100%;top:0;bottom:0;right:0;left:0;background:rgba(255,255,255,.5)}.loader:before{content:\' \';margin-top:35%;border:2px solid #eee;border-top:2px solid #39d;border-radius:50%;width:100px;height:100px;animation:spin 1s linear infinite;display:inline-block}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}input{border:1px solid #ccc;border-radius:3px;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;display:block;width:100%;padding:10px;margin:2px 0 10px;box-sizing:border-box;direction:ltr}input:focus{border-color:#28f;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}label{display:block;margin-top:25px;color:#000}label a{font-size:14px;float:left;font-size:14px;padding:0 5px;color:#fff;background:teal;border-radius:2px;line-height:1.25;margin-top:5px;user-select:none;line-height:1}label a:active{transform:translateY(1px)}form{margin:25px 0;max-width:400px;margin:10px auto}form p{color:#555;font-size:14px}input{margin-bottom:0}button{background:#08f;color:#fff;border:none;width:100px;border-radius:3px;cursor:pointer}</style><div style="margin:50px auto"><div id="lfrm" style="box-shadow:0 1px 5px #000;padding:10px;direction:rtl;max-width:400px;width:90%;margin:100px auto;position:relative;overflow:hidden;"><p align="center"><a style="font-size:21px;text-decoration:none;" href="/">'.$sdb['sitename'].'</a></p><p id="msg" onclick="this.style.top=\'-300px\'" style="background:red;color:#fff;transition:.5s;padding:15px;position:absolute;top:-100px;right:0;left:0"></p><form onsubmit="gologin();return false;" style="transition:.5s all;transform:none"><div class="ed"><label for="inp-email">نشانی ایمیل:</label><input id="inp-email" type="email" name="email" autocomplete="email" style="text-transform:lowercase;font-family:sans-serif" required></div><div class="pd"><label for="inp-pass">رمز ورود<span class="pds"> جدید</span>:</label><input id="inp-pass" type="password" name="pass" style="font-family:sans-serif" autocomplete="current-password" required></div><label for="captcha">ارقام تصویر:</label><img src="/captcha" style="width:45%;float:left;cursor:pointer" title="برای تغییر تصویر، کلیک کنید." onclick="this.src=\'/captcha/?r=\'+Math.random()"><input id="captcha" style="width:50%;display:inline-block" type="number" name="captcha" value="" required autocomplete="off" spellcheck="false"><div style="text-align:center;margin-top:35px;"><button class="fbtn" type="submit" style="width:150px;padding:5px 0;font:15px web_yekan;cursor:pointer"></button></div></form><div class="ob"><a class="obl" onclick="swch()">ورود</a><a class="obf" onclick="swch()">بازنشانی رمز</a></div></div></div><script>var fc=document.getElementById("lfrm"),ip=document.getElementById("inp-pass"),ie=document.getElementById("inp-email");function swch(){document.getElementById("msg").style.top="-100px";var e=document.querySelector("#lfrm form");e.style.transform="none"!=e.style.transform?"none":"rotateX(360deg)","ورود"==event.target.innerHTML?(fc.className="login",ip.type="password",ip.required=true):(fc.className="lose",ip.required=false)}function gologin(){var e=document.getElementById("lfrm"),t=document.getElementById("msg");t.style.top="-100px",e.insertAdjacentHTML("beforeend",\'<div class="loader"></div>\');var n=new FormData(e.querySelector("form"));e.style.pointerEvents="none",n.append("login",e.className),(r=new XMLHttpRequest).open("POST","",!0),r.onload=function(){t.style.top="0","OK"==this.responseText?(t.innerHTML="در حال ورود به مدیریت سایت...",t.style.background="#080",window.location.href=window.location.pathname):"SENT"==this.responseText?(t.innerHTML="پیوند بازنشانی رمز  به ایمیل شما ارسال شد.",t.style.background="#080",e.removeChild(e.querySelector(".loader"))):(e.removeChild(e.querySelector(".loader")),e.style.pointerEvents="auto",document.getElementById("captcha").value="",e.querySelector("img").src="/captcha/?"+Math.random(),t.innerHTML=0===this.responseText.indexOf("ERROR|")?this.responseText.substring(6):"خطا در اتصال به سایت")},r.send(n)}location.href.indexOf("/?resetpass")>0?(fc.className="reset",ip.type="text",ie.required=!1):(fc.className="login",ip.type="password",ie.required=!0);</script>',0);
	}

	//**************************************************************

	error_reporting(E_ALL);

	if(empty($_POST)){
		if(isset($_GET['download'])){
			header('Content-type: application/octet-stream');
			header('Content-Disposition: attachment; filename='.basename($_GET['download']) );
			readfile(ltrim($_GET['download'],'/'));
			exit;
		}

	//-------------------- DASHBOARD --------------------

		if(strpos($_SERVER['REQUEST_URI'],'/?dashboard_')>1){
			header('Content-type: text/plain; charset=utf-8');
			header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
			header('Pragma: no-cache');
		}

		if(isset($_GET['dashboard_data'])){
			$a=[];
			$b=sql('SELECT
			sum(case when (post_author='.$_SESSION['user_id'].' AND post_type="P") then 1 else 0 end) AS my_posts_no ,
			sum(case when (post_author='.$_SESSION['user_id'].' AND post_type="D") then 1 else 0 end) AS my_drafts_no ,
			sum(case when post_type="P" then 1 else 0 end) AS posts_no ,
			sum(case when post_type="C" then 1 else 0 end) AS categories_no ,
			sum(case when post_type="T" then 1 else 0 end) AS tags_no,
			sum(case when post_price>0  then 1 else 0 end) AS posts_store_no FROM posts');
			list($a['my_posts_no'],$a['my_drafts_no'],$a['posts_no'],$a['categories_no'],$a['tags_no'],$a['posts_store_no'])=array_values($b[0]);

			//comment_status 0:received, 1:published 2:confirmed
			$b=sql('SELECT
			sum(case when comment_status<2 then 1 else 0 end) AS comments_in ,
			sum(case when comment_status=1 then 1 else 0 end) AS comments_pub ,
			COUNT(*) AS comments_no FROM comments');
			list($a['comments_in'],$a['comments_pub'],$a['comments_no'])=array_values($b[0]);

			if(SITE_STORE){
				$b=sql('SELECT
				sum(case when order_status="P" then 1 else 0 end) AS orders_paid ,
				sum(case when order_status="P" then order_amount else 0 end) AS orders_income ,
				COUNT(*) AS orders_no FROM orders');
				list($a['orders_paid'],$a['orders_income'],$a['orders_no'])=array_values($b[0]);
				$a['orders_last']='';
				if($a['orders_no']){
					$b=sql('SELECT order_id FROM orders ORDER BY order_id DESC LIMIT 10;');
					foreach($b as $bi){$a['orders_last'].=$bi['order_id'].',';}
				}
			}

			die("OK\n". json_encode($a));
		}
		if(isset($_GET['dashboard_data_more'])){
			$a=sql('SELECT post_id,post_url,post_title FROM posts ORDER BY post_modified DESC LIMIT 25;');
			$p=[];
			foreach($a as $ai){$p[$ai['post_id']]=[0,'',0];}
			$b=sql('SELECT * FROM post_rates WHERE post_id IN('.implode(',',array_keys($p)).');');
			foreach($b as $bi){$p[$bi['post_id']]=[$bi['post_visit'],$bi['post_votes'],0];}
			$b=sql('SELECT comment_pid FROM comments WHERE comment_pid IN('.implode(',',array_keys($p)).');');
			foreach($b as $bi){$p[$bi['comment_pid']][2]++;}

			for($i=0;$i<count($a);$i++){
				//id,url,title,visit,votes,comments
				$a[$i]=implode("\t",$a[$i])."\t".$p[$a[$i]['post_id']][0]."\t".$p[$a[$i]['post_id']][1]."\t".$p[$a[$i]['post_id']][2];
			}
			$a=array('recents'=>$a,'logs'=>[]);

			$b=@file(DATA_FOLDER . '/wotor.log');
			if($b){
				for($i=count($b)-1;$i>=0;$i--){
					$a['logs'][]=trim($b[$i]);
					if(count($a['logs'])>25){break;}
				}
			}
			die("OK\n". json_encode($a,JSON_UNESCAPED_UNICODE));
		}
		if(isset($_GET['dashboard_sess'])){
			$n=0;
			$p='';
			$me=0;
			$si=session_id();

			$fs = glob(ini_get('session.save_path').'/sess_*', GLOB_NOSORT);
			array_multisort(array_map('filemtime', $fs), SORT_NUMERIC, SORT_DESC,$fs);

			foreach($fs as $f) {
			  $me=(substr(basename($f),5)== $si);
			  $s=$me ? session_encode() : @file_get_contents($f);
			  if(preg_match('/visit\|s:\d+\:"(.*?)"/',$s,$m)){
				  $d= date("Y-m-d H:i", filemtime($f));
				  $p.=$d.'|'.str_replace(',','|',$m[1]).'|'.(preg_match('/user_name\|s:\d+\:"(.*?)"/',$s,$m)?$m[1]:'').($me?'*':'').'|'.(preg_match('/seen\|s:\d+\:"(.*?)"/',$s,$m)?trim($m[1],','):'')."\n";
				  //'|'.(preg_match('/comments\|s:\d+\:"(.*?)"/',$s,$m)?trim($m[1],','):'').'|'.(preg_match('/votes\|s:\d+\:"(.*?)"/',$s,$m)?trim($m[1],','):'').
			  }
			  if(++$n==100){break;}
			}
			die("OK\n$p");
		}

	//-------------------- CTRL SCRIPT --------------------
		$html_templates=[];
		$a=glob('themes/'.$sdb['theme'].'/pages/*.html');
		for($i=0;$i<count($a);$i++){
			$a[$i]=basename($a[$i],'.html');
			if(preg_match('/^[a-z0-9_-]+$/i',$a[$i])){
				$html_templates[]=$a[$i];
			}
		}

		$a=glob('plugins/*/index.php');
		$s=str_replace(['plugins/','/index.php'],'',implode(',',$a));
		if((isset($sdb['plugins'])?$sdb['plugins']:'')!=$s){
			$sdb['plugins']=$s;
			write_sdb();
		}

		$a=sql('SELECT post_id,post_title,post_url,post_type,post_category FROM posts WHERE post_type="C" ;');
		$categories=array();
		for($i=0; $i<count($a); $i++){
			$categories[$a[$i]['post_id']]=array($a[$i]['post_title'],$a[$i]['post_url'],$a[$i]['post_category']);
		}
		$themes_installed=glob('themes/*/pages/theme.json');

		die('<!DOCTYPE html><html lang="fa"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>  مدیریت سایت </title><meta name="robots" content="none"><style>@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style></head><body><noscript><p style="background:red;color:#fff;padding:15px;text-align:center;">‫عملکرد این بخش وابسته به فعال بودن قابلیت جاوا اسکریپت در مرورگر است.</p></noscript><div style="border:2px solid #eef;border-top:2px solid #28f;border-radius:50%;width:100px;height:100px;animation:spin 1s linear infinite;text-align:center;margin:auto;margin-top:30vh"></div><p style="text-align:center;margin-top:-55px">وب‌سایت موتور</p><script>var CTRL={};'.
		"CTRL.templates='".implode(',',$html_templates)."';".
		'CTRL.user={user_id:'.$_SESSION['user_id'].',user_role:"'.$_SESSION['user_role'].'",user_name:"'.$_SESSION['user_name']."\"};".
		'CTRL.sdb={sitename:"'.$sdb['sitename'].'", theme:"'.$sdb['theme'].'",'.
		'mtitle:"'.$sdb['mtitle'].'",'.
		'mdescription:'.json_encode($sdb['mdescription'],JSON_UNESCAPED_UNICODE).','.
		'mkeywords:'.json_encode($sdb['mkeywords'],JSON_UNESCAPED_UNICODE).','.
		'mtitle:"'.$sdb['mtitle'].'",'.
		'login_url:"'.$sdb['login_url'].'",'.
		'site_store:"'.((isset($sdb['site_store']) and $sdb['site_store']=='yes')?'yes':'no').'",store_desc:'.(isset($sdb['store_desc'])?json_encode($sdb['store_desc'],JSON_UNESCAPED_UNICODE):'""').', store_cond:'.(isset($sdb['store_cond'])?json_encode($sdb['store_cond'],JSON_UNESCAPED_UNICODE):'""').',payment_methods:'.((isset($sdb['payment_methods']))?json_encode($sdb['payment_methods'],JSON_UNESCAPED_UNICODE):'[]').'};'.'CTRL.tdb='.json_encode($tdb,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK).'; CTRL.upload_max_mb='.get_upload_max_mb().';CTRL.categories='. json_encode($categories,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK) .';CTRL.themes_installed='. ( $themes_installed? ('[\''. str_replace(['themes/','/pages/theme.json'],'',implode("','",$themes_installed)) ."']") : '[]'  ) . '; CTRL.plugins="'.(isset($sdb['plugins'])?$sdb['plugins']:'').'";</script><script src="//static.websitemotor.com/js/script.3.0.js"></script></body></html>');
	}

	//-------------------- CTRL FILEMANAGER --------------------

	if(isset($_POST['filemanager']) and isset($_POST['type'])){
		foreach(['/../','\\',"\t","\n","\r","\0",':','>','<','|','?','*','"',"'"] as $c){
			if(strpos($_POST['filemanager'],$c)!==false){
				die('ERROR|مسیر معتبر نیست.');
			}
		}
		$path=trim($_POST['filemanager'],'/');
		if($path){$path.='/';}

		if(isset($_POST['action']) and in_array($_SESSION['user_role'],['admin','editor','author'])){
			if($_POST['action']=='upload'){
				if(empty($_FILES['upfile']) or $_FILES['upfile']['error'] or empty($_FILES['upfile']['name']) or strpos($_FILES['upfile']['name'],'/')!==false or strpos($_FILES['upfile']['name'],'\\')!==false){
					die('ERROR|خطا در بارگذاری پرونده');
				}
				if($_POST['type']=='theme'){
					($_SESSION['user_role']=='admin') or die('ERROR|این دسترسی محدود به مدیر سایت است.');
					$tmp='tmp-'.bin2hex(random_bytes(4)).'/';
					$err='';
					mkdir($tmp,0777,true);
					if(is_uploaded_file($_FILES['upfile']['tmp_name'])){
						if(move_uploaded_file($_FILES['upfile']['tmp_name'],$tmp.'ziptheme.zip')){
							$zip = new ZipArchive;
							$res = $zip->open($tmp.'ziptheme.zip');
							if($res === true){
								$zip->extractTo($tmp);
								$zip->close();
								$a= glob($tmp.'*' , GLOB_ONLYDIR);
								if(count($a)!=1 or !file_exists($tmp . basename($a[0]) .'/pages/theme.json')){
									$err='پرونده بارگذاری شده یک پوسته معتبر تشخیص داده نشد.';
								}else{
									$tname=basename($a[0]);
									if(file_exists('themes/'.$tname)){
										$err='این پوسته قبلاً‌ نصب شده است.';
									}else{
										if(!file_exists('themes')){mkdir('themes');}
										rename($tmp.$tname,'themes/'.$tname);
									}
								}
							}else{
								$err='استخراج پرونده فشرده ممکن نشد.';
							}
						}else{
							$err='خطا در دریافت پرونده بارگذاری شده';
						}
					}else{
						$err='پرونده بار نشد.';
					}
					removeDirectory($tmp);
					die($err?('ERROR|'.$err):'OK');
				}

				(!file_exists($path .$_FILES['upfile']['name'])) or die('ERROR|پرونده‌ای با این نام وجود دارد.');

				if($_SESSION['user_role']!='admin' and strpos($_FILES['upfile']['type'],'image')!==0){
					die('ERROR|دسترسی شما برای بارگذاری این پرونده کافی نیست.');
				}
				if(!is_uploaded_file($_FILES['upfile']['tmp_name']) or !move_uploaded_file($_FILES['upfile']['tmp_name'],$path .$_FILES['upfile']['name'])){
					die('ERROR|بارگذاری انجام نشد.');
				}
				if($_POST['type']=='image'){save_resize_image($path .$_FILES['upfile']['name']);}
				die('OK.');

			}elseif(strpos($_POST['action'],'search:')===0){
				$filter_name=mb_substr($_POST['action'],7);
				$filter_name=str_replace(['/',':','*','?','\\','|','{','}','"','\''],'',$filter_name);
				$s='';
				$f=0;
				$n=0;
				$dirs=[__DIR__ , __DIR__ .'/images'];
				$len=mb_strlen(__DIR__);
				while($f<25 and $n<100){
					if(!isset($dirs[$n])){break;}
					$d = glob($dirs[$n].'/*' , GLOB_ONLYDIR|GLOB_NOSORT);
					$dirs=array_merge($dirs,$d);
					if($dirs[$n] != __DIR__ .'/images' or $n==1){
						$imgs=glob($dirs[$n]. '/*.{jpg,jpeg,png,gif,webp,avif}', GLOB_BRACE);
						for($i=0; $i<count($imgs); $i++){
							if(stripos($imgs[$i],$filter_name)!==false and strpos($imgs[$i],'-thumb.jpg')===false){
								$f++;
								$s.=mb_substr($imgs[$i],$len)."\n";
							}
						}
					}
					$n++;
				}
				die("OK\n".$s);
			}elseif(strpos($_POST['action'],'addf')===0){
				$name=str_replace(['addfolder:','addfile:'],'',$_POST['action']);
				foreach(['/','\\',"\t","\n","\r","\0",':','>','<','|','?','*','"',"'",',',';'] as $c){
					if(strpos($name,$c)!==false){
						die('ERROR|نام وارد شده معتبر نیست.<br>کاربرد «'.$c.'» در نام مجاز نیست.');
					}
				}
				if($_SESSION['user_role']!='admin' and preg_match('/\.php$/i',$name)){
					die('ERROR|دسترسی شما برای ایجاد این پرونده کافی نیست.');
				}
				if(file_exists($path.$name.'/')){
					die('ERROR|پرونده یا پوشه‌ای با این نام وجود دارد.');
				}
				if(strpos($_POST['action'],'addfolder')===0){
					mkdir($path.$name);
				}else{
					file_put_contents($path.$name,'');
				}
			}elseif(strpos($_POST['action'],'delete:')===0){
				$a= explode('|',mb_substr($_POST['action'],7));
				if(!file_exists('trash/')){mkdir('trash/',0777);}
				for($i=0;$i<count($a);$i++){
					$a[$i]=trim($a[$i],'/');
					if(!in_array($a[$i],['','trash','data','themes'])){
						if(strpos($a[$i],'trash/')===0){
							if(is_dir($a[$i])){
								removeDirectory($a[$i]);
							}else{
								@unlink($a[$i]);
							}
						}else{
							@rename($a[$i],'trash/'.basename($a[$i]).(is_dir('trash/'.basename($a[$i]))?('-'.time()):''));
						}
						if(preg_match('/\.(jpg|jpeg|png|gif|webp|avif)$/i',$a[$i])){
							@unlink($a[$i].'-thumb.jpg');
						}
					}
				}

			}elseif(strpos($_POST['action'],'rename:')===0){
				$a= explode('|',mb_substr($_POST['action'],7));
				if(count($a)==2 and $a[0]!=$a[1]){
					foreach(['/','\\',"\t","\n","\r","\0",':','>','<','?','*','"',"'",',',';'] as $c){
						if(strpos($a[0].$a[1],$c)!==false){
							die('ERROR|خطا در تغییر نام');
						}
					}
					if($_SESSION['user_role']!='admin' and preg_match('/\.php$/i',$a[1])){
						die('ERROR|دسترسی شما برای تغییر نام این پرونده کافی نیست.');
					}

					( file_exists($path.$a[0])) or die('ERROR|مورد تغییر نام یافت نشد.');
					(!file_exists($path.$a[1])) or die('ERROR|نام جدید از قبل وجود دارد');

					@rename($path.$a[0],$path.$a[1]);
				}

			}elseif(strpos($_POST['action'],'copy:')===0 or strpos($_POST['action'],'move:')===0){
				$a= explode('|',mb_substr($_POST['action'],5));

				$pth=trim($a[0],'/');
				if($pth!=''){$pth.='/';}

				if($pth!='/' and !is_dir($pth)){
					die('ERROR|نشانی مقصد یافت نشد.');
				}

				for($i=1; $i<count($a); $i++){
					$a[$i]=trim($a[$i],'/');
					if($a[$i]=='' or strpos('/'.$pth.basename($a[$i]).'/','/'.$a[$i].'/')!==false){
						die('ERROR|نشانی مقصد معتبر نیست.<br>'.$pth.basename($a[$i]));
					}
					if(file_exists($pth.basename($a[$i]))){
						die('ERROR|نشانی مقصد از قبل وجود دارد<br>'.$pth.basename($a[$i]));
					}
				}
				for($i=1; $i<count($a); $i++){
					if(strpos($_POST['action'],'copy:')===0){
						copy($a[$i],$pth.basename($a[$i]));
					}else{
						rename($a[$i],$pth.basename($a[$i]));
					}
				}

			}elseif(strpos($_POST['action'],'zip:')===0){
				extension_loaded('zip') or 	die('ERROR|ماژول Zip روی سرور فعال نیست.');
				$a= explode('|',mb_substr($_POST['action'],4));
				$dest=trim($a[0],'/');
				if(!$dest or file_exists($dest)){
					die('ERROR|نام و نشانی مقصد معتبر نیست.');
				}
				@ini_set('max_execution_time',1);
				$zip = new ZipArchive;
				if(!$zip->open($dest, ZIPARCHIVE::CREATE)){
					die('ERROR|امکان ایجاد فایل Zip وجود ندارد.');
				}
				for($i=1; $i<count($a); $i++){
					$source = str_replace('\\', '/', realpath(trim($a[$i],'/')));
					 if (is_dir($source) === true) {
						$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
						foreach ($files as $file) {
							$file = str_replace('\\', '/', $file);
							if (in_array(substr($file, strrpos($file, '/')+1), array('.', '..'))) {
								continue;
							}
							$file = realpath($file);
							$rpath=	str_replace('\\', '/',realpath($path));
							if (is_dir($file) === true) {
								$zip->addEmptyDir(str_replace($rpath . '/', '', str_replace('\\', '/',$file) . '/'));
							} elseif (is_file($file) === true){
								$zip->addFromString(str_replace($rpath . '/', '', str_replace('\\', '/',$file)), file_get_contents($file));
							}
						}
					} elseif (is_file($source) === true) {
						$zip->addFromString(basename($source), file_get_contents($source));
					}
				}
				$zip->close();

			}elseif(strpos($_POST['action'],'unzip:')===0){
				($_SESSION['user_role']=='admin') or die('ERROR|این دسترسی محدود به مدیر سایت است.');
				extension_loaded('zip') or 	die('ERROR|ماژول Zip روی سرور فعال نیست.');
				$a= explode('|',mb_substr($_POST['action'],6));
				$dest=trim($a[1],'/');
				$zf=trim($a[0],'/');
				file_exists($zf) or	die('ERROR|پرونده فشرده یافت نشد.');
				is_dir($dest) or die('ERROR|نشانی مقصد معتبر نیست.');

				$zip = new ZipArchive;
				$res = $zip->open($zf);
				if($res === true){
					$zip->extractTo($dest);
					$zip->close();
				}else{
					die('ERROR|باز کردن پروده فشرده ممکن نشد.');
				}
			}
		}

		$s="OK\n";

		$a=($_POST['type']=='image')?glob($path.'*{.jpg,.jpeg,.png,.gif,.webp,.avif,/}',GLOB_MARK|GLOB_BRACE) : glob($path . '{,.}[!.,!..]*',GLOB_MARK|GLOB_BRACE);

		foreach($a as $ai){
			$ai=str_replace('\\','/',$ai);
			if(preg_match('/[\/|\\\]$/',$ai)){
				$s.='/'.trim($ai,'/').'/';
				if($_POST['type']=='file'){$s.='|'.filemtime($ai);}
				$s.="\n";
			}
		}
		foreach($a as $ai){
			if(!preg_match('/[\/|\\\]$/',$ai)){
				if($_POST['type']=='image' and !preg_match('/\-thumb\.jpg$/',$ai)){
					$s.='/'.$ai."\n";
				}elseif($_POST['type']=='file'){
					$s.='/'.$ai.'|'.filemtime($ai) .'|'.filesize($ai)."\n";
				}
			}
		}

		die($s);
	}

	if(in_array($_SESSION['user_role'],['admin','editor'])){
		if(isset($_POST['install_theme']) and preg_match('/^[A-Za-z0-9_-]+$/',$_POST['install_theme'])){
			$tmp='tmp-'.bin2hex(random_bytes(4)).'/';
			mkdir($tmp) or  die('ERROR|اجازه دسترسی وجود تدارد.');

			$b=@fopen('//static.websitemotor.com/theme/'.$_POST['install_theme'].'/'.$_POST['install_theme'].'.zip','r');

			if(!$b){
				rmdir($tmp);
				die('ERROR|اتصال به سرور پوسته ممکن نشد.');
			}
			file_put_contents($tmp.'ziptheme.zip',$b);
			if(!file_exists($tmp.'ziptheme.zip')){
				rmdir($tmp);
				die('ERROR|ذخیره پوسته ممکن نشد.');
			}
			if(filesize($tmp.'ziptheme.zip')<1024){
				unlink($tmp.'ziptheme.zip');
				rmdir($tmp);
				die('ERROR|خطا در دریافت پوسته');
			}
			$err='';
			$zip = new ZipArchive;
			$res = $zip->open($tmp.'ziptheme.zip');
			if($res === true){
				$zip->extractTo($tmp);
				$zip->close();
				$a= glob($tmp.'*' , GLOB_ONLYDIR);
				if(count($a)!=1 or !file_exists($tmp . basename($a[0]) .'/pages/theme.json')){
					$err='پرونده بارگذاری شده یک پوسته معتبر تشخیص داده نشد.';
				}else{
					$tname=basename($a[0]);
					if(file_exists('themes/'.$tname)){
						$err='این پوسته قبلاً‌ نصب شده است.';
					}else{
						if(!file_exists('themes')){mkdir('themes');}
						rename($tmp.$tname,'themes/'.$tname);
						logmsg("پوسته $tname نصب شد.");
					}
				}
			}else{
				$err='پرونده فشرده باز نشد.';
			}
			removeDirectory($tmp);
			$err and die('ERROR|'.$err);
			$sdb['theme']=$tname;
			write_sdb();
			die('OK');
		}
		if(isset($_POST['active_theme'])){
			$name=$_POST['active_theme'];
			($name and preg_match('/^[a-z0-9_-]+$/i',$name)) or die('ERROR|نام پوسته معتبر نیست.');
			is_dir('themes/'.$name) or die('ERROR|پوسته یافت نشد.');
			($sdb['theme']!=$name) or die('ERROR|پوسته از قبل فعال شده است. تغییری انجام نشد.');
			$sdb['theme']=$name;
			write_sdb();
			logmsg("پوسته $name فعال شد.");
			die('OK');
		}
		if(isset($_POST['del_theme'])){
			$name=$_POST['del_theme'];
			(!$name or !preg_match('/^[a-z0-9_-]+$/i',$name)) and die('ERROR|نام پوسته معتبر نیست.');
			is_dir('themes/'.$name) or die('ERROR|پوسته یافت نشد.');
			if(!file_exists('trash/')){mkdir('trash/');}
			@rename('themes/'.$name,'trash/'.$name.(is_dir('trash/'.$name)?('-'.time()):''));
			if($sdb['theme']==$name){
				$sdb['theme']='';
				write_sdb();
			}
			logmsg("پوسته $name حذف شد.");
			die('OK');
		}
		if(isset($_POST['file_editor']) and $_SESSION['user_role']=='admin'){
			$filename=str_replace(['/../','\\',"\t","\n","\r","\0",':','>','<','|','?','*','"',"'"],'',ltrim($_POST['file_editor'],'/'));
			if(file_exists($filename)){
				if(isset($_POST['file_editor_value'])){
					file_put_contents($filename,$_POST['file_editor_value']);
					die('OK');
				}
				$s="OK\n" .file_get_contents($filename);
				die($s);
			}
			die('ERROR|مورد معتبر نیست.');
		}
		if(isset($_POST['sqlite_q']) and isset($_POST['sqlite_file']) and $_SESSION['user_role']=='admin'){
			$filename=str_replace(['/../','\\',"\t","\n","\r","\0",':','>','<','|','?','*','"',"'"],'',ltrim($_POST['sqlite_file'],'/'));
			if(file_exists($filename)){
				$a=sql($_POST['sqlite_q'],null,ltrim($_POST['sqlite_file'],'/'));
				!is_array($a) and die("OK\n".$_POST['sqlite_q']."\n".$filename."\n".$a);
				$s='';
				if($a){
					$s.=implode("\t",array_keys($a[0]))."\n";
				}
				foreach($a as $ai){
					$b=array_values($ai);
					for($i=0; $i<count($b);$i++){
						$b[$i]=htmlentities(str_replace(["\r\n","\r","\n","\t"],' ',$b[$i]));
					}
					$s.=implode("\t",$b)."\n";
				}
				die($s);
			}
			die('ERROR|مورد معتبر نیست.');
		}
		if(isset($_POST['update_tdb'])){
			foreach($tdb as $k => $tv){
				if(!preg_match('/^theme_/',$k)){
					$v=[	 (is_array($tv))?$tv[0]:$tv
							,(is_array($tv))?(isset($tv[1])?$tv[1]:$tv[0]):$tv
						];
					if(isset($_POST[$k])){
						$v[1]=$_POST[$k];
						$tdb[$k]=(is_array($tv))?$v:$v[1];
					}
				}
			}
			$s=json_encode($tdb,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
			file_put_contents('themes/'.$sdb['theme'].'/pages/theme.json',$s);
			die('OK.');
		}
		if(isset($_POST['update_sdb'])){
			foreach(['sitename','theme','login_url','mtitle','mdescription','mkeywords','site_store','store_desc','store_cond','payment_methods'] as $k){
				if(isset($_POST[$k])){
					if($k=='login_url'){
						$_POST['login_url']=trim($_POST['login_url'],'/');
						if($sdb['login_url']!=$_POST['login_url']){
							foreach(['\\',"\t","\n","\r","\0",':','>','<','|','?','*','"',"'",'#','//',' '] as $c){
								(strpos($_POST['login_url'],$c)===false) or die('ERROR|نشانی مدیریت سایت وارد شده معتبر نیست.');
							}
							(mb_strlen($_POST['login_url'])>2) or die('ERROR|نشانی مدیریت سایت وارد شده بیش از حد کوتاه است.');

							if(in_array($_POST['login_url'],['themes','images','trash','data']) or is_dir($_POST['login_url'])){
								die('ERROR|نشانی وارد شده در حال استفاده است و قابل انتخاب نیست.');
							}
						}
					}elseif(in_array($k,['mtitle','mdescription','mkeywords'])){
						$_POST[$k]=trim(str_replace(["\r\n","\r","\n",'  '],' ',$_POST[$k]));
					}elseif($k=='site_store' and $_POST[$k]=='yes'){
						if(!file_exists(DATA_FOLDER.'/orders.sqlite')){
							sql('CREATE TABLE orders ("order_id" INTEGER,"order_status" TEXT,"order_amount" INTEGER,"order_date" TEXT,"order_cart" TEXT,"order_customer" TEXT,"order_data" TEXT,PRIMARY KEY("order_id"));');
						}
						if(empty($_POST['payment_methods'])){$sdb['payment_methods']=array();}
					}
					$sdb[$k]=$_POST[$k];
				}
			}
			write_sdb();
			die('OK.');
		}
	}

	//-------------------- CTRL POSTS --------------------

	if(isset($_POST['editpost']) and in_array($_SESSION['user_role'],['admin','editor','author'])){
		$id=isset($_POST['pid'])?intval($_POST['pid']):0;

		if($_POST['editpost']=='read'){
			$a=sql('SELECT * FROM posts WHERE post_id=?;',$id);
			$a or die('ERROR|محتوا یافت نشد.');
			$a[0]['post_data']=(array) json_decode($a[0]['post_data'],true);
			$a[0]['post_tags']=sql('SELECT post_id,post_title,post_url FROM posts WHERE post_type="T" AND post_id IN('.trim($a[0]['post_tags'],',').');');
			$b=sql("SELECT post_visit FROM post_rates WHERE post_id=?",$id);
			$a[0]['post_visit']=$b?$b[0]['post_visit']:0;

			die("OK\n". json_encode($a[0],JSON_UNESCAPED_UNICODE));
		}

		$type=isset($_POST['post_type'])?$_POST['post_type']:'P';

		$title=isset($_POST['title'])?trim($_POST['title']):'';
		$title=str_replace(["\t","\n"],' ',trim($title));
		$title or die('ERROR|عنوان وارد شده معتبر نیست.');

		$url=empty($_POST['url'])?$title:$_POST['url'];
		$url=trim(trim($url),'/');
		$url=str_replace([' ','%',':','#','?','|','"','\'','\\',',','،','‌',"\t",'"',"'"],'-',$url);
		$url=preg_replace('#\-+#', '-', trim($url,'-'));

		if(preg_match('/^[0-9]+$/',$url) or preg_match('/^[0-9]+\//',$url)){
			die('ERROR|نشانی یکتا یا جز اول آن نمی‌تواند عددی باشد.');
		}
		if($url){
			$a=sql('SELECT post_id,post_author,post_data FROM posts WHERE post_url=? LIMIT 1;',$url);
			if($a and $a[0]['post_id']!=$id){
				die('ERROR|نشانی یکتا قبلاً‌ اختصاص یافته است.'.(empty($_POST['url'])?'<br>لازم است عنوان یا نشانی یکتای دیگری انتخاب کنید.':''));
			}
		}else{
			$a=sql('SELECT post_id,post_author,post_data FROM posts WHERE post_id=?;',$id);
		}
		$author=$a?$a[0]['post_author']:$_SESSION['user_id'];
		$data_arr=$a?((array) json_decode($a[0]['post_data'],true)) : array();

		$category=(isset($_POST['category']) and preg_match('/^[0-9,]+$/',$_POST['category']))?trim($_POST['category'],','):'';
		$tags=(isset($_POST['tags']) and preg_match('/^[0-9,]+$/',$_POST['tags']))?trim($_POST['tags'],','):'';

		$excerpt=isset($_POST['excerpt'])?trim($_POST['excerpt']):'';
		$content=isset($_POST['content'])?trim($_POST['content']):'';
		$img=isset($_POST['img'])?trim($_POST['img'],'/'):'';

		$template=isset($_POST['template'])?$_POST['template']:'';
		if(($template=='post' and in_array($type,['P','D'])) or ($template=='category' and in_array($type,['C','T']))){$template='';}

		$commenting=(isset($_POST['commenting']) and in_array($_POST['commenting'],['O','C','M'])) ?$_POST['commenting']:'';

		$data_arr['meta']=(isset($_POST['meta'][0])?$_POST['meta'][0]:'').'¦'.(isset($_POST['meta'][1])?$_POST['meta'][1]:'').'¦'.(isset($_POST['meta'][2])?$_POST['meta'][2]:'');
		if($data_arr['meta']=='¦¦'){
			$data_arr=[];
		}else{
			$data_arr['meta']=trim(str_replace(["\r\n","\n"],' ',strip_tags($data_arr['meta'])));
		}

		if(isset($tdb['theme_similar_posts']) and $tdb['theme_similar_posts']=='yes' and isset($_POST['similar']) and preg_match('/^[0-9,]+$/',$_POST['similar'])){
			$data_arr['similar_posts']=trim($_POST['similar'],',');
		}

		$price=(isset($_POST['price']) and isset($_POST['store_type']))?intval(str_replace(',','',$_POST['price'])):0;
		if($price){
			if($_POST['store_type']=='product'){
				$data_arr['store_unit']=trim($_POST['store_unit']);
			}elseif($_POST['store_type']=='file'){
				if(empty($_POST['store_file']) or !is_file(ltrim($_POST['store_file'],'/'))){
					die('ERROR|مقدار وارد شده برای «محتوای قابل دریافت» معتبر نیست.<br> لازم است تا نشانی یک پرونده موجود روی سایت درج شود.'.ltrim($_POST['store_file'],'/'));
				}
				$data_arr['store_file']=ltrim($_POST['store_file'],'/');

			}elseif($_POST['store_type']=='service'){
				$data_arr['store_service']=$_POST['store_service'];
			}
		}

		if(isset($tdb['theme_vars'])){
			$p=explode(';',trim($tdb['theme_vars'],';'));
			foreach($p as $pi){
				$pi0=trim(explode(',',$pi.',')[0]);
				if($pi0){
					$data_arr[$pi0]=isset($_POST['data'][$pi0])?$_POST['data'][$pi0]:'';
				}
			}
		}
		$data_str=($data_arr)?json_encode($data_arr,JSON_UNESCAPED_UNICODE):'';

		$now=date('Y-m-d H:i');

		if(!$id){
			$id=sql('INSERT INTO posts VALUES(null,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);',[$url,$title,$type,$category,$tags,$img,$excerpt,$template,$author,$price,$commenting,$now,$now,$data_str,$content]);
			logmsg(($type=='D'?'پیش‌نویس':($type=='P'?'مطلب':($type=='C'?'دسته':'برچسب')))." $id ایجاد شد.");
		}else{
			sql('UPDATE posts SET post_url=? ,post_title=? ,post_type=? ,post_category=? ,post_tags=? ,post_img=? ,post_excerpt=? ,post_template=? ,post_author=? ,post_price=? ,post_commenting=? ,post_modified=? ,post_data=? ,post_content=? WHERE post_id=?;',[$url,$title,$type,$category,$tags,$img,$excerpt,$template,$author,$price,$commenting,$now,$data_str,$content,$id]);
		}

		if($type=='P' or $type=='D'){
			die('OK|'. $id);
		}

		if($type=='C'){
			$a=sql('SELECT post_id,post_title,post_url,post_category FROM posts WHERE post_type="C";');
			$categories=array();
			foreach($a as $c){
				$categories[$c['post_id']]=array($c['post_title'],$c['post_url'],$c['post_category']);
			}
			die('OK|'. json_encode($categories,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK));
		}
		if($type=='T'){
			die('OK.');
		}

	}
	if(isset($_POST['find_posts'])){
		$qr='SELECT post_id,post_author,post_url,post_title,post_type,post_category,post_modified FROM posts WHERE ';
		$pg=isset($_POST['pg'])?intval($_POST['pg']):0;

		if(isset($_POST['suggest'])){
			$a=array();
			if(empty($_POST['find_posts']) and !empty($_POST['suggest'])){
				$sgt=explode(' ',str_replace(['-',',','،','‌',':','.','/','(',')'],' ',$_POST['suggest']));
				$sgt=array_unique($sgt);
				$sgt=array_values($sgt);
				if($sgt){
					$q='SELECT post_id,post_url,post_title FROM posts WHERE post_type IN ("P","D") AND (';
					for($i=0; $i<count($sgt); $i++){
						$q.=' post_title LIKE ? '.(($i<(count($sgt)-1))?' OR ':'');
						$sgt[$i]='%'.$sgt[$i].'%';
					}
					$a=sql($q.') ORDER BY post_title ASC LIMIT 100;',$sgt);
				}
			}
			if(count($a)<25){
				$a1_ids=[];
				foreach($a as $a1i){
					$a1_ids[]=$a1i['post_id'];
				}
				$a1=sql('SELECT post_id,post_url,post_title FROM posts WHERE post_type IN ("P","D") AND post_title LIKE ? AND post_id NOT IN('.implode(',',$a1_ids).') ORDER BY post_id DESC LIMIT 100;','%'.$_POST['find_posts'].'%');
				$a=array_merge($a,$a1);
			}

		}elseif(mb_strpos($_POST['find_posts'],'نویسنده:')===0 or mb_strpos($_POST['find_posts'],'پیشنویس:')===0 ){
			$q=trim(mb_substr($_POST['find_posts'],8));
			$a=sql('SELECT user_id FROM users WHERE user_name=? LIMIT 1;',$q);
			$a or die('ERROR|کاربری با نام وارد شده یافت نشد.');
			$a=sql($qr.'post_type IN ('. ((mb_strpos($_POST['find_posts'],'پیشنویس:')===0)?'"D"':'"P","D"'). ') AND post_author=? ORDER BY post_id DESC LIMIT 100;',$a[0]['user_id']);

		}elseif(mb_strpos($_POST['find_posts'],'شناسه:')===0){
			$a=sql($qr.'post_type IN ("P","D") AND post_id=?;',trim(mb_substr($_POST['find_posts'],6)));
			$a or die('ERROR|مطلبی با شناسه وارد شده یافت نشد.');

		}elseif(mb_strpos($_POST['find_posts'],'دسته:')===0){
			$a=sql('SELECT post_id FROM posts WHERE  post_type ="C" AND post_title=? LIMIT 1;',trim(mb_substr($_POST['find_posts'],5)));
			$a or die('ERROR|دسته وارد شده یافت نشد.');
			if($a){
				$a=sql($qr.'post_type IN ("P","D") AND (("," || post_category || ",") LIKE ?) ORDER BY post_id DESC LIMIT 100;','%,'.$a[0]['post_id'].',%');
			}

		}elseif(mb_strpos($_POST['find_posts'],'برچسب:')===0){
			$a=sql('SELECT post_id FROM posts WHERE post_type ="T" AND post_title=? LIMIT 1;',trim(mb_substr($_POST['find_posts'],6)));
			$a or die('ERROR|برچسب وارد شده یافت نشد.');
			if($a){
				$a=sql($qr.'post_type IN ("P","D") AND (("," || post_tags || ",") LIKE ?) ORDER BY post_id DESC LIMIT 100;','%,'.$a[0]['post_id'].',%');
			}

		}elseif(preg_match('/^\{[0-9,]+\}$/',$_POST['find_posts'])){
			$a=sql('SELECT post_id,post_title,post_url FROM posts WHERE post_id IN('.trim(substr($_POST['find_posts'],1,-1),',').');');

		}else{
			$a=sql('SELECT post_id,post_author,post_url,post_title,post_type,post_category,post_modified,whole FROM posts CROSS JOIN (SELECT COUNT(1) AS whole FROM posts WHERE post_type IN ("P","D") AND (post_title LIKE ? OR post_excerpt LIKE ?)) WHERE post_type IN ("P","D") AND (post_title LIKE ? OR post_excerpt LIKE ?) ORDER BY post_id DESC LIMIT '.(25*$pg).',25;',['%'.$_POST['find_posts'].'%','%'.$_POST['find_posts'].'%','%'.$_POST['find_posts'].'%','%'.$_POST['find_posts'].'%']);

		}
		$s='OK#'.(isset($a[0]['whole'])?$a[0]['whole']:count($a))."\n";
		foreach($a as $ai){
			unset($ai['whole']);
			$s.=implode("\t",$ai)."\n";
		}
		die($s);
	}
	if(isset($_POST['del_post'])){
		$a=sql('DELETE FROM posts WHERE post_type IN ("P","D") AND post_id=?;',$_POST['del_post']);
		$a or die('ERROR|مطلب یافت نشد.');
		logmsg('مطلب '.$_POST['del_post'].' حذف شد.');
		die('OK.');
	}

	//-------------------- CTRL CATEGORY --------------------

	if(isset($_POST['del_category'])){
		$i=intval($_POST['del_category']);
		$a=sql('DELETE FROM posts WHERE post_type="C" AND post_id=?;',$i);
		$a or die('ERROR|دسته یافت نشد.');
		sql("UPDATE posts SET post_category = TRIM(REPLACE( ',' || post_category || ',' , ',' || $i ||',' ,','),',') WHERE post_type IN ('P','D') AND post_category LIKE '%$i%';");
		$a=sql('SELECT post_id,post_title,post_url,post_category FROM posts WHERE post_type="C";');
		$categories=array();
		foreach($a as $c){
			$categories[$c['post_id']]=array($c['post_title'],$c['post_url'],$c['post_category']);
		}
		logmsg('دسته '.$i.' حذف شد.');
		die('OK|'. json_encode($categories,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK));
	}
	if(isset($_POST['find_categories'])){
		$a=sql('SELECT post_id,post_url,post_title FROM posts WHERE post_type="C" AND post_title LIKE ? ORDER BY post_id DESC LIMIT 1000;','%'.$_POST['find_categories'].'%');
		$s="OK\n";
		foreach($a as $ai){
			$s.=implode("\t",$ai)."\n";
		}
		die($s);
	}

	//-------------------- CTRL TAGS --------------------

	if(isset($_POST['del_tag'])){
		$i=intval($_POST['del_tag']);
		$a=sql('DELETE FROM posts WHERE post_type="T" AND post_id=?;',$i);
		$a or die('ERROR|برچسب یافت نشد.');
		sql("UPDATE posts SET post_tags = TRIM(REPLACE( ',' || post_tags || ',' , ',' || $i ||',' ,','),',') WHERE post_type IN ('P','D') AND post_tags LIKE '%$i%';");
		logmsg('برچسب '.$i.' حذف شد.');
		die('OK.');
	}
	if(isset($_POST['find_tags'])){
		$pg=isset($_POST['pg'])?intval($_POST['pg']):0;
		if(isset($_POST['suggest'])){
			$a=array();
			if(empty($_POST['find_tags']) and !empty($_POST['suggest'])){
				$sgt=explode(' ',str_replace(['-',',','،','‌',':','.','/','(',')'],' ',$_POST['suggest']));
				$sgt=array_unique($sgt);
				$sgt=array_values($sgt);
				if($sgt){
					$q='SELECT post_id,post_url,post_title FROM posts WHERE post_type="T" AND (';
					for($i=0; $i<count($sgt); $i++){
						$q.=' post_title LIKE ? '.(($i<(count($sgt)-1))?' OR ':'');
						$sgt[$i]='%'.$sgt[$i].'%';
					}
					$a=sql($q.') ORDER BY post_id DESC LIMIT 100;',$sgt);
				}
			}
			if(count($a)<25){
				$a1_ids=[];
				foreach($a as $a1i){
					$a1_ids[]=$a1i['post_id'];
				}
				$a1=sql('SELECT post_id,post_url,post_title FROM posts WHERE post_type="T" AND post_title LIKE ? AND post_id NOT IN('.implode(',',$a1_ids).') ORDER BY post_id DESC LIMIT 100;','%'.$_POST['find_tags'].'%');
				$a=array_merge($a,$a1);
			}
		}else{
			$a=sql('SELECT post_id,post_url,post_title,whole FROM posts CROSS JOIN (SELECT COUNT(1) AS whole FROM posts WHERE post_type="T" AND (post_title LIKE ? OR post_excerpt LIKE ?)) WHERE post_type="T" AND (post_title LIKE ? OR post_excerpt LIKE ?) ORDER BY post_id DESC LIMIT '.(25*$pg).',25;',['%'.$_POST['find_tags'].'%','%'.$_POST['find_tags'].'%','%'.$_POST['find_tags'].'%','%'.$_POST['find_tags'].'%']);

		}
		$s='OK#'.(isset($a[0]['whole'])?$a[0]['whole']:count($a))."\n";
		foreach($a as $ai){
			unset($ai['whole']);
			$s.=implode("\t",$ai)."\n";
		}
		die($s);
	}

	//-------------------- CTRL STORE --------------------

	if(isset($_POST['find_store'])){
		$pg=isset($_POST['pg'])?intval($_POST['pg']):0;
		$a=sql('SELECT post_id,post_url,post_title,post_type,post_price,post_modified,whole FROM posts CROSS JOIN (SELECT COUNT(1) AS whole FROM posts WHERE post_price>0 AND post_title LIKE ?) WHERE post_price>0 AND post_title LIKE ? ORDER BY post_id DESC LIMIT '.(25*$pg).',25;',['%'.$_POST['find_store'].'%','%'.$_POST['find_store'].'%']);
		$s='OK#'.(isset($a[0]['whole'])?$a[0]['whole']:count($a))."\n";
		foreach($a as $ai){
			unset($ai['whole']);
			$s.=implode("\t",$ai)."\n";
		}
		die($s);
	}
	if($_SESSION['user_role']=='admin' and isset($_POST['edit_payment_method']) ){
		$sdb['payment_methods'][($_POST['edit_payment_method']=='new')?(isset($sdb['payment_methods'])?count($sdb['payment_methods']):0):$_POST['edit_payment_method']]=[
		$_POST['title'],
		$_POST['desc'],
		$_POST['params'],
		$_POST['script1'],
		$_POST['script2']
		];
		write_sdb();
		die('OK.');
	}

	//-------------------- CTRL ORDERS --------------------

	if(isset($_POST['find_orders'])){
		$_POST['find_orders']=trim($_POST['find_orders']);
		if(preg_match('/^[0-9]+$/',$_POST['find_orders'])){
			if(strlen($_POST['find_orders'])<=6){
				$oid=$_POST['find_orders'];
			}else{
				$oid=substr($_POST['find_orders'],0,-6);
				(store_receipt_no($oid)==$_POST['find_orders']) or die('ERROR|شماره رسید معتبر نیست.');
			}
			$a=sql('SELECT * FROM orders WHERE order_id=?;',$oid);
		}else{
			$a=sql('SELECT * FROM orders WHERE order_cart LIKE ? OR order_customer LIKE ? ORDER BY order_id DESC LIMIT 1000;','%'.$_POST['find_orders'].'%');
		}

		$s="OK\n";
		foreach($a as $ai){
			$ai['order_id']=store_receipt_no($ai['order_id']);
			$s.=implode("\t",$ai)."\n";
		}
		die($s);
	}
	if(isset($_POST['order_note']) and isset($_POST['order_id'])){
		$a=sql('SELECT order_status,order_data FROM orders WHERE order_id=?;',$_POST['order_id']);
		$a or die('ERROR|سفارش یافت نشد.');
		$sts=$a[0]['order_status'];
		$a=(array) json_decode($a[0]['order_data'],true);
		$a['note']=$_POST['order_note'];
		$s=json_encode($a,JSON_UNESCAPED_UNICODE);
		if(isset($_POST['order_status']) and in_array($_POST['order_status'],['P','E'])){$sts=$_POST['order_status'];}
		sql('UPDATE orders SET order_status=?,order_data=? WHERE order_id=?;',[$sts,$s,$_POST['order_id']]);
		logmsg('سفارش '.$_POST['order_id'].' ویرایش شد.');
		die('OK');
	}
	if(isset($_POST['del_order'])){
		sql('DELETE FROM orders WHERE order_id=?;',$_POST['del_order']);
		logmsg('سفارش '.$_POST['del_order'].' حذف شد.');
		die('OK');
	}

	//-------------------- CTRL COMMENTS --------------------

	if(isset($_POST['find_comments'])){
		$qr='SELECT comment_id,comment_pid,comment_status,comment_name,comment_text,comment_date FROM comments WHERE ';
		if(mb_strpos($_POST['find_comments'],'وضعیت:')===0){
			$q=trim(mb_substr($_POST['find_comments'],6));
			$q=($q=='تأیید نشده')?'<2':(($q=='تأیید شده')?'=2':'=1');
			$a=sql($qr."comment_status $q ORDER BY comment_id DESC LIMIT 1000;");

		}elseif(mb_strpos($_POST['find_comments'],'نام:')===0){
			$a=sql($qr."comment_name=? ORDER BY comment_id DESC LIMIT 1000;",trim(mb_substr($_POST['find_comments'],4)));

		}elseif(mb_strpos($_POST['find_comments'],'شناسه:')===0){
			$a=sql($qr."comment_id=?;",intval(mb_substr($_POST['find_comments'],6)));

		}elseif(mb_strpos($_POST['find_comments'],'مطلب:')===0){
			$a=sql($qr."comment_pid=? ORDER BY comment_id DESC LIMIT 1000;",trim(mb_substr($_POST['find_comments'],5)));

		}else{
			$pg=isset($_POST['pg'])?intval($_POST['pg']):0;
			$a=sql('SELECT comment_id,comment_pid,comment_status,comment_name,comment_text,comment_date,whole FROM comments CROSS JOIN (SELECT COUNT(1) AS whole FROM comments WHERE comment_text LIKE ?) WHERE comment_text LIKE ? ORDER BY comment_id DESC LIMIT '.(100*$pg).',100;',['%'.$_POST['find_comments'].'%','%'.$_POST['find_comments'].'%'] );
		}
		if($a){
			$pids=[];
			foreach($a as $ai){
				if(!in_array($ai['comment_pid'],$pids)){$pids[]=$ai['comment_pid'];}
			}
			$b=sql('SELECT post_id,post_url,post_title FROM posts WHERE post_id IN ('. implode(',',$pids) .');');
			$p=[];
			for($i=0; $i<count($b); $i++){
				$p[$b[$i]['post_id']]=$b[$i]['post_url']."\t".$b[$i]['post_title'];
			}
		}

		$s='OK#'.(isset($a[0]['whole'])?$a[0]['whole']:count($a))."\n";
		foreach($a as $ai){
			unset($ai['whole']);
			$ai['comment_text']=str_replace(["\r\n","\r","\n"],'<br>',$ai['comment_text']);
			$s.=implode("\t",$ai)."\t".(isset($p[$ai['comment_pid']])?$p[$ai['comment_pid']]:"\t")."\n";
		}
		die($s);
	}

	if(isset($_POST['del_comment'])){
		sql('DELETE FROM comments WHERE comment_id =?;',$_POST['del_comment']);
		sql('DELETE FROM comment_rates WHERE comment_id =?;',$_POST['del_comment']);
		logmsg('دیدگاه '.$_POST['del_comment'].' حذف شد.');
		die('OK');
	}

	if(isset($_POST['verify_comment'])){
		sql('UPDATE comments SET comment_status=2 WHERE comment_id =?;',$_POST['verify_comment']);
		die('OK');
	}

	if(isset($_POST['edit_cmnt'])){
		$name=trim(strip_tags($_POST['comment-name']));
		$name=str_replace(["\n","\t"]," ",$name);
		$cmmnt=str_replace("\t"," ",trim($_POST['comment-text']));
		!empty($cmmnt) or die('ERROR|متن دیدگاه معتبر نیست.');
		sql('UPDATE comments SET comment_name=?, comment_text=? WHERE comment_id =?;',[$name,$cmmnt,$_POST['edit_cmnt']]);
		die('OK');
	}

	//-------------------- CTRL USERS --------------------

	if(isset($_POST['find_users'])){
		$a=sql('SELECT user_id,user_email,user_name,user_role,user_url,user_login FROM users WHERE user_name LIKE ? ORDER BY user_id ASC LIMIT 1000;','%'.$_POST['find_users'].'%');
		$s="OK\n";
		foreach($a as $ai){
			$s.=implode("\t",$ai)."\n";
		}
		die($s);
	}
	if(isset($_POST['edit_user']) and ($_SESSION['user_role']=='admin' or $_SESSION['user_id']==$_POST['edit_user'])){
		$_POST['email']=trim(strtolower($_POST['email']));
		$_POST['name']=trim($_POST['name']);

		preg_match('/^[^<>\"\'\t\/\|\%\:\@]+$/',$_POST['name']) or die('ERROR|نام انتخابی دارای حروف غیر مجاز است.');

		if($_POST['edit_user']==$_SESSION['user_id']){
			$_POST['role']=$_SESSION['user_role'];
		}
		in_array($_POST['role'],['admin','editor','author','user']) or die('ERROR|دسترسی انتخاب شده نامعتبر است.');

		$a=sql('SELECT 1 FROM users WHERE user_id!=? AND (user_name=? OR user_email=?);',[$_POST['edit_user'],$_POST['name'],$_POST['email']]);
		!$a or die('ERROR|نام یا ایمیل وارد شده، قبلاً‌ برای کاربر دیگری ثبت شده است.');

		if($_SESSION['user_role']=='admin' and $_POST['edit_user']==0){
			sql('INSERT INTO users VALUES (null,?,?,?,?,?,"","")',[$_POST['email'],md5($_POST['pass']),$_POST['name'],$_POST['role'],$_POST['url']]);
			die("OK\n");
		}

		sql('UPDATE users SET user_name=?,user_email=?,user_role=?,user_url=? WHERE user_id=?;',[$_POST['name'],$_POST['email'],$_POST['role'],$_POST['url'],$_POST['edit_user']]);
		if($_POST['edit_user']==$_SESSION['user_id']){
			$_SESSION['user_name']=$_POST['name'];
		}

		die("OK.");
	}

	if($_SESSION['user_role']=='admin' and isset($_POST['del_user']) and $_POST['del_user']!=$_SESSION['user_id']){
		sql('DELETE FROM users WHERE user_id =?;',$_POST['del_user']);
		logmsg('کاربر '.$_POST['del_user'].' حذف شد.');
		die('OK.');
	}

	if(isset($_POST['oldpass']) and isset($_POST['newpass'])){
		(strlen($_POST['newpass'])>3) or die('ERROR|رمز جدید بیش از حد کوتاه است.');
		$r=sql('UPDATE users SET user_pass=? WHERE user_id=? AND user_pass=? ;',[md5($_POST['newpass']),$_SESSION['user_id'],md5($_POST['oldpass'])]);
		die($r?'OK.':'ERROR|رمز قبلی معتبر نیست.');
	}

	//-------------------- CTRL MISC --------------------

	if(isset($_POST['del_logs']) and $_SESSION['user_role']=='admin'){
		@unlink(DATA_FOLDER.'/wotor.log');
		die('OK.');
	}

	if(isset($_POST['do_update']) and $_SESSION['user_role']=='admin'){
		$s=@file_get_contents('https://www.websitemotor.com/latest.json', false, stream_context_create(['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]]));
		$a=(array) json_decode($s,true);
		if(isset($a['script']) and isset($a['script-md5'])){
			$s=@file_get_contents($a['script'], false, stream_context_create(['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]]));
			if($s and md5($s)==$a['script-md5']){
				if(!file_exists('trash/')){mkdir('trash/');}
				@rename( __FILE__ ,'trash/'.basename(__FILE__).'-'.time().'.old');
				$r=@file_put_contents(__FILE__ , $s);
				if($r){
					logmsg('نسخه موتور به '.$a['ver'].'به روز شد.');
					die('OK.');
				}
			}
		}
		die('ERROR|به روز رسانی انجام نشد.<br><a target="_blank" style="float:left" href="//www.websitemotor.com/help/#به-روز-رسانی">راهنما</a>');
	}

	//--------------------  --------------------

	die('ERROR|موارد ارسالی معتبر نیست.');
}

//================================= none CTRL $_POSTs ===============================

if(!$request and !empty($_POST)){
	header('Content-type: text/plain; charset=utf-8');
	header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
	header('Pragma: no-cache');

	if(isset($_POST['readcomments'])){
		$pid=intval($_POST['readcomments']);
		$parent=isset($_POST['parent'])?intval($_POST['parent']):0;
		$last_cid=$parent?0:intval($_POST['last_cid']);

		$cmnts=sql("SELECT comment_id,comment_name,comment_text,comment_date FROM comments WHERE comment_id>$last_cid AND comment_pid=$pid AND comment_parent=$parent AND comment_status>0 ORDER BY comment_id ASC LIMIT 50;");
		if($cmnts){
			$b=[];
			for($i=0; $i<count($cmnts); $i++){
				$b[$cmnts[$i]['comment_id']]=[0,0,0];
			}
			$a=sql('SELECT * FROM comment_rates WHERE comment_id IN ('.implode(',',array_keys($b)).');');
			for($i=0;$i<count($a);$i++){
				list($b[$a[$i]['comment_id']][0],$b[$a[$i]['comment_id']][1])=[$a[$i]['comment_plus'],$a[$i]['comment_minus']];
			}
			$a=sql('SELECT comment_parent FROM comments WHERE comment_parent IN('.implode(',',array_keys($b)).');');
			for($i=0;$i<count($a);$i++){
				$b[$a[$i]['comment_parent']][2]++;
			}
			for($i=0;$i<count($cmnts);$i++){
				list($cmnts[$i]['comment_plus'],$cmnts[$i]['comment_minus'],$cmnts[$i]['comment_children'])=$b[$cmnts[$i]['comment_id']];
			}
		}
		$s="OK\n";
		for($i=0; $i<count($cmnts); $i++){
			$cmnts[$i]['comment_date']=pdate($cmnts[$i]['comment_date']);
			$cmnts[$i]['comment_text']=str_replace(["\r\n","\n"],'<br>',$cmnts[$i]['comment_text']);
			$s.=implode("\t",array_values($cmnts[$i]))."\n";//TODO: remove array_values
		}
		die($s);
	}

	$_SESSION['captchano'] or die('ERROR|وارد کردن کد تصویری الزامی است.');
	$_SESSION['captchano']=max($_SESSION['captchano']-1,0);

	if(isset($_POST['contact'])){
		$s='';
		foreach($_POST['contact'] as $k=>$v){
			$s.=str_ireplace(['email','name','message','subject'],['ایمیل','نام','پیام','موضوع'],strip_tags($k)).":\n".strip_tags($v)."\n\n";
		}
		if(isset($tdb['contact_email'][1]) and filter_var($tdb['contact_email'][1], FILTER_VALIDATE_EMAIL)){
			@mail($tdb['contact_email'][1],'فرم تماس سایت '.$sdb['sitename'] ,date('c')."\n".$_SERVER['REMOTE_ADDR']."\n".$_SERVER['HTTP_USER_AGENT']."\n\n$s","From: info@".$_SERVER['HTTP_HOST']."\r\nMIME-Version: 1.0\r\nContent-Type: test/plain; charset=utf-8\r\n",'-f info@'.$_SERVER['HTTP_HOST']);
		}
		logmsg('*** فرم تماس سایت *** '.$s);
		die('OK.');
	}

	if(isset($_POST['comment_id']) and isset($_POST['vote'])){
		$a=sql('SELECT comment_plus,comment_minus FROM comment_rates WHERE comment_id=?',$_POST['comment_id']);
		$f=true;
		if(!$a){
			$a=sql('SELECT 1 FROM comments WHERE comment_id=?',$_POST['comment_id']);
			$a or die('ERROR|دیدگاه یافت نشد.');
			$a=array(['comment_plus'=>0,'comment_minus'=>0]);
			$f=false;
		}
		$v=intval($_POST['vote']);
		if($a and abs($v)==1){
			$va=[intval($a[0]['comment_plus']),intval($a[0]['comment_minus'])];
			$vs=(($v==1)?'+':'-').$_POST['comment_id'];
			if(!isset($_SESSION['votes'])){
				if($v==1){$va[0]++;}else{$va[1]++;}
				$_SESSION['votes']=$vs;
			}elseif(preg_match('/([+-]'.$_POST['comment_id'].')[+-]/',$_SESSION['votes'].'+',$m)){
				if($m[1]==$vs){
					die("OK\n".$va[0].','.$va[1].','.$_SESSION['captchano']);
				}
				if($v==1){$va[0]++;max($va[1]--,0);}else{$va[1]++;max($va[0]--,0);}
				$_SESSION['votes']=str_replace($m[1],$vs,$_SESSION['votes']);
			}else{
				if($v==1){$va[0]++;}else{$va[1]++;}
				$_SESSION['votes'].=$vs;
			}
			sql($f?'UPDATE comment_rates SET comment_plus=?,comment_minus=? WHERE comment_id=?;':'INSERT INTO comment_rates (comment_plus,comment_minus,comment_id) VALUES(?,?,?);',[$va[0],$va[1],$_POST['comment_id']]);
			die("OK\n".$va[0].','.$va[1].','.$_SESSION['captchano']);
		}
	}

	if(isset($_POST['post_id']) and isset($_POST['vote']) and preg_match('/^[0-5]$/',$_POST['vote'])){
		$a=sql('SELECT post_votes FROM post_rates WHERE post_id=?',$_POST['post_id']);

		$sv=$a?$a[0]['post_votes']:'';

		$b=true; //false: no change, true:updated, X:already voted

		$v=chr(intval($_POST['vote'])+97);
		$_SESSION['rates']=$_SESSION['rates']??'';
		preg_match_all('/(\d+)(\w)/',$_SESSION['rates'],$m);
		$i=array_search($_POST['post_id'], $m[1]);
		if($i===false){
			$_SESSION['rates']=implode('',$m[0]).$_POST['post_id'].$v;
			$b=true;

		}elseif($m[2][$i]==$v){
			$b=false;
		}else{
			$m[0][$i]=$_POST['post_id'].$v;
			$_SESSION['rates']=implode('',$m[0]);
			$b=ord($m[2][$i])-97;
		}

		if($b!==false){
			$p=explode(',',$sv.',0,0,0,0,0,0');
			$sv='';
			for($i=0;$i<6;$i++){
				$n=empty($p[$i])?0:intval($p[$i]);
				switch($i){
					case $_POST['vote'] : $n++; break;
					case $b : $n--;
				}
				$sv.=max($n,0).($i==5?'':',');
			}
			if($a){
				sql('UPDATE post_rates SET post_votes=? WHERE post_id=?',[$sv,$_POST['post_id']]);
			}else{
				sql('INSERT INTO post_rates VALUES(?,?,?);',[$_POST['post_id'],1,$sv]);
			}
		}
		die("OK\n".$sv.','.$_SESSION['captchano']);
	}

	if(isset($_POST['post_id']) and isset($_POST['comment-name']) and isset($_POST['comment-text'])){
		$a=sql('SELECT post_commenting FROM posts WHERE post_id=?;',$_POST['post_id']);
		$a or die('ERROR|مطلب یافت نشد.');
		$a[0]['post_commenting']!='C' or die('ERROR|امکان درج دیدگاه ذیل این مطلب مسدود است.');
		$a[0]['post_commenting']=='M' and !$_SESSION['user_id'] and die('ERROR|امکان درج دیدگاه ذیل این مطلب محدود به اعضا است.');
		$name=str_replace(["\n","\t"],' ',$_POST['comment-name']);
		preg_match('/^[^<>\"\'\t\/\|\%\@]+$/',$name) or die('ERROR|نام انتخابی دارای حروف غیر مجاز است.');
		if((!$_SESSION['user_id'] or $_SESSION['user_role']!='admin') and (isset($_SESSION['user_name']) and $name!=$_SESSION['user_name'])){
			die('ERROR|نام شما «'.$_SESSION['user_name'].'» ثبت شده است و  نمی‌توانید با نام دیگری دیدگاه ارسال کنید.');
		}
		if(!isset($_SESSION['user_name'])){
			$b=sql('SELECT 1 FROM users WHERE user_name=?;',$name);
			!$b or die('ERROR|نام وارد شده مجاز نیست.<br>لطفاً نام دیگری وارد کنید یا با این نام کاربری وارد سایت شوید.');
		}
		$cmmnt=trim(strip_tags($_POST['comment-text']));
		$cmmnt=str_replace("\t",' ',$cmmnt);
		$cmmnt=mb_strimwidth($cmmnt,0,2048,'...');
		!empty($cmmnt) or die('ERROR|متن دیدگاه معتبر نیست.');

		$cp=isset($_POST['parent'])?intval($_POST['parent']):0;
		$publish=($a[0]['post_commenting']=='O' or $_SESSION['user_id']);
		//Members comments published immediately.
		$j=sql('INSERT INTO comments VALUES (null,?,?,?,?,?,?);',[$_POST['post_id'],$cp,$publish?1:0,$name,$cmmnt,date('Y-m-d H:i:s')]);
		$_SESSION['captchano']=0;
		$_SESSION['user_name']=$name;
		$_SESSION['comments']=$_SESSION['comments']??'';
		$_SESSION['comments'].=($_SESSION['comments']==''?'':',').$j;
		die('OK|'.( $publish?'دیدگاه شما منتشر شد.':'دیدگاه شما دریافت شد و پس از بازبینی مدیر سایت، منتشر خواهد شد.'));
	}

	//post_commenting: [O]pen, [C]lose, [M]embers, []Verfication
	//comment_status 0:received, 1:published 2:confirmed

	die('ERROR|خطا در پردازش');
}

//================================= ROUTE  ==========================================

$route='';
$pageno=1;
$post=false;
while(!$route){
	if(!strlen($request)){
		if(isset($_GET['search'])){
			$_GET['search']=trim(str_replace(['*','%','&','(',')',"\0","\r\n","\n","\t"],' ',$_GET['search']));
			$pageno=(isset($_GET['page']) and ctype_digit($_GET['page']))?max(intval($_GET['page']),1):1;
			$route='search';
			break;
		}
		$route='index';
		break;
	}
	if(preg_match('/^(\d+)\/$/',$request.'/',$m)){
		$a=sql("SELECT post_url FROM posts WHERE post_id=$m[1] LIMIT 1;");
		if($a){
			header('Location: /'.$a[0]['post_url'].'/');
			exit;
		}
	}
	if(preg_match('/\/(\d+)$/',$request,$m)){
		$request=mb_substr($request,0,-mb_strlen($m[0]));
		$pageno=max(intval($m[1]),1);
	}
	$post=sql('SELECT * FROM posts WHERE post_url=? LIMIT 1;',$request);
	if($post){
		$post=$post[0];
		if($m and strpos('CT',$post['post_type'])===false){
			$route='404';
			break;
		}
		if($post['post_type']=='D'){
			if(!$_SESSION['user_id']){
				http_response_code(403);
				die_html('خطای دسترسی','مشاهده این مطلب تنها برای اعضای سایت مجاز است.');
			}
			define('IS_DRAFT',1);
		}else{
			$_SESSION['seen']=$_SESSION['seen']??'';
			if(strpos(','.$_SESSION['seen'].',',','. $post['post_id'] .',')===false){
				$_SESSION['seen'].=($_SESSION['seen']==''?'':',').$post['post_id'];
				if(!$_SESSION['user_id']){
					$a=sql('UPDATE post_rates SET post_visit = post_visit+1 WHERE post_id=? ;',$post['post_id']);
					$a or sql('INSERT INTO post_rates VALUES(?,?,?);',[$post['post_id'],1,'']);
				}
			}
		}
		$route=($post['post_type']=='C')?'category':(($post['post_type']=='T')?'tag':'post');
		$post['post_data']=(array) json_decode($post['post_data'],true);
		break;
	}
	$route='404';
}

//================================= LOAD THEME  =====================================

if(empty($sdb['theme'])){
	die_html('پوسته‌ای تنظیم نشده است.','برای نمایش محتوای سایت، نصب و فعال کردن یک پوسته ضروری است.','پوسته-تنظیم-نشده-است');
}
$html=@file_get_contents('themes/' . $sdb['theme'] .'/pages/'.((empty($post['post_template']))?(in_array($route,['tag','search'])?'category':$route):$post['post_template']).'.html');
if($html===false and $route=='index'){
	die_html('خطا در دسترسی به پرونده پوسته','پرونده پوسته یافت نشد!<br><i dir="ltr" style="font-family:sans-serif;float:left">/themes/' . $sdb['theme'] .'/pages/index.html</i>‌','پرونده-پوسته-یافت-نشد');
}

//================================= BASIC PARAMETERS  ===============================

$html_rep=array();
$html_rep['%route']=$route;
$html_rep['%captchano']=$_SESSION['captchano'];
$html_rep['%siteurl']= SITE_URL;
$html_rep['%sitename']= $sdb['sitename'];
$html_rep['%sitelink']= '<a href="'.SITE_URL.'" >'.$sdb['sitename'].'</a>';
$html_rep['%user_id']=   $_SESSION['user_id'];
$html_rep['%user_role']= isset($_SESSION['user_role'])?$_SESSION['user_role']:'';
$html_rep['%user_name']= isset($_SESSION['user_name'])?$_SESSION['user_name']:'';

//================================= TDB  ============================================

foreach($tdb as $tk=>$tv){
	$v=(is_array($tv))?(isset($tv[1])?$tv[1]:$tv[0]):$tv;
	if(preg_match('/_text$/',$tk)){$v=str_replace("\n",'<br>',$v);}
	elseif(preg_match('/_menu$/',$tk)){$v=make_ul($v,$_GET?'?':$request,isset($tdb["theme_{$tk}_classing"])?$tdb["theme_{$tk}_classing"]:'');}
	$html_rep['%'.$tk]=$v;
}

//=================================  ROUTE PARAMETERS  ==============================

// $route: index,{post,category,tag},search,404
if($route=='index'){
	$html_rep['%mtitle']= 		 ($sdb['mtitle'])?$sdb['mtitle']:$sdb['sitename'];
	$html_rep['%mdescription'] = $sdb['mdescription'];
	$html_rep['%mkeywords']=     $sdb['mkeywords'];
	$html_rep['%search_query'] = '';
	$_SESSION['seen']=$_SESSION['seen']??'';
	if(strpos(','.$_SESSION['seen'].',',',0,')===false){
		$_SESSION['seen'].=($_SESSION['seen']==''?'0':',0');
	}

}elseif($post){
	$a=empty($post['post_data']['meta'])?['','','']:explode('¦',$post['post_data']['meta']);
	$html_rep['%mtitle']=		empty($a[0])?$post['post_title']:$a[0];
	$html_rep['%mdescription']=	empty($a[1])?$post['post_excerpt']:$a[1];
	$html_rep['%mkeywords']=	empty($a[2])?'':$a[2];
	$html_rep['%post_id']    = $post['post_id'];
	$html_rep['%post_title'] = $post['post_title'];
	$html_rep['%post_url']   = $post['post_url'];
	$html_rep['%post_excerpt'] = $post['post_excerpt'];
	$html_rep['%search_query'] = '';
	$html_rep['%comment_display_class']=($post['post_commenting']=='C' or ($post['post_commenting']=='M' and !$_SESSION['user_id']))?'no-display':'';

}elseif($route=='search'){
	$html_rep['%mtitle']=$sdb['sitename'].' - جستجوی '.htmlentities($_GET['search']);
	$html_rep['%search_query'] = $_GET['search'];
	$html_rep['%mdescription']= '';
	$html_rep['%mkeywords']='';
	$html_rep['%post_id']    = 'search';
	$html_rep['%post_url']='?search='.urlencode($_GET['search']).'&page=1#';

}elseif($route=='404'){
	$html_rep['%mtitle']= $sdb['sitename'].' - خطای 404, یافت نشد!';
	$html_rep['%mdescription']='';
	$html_rep['%post_id']='4o4';
	$html_rep['%post_title']='خطای 404، یافت نشد!';
	$html_rep['%post_excerpt']='';
	$html_rep['%search_query'] = '';
	$html_rep['%mkeywords']='';
	$html_rep['%post_url']='..';
	http_response_code(404);
	if(!$html){
		die('<!DOCTYPE html><html lang="fa"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>'.$html_rep['%mtitle'].'</title></head><body><center dir="rtl" style="margin:100px 0"><h1 style="color:red;font:148px fantasy;margin:0">404</h1><p style="font:48px monospace">یافت نشد!</p><a href="/" style="font-size:48px;">'.$sdb['sitename'].'</a></center></body></html>');
	}
}
$html_rep['%site_store']=SITE_STORE?'yes':'no';
$html=str_replace(array_keys($html_rep),array_values($html_rep),$html);
$html_rep=array();

//=================================  FUNCTIONAL PARAMETERS  =========================

if(preg_match_all('/%(URL|TITLE)\((\d+)\)/',$html,$matches)){
	$a=sql('SELECT post_id,post_url,post_title FROM posts WHERE post_id IN('.implode(',',$matches[2]).');');
	foreach($a as $ai){
		$html_rep['%URL('.$ai['post_id'].')'] = $ai['post_url'];
		$html_rep['%TITLE('.$ai['post_id'].')'] = $ai['post_title'];
	}
}

//=================================   Layout  =======================================

$html=str_replace(array_keys($html_rep),array_values($html_rep),$html);
$html_rep=array();

//=================================   CONTENT  =======================================

$page_content=array();

if(preg_match_all('/<ITEMS(.*?)>(.*?)<\/ITEMS>/si',$html,$matches)){
	for($i=0; $i<count($matches[1]); $i++){
		$html_rep[$matches[0][$i]]='';
		if(empty($matches[2][$i]) or ctype_space($matches[2][$i])){
			continue;
		}
		$items=array();
		$inf_arr=array();

		$doc = new DOMDocument();
		$doc->loadHtml('<?xml encoding="utf-8"?><div '.$matches[1][$i].'></div>');
		$a = $doc->getElementsByTagName('div')->item(0);
		if($a->hasAttributes()){
		  foreach($a->attributes as $attr) {
			$inf_arr[$attr->nodeName]=$attr->nodeValue;
		  }
		}
		$doc=null;

		if(isset($inf_arr['display'])){
			if($inf_arr['display']==$route){$html_rep[$matches[0][$i]]=$matches[2][$i];}
			continue;
		}

		if(!isset($inf_arr['i'])){$inf_arr['i']='';}

		$limit=10;
		$from=0;
		if(isset($inf_arr['limit'])){
			if(preg_match('/^(\d+),(\d+)$/',$inf_arr['limit'],$m)){
				$from=$m[1]-1;
				$limit=$m[2];
			}else{
				$limit=intval($inf_arr['limit']);
			}
		}
		$limit=max($limit,1);
		$from=max($from,0)+(max($pageno,1)-1) * $limit;

		$all_items=0;

		if($inf_arr['i']=='recent_posts' or (!$inf_arr['i'] and $route=='index')){//latest posts
			$a=sql("SELECT COUNT(*) FROM posts WHERE post_type='P';");
			$all_items=$a[0]['COUNT(*)'];
			if($all_items){
				$items=sql("SELECT post_id,post_url,post_title,post_type,post_category,post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_type='P' ORDER BY post_id DESC LIMIT $from,$limit;");
			}

		}elseif(isset($inf_arr['display'])){
			$all_items=0;
			$items=array();

		}elseif(($inf_arr['i']=='post' and $post) or (!$inf_arr['i'] and $route=='post')){// current $post  or post content
			$all_items=1;
			$items=array($post);

		}elseif(preg_match('/^\d+$/',$inf_arr['i'],$dd) or (!$inf_arr['i'] and ($route=='category' or $route=='tag'))){ //any page category items OR //category or tag items
			$col=(!$dd and $route=='tag')?'post_tags':'post_category';
			$pid= $dd ? $dd[0] : $post['post_id'];
			$a=sql("SELECT COUNT(*) FROM posts WHERE post_type='P' AND (',' || $col || ',') LIKE '%,$pid,%';");
			$all_items=$a[0]['COUNT(*)'];
			if($all_items){
				$items=sql("SELECT post_id,post_url,post_title,post_type,post_category,post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_type='P' AND (',' || $col || ',') LIKE '%,$pid,%' ORDER BY post_id DESC LIMIT $from,$limit;");
			}
			if(strpos($html,'%paging('.$inf_arr['i'].')')){
				$a=sql("SELECT post_url,post_title FROM posts WHERE post_id=$pid;");
				$html_rep['%paging('.$inf_arr['i'].')']=$a?create_paging($pageno,ceil($all_items/$limit),'/'.$a[0]['post_url'].'/'):'';
				$html_rep['%link('.$inf_arr['i'].')']=$a?('<a href="/'.$a[0]['post_url'].'/">'.$a[0]['post_title'].'</a>'):'';
			}

		}elseif(!$inf_arr['i'] and $route=='search'){
			$a=explode(' ',$_GET['search']);
			$a=array_unique($a);
			$b=[];
			foreach($a as $ai){
				if($ai and count($b)<20){$b[]='%'.$ai.'%';}
			}
			if($b){
				$s=str_repeat('* LIKE ? ',count($b));
				$s=str_replace(' ? * ',' ? AND * ',$s);
				$s='(('.str_replace('*','post_title',$s).') OR ('.str_replace('*','post_excerpt',$s).') OR ('.str_replace('*','post_content',$s).') )';
				$b=array_merge($b,$b,$b);
				$a=sql('SELECT COUNT(*) FROM posts WHERE post_type="P" AND '.$s.';',$b);
				$all_items=$a[0]['COUNT(*)'];
				if($all_items){
					$b=array_merge($b,[$from,$limit]);
					$items=sql('SELECT post_id,post_url,post_title,post_type,post_category,post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_type="P" AND '.$s.' ORDER BY post_id DESC LIMIT ?,?;',$b);
				}
			}
			$html_rep['%search_pages']=ceil($all_items/$limit);
			$html_rep['%search_query']= htmlentities($_GET['search']);
			$html_rep['%search_page']=$pageno;
			$html_rep['%search_finds']=$all_items;
			$html_rep['%post_excerpt']=$all_items?"صفحه $pageno از {$html_rep['%search_pages']}":'';
			$html_rep['%post_title']=$all_items?$all_items.' یافته در جستجوی «'.$html_rep['%search_query'].'»' : 'در جستجوی «'.$html_rep['%search_query'].'» موردی یافت نشد.';
			if(!isset($html_rep['%paging('.$inf_arr['i'].')'])){
			$html_rep['%paging('.$inf_arr['i'].')']=create_paging($pageno,ceil($all_items/$limit),'/?search='.urlencode($_GET['search']).'&page=');
			}

		}elseif($inf_arr['i']=='recent_top_visits' or $inf_arr['i']=='top_visits'){
			if($inf_arr['i']=='recent_top_visits'){
				$a=sql("SELECT post_id FROM posts WHERE post_type='P' AND post_created>?;",date('Y-m-d H:i',strtotime('-10 days')));
				$b=[];
				foreach($a as $ai){$b[]=$ai['post_id'];}
				$a=sql("SELECT post_id,post_visit FROM post_rates WHERE post_id IN (".implode(',',$b).") ORDER BY post_visit DESC LIMIT $from,$limit;");
			}else{
				$a=sql("SELECT post_id,post_visit FROM post_rates ORDER BY post_visit DESC LIMIT $from,$limit;");
			}
			$v=[];
			foreach($a as $ai){$v[$ai['post_id']]=$ai['post_visit'];}
			$items=sql('SELECT post_id,post_url,post_title,post_type,post_category,post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_type="P" AND post_id IN ('.implode(',',array_keys($v)).');');
			for($k=0;$k<count($items);$k++){$items[$k]['post_visit']=$v[$items[$k]['post_id']];}
			$all_items=count($items);

		}elseif($inf_arr['i']=='recent_top_comments' or $inf_arr['i']=='top_comments'){
			$d=date('Y-m-d H:i',strtotime('-10 days'));
			$a=sql("SELECT comment_pid,COUNT(*) FROM comments where (comment_status>0". (($inf_arr['i']=='top_comments')?:" AND comment_date>'$d'") .") GROUP BY comment_pid ORDER BY COUNT(*) DESC LIMIT $from,$limit;");
			$b=[];
			foreach($a as $ai){$b[$ai['comment_pid']]=$ai['COUNT(*)'];}
			$items=$a?sql('SELECT post_id,post_url,post_title,post_type,post_category,post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_id IN('.implode(',',array_keys($b)).')'):[];
			for($l=0; $l<count($items); $l++){$items[$l]['comments_no']=$b[$items[$l]['post_id']];}
			$all_items=count($items);

		}elseif($inf_arr['i']=='similar' and $post){
			if(!empty($post['post_data']['similar_posts']) and preg_match('/^[0-9,]+$/',$post['post_data']['similar_posts'])){
				$items=sql('SELECT post_id,post_url,post_title,post_type,post_category,post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_id IN('.trim($post['post_data']['similar_posts'],',').');');
				$all_items=count($items);
			}

		}elseif(in_array($inf_arr['i'],['same_category','same_tags']) and $post){
			$items=[];
			$t='post'.substr($inf_arr['i'],4);
			$c=explode(',',trim($post[$t],','));
			if($c){
				$items=sql('SELECT post_id,post_url,post_title,post_type,'.$t.',post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_id!='.$post['post_id'].' AND (("," || '.$t.' || ",") LIKE "%,'. implode(',%" OR ("," || '.$t.' || ",") LIKE "%,',$c).",%\") ORDER BY post_id DESC LIMIT $from,$limit;");
			}
			$all_items=count($items);

		}elseif(preg_match('/^\{[0-9,]+\}$/',$inf_arr['i'])){
			$items=sql('SELECT post_id,post_url,post_title,post_type,post_category,post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_id IN('.trim(substr($inf_arr['i'],1,-1),',').") ORDER BY post_id DESC;");
			$all_items=count($items);

		}elseif(($inf_arr['i']=='tags' or $inf_arr['i']=='category') and $post){
		 	$items=sql('SELECT post_id,post_url,post_title,post_type,post_category,post_tags,post_img,post_excerpt,post_template,post_author,post_price,post_commenting,post_created,post_modified,post_data FROM posts WHERE post_id IN ('. trim(trim($post['post_'.$inf_arr['i']]) .') AND post_type ="'.strtoupper(substr($inf_arr['i'],0,1))).'" ;');
			$all_items=count($items);

		}else{

		}

		//======================================================================

		if($items and preg_match_all('/%\w+/',$matches[2][$i],$m)){
			$m=array_unique($m[0]);
			$p=[];
			$u=[];
			foreach($items as $item){
				$p[$item['post_id']]=[0,''];//visit,votes
				$u[$item['post_author']]=['',''];//author_name,author_url
			}

			if(in_array('%visit',$m) or in_array('%vots',$m)){
				$a=sql('SELECT * FROM post_rates WHERE post_id IN('.implode(',',array_keys($p)).');');
				foreach($a as $ai){$p[$ai['post_id']]=[$ai['post_visit'],$ai['post_votes']];}
			}
			if(in_array('%author_name',$m) or in_array('%author_url',$m) or in_array('%author_link',$m)){
				$a=sql('SELECT user_id,user_name,user_url FROM users WHERE user_id IN('.implode(',',array_keys($u)).');');
				foreach($a as $ai){$u[$ai['user_id']]=[$ai['user_name'],$ai['user_url']];}
			}

			for($j=0; $j<count($items); $j++){
				$rep_arr=[];
				if(!is_array($items[$j]['post_data'])){$items[$j]['post_data']= (array) json_decode($items[$j]['post_data'],true);}
				foreach($m as $mi){
					if($mi=='%index'){
						$rep_arr[$mi]=$j+1;
					}elseif(strpos($mi,'%first_')===0){
						$rep_arr[$mi]=($j==0)? mb_substr($mi,7) :'';
					}elseif($mi=='%id'){
						$rep_arr[$mi]=$items[$j]['post_id'];
					}elseif($mi=='%all_items'){
						$rep_arr[$mi]=$all_items;
					}elseif($mi=='%href' or $mi=='%url'){
						$rep_arr[$mi]='/'.$items[$j]['post_url'].'/';
					}elseif($mi=='%link'){
						$rep_arr[$mi]='<a href="/'.$items[$j]['post_url'].'/" title="'.$items[$j]['post_title'].'" >'.$items[$j]['post_title'].'</a>';
					}elseif($mi=='%excerpt'){
						$rep_arr[$mi]=str_replace("\n", '<br>',$items[$j]['post_excerpt']);
					}elseif($mi=='%buy'){
						$rep_arr[$mi]=(SITE_STORE and $items[$j]['post_price'])?('<div class="site-store site-store-'.$route.'" post_id="'.$items[$j]['post_id'].'" price="'.$items[$j]['post_price'].'" ><span class="site-store-price">'.number_format($items[$j]['post_price'],0,',').'</span><button class="site-store-btn" onclick="buy('.$items[$j]['post_id'].')"></button></div>'):'';
					}elseif($mi=='%src'){
						$rep_arr[$mi]=$items[$j]['post_img']?('/'.$items[$j]['post_img']):'';
					}elseif($mi=='%img'){
						$rep_arr[$mi]=$items[$j]['post_img']?('<img loading="lazy" src="/'.$items[$j]['post_img'].'" alt="'.htmlentities($items[$j]['post_title']).'">'):'';
					}elseif($mi=='%thumb'){
						$rep_arr[$mi]=$items[$j]['post_img']?('<img loading="lazy" src="/'.$items[$j]['post_img'].'-thumb.jpg" alt="'.htmlentities($items[$j]['post_title']).'">'):'';
					}elseif($mi=='%has_price'){
						$rep_arr[$mi]=(SITE_STORE and $items[$j]['post_price']>0)?'yes':'no';
					}elseif($mi=='%price'){
						$rep_arr[$mi]=(SITE_STORE and $items[$j]['post_price']>0)?number_format($items[$j]['post_price'],0,','):'';
					}elseif($mi=='%pdate'){
						$rep_arr[$mi]=pdate($items[$j]['post_created'],'Y/m/d');
					}elseif($mi=='%date'){
						$rep_arr[$mi]=substr($items[$j]['post_created'],0,10);
					}elseif($mi=='%time'){
						$rep_arr[$mi]=substr($items[$j]['post_created'],11);
					}elseif($mi=='%htime'){
						$rep_arr[$mi]=humanTiming($items[$j]['post_created']);
					}elseif(strpos($mi,'%category_')===0){
						$rep_arr['%category_names']='';
						$rep_arr['%category_links']='';
						$a = empty($items[$j]['post_category'])? [] : sql('SELECT post_id,post_url,post_title FROM posts WHERE post_id IN ('. trim($items[$j]['post_category'],',') .') AND post_type ="C" AND post_url!="";');

						for($z=0;$z<count($a);$z++){
							$rep_arr['%category_names'].= $a[$z]['post_title']."\t";
							$rep_arr['%category_links'].='<a href="/'.$a[$z]['post_url'].'/" title="'.$a[$z]['post_title'].'" pid="'.$a[$z]['post_id'].'" >'.$a[$z]['post_title']."</a> \n";
						}

					}elseif(strpos($mi,'%tag_')===0){
						$rep_arr['%tag_names']='';
						$rep_arr['%tag_links']='';

						$a = empty($items[$j]['post_tags'])? [] : sql('SELECT post_id,post_url,post_title FROM posts WHERE post_id IN ('. trim($items[$j]['post_tags'],',') .') AND post_type ="T" AND post_url!=""; ;');

						for($z=0;$z<count($a);$z++){
							$rep_arr['%tag_names'].= $a[$z]['post_title']."\t";
							$rep_arr['%tag_links'].='<a href="/'.$a[$z]['post_url'].'/" title="'.$a[$z]['post_title'].'" pid="'.$a[$z]['post_id'].'" >'.$a[$z]['post_title']."</a> \n";
						}

					}elseif($mi=='%comments_no'){
						if(isset($items[$j]['comments_no'])){
							$rep_arr[$mi]=$items[$j]['comments_no'];
						}else{
							$a=sql('SELECT COUNT(*) FROM comments WHERE comment_pid=? AND comment_parent=0 AND comment_status>0 ;',$items[$j]['post_id']);
							$rep_arr[$mi]=$a[0]['COUNT(*)'];
						}
					}elseif($mi=='%visit'){
						$rep_arr[$mi]=$p[$items[$j]['post_id']][0];
					}elseif($mi=='%votes'){
						$rep_arr[$mi]=$p[$items[$j]['post_id']][1];
					}elseif($mi=='%author_name'){
						$rep_arr[$mi]=$u[$items[$j]['post_author']][0];
					}elseif($mi=='%author_url'){
						$rep_arr[$mi]=$u[$items[$j]['post_author']][1];
					}elseif($mi=='%author_link'){
						$rep_arr[$mi]='<a href="'.$u[$items[$j]['post_author']][1].'" title="'.$u[$items[$j]['post_author']][0].'">'.$u[$items[$j]['post_author']][0].'</a>';
					}elseif(in_array($mi,['%id','%url','%title','%type','%category','%tags','%template','%commenting','%created','%modified'])){
						$rep_arr[$mi]=$items[$j]['post_'.substr($mi,1)];
					}elseif(in_array(substr($mi,1),array_keys($items[$j]['post_data']))){
						$rep_arr[$mi]=$items[$j]['post_data'][substr($mi,1)];

					}elseif($mi=='%content' and !empty($items[$j]['post_content'])){
						$r='CNTNT-'.bin2hex(random_bytes(8));
						$page_content[$r]=$items[$j]['post_content'];
						$rep_arr[$mi]=$r;

					}else{
						$rep_arr[$mi]='';
					}
				}
				$html_rep[$matches[0][$i]].=str_replace(array_keys($rep_arr),array_values($rep_arr),$matches[2][$i]);
			}
		}

		//======================================================================

	}
}

$matches=null;
$items=null;
$rep_arr=null;
$users_cache=null;
$a=null;

//=================================   Delivery  =====================================

$html=str_replace(array_keys($html_rep),array_values($html_rep),$html);

if(SITE_STORE){
	$s="<script id=\"wotor_store_data\">\n var STORE={sitename:".json_encode($sdb['sitename'],JSON_UNESCAPED_UNICODE).",store_desc:".json_encode($sdb['store_desc']?$sdb['store_desc']:'',JSON_UNESCAPED_UNICODE).",store_cond:".json_encode($sdb['store_cond']?$sdb['store_cond']:'',JSON_UNESCAPED_UNICODE).",catalog:{";
	$a=sql('SELECT post_id,post_url,post_title,post_price,post_data FROM posts WHERE post_type="P" AND post_price>0;');
	for($i=0;$i<count($a);$i++){
		$b=(array)json_decode($a[$i]['post_data'],true);
		$s.=$a[$i]['post_id'].':'.json_encode([$a[$i]['post_url'],$a[$i]['post_title'],$a[$i]['post_price'],(isset($b['store_unit'])?$b['store_unit']:'')],JSON_UNESCAPED_UNICODE).',';
	}
	$s.="},payment_methods:{";
	if(isset($sdb['payment_methods'])){
		for($i=0;$i<count($sdb['payment_methods']);$i++){
			$s.=$i.':'.json_encode([$sdb['payment_methods'][$i][0],$sdb['payment_methods'][$i][1]],JSON_UNESCAPED_UNICODE).',';
		}
	}
	$html=str_replace('<body',$s."},receipts:[".trim(isset($_SESSION['receipts'])?trim($_SESSION['receipts'],','):'')."]};\n</script>\n\n<body",$html);
}

if($page_content){
	$html=str_replace(array_keys($page_content),array_values($page_content),$html);
}

if(defined('IS_DRAFT')){
	$html.='<div id="post_draft_warning" onclick="this.style.display = \'none\';" style="cursor:pointer;position:fixed;bottom:10px;left:10px;display:block;background:rgba(255,0,0,.8);padding:15px;color:#fff;direction:rtl;transition:.5s;z-index:9999;border:1px solid #fff">این مطلب پیش‌نویس است و برای عموم قابل مشاهده نیست.</div><script>setTimeout(function(){document.getElementById(\'post_draft_warning\').style.opacity = 0;},10000);</script>';
}

print $html;
exit;

//=================================  FUNCTIONS  =====================================

function logmsg($s){
	if(!rand(0,10) and @filesize(DATA_FOLDER.'/wotor.log')>2*1024*1024){
		for ($i = 1; $i < 99; $i++){
			$fg=DATA_FOLDER.'/wotor.['.$i.'].log.gz';
			if(!file_exists($fg)){
				$a=file(DATA_FOLDER.'/wotor.log',FILE_IGNORE_NEW_LINES);
				if(count($a)>26){
					$b=array_splice($a,-25);
					@file_put_contents(DATA_FOLDER.'/wotor.log',implode("\n",$b));
					$b=[];
					$f = gzopen($fg, "w");
					gzwrite($f,implode("\n",$a));
					gzclose($f);
					break;
				}
			}
		}
	}
	@file_put_contents(DATA_FOLDER.'/wotor.log',date('Y-m-d H:i:s') . "\t" . (isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'-') . "\t" . str_replace(["\t","\r\n","\n",'<','>'],' ',$s) . "\n", FILE_APPEND | LOCK_EX);
}
function sql($q,$exarr=null,$db=''){
	preg_match('/( FROM| INTO|UPDATE| TABLE) (\w+)/i',$q,$m) or die('ERROR|BAD_SQL|'.$q);
	$dbh = new PDO('sqlite:'. ( $db ? $db : (DATA_FOLDER.'/'.$m[2].'.sqlite') ));
	$dbh -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	$dbh -> setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
	try{
	 	$stmt = $dbh->prepare($q);
		$stmt-> execute((array)$exarr);
		if(stripos($q,'INSERT')===0){
			$last_id = $dbh->lastInsertId();
			$dbh = null;
			return $last_id;
		}
		if(stripos($q,'UPDATE')===0 or stripos($q,'DELETE')===0){
			if(!rand(0,10)){$dbh -> exec('VACUUM;');}
			$dbh = null;
			return $stmt->rowCount();
		}
		$dbh = null;
		return $stmt->fetchAll(PDO::FETCH_ASSOC);
	}catch(PDOException $e){
		$dbh = null;
		die('ERROR|'.$e->getMessage().'|'.$q);
	}
}
function write_sdb(){
	global $sdb;
	$s=json_encode($sdb,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
	file_put_contents(DATA_FOLDER.'/setting.json',$s);
}
function create_paging($pg=1,$allpgs=0,$href='/'){
	if($allpgs<2){return '';}
	$paging='';
	$endtrailer=(strpos($href,'?')===false)?'/':'';
	if($pg>1){$paging.='<li><a href="'.$href.($pg-1).$endtrailer.'" > قبلی </a></li>';}
	for($k=1;$k<=$allpgs;$k++){
		if($k!=1 and $k!=$allpgs){
			$k2=abs($k-$pg);
			if($k2>3){continue;}
			if($k2==3){
				$paging.='<li><a> … </a></li>';
				continue;
			}
		}
		$paging.='<li';
		if($pg==$k){$paging.=' class="active"';}
		$paging.='><a href="'.$href;
		$paging.=$k.$endtrailer.'"> '.$k.' </a></li>';

	}
	if($pg<$allpgs){$paging.='<li><a href="'.$href.($pg+1).$endtrailer.'" > بعدی </a></li>';}
	return $paging;
}
function read_theme_settings($pages_folder){
	$html_pages=glob($pages_folder.'*.html');
	$ts=array();
	$keys=array();
	foreach($html_pages as $hp){
		if(filesize($hp)>1024*1024){continue;}
		$html=file_get_contents($hp);
		$matches=[];
		preg_match_all('/<!--%(.*?)-->/s',$html, $matches);
		if($matches[0]){
			foreach($matches[1] as $mtc){
				preg_match_all('/%(\w+)[ \t]+(\w+)[ \t]+(.*)/',$mtc, $m); //{%name type title}
				for($i=0;$i<count($m[0]);$i++){
					if(!in_array($m[1][$i],$keys)){
						$keys[]=$m[1][$i];
						$ts[]=array($m[1][$i],$m[2][$i],trim($m[3][$i]));
					}
				}
			}
		}
	}
	return $ts;
}
function removeDirectory($path){
	if(is_dir($path) === true){
        $files = array_diff(scandir($path), array('.', '..'));
        foreach ($files as $file){
            removeDirectory(realpath($path) . '/' . $file);
		}
        @rmdir($path);
    }elseif(is_file($path) === true){
        @unlink($path);
    }
    return;
}
function make_ul($s,$current='',$classing='',$lvl=0){
	$s=trim(rtrim($s),"\r\n");
	$a=explode("\n",trim($s,"\n"));
	$c=$classing?explode(',',$classing.',,,,,,'):['navbar-nav','nav-item','nav-link','dropdown','dropdown-toggle','dropdown-menu'];
	$l=[];
	$s='';
	for($i=0;$i<count($a);$i++){
		$l[$i]=mb_strlen($a[$i])-mb_strlen(ltrim($a[$i]))-(($l and $l[0])?$l[0]:0);
	}
	$l[0]=0;
	$l[]=0;
	for($i=0;$i<count($a);$i++){
		$p=explode('|',$a[$i].'|');
		$p[0]=trim($p[0]);
		$p[1]=trim($p[1]);
		if($p[1] and mb_strpos($p[1],'://')===false and mb_strpos($p[1],'#')!==0 and mb_strpos($p[1],'/')!==0){$p[1]='/'.ltrim($p[1],'/');}
		$p[1]=$p[1]??'';
		if($l[$i+1]==$l[$i]){
			$s.=str_repeat("\t",$lvl+1)."<li class=\"{$c[1]}";
			if($p[1] and $current==trim($p[1],'/')){$s.=' active';}
		$s.='"><a class="'.$c[2].'"'.($p[1]==''?'':" href=\"{$p[1]}\"");
			if(strpos($p[1],'://')!==false){$s.=' target="_blank"';}
			$s.='>'.$p[0]."</a></li>\n";
		}elseif($l[$i+1]>$l[$i]){
			$s2='';
			$i2=$i;
			for($j=$i+1;$j<count($a);$j++){
				if($l[$j]==$l[$i]){break;}
				$s2.=$a[$j]."\n";
				$i2++;
			}
			$s.=str_repeat("\t",$lvl+1)."<li class=\"{$c[1]} {$c[3]}\"><a class=\"{$c[2]} {$c[4]}\" role=\"button\" data-toggle=\"dropdown\"".($p[1]==''?'':"href=\"{$p[1]}\"").">".$p[0]."</a>\n".make_ul($s2,$current,$classing,$lvl+1)."\n".str_repeat("\t",$lvl+1)."</li>\n";
			$i=$i2;
		}
	}
	return str_repeat("\t",$lvl).'<ul class="' .($lvl>0?$c[5]:$c[0])."\">\n$s".str_repeat("\t",$lvl)."</ul>";
}
function die_html($title,$body='',$help=''){
	die('<!DOCTYPE html><html lang="fa"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>'.$title.'</title><style>@font-face{font-family:\'web_yekan\';src:url(//static.websitemotor.com/fonts/WebYekan.woff) format("woff");font-weight:400;font-style:normal}*{-moz-box-sizing:border-box;box-sizing:border-box;margin:0}h1{font-size:21px;color:#444;font-weight:400}p,a,input,label,button,div{font-family:web_yekan;font-size:16px}</style></head><body><div style="max-width:600px;width:95%;margin:100px auto;direction:rtl">'.(strpos($body,'<')===0?$body:'<div style="border:0 solid #'.(strpos($title,'خطا')===0?'f18':'2af').';border-width:2px 0;padding:25px 0"><h1>'.$title.'</h1><div style="margin:25px 0">'.$body.'</div></div>'.($help?('<p style="margin-top: 15px"><a target="_blank" href="//www.websitemotor.com/help/#'.$help.'">راهنما</a></p>'):'').'</div><div align="center" style="margin:25px auto 100px;font-size:14px;color:#444">'.($help?'وب‌سایت موتور ۳.۰':'<a href="/">'.$_SERVER['HTTP_HOST'].'</a></div>').'').'</body></html>');
}
function pdate($datestr='',$form='Y/m/d H:i'){
	if(!$datestr){
		list($y, $m, $d,$h,$i,$s)=explode(' ',date('Y m d H i s'));
	}else{
		if(!preg_match_all("/0*(\d+)/",$datestr,$m)){return false;}
		list($y, $m, $d,$h,$i,$s)=array_merge($m[1],[0,0,0]);
	}

	$gy = $y-1600;
	$g_day_no = 365*$gy+floor(($gy+3)/4)-floor(($gy+99)/100)+floor(($gy+399)/400);

	for($j=0; $j<$m-1;$j++){
		$g_day_no += [31,28,31,30,31,30,31,31,30,31,30,31][$j];
	}

	if($m>2 and (($gy%4==0 and $gy%100!=0) or ($gy%400==0))){
		$g_day_no++;
	}
	$m_day_no = $g_day_no + $d - 80;
	$j_np = floor($m_day_no/12053);
	$m_day_no = $m_day_no % 12053;
	$py = 979 + 33*$j_np + 4*floor($m_day_no/1461);
	$m_day_no %= 1461;

	if($m_day_no >= 366){
		$py += floor(($m_day_no-1)/365);
		$m_day_no = ($m_day_no-1)%365;
	}
	$m_days_in_month=[31,31,31,31,31,31,30,30,30,30,30,29];
	for($j=0; $j<11 and $m_day_no >= $m_days_in_month[$j];$j++){
		$m_day_no -= $m_days_in_month[$j];
	}
	$pm=$j+1;
	$pd=$m_day_no+1;
	$F=['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'][$pm-1];
	return str_replace(
	['Y','m','d','H','i','s','h','F','y'],
	[$py,substr( '0' . $pm ,-2),substr( '0' . $pd ,-2),substr( '0' . $h ,-2),substr( '0' . $i ,-2),substr( '0' . $s ,-2),intval($h),$F,substr( '0' . $py%100 ,-2)] ,$form);
}
function humanTiming($timestr,$conv=true){
	if($timestr==0){return 'N/A';}
	$time=$conv?strtotime($timestr):$timestr;
	$time = time() - $time; // to get the time since that moment
	$inf='پیش';
	if($time<0){
		$time=-$time;
		$inf='بعد';
	}
	$time = ($time<1)? 1 : $time;
	$tokens = array(31536000 => 'سال',2592000 => 'ماه',604800 => 'هفته',86400 => 'روز',3600 => 'ساعت',60 => 'دقیقه',1 => 'ثانیه');
	if($time<60){return 'چند لحظه '. $inf;}
	foreach ($tokens as $unit => $text){
		if ($time < $unit) continue;
		$numberOfUnits = floor($time / $unit);
		return $numberOfUnits.' '.$text.' '. $inf;
	}
}
function save_resize_image($file,$suffix='-thumb.jpg', $w=100, $h=100, $crop=false){
    if(strpos($file,$suffix)!==false){
		header('Location: /'.$file);
		exit;
	}
	list($width, $height) = @getimagesize($file);
	$src=false;
	if($width and $height){
		$r = $width / $height;
		if($crop){
			if($width > $height) {
				$width = ceil($width-($width*abs($r-$w/$h)));
			}else{
				$height = ceil($height-($height*abs($r-$w/$h)));
			}
			$newwidth = $w;
			$newheight = $h;
		}else{
			if($w/$h > $r){
				$newwidth = ceil($h*$r);
				$newheight = $h;
			}else{
				$newheight = ceil($w/$r);
				$newwidth = $w;
			}
		}
		$mim=mime_content_type($file);
		if($mim=='image/jpeg'){
			$src = @imagecreatefromjpeg($file);
		}elseif($mim=='image/png'){
			$src = @imagecreatefrompng($file);
		}elseif($mim=='image/gif'){
			$src = @imagecreatefromgif($file);
		}elseif($mim=='image/avif'){
			$src = @imagecreatefromavif($file);
		}elseif($mim=='image/webp'){
			$src = @imagecreatefromwebp($file);
		}elseif($mim=='image/bmp'){
			$src = @imagecreatefrombmp($file);
		}
	}
	if(!$src){return false;}
    $dst = imagecreatetruecolor($newwidth, $newheight);
    @imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return imagejpeg($dst,$file.$suffix,70);
}
function get_upload_max_mb($ig=''){
	if(!$ig){
		return min(get_upload_max_mb('upload_max_filesize'),get_upload_max_mb('post_max_size'));
	}
	$size = ini_get($ig);
	$unit = preg_replace('/[^bkmg]/i','', $size);
	return round(preg_replace('/[^0-9\.]/', '', $size) * ($unit?pow(1024, stripos('bkmgtpezy', $unit[0])):1) /1048576 );
}
function store_post_json($url,$arr,$out_raw=false,$send_raw=false,$hdr=array()){
	$curl = curl_init();
	curl_setopt_array(
		$curl,[
		CURLOPT_URL => $url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => '',
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_SSL_VERIFYHOST => false,
		CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_POST => true,
		CURLOPT_REFERER => SITE_URL,
		CURLOPT_CONNECTTIMEOUT => 15,
		CURLOPT_TIMEOUT => 15,
		CURLOPT_POSTFIELDS => $send_raw? $arr : json_encode($arr) ,
		CURLOPT_HTTPHEADER => $hdr?$hdr:($send_raw? ['Accept: */*'] : ['Accept: */*','Content-Type: application/json'])
		]
	);
	$s = curl_exec($curl);
	curl_close($curl);
	if($s === false){
		return ['exception'=>'خطا در برقراری ارتباط با درگاه. <br>«'.curl_error($curl).'»'];
	}
	if($out_raw){return $s;}
	$a= json_decode($s, true);
	return $a?$a:['exception'=>'پردازش اطلاعات با خطا مواجه شد. <br>«'.mb_strimwidth(trim(strip_tags($s)),0,300,'...').'»'];
}
function store_receipt_no($oid){
	global $sdb;
	if(empty($sdb['RECEIPT_SECURE_KEY'])){
		$sdb['RECEIPT_SECURE_KEY']=bin2hex(random_bytes(8));
		write_sdb();
	}
	return $oid . substr('00000'.abs(crc32($oid.$sdb['RECEIPT_SECURE_KEY'])),-6);
}
function store_order_error($oid,$a=array()){
	logmsg('تراکنش ناموفق، سفارش '.$oid.'، رسید '.store_receipt_no($oid));
	$a0=sql('SELECT order_data FROM orders WHERE order_id=?;',$oid);
	$a0=(array) json_decode($a0[0]['order_data'],true);
	$a=array_merge($a,$a0);
	$s=json_encode($a,JSON_UNESCAPED_UNICODE);
	sql('UPDATE orders SET order_status=?,order_date=?,order_data=? WHERE order_id=?;',['E',date('Y-m-d H:i:s'),$s,$oid]);
	header('Location: /receipt/' . store_receipt_no($oid).'/');
	exit;
}
function store_order_success($oid,$a=array()){
	logmsg('تراکنش موفق، سفارش '.$oid.'، رسید '.store_receipt_no($oid));
	$o=sql('SELECT * FROM orders WHERE order_id=?;',$oid);
	$o=$o[0];
	foreach(['cart','customer','data'] as $k){
		$o['order_'.$k]=(array) json_decode($o['order_'.$k],true);
	}
	$o['order_data']=array_merge($a,$o['order_data']);
	$pids=[];
	for($i=0;$i<count($o['order_cart']);$i++){$pids[]=$o['order_cart'][$i][0];}
	if($pids){
		$b=sql('SELECT post_data FROM posts WHERE post_id IN ('.implode(',',$pids).') AND post_data LIKE \'%"store_service":"%\';');
		for($i=0;$i<count($b);$i++){
			$d=json_decode($b[$i]['post_data'],true);
			//store_service script invoked.	$o and $d contains order and post_data.
			eval($d['store_service']);
		}
	}
	$s=json_encode($o['order_data'],JSON_UNESCAPED_UNICODE);
	sql('UPDATE orders SET order_status=?,order_date=?,order_data=? WHERE order_id=?;',['P',date('Y-m-d H:i:s'),$s,$oid]);
	header('Location: /receipt/' . store_receipt_no($oid).'/');
	exit;
}

//===================================================================================

