<?php

//*************************************************************************
// google_keyword_planner.php : implementation file
// Version : 1.0
// Date :  December 2013
// Author : Andre Dolenko
// Email :  bigfozzy@gmail.com
// Latest Version : http://x-datas.com/
//*************************************************************************

//////////////////////////////////////////////////// Yandex Wordtstat /////////////////////////////////////////////////////////////////////////
class CGoogleKeywordPlanner extends CBaseWebAPI
{
    
///////////////////////////////////////////////////

    // конструктор        
    
function CGoogleKeywordPlanner($out_path,$pause_per_request,$pause_bad_request,$use_proxy,$proxy_timeout)
    {
        
// имя сборщика
        
$this->name="Сборщик подсказок Google.KeywordPlanner";
        
// аббревиатура сборщика
        
$this->abbreviature="GKPLANNER";

        
// запрашиваемый урл с параметрами
        
$this->requested_url "https://adwords.google.com/ko/KeywordPlanner/Home";

        
// иконка сборщика
        
global $app;        
        
$app->set_tray_icon(__FILE__.".ico");

        
// базовый конструктор
        
$this->CBaseWebAPI($out_path,$pause_per_request,$pause_bad_request,$use_proxy,$proxy_timeout);
    }

    
// надо ли пропускать запрс
    
protected function is_skip_query($query)
    {      
            return 
false;
    }    
    
// инициализировать сборщкик
    
protected function init()
    {
        
// глобальные
        
global $browser,$anchor,$input,$button,$div,$log;

        
// переходим на старотовую страницу
        
$browser->navigate($this->requested_url);
        
sleep(2);

        
// залогинится
        
$this->login();
        
sleep(3);

        
// перейдем в оценщик трафика        
        
$div->get_by_attribute("id","gwt-debug-splash-panel-stats-selection-input",false)->send_mouse_move(2,2);
        
$div->get_by_attribute("id","gwt-debug-splash-panel-stats-selection-input",false)->send_mouse_click(2,2);
        
$div->get_by_attribute("id","gwt-debug-splash-panel-stats-selection-input",false)->focus();
        
$log->event_add(" go to trafic estimator ");        

        
// подождать загрузку
        
$this->wait_loading();
        
sleep(2);                
    }

    
// подождать загрузку
    
protected function wait_loading()
    {
        global 
$element,$log;

        while (
$element->get_by_inner_text("Loading...")->get_x()>0)
        {
            
$log->event_add(".");
            
sleep(1);
        }
    }

    
// залогинится
    
protected function login()
    {
        
// глобальные
        
global $browser,$anchor,$input,$button,$label;

        
$button->get_by_name("signIn");

        
// логинемся
        
if ($button->get_x_by_attribute("id","signIn",false)>0)
        {
            
// перейдем к форме логина
            
sleep(2);

            
// получим случайные логин-пароль
            
$login_psw=explode(";",CTextFile::get_random_line("in/accounts.txt"));
            
$login=$login_psw[0];
            
$password=$login_psw[1];
                            
            
// залогинемся
            
while ($input->get_x_by_attribute("id","Email",false)>0)
            {
                echo 
"logining ... ";
                
$input->get_by_attribute("id","Email",false)->send_input($login."\t");
                
$input->get_by_attribute("id","Passwd",false)->send_input($password);
                
$button->get_by_attribute("id","signIn",false)->send_mouse_move(2,2);
                
$button->get_by_attribute("id","signIn",false)->send_mouse_click(2,2);
                
sleep(3);
            }            
        }        
    }
        
    
///////////////////////////////////////////////////

    // проверить правильно ли прошел запрос
    
protected function is_query_good()
    {    
        global 
$folder;

        if (
$this->body=="")
            return 
false;
        
$res_file=$folder->get_all_items("tmp");
        if (
$res_file=="")
            return 
false;
        return 
true;
    }

    
///////////////////////////////////////////////////

