<?php
  /**
   * Content 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 Content
  {
	  private $cattree = array();
	  private $catlist = array();
	  public $cid = null;
	  public $tag = null;
	  
      /**
       * Content::__construct()
       * 
       * @return
       */
      function __construct()
      {
		  $this->cattree = $this->getCatTree();
		  $this->getCid();
		  $this->getTag();

      }

	  /**
	   * Content::getCid()
	   * 
	   * @return
	   */
	  private function getCid()
	  {
	  	  global $core, $DEBUG;
		  
		  if (isset($_GET['cid'])) {
			  $cid = (is_numeric($_GET['cid']) && $_GET['cid'] > -1) ? intval($_GET['cid']) : false;
			  $cid = sanitize($cid,8,true);
			  
			  if ($cid == false) {
				  ($DEBUG) ? $core->error("..نامعتبـر انتخـاب نموده ایـد Cid شمـا یک","Content::getCid()") : redirect_to($_SERVER['SCRIPT_NAME']);
			  } else
				  return $this->cid = $cid;
		  }
	  }

	  /**
	   * Content::getCid()
	   * 
	   * @return
	   */
	  private function getTag()
	  {
	  	  global $core;
		  
		  if (isset($_GET['tag'])) {
			  $this->tag = sanitize($_GET['tag'],20,false);
			  return $this->tag;
		  }
	  }
	  	  
      /**
       * Content::getMenuList()
       * 
       * @return
       */
	  public function getMenuList()
	  {
		  global $db;
		  
		  if ($menurow = $db->fetch_all("SELECT * FROM menus ORDER BY position")) {
			  print "<ul>\n";
			  foreach ($menurow as $row) {
				  print '<li id="list_' . $row['id'] . '">' . '<div><a href="javascript:void(0)" id="item_' . $row['id'] . '" rel="' . $row['name'] . '" class="delete">' 
				  . '<img src="images/delete.png" alt="" class="tooltip" title="حـذف"/></a>' 
				  . '<a href="index.php?do=menus&amp;action=edit&amp;id=' . $row['id'] . '" class="parent">' . $row['name'] . '</a></div>';
				  print "</li>\n";
			  }
		  }
		  unset($row);
		  print "</ul>\n";
	  }

      /**
       * Content::getMenuList()
       * 
       * @return
       */
	  public function getMenu()
	  {
		  global $db, $core;
		  
		  if($menurow = $db->fetch_all("SELECT m.*, p.id, p.home_page,p.slug"
		  . "\n FROM menus as m" 
		  . "\n LEFT JOIN pages AS p ON p.id = m.page_id" 
		  . "\n WHERE m.active = '1'"
		  . "\n ORDER BY m.position")){
			  
			  $res =  "<ul class=\"pagemenu\">";
			  foreach ($menurow as $row) {
                  $url = ($core->seo == 1) ? $core->site_url . '/view-content/' . intval($row['id']) . '/' . sanitize($row['slug']) . '.html' : $display = $core->site_url . '/content.php?id=' . intval($row['id']);
				  $mainurl = ($row['home_page']) ?  $core->site_url : $url;
				  $res .= "<li><a href=\"" . $mainurl . "\">" . $row['name'] . "</a></li>\n";
			  }
            $res .=  "</ul>";
			print $res;
			unset($row);
		  }
	  }
	  
	  /**
	   * Content::processMenu()
	   * 
	   * @return
	   */
	  public function processMenu()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['name']))
			  $core->msgs['name'] = '..لطفـا نـام منـو را وارد نمائیـد';
		  
		  if ($_POST['content_type'] == "NA")
			  $core->msgs['content_type'] = '..لطفـا نوع محتـوا را انتخـاب نمائیـد';
		  
		  if (empty($core->msgs)) {
			  $data = array(
				  'name' => sanitize($_POST['name']), 
				  'page_id' => intval($_POST['page_id']),
				  'content_type' => sanitize($_POST['content_type']),
				  'link' => (isset($_POST['web'])) ? sanitize($_POST['web']) : "NULL",
				  'target' => (isset($_POST['target'])) ? sanitize($_POST['target']) : "DEFAULT(target)",
				  'active' => intval($_POST['active'])
			  );
			  
			  ($core->id) ? $db->update("menus", $data, "id='" . (int)$core->id . "'") : $db->insert("menus", $data);
			  $message = ($core->id) ? '<span>!موفقیـت</span>!منـو با موفقیـت بروز رسـانی شـد' : '<span>!موفقیـت</span>!منـو با موفقیـت اضـافـه شـد';
			  
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert('<span>!تـوجـه</span>.چیـزی برای پردازش وجـود ندارد');
			
		  } else
			  print $core->msgStatus();
	  }
	  	  
      /**
       * Content::getCatTree()
       * 
       * @return
       */
      protected function getCatTree()
	  {
		  global $db, $core;
		  $query = $db->query('SELECT * FROM categories ORDER BY parent_id, position');
		  
		  while ($row = $db->fetch($query)) {
			  $this->cattree[$row['id']] = array(
			        'id' => $row['id'],
					'name' => $row['name'], 
					'parent_id' => $row['parent_id']
			  );
		  }
		  return $this->cattree;
	  }

      /**
       * Content::getCatList()
       * 
       * @return
       */
      public function getCatList()
	  {
		  global $db, $core;
		  $query = $db->query("SELECT * FROM categories" 
		  . "\n WHERE active = 1"
		  . "\n ORDER BY parent_id, position");

		  while ($row = $db->fetch($query)) {
			  $catlist[$row['id']] = array(
			        'id' => $row['id'],
					'name' => $row['name'], 
					'parent_id' => $row['parent_id'],
					'active' => $row['active'],
					'slug' => $row['slug']
			  );
		  }
		  return $catlist;
	  }

      /**
       * Content::getSortCatList()
       * 
	   * @param integer $parent_id
       * @return
       */
      public function getSortCatList($parent_id = 0)
	  {
		  global $core;
		  
		  $subcat = false;
		  $class = ($parent_id == 0) ? "parent" : "child";

		  foreach ($this->cattree as $key => $row) {
			  if ($row['parent_id'] == $parent_id) {
				  if ($subcat === false) {
					  $subcat = true;
					  print "<ul>\n";
				  }
				  
				  print '<li id="list_' . $row['id'] . '">'
				  .'<div><a href="javascript:void(0)" id="item_'.$row['id'].'" rel="' . $row['name'] . '" class="delete">'
				  .'<img src="images/delete.png" alt="" class="tooltip" title="حـذف"/></a>'
				  .'<a href="index.php?do=categories&amp;action=edit&amp;id=' . $row['id'] . '" class="'.$class.'">' . $row['name'] . '</a></div>';
				  $this->getSortCatList($key);
				  print "</li>\n";
			  }
		  }
		  unset($row);
		  
		  if ($subcat === true)
			  print "</ul>\n";
	  }

      /**
       * Content::getCategories()
       * 
	   * @param mixed $array
	   * @param integer $parent_id
       * @return
       */
	  public function getCategories($array, $parent_id = 0)
	  {
		  global $core;
		  
		  $subcat = false;
		  
		  foreach ($array as $key => $row) {
			  
			  if ($row['parent_id'] == $parent_id) {
				  if ($subcat === false) {
					  $subcat = true;
					  
					  print "<ul>\n";
				  }
                  $active = ($row['id'] == $this->cid) ? " class=\"active\"" : "";
				  $url = ($core->seo == 1) ? $core->site_url . '/category/' . intval($row['id']) . '/' . sanitize($row['slug']) . '.html' :  $core->site_url . '/category.php?cid=' . intval($row['id']);

				  $link = '<a href="'.$url.'"' . $active . '><span>' . $row['name'] . '</span></a>';
				  print '<li>';
				  print $link;
				  $this->getCategories($array, $key);
				  print "</li>\n";
			  }
		  }
		  unset($row);
		  
		  if ($subcat === true)
			  print "</ul>\n";
	  }
	  
      /**
       * Content::getCatDropList()
       * 
	   * @param mixed $parent_id
	   * @param integer $level
	   * @param mixed $spacer
	   * @param bool $selected
       * @return
       */
	  public function getCatDropList($parent_id, $level = 0, $spacer, $selected = false)
	  {
		  if($this->cattree) {
			  foreach ($this->cattree as $key => $row) {
				  $sel = ($row['id'] == $selected) ? " selected=\"selected\"" : "" ;
				  if ($parent_id == $row['parent_id']) {
					  print "<option value=\"" . $row['id'] . "\"".$sel.">";
					  
					  for ($i = 0; $i < $level; $i++)
						  print $spacer;
					  
					  print $row['name'] . "</option>\n";
					  $level++;
					  $this->getCatDropList($key, $level, $spacer, $selected);
					  $level--;
				  }
			  }
			  unset($row);
		  }
	  }

	  /**
	   * Content::processCategory()
	   * 
	   * @return
	   */
	  public function processCategory()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['name']))
			  $core->msgs['name'] = '..لطفـا نـام دستـه بنـدی را وارد نمائیـد';
		  
		  if (empty($core->msgs)) {
			  $data = array(
				  'name' => sanitize($_POST['name']), 
				  'parent_id' => intval($_POST['parent_id']), 
				  'slug' => paranoia($_POST['name']),
				  'description' => sanitize($_POST['description']),
				  'metakeys' => sanitize($_POST['metakeys']),
				  'metadesc' => sanitize($_POST['metadesc']),
				  'active' => intval($_POST['active'])
			  );
			  
			  ($core->id) ? $db->update("categories", $data, "id='" . (int)$core->id . "'") : $db->insert("categories", $data);
			  $message = ($core->id) ? '<span>!موفقیـت</span>!دستـه بنـدی با موفقیـت بروز رسـانی شـد' : '<span>!موفقیـت</span>!دستـه بنـدی با موفقیـت اضـافـه شـد';
			  
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert('<span>!تـوجـه</span>.چیـزی برای پردازش وجـود ندارد');
			
		  } else
			  print $core->msgStatus();
	  }

      /**
       * Content::rendertCategories()
       * 
       * @return
       */
      public function rendertCategories()
      {
          global $db, $pager, $core;
		  
		  require_once(BASEPATH . "lib/class_paginate.php");
		  $pager = new Paginator();
		  
		  $counter = countEntries('products',"cid",$this->cid."' AND active = '1");
		  $pager->items_total = $counter;
		  $pager->default_ipp = $core->perpage;
		  $pager->paginate();
		  
		  if ($counter == 0) {
			$pager->limit = "";
		  }
		  
		  $sql = "SELECT p.id as pid, p.title, p.description, p.hits, p.slug, p.price,p.thumb,p.vote_up,p.vote_down,p.rating,p.audio," 
		  . "\n c.id as cid, c.name,"
		  . "\n DATE_FORMAT(p.created, '" . $core->long_date . "') as cdate," 
		  . "\n (SELECT COUNT(pid) FROM comments WHERE pid = p.id) as comments"
		  . "\n FROM products as p" 
		  . "\n LEFT JOIN categories as c ON p.cid = c.id" 
		  . "\n WHERE c.id = '" . $this->cid . "'"
		  . "\n AND c.active = '1'"
		  . "\n AND p.active = '1'"
		  . "\n ORDER BY p.created DESC " . $pager->limit;
		  
		  $row = $db->fetch_all($sql);
		  
		  return ($row) ? $row : 0;
      }
	  
      /**
       * Content::getFileTree()
       * 
       * @return
       */
      public function getFileTree()
	  {
		  global $db, $core;
		  
		  $sql = "SELECT *,DATE_FORMAT(created, '" . $core->long_date . "') as cdate FROM files ORDER BY name";
          $row = $db->fetch_all($sql);
          
		  return ($row) ? $row : 0;
	  }

	  /**
	   * Content::processFile()
	   * 
	   * @return
	   */
	  public function processFile()
	  {
		  global $db, $core;

		  if (!is_file($core->file_dir . $_POST['filename']))
			  $core->msgs['filename'] = '!نـام فایـل وارد شـده وجـود ندارد';

		  if (empty($_POST['alias']))
			  $core->msgs['alias'] = '..لطفـا نـام مستعـار فایـل را وارد نمائیـد';

		  if (!is_dir($core->file_dir))
			  $core->msgs['filedir'] = '!مسیـر آپـلــود وجـود ندارد';
		  
		  if (!is_writeable($core->file_dir))
			  $core->msgs['filedir'] = '!مسیـر آپـلــود قابـل نوشتـن نمی باشـد';

		  if (empty($core->msgs)) {
			  $filename = $core->file_dir . $_POST['filename'];
			  $filesize = filesize($filename);
				  $data = array(
					  'name' => sanitize($_POST['filename']), 
					  'alias' => sanitize($_POST['alias']), 
					  'filesize' => $filesize,
					  'created' => "NOW()",
					  'active' => 1
				  );
			  
			  $db->insert("files", $data);
			  ($db->affected()) ? $core->msgOk('<span>!موفقیـت</span>!فایـل با موفقیـت اضـافـه شـد') :  $core->msgAlert('<span>Alert!</span>Nothing to process.');
			
		  } else
			  print $core->msgStatus();
	  }
	  	  	  	  	  	  	  
      /**
       * Content::getGateways()
       * 
       * @return
       */
      public function getGateways($active = false)
      {
          global $db;
		  
		  $where = ($active) ? "WHERE active = '1'" : null ;
          $sql = "SELECT * FROM gateways" 
		  . "\n " . $where
		  . "\n ORDER BY name";
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

	  
	  /**
	   * Content::processGateway()
	   * 
	   * @return
	   */
	  public function processGateway()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['displayname']))
			  $core->msgs['displayname'] = '..لطفـا نـام دروازه پرداخـت را وارد نمائیـد';

		  if (empty($_POST['extra']))
			  $core->msgs['extra'] = '..لطفـا یک ایـمیـل معتبـر وارد نمائیـد';
			  			  		  
		  if (empty($core->msgs)) {
			  $data = array(
					  'displayname' => sanitize($_POST['displayname']), 
					  'extra' => sanitize($_POST['extra']),
					  'extra2' => sanitize($_POST['extra2']),
					  'extra3' => sanitize($_POST['extra3']),
					  'demo' => intval($_POST['demo']),
					  'active' => intval($_POST['active'])
			  );

			  $db->update("gateways", $data, "id='" . (int)$core->id . "'");
			  ($db->affected()) ? $core->msgOk('<span>!موفقیـت</span>..پیکـربنـدی دروازه پرداخـت با موفقیـ انجـام شـد') :  $core->msgAlert('<span>!تـوجـه</span>.چـیـزی برای پردازش وجـود ندارد');
		  } else
			  print $core->msgStatus();
	  }

	  /**
	   * Content::createSiteMap()
	   * 
	   * @return
	   */
	  private function createSiteMap()
	  {
		  global $db, $core;
		  
		  $sql1 = "SELECT id, slug, created FROM pages ORDER BY created DESC";
		  $pages = $db->query($sql1);

		  $sql2 = "SELECT id, slug, created FROM products ORDER BY created DESC";
		  $items = $db->query($sql2);
		  
		  $smap = "";
		  
		  @header('<?phpxml version="1.0" encoding="UTF-8"?>');
		  $smap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\r\n';
		  $smap .= "<url>\r\n";
		  $smap .= "<loc>" . SITEURL . "/index.php</loc>\r\n";
		  $smap .= "<lastmod>" . date('Y-m-d') . "</lastmod>\r\n";
		  $smap .= "</url>\r\n";

		  while ($row = $db->fetch($pages)) {
			  if ($core->seo == 1) {
				  $url = $core->site_url . '/view-content/' . intval($row['id']) . '/' . sanitize($row['slug']) . '.html';
			  } else
				  $url = $core->site_url . '/content.php?id=' . intval($row['id']);
			  
			  $smap .= "<url>\r\n";
			  $smap .= "<loc>" . $url . "</loc>\r\n";
			  $smap .= "<lastmod>" . date('Y-m-d') . "</lastmod>\r\n";
			  $smap .= "<changefreq>هفتـگـی</changefreq>\r\n";
			  $smap .= "</url>\r\n";
		  }

		  while ($row = $db->fetch($items)) {
			  if ($core->seo == 1) {
				  $url = $core->site_url . '/view-item/' . intval($row['id']) . '/' . sanitize($row['slug']) . '.html';
			  } else
				  $url = $core->site_url . '/item.php?pid=' . intval($row['id']);
			  
			  $smap .= "<url>\r\n";
			  $smap .= "<loc>" . $url . "</loc>\r\n";
			  $smap .= "<lastmod>" . date('Y-m-d') . "</lastmod>\r\n";
			  $smap .= "<changefreq>هفتـگـی</changefreq>\r\n";
			  $smap .= "</url>\r\n";
		  }
		  
		  $smap .= "</urlset>";
		  
		  return $smap;
	  }

      /**
       * Content::writeSiteMap()
       * 
       * @return
       */
	  public function writeSiteMap()
	  {
		  global $core;
		  
		  $filename = BASEPATH . 'sitemap.xml';

		  if (is_writable($filename)) {
			  $handle = fopen($filename, 'w');
			  fwrite($handle, $this->createSiteMap());
			  fclose($handle);
			  $core->msgOk('<span>!موفقیـت</span>!نقشـه سایـت با موفقیـت ایجـاد شـد');
		  } else
			  $core->msgError('<span>!خـطا</span> sitemap.xml خـطا در ایجـاد<br />!وجـود دارد و قابـل نوشتـن می باشـد '.$filename.' مطمئـن شویـد نـام فایـل ',false);
	  }
	  	  
	  /**
	   * Content::processNewsletter()
	   * 
	   * @return
	   */
	  public function processNewsletter()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['subject']))
			  $core->msgs['subject'] = "..لطفـا موضـوع خبـرنـامـه خود را وارد نمائیـد";
		  
		  if (empty($_POST['body']))
			  $core->msgs['body'] = "!لطفـا پیـام ایـمیـل را وارد نمائیـد";
		  
		  if (empty($core->msgs)) {
				  $to = sanitize($_POST['recipient']);
				  $subject = sanitize($_POST['subject']);
				  $body = cleanOut($_POST['body']);

			  switch ($to) {
				  case "all":
					  require_once(BASEPATH . "lib/class_mailer.php");
					  $mailer = $mail->sendMail();
					  $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100));
					  
					  $sql = "SELECT email, CONCAT(fname,' ',lname) as name FROM users WHERE id != 1";
					  $userrow = $db->fetch_all($sql);
					  
					  $replacements = array();
					  if($userrow) {
						foreach ($userrow as $cols) {
							$replacements[$cols['email']] = array('[NAME]' => $cols['name'],'[SITE_NAME]' => $core->site_name,'[URL]' => $core->site_url);
						}
						
						$decorator = new Swift_Plugins_DecoratorPlugin($replacements);
						$mailer->registerPlugin($decorator);
						
						$message = Swift_Message::newInstance()
								  ->setSubject($subject)
								  ->setFrom(array($core->site_email => $core->site_name))
								  ->setBody($body, 'text/html');
						
						foreach ($userrow as $row)
							$message->addTo($row['email'], $row['name']);
						unset($row);
						
						$numSent = $mailer->batchSend($message);
					  }
					  break;
					  
				  case "newsletter":
					  require_once(BASEPATH . "lib/class_mailer.php");
					  $mailer = $mail->sendMail();
					  $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100));

					  $sql = "SELECT email, CONCAT(fname,' ',lname) as name FROM users WHERE newsletter = '1' AND id != 1";
					  $userrow = $db->fetch_all($sql);
						  
					  $replacements = array();
					  if($userrow) {
						  foreach ($userrow as $cols) {
							  $replacements[$cols['email']] = array('[NAME]' => $cols['name'],'[SITE_NAME]' => $core->site_name,'[URL]' => $core->site_url);
						  }
						  
						  $decorator = new Swift_Plugins_DecoratorPlugin($replacements);
						  $mailer->registerPlugin($decorator);
						  
						  $message = Swift_Message::newInstance()
									->setSubject($subject)
									->setFrom(array($core->site_email => $core->site_name))
									->setBody($body, 'text/html');
						  
						  foreach ($userrow as $row)
							  $message->addTo($row['email'], $row['name']);
						  unset($row);
						  
						  $numSent = $mailer->batchSend($message);
					  }
					  break;
					  				  	  
				  default:
					  require_once(BASEPATH . "lib/class_mailer.php");
					  $mailer = $mail->sendMail();	
					  			  
					  $row = $db->first("SELECT email, CONCAT(fname,' ',lname) as name FROM users WHERE email LIKE '%" . sanitize($to) . "%'");
					  
					  $newbody = str_replace(array('[NAME]', '[SITE_NAME]', '[URL]'), 
					  array($row['name'], $core->site_name, $core->site_url), $body);

					  $message = Swift_Message::newInstance()
								->setSubject($subject)
							    ->setTo(array($to => $row['name']))
								->setFrom(array($core->site_email => $core->site_name))
								->setBody($newbody, 'text/html');
					  
					  $numSent = $mailer->send($message);
					  break;
			  }

			  ($numSent) ? $core->msgOk("<span>!موفقیـت</span>!همـه ایـمیـل/هـا با موفقیـت ارسـال شـدنـد") :  $core->msgAlert("<span>!خـطا</span>!ناتوانی رسیدن برخـی از ایـمیـل ها");

		  } else
			  print $core->msgStatus();
	  }

      /**
       * Content::getHomePage()
       * 
       * @return
       */
      public function getHomePage()
      {
          global $db, $core;
          $sql = "SELECT * FROM pages WHERE home_page = '1'";
          $row = $db->first($sql);
          
          return ($row) ? $row : 0;
      }
	  
      /**
       * Content::getPages()
       * 
       * @return
       */
      public function getPages()
      {
          global $db, $core;
          $sql = "SELECT *, DATE_FORMAT(created, '".$core->short_date."') as cdate FROM pages ORDER BY title ASC";
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

	  /**
	   * Content:::processPage()
	   * 
	   * @return
	   */
	  public function processPage()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['title']))
			  $core->msgs['title'] = "!لطفـا عنـوان صفحـه را ورادنمائیـد";

		  if (empty($_POST['body']))
			  $core->msgs['body'] = "!محتـوای صفحـه مـورد نیـاز اسـت";
			  		  
		  if (empty($core->msgs)) {
			  $data = array(
				  'title' => sanitize($_POST['title']), 
				  'slug' => (empty($_POST['slug'])) ? paranoia($_POST['title']) : paranoia($_POST['slug']),
				  'body' => $_POST['body'],
				  'created' => sanitize($_POST['created']),
				  'contact' => intval($_POST['contact']),
				  'faq' => intval($_POST['faq']),
				  'home_page' => intval($_POST['home_page']),
				  'active' => intval($_POST['active'])
			  );


			  if ($data['home_page'] == 1) {
				  $home['home_page'] = "DEFAULT(home_page)";
				  $db->update("pages", $home);
			  }
			  
			  if ($data['contact'] == 1) {
				  $contact['contact'] = "DEFAULT(contact)";
				  $db->update("pages", $contact);
			  }

			  if ($data['faq'] == 1) {
				  $faq['faq'] = "DEFAULT(faq)";
				  $db->update("pages", $faq);
			  }
			   
			  if (!$core->id) {
				  $data['created'] = "NOW()";
			  }
			  
			  ($core->id) ? $db->update("pages", $data, "id='" . (int)$core->id . "'") : $db->insert("pages", $data);
			  $message = ($core->id) ? '<span>!موفقیـت</span>!صفحـه محتـوا با موفقیـت بروز رسـانی شـد' : '<span>!موفقیـت</span>!صفحـه محتـوا با موفقیـت اضـافـه شـد';
			  
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert('<span>!تـوجـه</span>.چیـزی برای پـردازش وجـود ندارد');
		  } else
			  print $core->msgStatus();
	  }
	  
      /**
       * Content::getEmailTemplates()
       * 
       * @return
       */
      public function getEmailTemplates()
      {
          global $db;
          $sql = "SELECT * FROM email_templates ORDER BY name ASC";
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

	  /**
	   * Content:::processEmailTemplate()
	   * 
	   * @return
	   */
	  public function processEmailTemplate()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['name']))
			  $core->msgs['name'] = "!لطفـا عنـوان قـالـب را وارد نمائیـد";
		  
		  if (empty($_POST['subject']))
			  $core->msgs['subject'] = "!لطفـا موضـوع ایـمیـل را وارد نمائیـد";

		  if (empty($_POST['body']))
			  $core->msgs['body'] = "!محتـوای قـالـب مورد نیـاز می باشـد";
			  		  
		  if (empty($core->msgs)) {
			  $data = array(
					  'name' => sanitize($_POST['name']), 
					  'subject' => sanitize($_POST['subject']),
					  'body' => $_POST['body'],
					  'help' => sanitize($_POST['help'])
			  );

			  $db->update("email_templates", $data, "id='" . (int)$core->id . "'");
			  ($db->affected()) ? $core->msgOk("<span>!موفقیـت</span>.قـالـب ایـمیـل با موفقیـت بروز رسـانی شـد") :  $core->msgAlert("<span>!تـوجـه</span>.چیـزی برای پـردازش وجـود ندارد");
		  } else
			  print $core->msgStatus();
	  }

      /**
       * Content::getNews()
       * 
       * @return
       */
      public function getNews()
      {
          global $db, $core;
		  
          $sql = "SELECT *, DATE_FORMAT(created, '".$core->short_date."') as cdate FROM news ORDER BY title ASC";
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

      /**
       * Content::renderNews()
       * 
       * @return
       */
      public function renderNews()
      {
          
		  global $db, $core;
		  
          $sql = "SELECT *, DATE_FORMAT(created, '" .$core->short_date . "') as cdate FROM news WHERE active = 1";
          $row = $db->first($sql);
          
          return ($row) ? $row : 0;
      }
	  
	  /**
	   * Content::processNews()
	   * 
	   * @return
	   */
	  public function processNews()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['title']))
			  $core->msgs['title'] = '..لطفـا عنوان اخبـار را وراد نمائیـد';

		  if (empty($_POST['body']))
			  $core->msgs['body'] = '..محتـوای اخبـار را وارد نمائیـد';
			  		  
		  if (empty($_POST['created']))
			  $core->msgs['created'] = '..لطفـا تاریـخ معتبـر را وارد نمائیـد';
		  
		  if (empty($core->msgs)) {
			  $data = array(
				  'title' => sanitize($_POST['title']), 
				  'author' => sanitize($_POST['author']), 
				  'body' => $_POST['body'],
				  'created' => sanitize($_POST['created']),
				  'active' => intval($_POST['active'])
			  );

			  if ($data['active'] == 1) {
				  $news['active'] = "DEFAULT(active)";
				  $db->update("news", $news);
			  }
			  
			  ($core->id) ? $db->update("news", $data, "id='" . (int)$core->id . "'") : $db->insert("news", $data);
			  $message = ($core->id) ? '<span>!موفقیـت</span>!اخبـار با موفقیـت بروز رسـانی شـد' : '<span>!موفقیـت</span>!اخبـار با موفقیـت اضـافـه شـد';
			  
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert('<span>!تـوجـه</span>.چیـزی برای پـردازش وجـود ندارد');
		  } else
			  print $core->msgStatus();
	  }

      /**
       * Content::getFaq()
       * 
       * @return
       */
      public function getFaq()
      {
          global $db, $core;
		  
          $sql = "SELECT * FROM faq ORDER BY position";
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

	  /**
	   * Content::processFaq()
	   * 
	   * @return
	   */
	  public function processFaq()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['question']))
			  $core->msgs['question'] = '..لطفـا پرسـش را وراد نمائیـد';

		  if (empty($_POST['answer']))
			  $core->msgs['answer'] = '..لطفـا پاسـخ را وراد نمائیـد';
		  
		  if (empty($core->msgs)) {
			  $data = array(
				  'question' => sanitize($_POST['question']), 
				  'answer' => $_POST['answer'] 
			  );
			  
			  ($core->id) ? $db->update("faq", $data, "id='" . (int)$core->id . "'") : $db->insert("faq", $data);
			  $message = ($core->id) ? '<span>!موفقیـت</span>!با موفقیـت بروز رسـانی شـد F.A.Q.' : '<span>!موفقیـت</span>.با موفقیـت اضافـه شـد F.A.Q.';
			  
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert('<span>!تـوجـه</span>.چیـزی برای پـردازش وجـود ندارد');
		  } else
			  print $core->msgStatus();
	  }
	  	  
	  /**
	   * Content::getCommentsConfig()
	   * 
	   * @return
	   */
	  public function getCommentsConfig()
	  {
		  global $db;
		  
		  $sql = "SELECT * FROM comments_config";
          return $row = $db->first($sql);
	  }

	  /**
	   * Comments::processCommentConfig()
	   * 
	   * @return
	   */
	  public function processCommentConfig()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['dateformat']))
			  $core->msgs['dateformat'] = '..لطفـا فرمـت معتبـر تاریـخ را وراد نمائیـد';
		  
		  if (empty($core->msgs)) {
			  $data = array(
					'username_req' => intval($_POST['username_req']), 
					'email_req' => intval($_POST['email_req']),
					'show_captcha' => intval($_POST['show_captcha']),
					'show_www' => intval($_POST['show_www']),
					'show_username' => intval($_POST['show_username']),
					'show_email' => intval($_POST['show_email']),
					'auto_approve' => intval($_POST['auto_approve']),
					'notify_new' => intval($_POST['notify_new']),
					'public_access' => intval($_POST['public_access']),
					'sorting' => sanitize($_POST['sorting'],4),
					'blacklist_words' => trim($_POST['blacklist_words']),
					'char_limit' => intval($_POST['char_limit']),
					'perpage' => intval($_POST['perpage']),
					'dateformat' => sanitize($_POST['dateformat'])
			  );
			  
			  $db->update("comments_config", $data);
			  ($db->affected()) ? $core->msgOk('<span>!موفقیـت</span>!پیکـربنـدی نظـرات با موفقیـت بروز رسـانی شـد') :  $core->msgAlert('<span>!تـوجـه</span>.چیـزی برای پـردازش وجـود ندارد');
				 
		  } else
			  print $core->msgStatus();
	  }
	  	  	  
	  /**
	   * Content::getComments()
	   *
	   * @param bool $sort
	   * @return
	   */
	  public function getComments($from = false)
	  {
		  global $db, $item, $pager;
		  
		  require_once(BASEPATH . "lib/class_paginate.php");
          $pager = new Paginator();
		  
		  $comconfig = $this->getCommentsConfig();
		  $total = ($item->pid) ? countEntries("comments","pid",$item->pid) : countEntries("comments");
          $counter = $total;
          $pager->items_total = $counter;
          $pager->default_ipp = $comconfig['perpage'];
          $pager->paginate();
          
          if ($counter == 0) {
              $pager->limit = null;
          }

		  if (isset($_GET['sort'])) {
			  list($sort, $order) = explode("-", $_GET['sort']);
			  $sort = sanitize($sort);
			  $order = sanitize($order);
			  if (in_array($sort, array("username", "email", "created"))) {
				  $ord = ($order == 'DESC') ? " DESC" : " ASC";
				  $sorting = " c." . $sort . $ord;
			  } else {
				  $sorting = " c.created DESC";
			  }
		  } else {
			  $sorting = " c.created DESC";
		  }
		  
          if (isset($_POST['fromdate']) && $_POST['fromdate'] <> "" || isset($from) && $from != '') {
              $enddate = date("Y-m-d");
              $fromdate = (empty($from)) ? $_POST['fromdate'] : $from;
              if (isset($_POST['enddate']) && $_POST['enddate'] <> "") {
                  $enddate = $_POST['enddate'];
              }
              $where =($item->pid) ? " WHERE c.created BETWEEN '" . trim($fromdate) . "' AND '" . trim($enddate) . " 23:59:59' AND p.id = '".$item->pid."'": " WHERE c.created BETWEEN '" . trim($fromdate) . "' AND '" . trim($enddate) . " 23:59:59'";
          } 
		  if($item->pid) {
			  $where = " WHERE p.id = '".$item->pid."'";
		  } else
			  $where = (isset($where)) ? $where : null ;

          $sql = "SELECT c.*, c.id as cid, p.id as id, p.title,"
		  . "\n DATE_FORMAT(c.created, '" . $comconfig['dateformat'] . "') as cdate"
		  . "\n FROM comments as c" 
		  . "\n LEFT JOIN products AS p ON p.id = c.pid"
		  . "\n ".$where.""
		  . "\n ORDER BY " . $sorting . $pager->limit;
		  $row = $db->fetch_all($sql);
		  
		  return ($row) ? $row : 0;
	  }

      /**
       * Content::getCommentFilter()
       * 
       * @return
       */
      public function getCommentFilter()
	  {
		  $arr = array(
				 'username-ASC' => 'Username &uarr;',
				 'username-DESC' => 'Username &darr;',
				 'email-ASC' => 'User Email &uarr;',
				 'email-DESC' => 'User Email &darr;',
				 'created-ASC' => 'Comment Created &uarr;',
				 'created-DESC' => 'Comment Created &darr;'
		  );
		  
		  $filter = '';
		  foreach ($arr as $key => $val) {
				  if ($key == get('sort')) {
					  $filter .= "<option selected=\"selected\" value=\"$key\">$val</option>\n";
				  } else
					  $filter .= "<option value=\"$key\">$val</option>\n";
		  }
		  unset($val);
		  return $filter;
	  } 

	  /**
	   * Content::keepTags()
	   *
	   * @param mixed $str
	   * @param mixed $tags
	   * @return
	   */
	  public function keepTags($string, $allowtags = null, $allowattributes = null)
	  {
		  $string = strip_tags($string, $allowtags);
		  if (!is_null($allowattributes)) {
			  if (!is_array($allowattributes))
				  $allowattributes = explode(",", $allowattributes);
			  if (is_array($allowattributes))
				  $allowattributes = implode(")(?<!", $allowattributes);
			  if (strlen($allowattributes) > 0)
				  $allowattributes = "(?<!" . $allowattributes . ")";
			  $string = preg_replace_callback("/<[^>]*>/i", create_function('$matches', 'return preg_replace("/ [^ =]*' . $allowattributes . '=(\"[^\"]*\"|\'[^\']*\')/i", "", $matches[0]);'), $string);
		  }
		  return $string;
	  }

	  /**
	   * Content::censored()
	   *
	   * @param mixed $string
	   * @param mixed $words
	   * @return
	   */
	  public function censored($string, $words)
	  {
		  $array = explode("\r\n",$words);
		  reset($array);
		  
		  foreach ($array as $row) {
			  $string = preg_replace("`$row`", "***", $string);
		  }
		  unset($row);
		  return $string;
	  }
	  	  	  
	  /**
	   * Content::getDiscounts()
	   * 
	   * @return
	   */
	  public function getDiscounts()
	  {
		  global $db, $core;
		  
		  $sql = "SELECT *, DATE_FORMAT(created, '".$core->short_date."') as cdate FROM coupons";
          $row = $db->fetch_all($sql);
          
		   return ($row) ? $row : 0;
	  }

	  /**
	   * Content::processDiscount()
	   * 
	   * @return
	   */
	  public function processDiscount()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['title']))
			  $core->msgs['title'] = "..لطفـا عنـوان تخفیـف را وارد نمائیـد";
		  
		  if (empty($_POST['code']))
			  $core->msgs['code'] = "..لطفـا کـد تخفیـف را وارد نمائیـد";

		  if (empty($_POST['discount']))
			  $core->msgs['discount'] = "..لطفـا مبلـغ تخفیـف را وارد نمائیـد";

		  if (empty($_POST['minval']))
			  $core->msgs['minval'] = "..لطفـا حداقـل مقـدار را وارد نمائیـد";
			  		  		  
		  if (empty($core->msgs)) {
			  $data = array(
				  'title' => sanitize($_POST['title']), 
				  'code' => sanitize($_POST['code']), 
				  'discount' => intval($_POST['discount']),
				  'type' => intval($_POST['type']),
				  'minval' => floatval($_POST['minval']),
				  'active' => intval($_POST['active'])
			  );
			  
			  if(!post('id')) {
				  $data['created'] = "NOW()";
			  }
			  ($core->id) ? $db->update("coupons", $data, "id='" . $core->id . "'") : $db->insert("coupons", $data);
			  $message = ($core->id) ? '<span>!موفقیـت</span>!کوپـن/تخفیـف با موفقیـت بروز رسـانی شـد' : '<span>!موفقیـت</span>!بروز رسـانی کوپـن/تخفیـف با موفقیـت اضـافـه شـد';
			  
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert('<span>!تـوجـه</span>.چیـزی برای پـردازش وجـود ندارد');

		  } else
			  print $core->msgStatus();
	  }
	  
      /**
       * Content::getContentType()
       * 
	   * @param bool $selected
       * @return
       */ 	  
      public function getContentType($selected = false)
	  {
		  $arr = array(
				'page' => 'Content Page',
				'web' => 'External Link'
		  );
		  
		  $contenttype = '';
		  foreach ($arr as $key => $val) {
              if ($key == $selected) {
                  $contenttype .= "<option selected=\"selected\" value=\"" . $key . "\">" . $val . "</option>\n";
              } else
                  $contenttype .= "<option value=\"" . $key . "\">" . $val . "</option>\n";
          }
          unset($val);
          return $contenttype;
      }

      /**
       * Content::rendertTags()
       * 
       * @return
       */
      public function rendertTags()
      {
          global $db, $pager, $core;
		  
		  require_once(BASEPATH . "lib/class_paginate.php");
		  $pager = new Paginator();
		  
		  $counter = countEntries('products',"cid",$this->cid."' AND active = '1");
		  $pager->items_total = $counter;
		  $pager->default_ipp = $core->perpage;
		  $pager->paginate();
		  
		  if ($counter == 0) {
			$pager->limit = "";
		  }
		  
		  $sql = "SELECT p.id as pid, p.title, p.description, p.hits, p.slug, p.price,p.thumb,p.vote_up,p.vote_down,p.rating,p.audio," 
		  . "\n c.id as cid, c.name,"
		  . "\n DATE_FORMAT(p.created, '" . $core->long_date . "') as cdate," 
		  . "\n (SELECT COUNT(pid) FROM comments WHERE pid = p.id) as comments"
		  . "\n FROM products as p" 
		  . "\n LEFT JOIN categories as c ON p.cid = c.id" 
		  . "\n LEFT JOIN tags as t ON t.pid = p.id" 
		  . "\n WHERE t.tag = '" . $this->tag . "'"
		  . "\n AND c.active = '1'"
		  . "\n AND p.active = '1'"
		  . "\n ORDER BY p.created DESC " . $pager->limit;
		  
		  $row = $db->fetch_all($sql);
		  
		  return ($row) ? $row : 0;
      }

      /**
       * Content::getTagName()
       * 
       * @return
       */
      public function getTagName()
      {
          global $db;
		  
		  $sql = "SELECT tag FROM tags WHERE tag = '" . $db->escape($this->tag) . "'";
		  $row = $db->first($sql);
		  
		  return ($row) ? $row : 0;
      }

	  /**
	   * Content::getContentPage()
	   * 
	   * @return
	   */
	  public function getContentPage()
	  {
		  global $db, $core;

		  $sql = "SELECT * FROM pages" 
		  . "\n WHERE id = '" . $core->id . "'" 
		  . "\n AND active = '1'";
		  $row = $db->first($sql);
		  
		  return ($row) ? $row : 0;
	  }
	  	  	  
      /**
       * Content::getCartCounter()
       * 
       * @return
       */ 	  
      public function getCartCounter()
	  {
		  global $db, $core, $user;
		  
		  if($row = $db->first("SELECT sum(price) as ptotal, COUNT(*) as itotal FROM cart WHERE user_id = '" . $db->escape($user->sesid) . "'")){
			 $itotal =  ($row['itotal'] == 0) ? '-': $row['itotal'];
			 $ptotal =  ($row['ptotal'] == 0) ? '-': $core->formatMoney($row['ptotal']);
			  print $itotal.' / '.$ptotal;
		  } else {
			   print '-/-';
		  }
      }

      /**
       * Content::getCartContent()
       * 
       * @param mixed $sesid
       * @return
       */
      public function getCartContent($sesid = false)
      {
          global $db, $user;
		  
		  $uid = ($sesid) ? $sesid : $user->sesid;
		  
		  $sql = "SELECT c.*, p.id as pid, p.title, p.price, COUNT(c.pid) as total" 
		  . "\n FROM cart as c" 
		  . "\n LEFT JOIN products as p ON p.id = c.pid" 
		  . "\n WHERE c.user_id = '" . $db->escape($uid) . "'" 
		  . "\n GROUP BY c.pid ORDER BY c.id DESC";
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

      /**
       * Content::getCartTotal()
       * 
       * @param mixed $sesid
       * @return
       */
      public function getCartTotal($sesid = false)
      {
          global $db, $user;
		  
		  $uid = ($sesid) ? $sesid : $user->sesid;
		  
		  $sql = "SELECT sum(c.price) as total, COUNT(c.pid) as titems, e.coupon" 
		  . "\n FROM cart as c" 
		  . "\n LEFT JOIN extras as e ON e.user_id = c.user_id" 
		  . "\n WHERE c.user_id = '" . $db->escape($uid) . "'";

          $row = $db->first($sql);
          
          return ($row) ? $row : 0;
      }
	  	  	  	  
	  
      /**
       * Content::renderCart()
       * 
       * @return
       */
	  public function renderCart()
	  {
		  global $db, $core, $user;
		  
		  $sql = "SELECT p.id as pid, p.title, p.slug, p.price, p.thumb," 
		  . "\n COUNT(c.pid) as total" 
		  . "\n FROM products as p" 
		  . "\n LEFT JOIN cart as c ON p.id = c.pid" 
		  . "\n WHERE c.user_id = '" . $db->escape($user->sesid) . "'" 
		  . "\n GROUP BY c.pid ORDER BY c.id DESC";
		  
		  $reault = $db->fetch_all($sql);
		  $trow = $db->first("SELECT sum(price) as total FROM cart WHERE user_id = '" . $db->escape($user->sesid) . "'");
		  
		  if (!$reault) {
			  $core->msgInfo('<span>!تـوجـه</span>!سبـد خریـد شمـا خالـی می باشـد',false);
		  } elseif($trow['total'] > 3000) {
			  $core->msgError('<span>!خـطا</span> مجـموع سبـد خریـد شمـا به پایـان رسیـده ' . $core->formatMoney($trow['total']).'. .لطفـا با پشتیبـانی تمـاس بگیـریـد ',false);
		  } else {
			  print "<ul class=\"cart\">";
			  foreach ($reault as $row) {
				  $thumb = ($row['thumb']) ? PRODIMGURL . 'thumbs/' . $row['thumb'] : UPLOADURL . 'blank.png';
				  $url = ($core->seo) ? $core->site_url . '/view-item/' . intval($row['pid']) . '/' . sanitize($row['slug']) . '.html' : $core->site_url . '/item.php?pid=' . intval($row['pid']);
				  
				  print ' 
				  <li><img src="' . $thumb . '" alt="" height="35" class="thumb2"/>'
				  . '<a href="javascript:void(0);" class="del-cart" id="delid_' . $row['pid'] . '">'
				  . '<img src="' . SITEURL . '/images/del.png" alt="" title="حـذف" class="tooltip remove-item"/></a>'
				  . '<div><a href="' . $url . '">' . sanitize($row['title'], 30, false) . '&nbsp;</a>'
				  . '<span>' . $core->formatMoney($row['price']) . ' x ' . $row['total'] . '&nbsp;</span></div>
				  </li>';
			  }
			  print "</ul>";
			  print '<div class="subtotal">'
			  . '<span><a href="' . SITEURL . '/checkout.php">پـرداخـت<img src="' . SITEURL . '/images/checkout.png" alt=""  /></a></span>'
			  . '' . $core->formatMoney($trow['total']) . ' : جمع کل</div>';
		  }
	  }
	  
	  
      /**
       * Content::getSearchResults()
       * 
       * @return
       */
      public function getSearchResults($keyword)
      {
          global $db, $core;
          
          $row = $db->fetch_all("SELECT * ,MATCH(title, body) AGAINST('$keyword') AS score, id as pid," 
		  . "\n DATE_FORMAT(created, '".$core->short_date."') as cdate" 
		  . "\n FROM products" 
		  . "\n WHERE MATCH(title, body) AGAINST('$keyword)' IN BOOLEAN MODE)" 
		  . "\n ORDER BY score ASC" 
		  . "\n LIMIT 20");
          
          return ($row) ? $row : 0;
      }
	  
	  
      /**
       * Content::getContentType()
       * 
       * @return
       */ 
	  public function getMeta()
	  {
		  global $core, $row, $item;
		  $sep = " | ";
		  $meta = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
		  $meta .= "<title>" . $core->site_name;
		  if ($this->cid) {
			  $meta .= $sep . $row['name'];
		  } elseif ($item->pid) {
			  $meta .= $sep . $row['title'];
		  } elseif ($core->id) {
			  $meta .= $sep . $row['title'];
		  } elseif ($this->tag) {
			  $meta .= $sep . $row['tag'];
		  }
		  $meta .= "</title>\n";
		  $meta .= "<meta name=\"keywords\" content=\"";
		  if ($this->cid) {
			  if ($row['metakeys']) {
				  $meta .= $row['metakeys'];
			  } else {
				  $meta .= $core->metakeys;
			  }
				  
		  } elseif ($item->pid) {
			  if ($row['metakeys']) {
				  $meta .= $row['metakeys'];
			  } else {
				  $meta .= $core->metakeys;
			  }
		  } else{
			  $meta .= $core->metakeys;
		  }
		  $meta .= "\" />\n";
		  $meta .= "<meta name=\"description\" content=\"";
		  if ($this->cid) {
			  if ($row['metadesc']) {
				  $meta .= $row['metadesc'];
			  } else {
				  $meta .= $core->metadesc;
			  }
				  
		  } elseif ($item->pid) {
			  if ($row['metadesc']) {
				  $meta .= $row['metadesc'];
			  } else {
				  $meta .= $core->metadesc;
			  }
		  } else{
			  $meta .= $core->metadesc;
		  }
		  $meta .= "\" />\n";
		  $meta .= "<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"" .SITEURL ."/assets/favicon.ico\" />\n";
		  $meta .= "<meta name=\"publisher\" content=\"" . $core->company . "\" />\n";
		  $meta .= "<meta name=\"copyright\" content=\"" . $core->company . " &copy; All Rights Reserved\" />\n";
		  $meta .= "<meta name=\"language\" content=\"English\" />\n";
		  $meta .= "<meta name=\"robots\" content=\"index\" />\n";
		  $meta .= "<meta name=\"robots\" content=\"follow\" />\n";
		  $meta .= "<meta name=\"revisit-after\" content=\"1 day\" />\n";
		  $meta .= "<meta name=\"generator\" content=\"Powered by DDP v" . $core->version . "\" />\n";
		  return $meta;
	  }
  }
?>