<?php
namespace IPS\core\modules\admin\promotion;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * SEO
 */
class _seovisitors extends \IPS\Dispatcher\Controller
{
	protected function manage()
	{

		\IPS\Output::i()->title	= 'Посетители с поисковых систем';
		
		$table = new \IPS\Helpers\Table\Db( 'search_visitors', \IPS\Http\Url::internal('app=core&module=promotion&controller=seovisitors'));
		if(\IPS\Request::i()->filter) {
			if(\IPS\Request::i()->keywords) $table->baseUrl = $table->baseUrl->setQueryString('keywords',\IPS\Request::i()->keywords);
			if(\IPS\Request::i()->engine) $table->baseUrl = $table->baseUrl->setQueryString('engine',\IPS\Request::i()->engine);
		}
		$table->include = array('keywords','engine','url','name','date');
		$table->sortBy = $table->sortBy ?: 'date';
		$table->sortDirection = $table->sortDirection ?: 'desc';
		$table->langPrefix = 'seovisitors_';


		$table->joins = array(
			array(
				'select' => 'm.name',
				'from' => array( 'core_members', 'm' ),
				'where' => 'm.member_id=search_visitors.member'
			)
		);

		$table->parsers = array(
			'date'=>function($val,$row) {
				return \IPS\DateTime::ts( $val )->relative();
			},
			'name' => function( $val, $row )
			{
				if($val) return "<a href='" . \IPS\Http\Url::internal( 'app=core&module=members&controller=members&do=edit&id=' ) . $row['member'] . "'>" . htmlentities( $val, \IPS\HTMLENTITIES, 'UTF-8', FALSE ) . "</a>";
				else return \IPS\Member::loggedIn()->language()->addToStack( 'guest' );
			},
			'keywords'=>function ($val,$row) {
				return "<a href='" . \IPS\Http\Url::internal( 'app=core&module=promotion&controller=seovisitors&filter=keywords&keywords=' ) . $val . "'>" . htmlentities( $val, \IPS\HTMLENTITIES, 'UTF-8', FALSE ) . "</a>";
			},
			'engine'=>function ($val,$row) {
				return "<a href='" . \IPS\Http\Url::internal( 'app=core&module=promotion&controller=seovisitors&filter=engine&engine=' ) . $val . "'>" . htmlentities( $val, \IPS\HTMLENTITIES, 'UTF-8', FALSE ) . "</a>";
			}
		);

		$table->filters = array(
			'keywords'=>"keywords LIKE '".htmlentities( \IPS\Request::i()->keywords, \IPS\HTMLENTITIES, 'UTF-8', FALSE )."'",
			'engine'=>"engine LIKE '".htmlentities( \IPS\Request::i()->engine, \IPS\HTMLENTITIES, 'UTF-8', FALSE )."'"
		);

		$table = preg_replace(array("/data-page='[0-9]*'/",'/data-action="tableFilter"/','/data-action="tableSort"/'), '', (string) $table);

		\IPS\Member::loggedIn()->language()->parseOutputForDisplay($table);
		\IPS\Output::i()->output = str_replace(array(
			'seovisitors_keywords',
			'seovisitors_engine',
			'seovisitors_url',
			'seovisitors_name',
			'seovisitors_date'),
		array('Ключевики','Поисковик','Страница','Пользователь','Дата'),$table);
		
		
		
		
	}

	protected static $engines  = array(
		array( 'name' => 'Google', 'match' => '/http(s)?\:\/\/www\.google/', 'parser' => 'parseGoogleUrl' ),
		array( 'name' => 'Bing', 'match' => '/http\:\/\/www\.bing/', 'parser' => 'parseBingUrl' ),
		array( 'name' => 'Bing', 'match' => '/http\:\/\/www\.bing/', 'parser' => 'parseBingUrl' ),
		array( 'name' => 'Facebook', 'match' => '/http\:\/\/www\.facebook/', 'parser' => 'parseFacebookUrl' ),
		array( 'name' => 'Yandex', 'match' => '/http\:\/\/(www\.)?yandex/', 'parser' => 'parseYandexUrl'),
		array( 'name' => 'Rambler', 'match' => '/http\:\/\/(nova\.)?rambler/', 'parser' => 'parseRamblerUrl'),
		array( 'name' => 'Mail.ru', 'match' => '/http\:\/\/(go\.)?mail/', 'parser' => 'parseMailruUrl')
	);
	
	
	public static function track( $referrer, $queryString, $memberId )
	{

		/*

		CREATE TABLE IF NOT EXISTS `search_visitors` (
		  `id` int(11) NOT NULL AUTO_INCREMENT,
		  `member` int(11) DEFAULT NULL,
		  `date` int(11) NOT NULL DEFAULT '0',
		  `engine` varchar(50) NOT NULL,
		  `keywords` varchar(250) NOT NULL,
		  `url` varchar(2048) NOT NULL,
		  PRIMARY KEY (`id`),
		  KEY `idx_date_engine` (`date`,`engine`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

		*/

		foreach( self::$engines as $engine )
		{
			if( preg_match( $engine['match'], $referrer ) )
			{
				
				$obj = new self;
			
				$keywords = trim( $obj->{$engine['parser']}( $referrer ) );
				if ( !empty( $keywords ) )
				{
					
					\IPS\DB::i()->insert( 'search_visitors', array( 'date' => time(), 'member' => intval( $memberId ), 'engine' => $engine['name'], 'keywords' => $keywords, 'url' => $queryString ) );
					
				}
			
				break;
			}
		}
		
	}