    // выполним запрос
    
protected function init_query($query)
    {
        
// текущий запрос
        
$this->current_query=$query;

        
// больше ничего не надо
        
return null;
    }

    
// выполним запрос
    
protected function run_query($ch)
    {
        
// глобальные
        
global $input,$button,$webpage,$span,$anchor,$image,$browser,$app,$window,$element,$app,$keyboard,$div,$log,$folder,$textarea;

        
// сделаем файл с текущей порцией слов        
        
CTextFile::write("tmp.txt",iconv("windows-1251","utf-8//IGNORE",$this->current_query)."\r\n");
        
$window->execute_open_file("Выбор","tmp.txt","&Открыть",false,true);
        
$log->event_add(" f ");
        
        
// проверить что нужен логин
        
if ($span->get_x_by_inner_text("Modify search",false)>0)
        {
            
$log->event_add(" 2 ");
            
$span->get_by_inner_text("Modify search",false)->send_mouse_move(2,2);
            
$span->get_by_inner_text("Modify search",false)->send_mouse_click(2,2);
            
sleep(1);

            
// выбреем файл
            
$keyboard->send_key(9);
            
$keyboard->send_key(9);
            
$keyboard->send_key(9);            
            
sleep(1);
            
$keyboard->send_key(32);
            
sleep(5);

            
// подождать загрузку
            
$this->wait_loading();
            
$log->event_add(" s ");

            
// нажимем кнопку получения результатов
            
$objs=$span->get_all_by_attribute("id","gwt-debug-upload-ideas-button-content",false);
            for (
$ii=0;$ii<$objs->get_count();$ii++)
            {
                if (
$objs[$ii]->get_x()>0)
                {
                    
$objs[$ii]->send_mouse_move(3,4);
                    
$objs[$ii]->send_mouse_click(3,4);
                    
sleep(1);
                    break;
                }
            }

            
// подождать загрузку
            
$this->wait_loading();
            
$log->event_add(" g ");
        }
        else
        {
            
$log->event_add(" 1 ");            

            
// выбреем файл
            
$keyboard->send_key(9);
            
$keyboard->send_key(9);
            
$keyboard->send_key(9);
            
$keyboard->send_key(9);
            
sleep(1);
            
$keyboard->send_key(32);
            
sleep(5);
            

            
// подождать загрузку
            
$this->wait_loading();
            
$log->event_add(" s ");
    
            
// нажимем кнопку получения результатов
            
$objs=$span->get_all_by_attribute("id","gwt-debug-upload-ideas-button-content",false);
            for (
$ii=0;$ii<$objs->get_count();$ii++)
            {
                if (
$objs[$ii]->get_x()>0)
                {
                    
$objs[$ii]->send_mouse_move(3,4);
                    
$objs[$ii]->send_mouse_click(3,4);
                    
sleep(1);
                    break;
                }
            }
            
            
            
// подождать загрузку
            
$this->wait_loading();
            
$log->event_add(" g ");
        }
        
sleep(5);

        
// проверим не случилось ли ошибки
        
$objs=$span->get_all_by_inner_text("Ignore and upload file",false);
        for (
$ii=0;$ii<$objs->get_count();$ii++)
        {
            if (
$objs[$ii]->get_x()>0)
            {
                
$objs[$ii]->send_mouse_move(3,4);
                
$objs[$ii]->send_mouse_click(3,4);
                
sleep(10);
                break;
            }
        }        
        if (
$div->get_by_inner_text("Keyword ideas",true)->get_x()>0)
        {
            
$div->get_by_inner_text("Keyword ideas",true)->focus();
            
$div->get_by_inner_text("Keyword ideas",true)->send_mouse_move(2,2);
            
$div->get_by_inner_text("Keyword ideas",true)->send_mouse_click(2,2);        
            
sleep(3);
        }


        
// ждем появления кнопки скачать
        
while ($span->get_all_by_inner_text("Download",true)->get(1)->get_x()<=0)
        {
            
$log->event_add(".");
            
sleep(1);
        }
        
sleep(2);
            
        
// нажмем скачать полученные результаты
        
$span->get_all_by_inner_text("Download",true)->get(1)->focus();
        
$span->get_all_by_inner_text("Download",true)->get(1)->send_mouse_move(2,2);
        
$span->get_all_by_inner_text("Download",true)->get(1)->send_mouse_click(2,2);        
        
sleep(1);
        
$log->event_add(" d ");

        
// подтвердим закачку
        
$span->get_by_attribute("id","gwt-debug-download-button-content",false)->focus();
        
$span->get_by_attribute("id","gwt-debug-download-button-content",false)->send_mouse_move(2,2);
        
$span->get_by_attribute("id","gwt-debug-download-button-content",false)->send_mouse_click(2,2);
        
sleep(2);
        
$log->event_add(" l ");

        
// нажмем на ссылку скачки
        
$browser->disable_download_file_dialog(true);
        
$browser->set_default_download("tmp");
        
$window->execute_download_file();        
        
$anchor->get_by_inner_text("Your download is now available.",false)->send_mouse_move(2,2);
        
$anchor->get_by_inner_text("Your download is now available.",false)->send_mouse_click(2,2);        

        for (
$ii=0;$ii<15;$ii++)
        {
            
sleep(1);
            
$res_file=trim($folder->get_all_items("tmp"));
            if (
$res_file=="")
                
$log->event_add(" . ");
            else 
                break;
        }
        
sleep(55);


        
$log->event_add(" d ");
        
        
// уберем лишнее окно
        
$browser->set_count(1);
        
sleep(2);

        
// закроем диалог загрузки
        
$span->get_by_attribute("id","gwt-debug-close-button-success-content",false)->send_mouse_move(2,2);
        
$span->get_by_attribute("id","gwt-debug-close-button-success-content",false)->send_mouse_click(2,2);
        
sleep(2);
        
$log->event_add(" r ");

        
// результат
        
$this->body    $webpage->get_body();
    }

    
///////////////////////////////////////////////////

    // перезапуск
    
protected function restart()
    {
        global 
$script_main_file,$app,$log;
        
$log->event("restarting $script_main_file .... ");
        
$log->event_mail("restarting $script_main_file .... ",$this->write_stat());
        
$app->restart($script_main_file);
        die();
    }

    
// сохранить обработанные поисковые результаты в файл 
    
function save()
    {    
        global 
$folder,$log;

        
$res_item=trim($folder->get_all_items("tmp"));
        
$res=iconv("utf-16","windows-1251//IGNORE",CTextFile::read($res_item));
        
        
CTextFile::add($this->out_path,$res);        
        
$log->event_add(CTextFile::get_lines_count($res_item));        
        
CFile::delete($res_item);
        
$log->event_end("");        
    }

    
///////////////////////////////////////////////////
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
?>