#!/usr/bin/perl

#########################################################################
# SEO check																#
#                                                                       #
# Author: Pavel Mracek mrak(at)mrak(dot)cz                              #
# Version: 0.2                                                          #
#########################################################################
#
#   Use:
#	Use: seo_check.pl [-d ] -u URL search keys'
#
#########################################################################
# This file may be distributed under the terms of the GNU General       #
# Public License.                                                       #
#########################################################################

##
##
##
use LWP::Simple;
use LWP::Debug;
use LWP::UserAgent;
use HTTP::Request;
use Getopt::Std;

use URI::Escape;
# qw( uri_unescape );

# 0- jen pozice (ciselne)
# 1- vypis adress na pozicich
# 2- vypis http url + dalsi veci 
my ($debug)=0;




##-------------------------
my $err;
my $url;
my @search;

&getopts("du:");

$debug = ($opt_d ? $opt_d : $debug);

if( $opt_u =~ /[\w\-\d\.]+\.\w{2,6}/ ){
  	$url = $opt_u;
	if(@ARGV>0){
		@search = query_encode(@ARGV);
	}else{
		$err = "Nezadal jsi argument pro vyhledavani\n";
	}
}else{
	$err = "Nezadal jsi URL\n";
}

if($err){
	print $err;
	print "Use: seo_check.pl [-d ] -u URL search keys'\n";
	exit;
}

print "URL: $url\t\tSLOVA: ".join(' ', @search)."\n";
#print "parametry \turl: $url\n\t\tsearch: ".join(' ', @search)."\n" if($debug);


#---------------------------------

sub query_encode(@){
	my (@q);
	my $k;
	foreach $k (@_){
		#push(@q, URI::Escape::uri_escape_utf8($k));
		push(@q, URI::Escape::uri_escape($k));
	}
	return @q;
}


#sub get_url($){
#	 my ($url)=@_;
#	#$url =~ s/&amp;/&/g;
#	print "getting $url ..." if $debug;
#	 my $content = get($url);
#	print "OK\n" if $debug;
#     return \$content;
#}

sub get_url($){
        my ($url)=@_;
        my @times;
		$url =~ s/&amp;/&/g;
        my $req = HTTP::Request->new(GET => $url);
		#$req->content(’query=libwww-perl&mode=dist’);

		print "getting $url ..." if($debug > 1);
        my $ua = LWP::UserAgent->new(
                                agent => 'seo-check/0.1',
                                timeout => '30'
                                        );
        $times[0]=time();
        my $res = $ua->request($req);
        $times[1]=time();
        if ($res->is_error) {
                print STDERR $res->status_line, "\n" if $debug;
                return undef;
        }else{
			print "OK\n" if($debug>1);
		}
        print STDERR "Status: ".$res->status_line."\n" if($debug>1);
        #print STDERR "Headers:\n".$res->headers_as_string() if($debug>1);
        print STDERR "Response time: ".($times[1] - $times[0])."sec\n" if($debug>1);

        # LWP::Debug::conns("read $n bytes: $data");
 		return \$res->content;
}


sub check_seznam(){
	#query: http://search.seznam.cz/?sourceid=szn-HP&thru=&q=slovo
	my ($hostname)= 'http://search.seznam.cz';
 	# http://search.seznam.cz/?q=kore%C4%8Dkov%C3%A9+rypadlo
	my ($query)= '/?q='.join('+',@search);
	my ($page)=0;
	my ($count)=0;
	do{	
		# Nacteni stranky
		my ($page_ref) = get_url($hostname.$query);
		#print substr($$page_ref, 250, 425);
		if(defined $$page_ref){ 
			$page++;
		}else{
			print STDERR "Error URL: $hostname$query\n";
			return 0;
		}
		# Hledame pozadavanou URL
		my ($pozice)  = search_url_seznam($page_ref, $url, \$count);
		if($pozice){
			# print "pozice na seznam.cz: $pozice\n";
			return $pozice;
		}else{			
		# Hledame URL na dalsi stranku
			$query = search_url_seznam_next($page_ref);
		}
	}while($page<10);
	return "not found";
}

sub search_url_seznam($$$){
	my ($page, $url, $count) = @_;
	my ($chunk);
	while($$page =~ /class="result"\>(.+?)\<\/table\>/img){
		$chunk=$1;
		#print $chunk;
		#<table class="result">
		#<a href=""
		if($chunk =~ /<td class="limiter">/im){
			$$count++;
			if($chunk =~ /<a href="http:\/\/([\w\d\.\-]+\.\w{2,6})\/.+?"/){
				print "...seznam $$count: $1\n" if $debug;
				if($1 =~ /$url/){
					return $$count;
				}
			}
		}
	}
	return 0;
}


sub search_url_seznam_next($){
	my ($page) = @_;
	if($$page =~ /<span\s+class="next"><a\s+href="([^"]+)">.+?<\/a><\/span/im){
		return $1;
	}
	return 0;
}

# ---------------------------------------------------------

sub check_google(){
	#query: http://www.google.cz/search?hl=cs&q=linux+htb&aq=f&aqi=&aql=&oq=&gs_rfai=
	my ($hostname)= 'http://www.google.com';
	my ($query)= '/search?hl=cs&q='.join('+',@search).'&aq=f&aqi=&aql=&oq=&gs_rfai=';
	my ($page)=0;
	my ($count)=0;
	do{	
		# Nacteni stranky
		my ($page_ref) = get_url($hostname.$query);
		#print substr($$page_ref, 250, 425);
		if(defined $$page_ref){ 
			$page++;
		}else{
			print STDERR "Error URL: ".$hostname.$query."\n";
			return 0;
		}
		# Hledame pozadavanou URL
		my ($pozice)  = search_url_google($page_ref, $url, \$count);
		if($pozice){
			# print "pozice na google.com: $pozice\n";
			return $pozice;
		}else{			
		# Hledame URL na dalsi stranku
			$query = search_url_google_next($page_ref);
		}
	}while($page<10);
	return "not found";
}

sub search_url_google($$$){
	my ($page, $url, $count) = @_;
	my ($chunk);
	# <h3 class="r"><a href="http://luxik.cdi.cz/~devik/qos/htb/manual/userg.htm" class=l><em>HTB</em> manual - user  guide</a></h3>
	while($$page =~ /<h\d\s+class="r"><a href="http:\/\/([\w\d\.\-]+\.\w{2,6})\/.*?"\sclass=l>.+?<\/h\d>/img){
			$$count++;
				print "...google $$count: $1\n" if $debug;
				if($1 =~ $url){
					return $$count;
				}
	}
	return 0;
}

sub search_url_google_next($){
	my ($page) = @_;
	# <td class=b><a href="/search?q=htb+linux&amp;hl=cs&amp;ei=gkVQTMnHC86oOM6zkLIB&amp;start=10&amp;sa=N" class=pn 
	if($$page =~ /<td class=b><a href="(\/search[^"]+?start=\d0[^"]+)"\s+class=pn/im){
		return $1;
	}
	return 0;
}


################ main

my ($seznam_result) = check_seznam();
print "Poradi SEZNAM.CZ: $seznam_result\n";

my ($google_result) = check_google();
print "Poradi GOOGLE.COM: $google_result\n";

exit;

1;