	protected function parseGoogleUrl($url)
	{
		$matches = array();
		if(preg_match('/imgres/', $url) && preg_match('/prev\=([^\&]+)/', $url, $matches))
		{
			$url = urldecode($matches[1]);
		}
		
		$matches = array();
		if(preg_match('/q\=([^\&]+)/', $url, $matches))
		{
			if(isset($matches[1]))
			{
				$keywords = $matches[1];
				$keywords = urldecode($keywords);
				$keywords = str_replace('+', ' ', $keywords);
				$keywords = str_replace('%20', ' ', $keywords);
				return $keywords;
			}
		}
		
		return null;
	}
	
	protected function parseBingUrl($url)
	{
		$matches = array();
		if(preg_match('/q\=([^\&]+)/', $url, $matches))
		{
			if(isset($matches[1]))
			{
				$keywords = $matches[1];
				$keywords = urldecode($keywords);
				$keywords = str_replace('+', ' ', $keywords);
				$keywords = str_replace('%20', ' ', $keywords);
				return $keywords;
			}
		}
		
		return null;
	}
	
	protected function parseYahooUrl($url)
	{
		$matches = array();
		if(preg_match('/p\=([^\&]+)/', $url, $matches))
		{
			if(isset($matches[1]))
			{
				$keywords = $matches[1];
				$keywords = urldecode($keywords);
				$keywords = str_replace('+', ' ', $keywords);
				$keywords = str_replace('%20', ' ', $keywords);
				return $keywords;
			}
		}
		
		return null;
	}
	
	protected function parseFacebookUrl($url)
	{
		$matches = array();
		if(preg_match('/l\.php\?u\=([^\&]+)/', $url, $matches))
		{
			if(isset($matches[1]))
			{
				$keywords = $matches[1];
				$keywords = urldecode($keywords);
				$keywords = str_replace('http://', '', $keywords);
				$keywords = str_replace('https://', '', $keywords);
				$keywords = str_replace('+', ' ', $keywords);
				$keywords = str_replace('%20', ' ', $keywords);
				return $keywords;
			}
		}
		elseif(preg_match('/end\.php/', $url))
		{
			return 'Sponsored Ad';
		}
		
		return null;
	}
	protected function parseYandexUrl($url)
	{
		$matches = array();
		if(preg_match('/text\=([^\&]+)/', $url, $matches))
		{
			if(isset($matches[1]))
			{
				$keywords = $matches[1];
				$keywords = urldecode($keywords);
				$keywords = str_replace('+', ' ', $keywords);
				$keywords = str_replace('%20', ' ', $keywords);
				return $keywords;
			}
		}
		
		return null;
	}
	protected function parseRamblerUrl($url)
	{
		$matches = array();
		if(preg_match('/query\=([^\&]+)/', $url, $matches))
		{
			if(isset($matches[1]))
			{
				$keywords = $matches[1];
				$keywords = urldecode($keywords);
				$keywords = str_replace('+', ' ', $keywords);
				$keywords = str_replace('%20', ' ', $keywords);
				return $keywords;
			}
		}
		if(preg_match('/words\=([^\&]+)/', $url, $matches))
		{
			if(isset($matches[1]))
			{
				$keywords = $matches[1];
				$keywords = urldecode($keywords);
				$keywords = str_replace('+', ' ', $keywords);
				$keywords = str_replace('%20', ' ', $keywords);
				return $keywords;
			}
		}
		return null;
	}
	protected function parseMailruUrl($url)
	{
		$matches = array();
		if(preg_match('/q\=([^\&]+)/', $url, $matches))
		{
			if(isset($matches[1]))
			{
				$keywords = $matches[1];
				$keywords = urldecode($keywords);
				$keywords = str_replace('+', ' ', $keywords);
				$keywords = str_replace('%20', ' ', $keywords);
				return $keywords;
			}
		}
		
		return null;
	}
	
}