<?php
  /**
   * Core Class
   *
   * @package Digital Downloads Pro
   * @author wojoscripts.com
   * @copyright 2010
   * @version $Id: class_core.php, v2.00 2011-07-10 10:12:05 gewa Exp $
   */
  
  if (!defined("_VALID_PHP"))
      die('. دسترسی مستقیم به این محل مجاز نمی باشد');
  
  class Core
  {
      
	  public $msgs = array();
	  public $showMsg;
	  private $sTable = "settings";
	  public $action = null;
	  public $id = null;
	  public $do = null;
      public $year = null;
      public $month = null;
      public $day = null;
	  
	  
      /**
       * Core::__construct()
       * 
       * @return
       */
      function __construct()
      {
          $this->getSettings();
		  $this->getAction();
		  $this->getDo();
		  $this->getId();
		  
		  ($this->dtz) ? date_default_timezone_set($this->dtz) : date_default_timezone_set('GMT');
		  
          $this->year = (get('year')) ? get('year') : strftime('%Y');
          $this->month = (get('month')) ? get('month') : strftime('%m');
          $this->day = (get('day')) ? get('day') : strftime('%d');
          
          return mktime(0, 0, 0, $this->month, $this->day, $this->year);
      }

	  /**
	   * Core::getId()
	   * 
	   * @return
	   */
	  private function getId()
	  {
	  	  global $core, $DEBUG;
		  
		  if (isset($_GET['id'])) {
			  $id = (is_numeric($_GET['id']) && $_GET['id'] > -1) ? intval($_GET['id']) : false;
			  $id = sanitize($id,8,true);
			  
			  if ($id == false) {
				  ($DEBUG) ? $this->error(" نامعتبـر انتخـاب نموده ایـد Id شمـا یک ","Core::getId()") : redirect_to($this->site_url.'/404.php');
			  } else
				  return $this->id = $id;
		  }
	  }
	        
      /**
       * Core::getSettings()
       *
       * @return
       */
      private function getSettings()
      {
          global $db;
          $sql = "SELECT * FROM " . $this->sTable;
          $row = $db->first($sql);
          
          $this->site_name = $row['site_name'];
		  $this->company = $row['company'];
          $this->site_url = $row['site_url'];
		  $this->site_email = $row['site_email'];
		  $this->seo = $row['seo'];
		  $this->perpage = $row['perpage'];
		  $this->backup = $row['backup'];
		  $this->thumb_w = $row['thumb_w'];
		  $this->thumb_h = $row['thumb_h'];
		  $this->img_w = $row['img_w'];
		  $this->img_h = $row['img_h'];
		  $this->file_dir = $row['file_dir'];
		  $this->short_date = $row['short_date'];
		  $this->long_date = $row['long_date'];
		  $this->dtz = $row['dtz'];
		  $this->featured = $row['featured'];
		  $this->popular = $row['popular'];
		  $this->free_allowed = $row['free_allowed'];
		  $this->logo = $row['logo'];
		  $this->currency = $row['currency'];
		  $this->cur_symbol = $row['cur_symbol'];
		  $this->offline = $row['offline'];
		  $this->reg_verify = $row['reg_verify'];
		  $this->notify_admin = $row['notify_admin'];
		  $this->auto_verify = $row['auto_verify'];
		  $this->reg_allowed = $row['reg_allowed'];
		  $this->user_limit = $row['user_limit'];
		  $this->analytics = $row['analytics'];
          $this->metakeys = $row['metakeys'];
          $this->metadesc = $row['metadesc'];
		  $this->mailer = $row['mailer'];
		  $this->smtp_host = $row['smtp_host'];
		  $this->smtp_user = $row['smtp_user'];
		  $this->smtp_pass = $row['smtp_pass'];
		  $this->smtp_port = $row['smtp_port'];
		  
		  $this->version = $row['version'];

      }

      /**
       * Core::processConfig()
       * 
       * @return
       */
	  public function processConfig()
	  {
		  global $db;
		  
		  if (empty($_POST['site_name']))
			  $this->msgs['site_name'] = "!لطفـا نـام وب سایـت را وارد نمائیـد";
		  
		  if (empty($_POST['site_url']))
			  $this->msgs['site_url'] = "!لطفـا آدرس وب سایـت را وارد نمائیـد";
		  
		  if (empty($_POST['site_email']))
			  $this->msgs['site_email'] = "!لطفـا ایـمیـل معتبـر وب سایـت را وارد نمائیـد";
		  
		  if (empty($_POST['thumb_w']))
			  $this->msgs['thumb_w'] = "!لطفـا عرض تصـویـر کوچـک را وارد نمائیـد";
		  
		  if (empty($_POST['thumb_h']))
			  $this->msgs['thumb_h'] = "!لطفـا ارتفاع تصـویـر کوچـک را وارد نمائیـد";

		  if (empty($_POST['img_w']))
			  $this->msgs['img_w'] = "!لطفـا عرض تصـویـر را وارد نمائیـد";
		  
		  if (empty($_POST['img_h']))
			  $this->msgs['img_h'] = "!لطـفا ارتفـاع تصـویـر را وارد نمائیـد";

		  if (empty($_POST['file_dir']))
			  $this->msgs['file_dir'] = "!لطفـا مسیـر معتبـر فایـل را وارد نمائیـد";
			  			  
		  if (empty($_POST['currency']))
			  $this->msgs['currency'] = '.لطفـا ارز معتبـر وارد نمائیـد';

		  if (empty($_POST['featured']))
			  $this->msgs['featured'] = '.لطفـا تعـداد محصـولات ویـژه را وارد نمائیـد';
			  
		  if (empty($_POST['popular']))
			  $this->msgs['popular'] = '.لطفـا تعـداد محصـولات محـبوب را وارد نمائیـد';
			  
		  if (empty($_POST['perpage']))
			  $this->msgs['perpage'] = '.لطفـا تعـداد محصـولاتی که در صفحـه می بایسـت نمایـش داده شوند را وارد نمائیـد';
			  
			  
		  if (isset($_POST['logo'])) {
			  if (!preg_match("/(\.jpg|\.png|\.gif|\.bmp|\.jpeg|\.swf)$/i", $_POST['logo']))
				  $this->msgs['logo'] = 'Illegal file type. Only jpg,png,gif and swf file types allowed.';
		  }
		    
		  if ($_POST['mailer'] == "SMTP") {
			  if (empty($_POST['smtp_host']))
				  $this->msgs['smtp_host'] = '!را وارد نمائیـد SMTP لطفـا میزبان معتبر';
			  if (empty($_POST['smtp_user']))
				  $this->msgs['smtp_user'] = '!را وارد نمائیـد SMTP لطفـا نام کاربری معتبر';
			  if (empty($_POST['smtp_pass']))
				  $this->msgs['smtp_pass'] = '!را وارد نمائیـد SMTP لطفـا کلمه عبور معتبر';
			  if (empty($_POST['smtp_port']))
				  $this->msgs['smtp_port'] = '!را وارد نمائیـد SMTP لطفـا پورت معتبر';
		  }
		  
		  if (empty($this->msgs)) {
			  $data = array(
					  'site_name' => sanitize($_POST['site_name']), 
					  'company' => sanitize($_POST['company']),
					  'site_url' => sanitize($_POST['site_url']),
					  'site_email' => sanitize($_POST['site_email']),
					  'seo' => intval($_POST['seo']),
					  'perpage' => intval($_POST['perpage']),
					  'thumb_w' => intval($_POST['thumb_w']),
					  'thumb_h' => intval($_POST['thumb_h']),
					  'img_w' => intval($_POST['img_w']),
					  'img_h' => intval($_POST['img_h']),
					  'file_dir' => sanitize($_POST['file_dir']),
					  'short_date' => sanitize($_POST['short_date']),
					  'long_date' => sanitize($_POST['long_date']),
					  'dtz' => trim($_POST['dtz']),
					  'currency' => sanitize($_POST['currency']),
					  'cur_symbol' => sanitize($_POST['cur_symbol']),
					  'offline' => intval($_POST['offline']),
					  'featured' => intval($_POST['featured']),
					  'popular' => intval($_POST['popular']),
					  'free_allowed' => intval($_POST['free_allowed']),
					  'reg_verify' => intval($_POST['reg_verify']),
					  'auto_verify' => intval($_POST['auto_verify']),
					  'reg_allowed' => intval($_POST['reg_allowed']),
					  'notify_admin' => intval($_POST['notify_admin']),
					  'user_limit' => intval($_POST['user_limit']),
					  'analytics' => trim($_POST['analytics']),
					  'metadesc' => trim($_POST['metadesc']),
					  'metakeys' => trim($_POST['metakeys']),
					  'mailer' => sanitize($_POST['mailer']),
					  'smtp_host' => sanitize($_POST['smtp_host']),
					  'smtp_user' => sanitize($_POST['smtp_user']),
					  'smtp_pass' => sanitize($_POST['smtp_pass']),
					  'smtp_port' => intval($_POST['smtp_port'])

			  );
			  
			  if (isset($_POST['dellogo']) && $_POST['dellogo'] == 1) {
				  $data['logo'] = "NULL";
			  } elseif (isset($_POST['logo'])) {
				  if ($this->logo)
					  unlink(UPLOADS . $this->logo);
				  $data['logo'] = sanitize($_POST['logo']);
			  } else {
				  $data['logo'] = $this->logo;
			  }
			  
			  $db->update($this->sTable, $data);
			  ($db->affected()) ? $this->msgOk("<span>!موفقیـت</span>!پیکـربنـدی سیسـتم با موفقیـت بروز رسـانی شـد") : $this->msgAlert("<span>!تـوجـه</span>.چیـزی برای پـردازش وجـود ندارد");
		  } else
			  print $this->msgStatus();
	  }
	  	 
      /**
       * Core::getShortDate()
       * 
       * @return
       */ 
      public function getShortDate($selected = '')
	  {
		  $arr = array(
				 '%m-%d-%Y' => '12-21-2009 (MM-DD-YYYY)',
				 '%e-%c-%Y' => '21-12-2009 (D-M-YYYY)',
				 '%m-%e-%y' => '12-21-09 (M-D-YY)',
				 '%e-%c-%y' => '21-12-09 (D-M-YY)',
				 '%d %b %Y' => 'Dec 21 2009'
		  );
		  
		  $shortdate = '';
		  $sel = ($selected !='') ? $selected : $this->short_date;
		  foreach ($arr as $key => $val) {
              if ($key == $sel ) {
                  $shortdate .= "<option selected=\"selected\" value=\"" . $key . "\">" . $val . "</option>\n";
              } else
                  $shortdate .= "<option value=\"" . $key . "\">" . $val . "</option>\n";
          }
          unset($val);
          return $shortdate;
      }
	  
      /**
       * Core::getLongDate()
       * 
       * @return
       */ 	  
      public function getLongDate($selected = '')
	  {
		  $arr = array(
				'%M %d, %Y' => 'December 21, 2009',
				'%d %M %Y %H:%i' => '21 December 2009 19:00',
				'%M %W, %Y' => 'December 21st, 2009',
				'%W %M, %Y' => '21st December, 2009',
				'%W %D %M, %Y' => 'Monday 21st December, 2009',
				'%W %D %M %Y %h:%i' => 'Monday 21st December 2009 07:00',
				'%a %d, %M %Y' => 'Mon. 12, December'
		  );
		  
		  $longdate = '';
		  $sel = ($selected !='') ? $selected : $this->long_date;
		  foreach ($arr as $key => $val) {
              if ($key == $sel ) {
                  $longdate .= "<option selected=\"selected\" value=\"" . $key . "\">" . $val . "</option>\n";
              } else
                  $longdate .= "<option value=\"" . $key . "\">" . $val . "</option>\n";
          }
          unset($val);
          return $longdate;
      }

      /**
       * Core::getTimezones()
       * 
       * @return
       */
	  public function getTimezones()
	  {
		  $data = '';
		  $tzone = DateTimeZone::listIdentifiers();
		  $data .='<select name="dtz" style="width:220px">';
		  foreach ($tzone as $zone) {
			  $selected = ($zone == $this->dtz) ? ' selected="selected"' : '';
			  $data .= '<option value="' . $zone . '"' . $selected . '>' . $zone . '</option>';
		  }
		  $data .='</select>';
		  return $data;
	  }
	  	  	  	  
      /**
       * Core::monthList()
       * 
       * @return
       */ 	  
      public function monthList()
	  {
		  $selected = is_null(get('month')) ? strftime('%m') : get('month');
		  
		  $arr = array(
				'01' => "Jan",
				'02' => "Feb",
				'03' => "Mar",
				'04' => "Apr",
				'05' => "May",
				'06' => "Jun",
				'07' => "Jul",
				'08' => "Aug",
				'09' => "Sep",
				'10' => "Oct",
				'11' => "Nov",
				'12' => "Dec"
		  );
		  
		  $monthlist = '';
		  foreach ($arr as $key => $val) {
			  $monthlist .= "<option value=\"$key\"";
			  $monthlist .= ($key == $selected) ? ' selected="selected"' : '';
			  $monthlist .= ">$val</option>\n";
          }
          unset($val);
          return $monthlist;
      }

      /**
       * Core::yearList()
	   *
       * @param mixed $start_year
       * @param mixed $end_year
       * @return
       */
	  function yearList($start_year, $end_year)
	  {
		  $selected = is_null(get('year')) ? date('Y') : get('year');
		  $r = range($start_year, $end_year);
		  
		  $select = '';
		  foreach ($r as $year) {
			  $select .= "<option value=\"$year\"";
			  $select .= ($year == $selected) ? ' selected="selected"' : '';
			  $select .= ">$year</option>\n";
		  }
		  return $select;
	  }
	  	  
      /**
       * Core::monthlyStats()
       * 
       * @return
       */ 	  
      public function monthlyStats()
	  {
          global $db;
          $sql = "SELECT id, COUNT(id) as total" 
		  . "\n FROM users" 
		  . "\n WHERE created > '" . $this->year . "-" . $this->month . "-01'" 
		  . "\n AND created < '" . $this->year . "-" . $this->month . "-31 23:59:59'";
          
          $row = $db->first($sql);
          
		  return ($row['total'] > 0) ? $row : false;
      }
	  
      /**
       * Core::getStats()
       * 
       * @return
       */ 	  
      public function getStats()
	  {
          global $db;
          $sql = "SELECT id, COUNT(id) as total, DAY(created) as day FROM users" 
		  . "\n WHERE YEAR(created) = '" . $this->year . "'"
		  . "\n AND MONTH(created) = '" . $this->month . "' GROUP BY DATE(created)"; 
          
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

	  /**
	   * Core::formatMoney()
	   * 
	   * @param mixed $amount
	   * @return
	   */
	  public function formatMoney($amount)
	  {
		  return ($amount == 0) ? "<span style=\"color:red\">رایــگـان</span>" : $this->cur_symbol . number_format($amount, 2, '.', ',') . $this->currency;
	  }

	  /**
	   * readFile()
	   * 
	   * @param mixed $filename
	   * @param boll $retbytes
	   * @return
	   */
	  public function readFile($filename,$retbytes=true) {  
		 $chunksize = 1*(1024*1024);
		 $buffer = '';  
		 $cnt =0;  
	
		 $handle = fopen($filename, 'rb');  
		 if ($handle === false) {  
			 return false;  
		 }  
		 while (!feof($handle)) {  
			 $buffer = fread($handle, $chunksize);  
			 echo $buffer;  
			 ob_flush();  
			 flush();  
			 if ($retbytes) {  
				 $cnt += strlen($buffer);  
			 }  
		 }  
			 $status = fclose($handle);  
		 if ($retbytes && $status) {  
			 return $cnt;
		 }  
		 return $status;  
	   
	  } 

	  /**
	   * fetchFile()
	   * 
	   * @return
	   */
	  public function fetchFile($dirname, $fname, &$file_path)
	  {
		  $dir = opendir($dirname);
		  
		  while ($file = readdir($dir)) {
			  if (empty($file_path) && $file != '.' && $file != '..') {
				  if (is_dir($dirname . '/' . $file)) {
					  fetchFile($dirname . '/' . $file, $fname, $file_path);
				  } else {
					  if (file_exists($dirname . '/' . $fname)) {
						  $file_path = $dirname . '/' . $fname;
						  return;
					  }
				  }
			  }
		  }
	  }

      /**
       * Core::verifyTxnId()
       * 
       * @param mixed $txn_id
       * @return
       */
      public function verifyTxnId($txn_id)
      {
          global $db;
          
          $sql = $db->query("SELECT id" 
				. "\n FROM transactions" 
				. "\n WHERE txn_id = '" . sanitize($txn_id) . "'" 
				. "\n LIMIT 1");
		  		
          if ($db->numrows($sql) > 0)
              return false;
          else
              return true;
      }
	      	  				  
      /**
       * Core::getRowById()
       * 
       * @param mixed $table
       * @param mixed $id
       * @param bool $and
       * @param bool $is_admin
       * @return
       */
      public function getRowById($table, $id, $and = false, $is_admin = true)
      {
          global $db;
		  $id = sanitize($id, 8, true);
		  if ($and) {
			  $sql = "SELECT * FROM " . (string)$table . " WHERE id = '" . $db->escape((int)$id) . "' AND " . $db->escape($and) . "";
		  } else
			  $sql = "SELECT * FROM " . (string)$table . " WHERE id = '" . $db->escape((int)$id) . "'";
		  
          $row = $db->first($sql);
          
		  if ($row) {
			  return $row;
		  } else {
			  if ($is_admin)
				  $this->error("نامعتبـر انتخـاب نمـوده ایـد Id شمـا یک - #".$id, "Core::getRowById()");
		  }
	  }

      /**
       * Core::msgAlert()
       * 
	   * @param mixed $msg
	   * @param bool $fader
	   * @param bool $altholder
       * @return
       */	  
	  public function msgAlert($msg, $fader = true, $altholder = false)
	  {
		$this->showMsg = "<div class=\"msgAlert\">" . $msg . "</div>";
		if ($fader == true)
		  $this->showMsg .= "<script type=\"text/javascript\"> 
		  // <![CDATA[
		  $(document).ready(function() {       
			setTimeout(function() {       
			  $(\".msgAlert\").customFadeOut(\"slow\",    
			  function() {       
				$(\".msgAlert\").remove();  
			  });
			},
			4000);
		  });
		  // ]]>
		  </script>";	
		  
		  print ($altholder) ? '<div id="alt-msgholder">'.$this->showMsg.'</div>' : $this->showMsg;
	  }

      /**
       * Core::msgOk()
       * 
	   * @param mixed $msg
	   * @param bool $fader
	   * @param bool $altholder
       * @return
       */	  
	  public function msgOk($msg, $fader = true, $altholder = false)
	  {
		$this->showMsg = "<div class=\"msgOk\">" . $msg . "</div>";
		if ($fader == true)
		  $this->showMsg .= "<script type=\"text/javascript\"> 
		  // <![CDATA[
		  $(document).ready(function() {       
			setTimeout(function() {       
			  $(\".msgOk\").customFadeOut(\"slow\",    
			  function() {       
				$(\".msgOk\").remove();  
			  });
			},
			4000);
		  });
		  // ]]>
		  </script>";	
		  
		  print ($altholder) ? '<div id="alt-msgholder">'.$this->showMsg.'</div>' : $this->showMsg;
	  }

      /**
       * Core::msgError()
       * 
	   * @param mixed $msg
	   * @param bool $fader
	   * @param bool $altholder
       * @return
       */	  
	  public function msgError($msg, $fader = true, $altholder = false)
	  {
		$this->showMsg = "<div class=\"msgError\">" . $msg . "</div>";
		if ($fader == true)
		  $this->showMsg .= "<script type=\"text/javascript\"> 
		  // <![CDATA[
		  $(document).ready(function() {       
			setTimeout(function() {       
			  $(\".msgError\").customFadeOut(\"slow\",    
			  function() {       
				$(\".msgError\").remove();  
			  });
			},
			4000);
		  });
		  // ]]>
		  </script>";	
	  
		  print ($altholder) ? '<div id="alt-msgholder">'.$this->showMsg.'</div>' : $this->showMsg;
	  } 	


	  /**
	   * msgInfo()
	   * 
	   * @param mixed $msg
	   * @param bool $fader
	   * @param bool $altholder
	   * @return
	   */
	  public function msgInfo($msg, $fader = true, $altholder = false)
	  {
		$this->showMsg = "<div class=\"msgInfo\">" . $msg . "</div>";
		if ($fader == true)
		  $this->showMsg .= "<script type=\"text/javascript\"> 
		  // <![CDATA[
		  $(document).ready(function() {       
			setTimeout(function() {       
			  $(\".msgInfo\").customFadeOut(\"slow\",    
			  function() {       
				$(\".msgInfo\").remove();  
			  });
			},
			4000);
		  });
		  // ]]>
		  </script>";
	  
		  print ($altholder) ? '<div id="alt-msgholder">'.$this->showMsg.'</div>' : $this->showMsg;
	  }
	    
      /**
       * Core::msgStatus()
       * 
       * @return
       */
	  public function msgStatus()
	  {
		  $this->showMsg = "<div class=\"msgError\"><span>!خـطا</span>: هنگـام بررسی، خـطایی رخ داده اسـت<ul class=\"error\">";
		  foreach ($this->msgs as $msg) {
			  $this->showMsg .= "<li>" . $msg . "</li>\n";
		  }
		  $this->showMsg .= "</ul></div>";
		  
		  return $this->showMsg;
	  }	  

	  /**
	   * doForm()
	   * 
	   * @param mixed $data
	   * @param string $url
	   * @param integer $reset
	   * @param integer $clear
	   * @param string $form_id
	   * @param string $msgholder
	   * @return
	   */  
	  public function doForm($data, $url = "controller.php", $reset = 0, $clear = 0, $form_id = "admin_form", $msgholder = "msgholder")
	  {
		  $display ='
		  <script type="text/javascript">
		  // <![CDATA[
			  $(document).ready(function () {
				  var options = {
					  target: "#' . $msgholder . '",
					  beforeSubmit:  showLoader,
					  success: showResponse,
					  url: "' . $url . '",
					  resetForm : ' . $reset . ',
					  clearForm : ' . $clear . ',
					  data: {
						  ' .$data . ': 1
					  }
				  };
				  $("#' . $form_id . '").ajaxForm(options);
			  });
			  
			  function showLoader() {
				  $("#loader").fadeIn(200);
			  }
		  
			  function hideLoader() {
				  $("#loader").fadeOut(200);
			  };	
			  		  
			  function showResponse(msg) {
				  hideLoader();
				  $(this).html(msg);
				  $("html, body").animate({
					  scrollTop: 0
				  }, 600);
			  }
			  ';
          $display .='
		  // ]]>
		  </script>';
		  
		  print $display;
	  }
	  
      /**
       * Core::error()
       * 
	   * @param mixed $msg
	   * @param mixed $source
       * @return
       */
      public function error($msg, $source)
      {

          $the_error = "<div class=\"msgError\">";
          $the_error .= "<span>!خـطای سیـستم</span><br />";
          $the_error .= "DB خـطا : ".$msg." <br /> اطـلاعـات بیشـتر : <br />";
          $the_error .= "<ul>";
          $the_error .= "<li> تاریـخ : " . date("F j, Y, g:i a") . "</li>";
		  $the_error .= "<li> وظیـفه : " . $source . "</li>";
          $the_error .= "<li> اسکریپـت : " . $_SERVER['REQUEST_URI'] . "</li>";
		  $the_error .= "<li>&lsaquo; <a href=\"javascript:history.go(-1)\"><strong>بازگشـت به صفحـه قبـل</strong></a></li>";
          $the_error .= '</ul>';
          $the_error .= '</div>';
          print $the_error;
          die();
      }
  
      /**
       * Core::getAction()
       * 
       * @return
       */
	  private function getAction()
	  {
		  if (isset($_GET['action'])) {
			  $action = ((string)$_GET['action']) ? (string)$_GET['action'] : false;
			  $action = sanitize($action);
			  
			  if ($action == false) {
				  $this->error(".شمـا اقدام به انتخـاب یک روش نامعتبـر نموده ایـد","Core::getAction()");
			  } else
				  return $this->action = $action;
		  }
	  }
  
      /**
       * Core::getDo()
       * 
       * @return
       */
	  private function getDo()
	  {
		  if (isset($_GET['do'])) {
			  $do = ((string)$_GET['do']) ? (string)$_GET['do'] : false;
			  $do = sanitize($do);
			  
			  if ($do == false) {
				  $this->error("You have selected an Invalid Do Method","Core::getDo()");
			  } else
				  return $this->do = $do;
		  }
	  }
  }
?>