<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Backend extends MY_Controller {

	
	public function validate()
	{


		$process[0]['title'] 	= __("Crawling website");
		$process[0]['action'] 	= 'crawl';

		$process[1]['title'] 	= __("Calculating Traffics");
		$process[1]['action'] 	= 'traffic';	

		$process[2]['title'] 	= __("Analyzing Technologies");
		$process[2]['action'] 	= 'technologies';

		$process[3]['title'] 	= __("Validating Search Engine Index");
		$process[3]['action'] 	= 'engine';

		$process[4]['title'] 	= __("Google Page Speed");
		$process[4]['action'] 	= 'pagespeed';

		$process[5]['title'] 	= __("Bounce Rate");
		$process[5]['action'] 	= 'bouncerate';

		$process[6]['title'] 	= __("Domain Authority");
		$process[6]['action'] 	= 'da';

		$process[7]['title'] 	= __("Validating W3C");
		$process[7]['action'] 	= 'w3c';

		$process[8]['title'] 	= __("Checking Blacklist Domain");
		$process[8]['action'] 	= 'google_safe';

		$process[9]['title'] 	= __("Searching For Broken Links");
		$process[9]['action'] 	= 'internalLinks';

		$process[10]['title'] 	= __("Getting Server Information");
		$process[10]['action'] 	= 'serverInfo';


		$process[11]['title'] 	= __("Calculating Score");
		$process[11]['action'] 	= 'score';

		




		$url 	= $this->input->post("url");

		if(preg_match("#https?://#", $url) === 0)
			$url = 'http://' . $url;

		$data 	= parse_url($url);
		$domain = $data['host'];
		
		$domain = str_ireplace("www.", "",$domain);
		$domain = mb_strtolower($domain);
		$domain_curl = "http://".$domain;
		if($data['scheme'])
			$domain_curl = $data['scheme']."://".$domain;
			
		$json['domain'] = $domain;
		$json['new'] 	= TRUE;
		if(hasbadWords($domain))
		{
			unset($json['process']);
			$json['error'] = __("The domain name contains forbidden words");
		}
		else
		{
			if(is_valid_domain_name($domain_curl))
			{
				if(ping($domain_curl))
				{
					$exist = $this->Admin->getTable("sites",array("url" => $domain));
					if($exist->num_rows() == 1)
						$json['new'] = FALSE;
					$json['process'] = $process;
					$this->Admin->setTableIgnore("sites",array("url" => $domain,"registered" => date("Y-m-d H:i:s")));

				}
				else
				{
					$json['error'] = __("Your website is down or not is valid");
				}
				
			}
			else
			{			
				$json['error'] = __("Domain not is valid");
			}
		}

		/*if(!$json['error'])
		{
			$site 			= $exist->row();
			$days			= getDaysDiff($site->updated,date("Y-m-d H:i:s"));
			$json['days'] 	= $days;
			if(intval($days) < intval(config_item("update_inverval")))
			{
				unset($json['process']);
				$json['error'] = str_ireplace("$day$",config_item("update_inverval"),__("You can update only every $day$ days"));
			}
		}*/


		

		echo_json($json);
	}

	public function process()
	{
		$json['ok'] 	=true;
		$action 		= $this->input->post("action");
		$domain 		= $this->input->post("domain");
		$domain_curl 	= "http://".$domain;
		if(!is_valid_domain_name($domain_curl))
			return false;
		
		/*if(!ping($domain_curl))
			return false;*/
		$this->load->helper('seo');		
		
		switch ($action) {
			case 'crawl':
				$save['body'] 				= sanitize_output(_curl($domain_curl));		
				$save['body'] 				= mb_convert_encoding($save['body'], 'HTML-ENTITIES', 'UTF-8');						
				$save['headers'] 			= _curl_headers($domain_curl);												
				$save['metaTitle'] 			= getMeta($save['body'],"title");
				$save['metaDescription'] 	= getMeta($save['body'],"description");
				$save['metaKeywords'] 		= getMeta($save['body'],"keywords");
				$save['metaH1'] 			= mb_substr_count($save['body'], "<h1");
				$save['metaH2'] 			= mb_substr_count($save['body'], "<h2");
				$save['metaH3'] 			= mb_substr_count($save['body'], "<h3");
				$save['metaH4'] 			= mb_substr_count($save['body'], "<h4");				
				$save['favicon'] 			= getFavIcon($save['body']);				
				$save['hasAMP'] 			= hasAMP($save['body']);				
				$this->Admin->updateTable("sites",$save,array("url" => $domain));
				$this->db->query("UPDATE {PRE}sites SET url=LOWER(url) WHERE url = '$domain'");
				break;						
			case 'traffic':				
				$alexa 						= getAlexaRank($domain);
				$save['alexaLocal'] 		= $alexa['local']['rank'];
				$save['alexaLocalCountry'] 	= $alexa['local']['country'];
				$save['alexaGlobal'] 		= $alexa['global']['rank'];
				$save['uniqueVisitsDaily'] 	= (int)(pow($alexa['local']['rank'],-0.732)*6000000);
				$save['pagesViewsDaily'] 	= (int)($save['uniqueVisitsDaily']*1.85);
				
				$this->Admin->updateTable("sites",$save,array("url" => $domain));
				$this->db->query("UPDATE {PRE}sites SET IncomeDaily=((uniqueVisitsDaily*0.017)*0.07) WHERE  url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET IncomeDaily=(IncomeDaily*1.5) WHERE alexaLocal <= 1000 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET IncomeDaily=(IncomeDaily*2) WHERE alexaLocal <= 100 AND url='$domain'");
				break;
			case 'technologies':
				if(config_item("4p1_key"))
				{
				 	$technologies 		= getBuiltWith(config_item("4p1_key"),$domain);
				 	
				 	if($technologies->results->technologies)
				 	{
				 		$this->Admin->deleteTable("technologies",array("url" => $domain));	
				 		$save 			= array();
				 		foreach ($technologies->results->technologies as $key => $value) {				 			
				 			
				 			$save[$key]["url"] 		= $domain;
				 			$save[$key]["name"] 	= $value->name;
				 			$save[$key]["icon"] 	= $value->icon_name;
				 			$save[$key]["tag1"] 	= $value->tags[0];
				 			$save[$key]["tag2"] 	= $value->tags[1];				 			
				 			
				 		}	
				 		$this->Admin->setTable("technologies",$save,true);			 		
				 	}				

				}
				break;			
			case 'engine':
				$save["googleIndex"] 	= intval(getGoogleCount($domain));
				$save["yahooIndex"] 	= intval(getYahooCount($domain));
				$save["bingIndex"] 		= intval(getBingCount($domain));
				$save["robots"] 		= remote_file_exists("http://".$domain."/robots.txt");
				$save["sitemap"] 		= remote_file_exists("http://".$domain."/sitemap.xml");
				$this->Admin->updateTable("sites",$save,array("url" => $domain));
				break;						
			
			case 'pagespeed':				
				$key = config_item("google_page_speed_key");
				if($key)
				{
					$data 					= getSpeedData($key,$domain);					
					$save['pageSpeed'] 		= intval($data->score);
					if($save['pageSpeed']>0)
						$this->Admin->updateTable("sites",$save,array("url" => $domain));	
				}				
				break;	

			case 'bouncerate':				
				$save['bounceRate'] 		= intval(getAlexaBounceRate($domain));
				$this->Admin->updateTable("sites",$save,array("url" => $domain));
				break;

			case 'da':				
				$save['domainAuthority'] 		= intval(domainAuthority($domain));
				if($save['domainAuthority']>0)
					$this->Admin->updateTable("sites",$save,array("url" => $domain));
				break;
			case 'w3c':				
				$save['w3c'] 		= intval(getW3C($domain));				
				if(connect($domain, 443))
					$save['https'] = '1';
				$this->Admin->updateTable("sites",$save,array("url" => $domain));
				break;
			case 'google_safe':				
				$save['google_safe'] 		= googleSafe($domain);								
				$this->Admin->updateTable("sites",$save,array("url" => $domain));
				break;	
			case 'internalLinks':				
				$site_obj 	= $this->Admin->getTable("sites",array("url" => $domain));
				$site 		= $site_obj->row();
				$links 		= getAllLinks($site->body,$domain,10);
				foreach ($links as $key => $value) 
				{	
					$response = "ERROR -";
					if(ping($value))
						$response = "OK -";
					$links_raw .= $response.$value."<br>";
				}								
				$save['links'] 		= $links_raw;					
				$this->Admin->updateTable("sites",$save,array("url" => $domain));
				break;	

				case 'serverInfo':		
					$site_obj 			= $this->Admin->getTable("sites",array("url" => $domain));
					$site 				= $site_obj->row();
					$ips 				= gethostbynamel($domain);								
					$save['ip'] 		= implode(";",$ips);		
					if($site->ip != $save['ip'] || $site->city == '')
					{
						$ipInfo 			= getIPInfo($ips[0]); 								
						$save['city']		= $ipInfo->city;
						$save['country']	= $ipInfo->country;
						$save['region']		= $ipInfo->regionName;
						$save['isp']		= $ipInfo->isp;
					}
				$this->Admin->updateTable("sites",$save,array("url" => $domain));
				break;
			case 'score':				
				$this->db->query("UPDATE {PRE}sites SET score=0 WHERE  url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+7 WHERE  https = 1 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+8 WHERE  pageSpeed > 50 AND pageSpeed <= 80 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+16 WHERE  pageSpeed > 80 AND pageSpeed <= 85 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+23 WHERE  pageSpeed > 85 AND pageSpeed <= 91 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+36 WHERE  pageSpeed > 91 AND pageSpeed <= 98 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+48 WHERE  pageSpeed > 98 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+12 WHERE  w3c > 0 AND w3c <=5 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+27 WHERE  w3c = 0 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+19 WHERE  (metaH1 > 0 OR metaH2 > 0) AND url='$domain'");
				

				// Bonus google_safe
				$this->db->query("UPDATE {PRE}sites SET score=score+9 WHERE  google_safe = 1 AND url='$domain'");

				// Penalty google_safe
				$this->db->query("UPDATE {PRE}sites SET score=score-46 WHERE  google_safe = 0 AND url='$domain'");

				// Bonus domainAuthority
				$this->db->query("UPDATE {PRE}sites SET score=score+(domainAuthority/3) WHERE  domainAuthority >=50 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+(domainAuthority/4) WHERE  domainAuthority >=20  AND domainAuthority < 50 AND url='$domain'");

				// Penalty domainAuthority
				$this->db->query("UPDATE {PRE}sites SET score=score-10 WHERE  score>90 AND domainAuthority < 80 AND url='$domain'");
				
				// Penalty Title and Description
				$this->db->query("UPDATE {PRE}sites SET score=score-10 WHERE  (CHAR_LENGTH(metaTitle)>180 OR CHAR_LENGTH(metaTitle)<5) AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score-10 WHERE  (CHAR_LENGTH(metaDescription)>250 OR CHAR_LENGTH(metaDescription)<5) AND url='$domain'");
				
				// Bonus Alexa
				$this->db->query("UPDATE {PRE}sites SET score=score+10 WHERE  score<85 AND alexaGlobal < 800 AND alexaGlobal > 0 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+10 WHERE  score<85 AND alexaGlobal < 100 AND alexaGlobal > 0 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+10 WHERE  score<85 AND alexaLocal < 100 AND alexaLocal > 0 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=score+10 WHERE  alexaLocal < 10 AND alexaLocal > 0 AND url='$domain'");


				// Fixed Value
				$this->db->query("UPDATE {PRE}sites SET score=0 WHERE  score < 0 AND url='$domain'");
				$this->db->query("UPDATE {PRE}sites SET score=99 WHERE  (score >99 OR domainAuthority > 99) AND url='$domain'");

				// Penalty domainAuthority
				$this->db->query("UPDATE {PRE}sites SET score=score-10 WHERE  score>90 AND domainAuthority < 90 AND url='$domain'");

				// Penalty Index Google
				$this->db->query("UPDATE {PRE}sites SET score=score-10 WHERE  googleIndex < 10 AND url='$domain'");
				// Completed
				$this->db->query("UPDATE {PRE}sites SET completed=1 WHERE url='$domain'");



				break;

			default:
				# code...
				break;
		}

		echo_json($json);
	}

	public function bookmark()
	{
		if(is_logged())
		{
			$idsite 	= intval($this->input->post("idsite",true));
			$action = intval($this->input->post("action",true));
			$site 	=  $this->Admin->getTable("sites",array("id" => $idsite));
			if($site->num_rows() == 1)
			{
				// Add
				if($action == '2')
				{
					$this->Admin->setTable("bookmarks",array("iduser" => _user("id"),"idsite" => $idsite));
				}

				// Remove
				if($action == '1')
				{
					$this->Admin->deleteTable("bookmarks",array("iduser" => _user("id"),"idsite" => $idsite));	
				}

			}
			else
			{
				show_404();
			}
		}
		else
		{
			show_404();
		}
	}


	
}
