ANTICHAT Forum
HOME FORUMS MEMBERS RECENT POSTS LOG IN  
Баннер 1   Баннер 2
НОВЫЕ ТОРГОВАЯ НОВОСТИ
loading...
Скрыть
Вернуться   ANTICHAT > ПРОГРАММИРОВАНИЕ > PHP
   
 
 
Опции темы Поиск в этой теме Опции просмотра

  #11  
Старый 28.06.2009, 02:35
NULL_byte
Новичок
Регистрация: 18.05.2008
Сообщений: 4
С нами: 9464522

Репутация: 19
По умолчанию

Класс для работы с антикапчей:
PHP код:
<?php

/*
 * @name: anti-captcha.php
 * @description: Class to communicate AC's API
 * @author: NULL_byte
 * @contacts: www.null-byte.info
 * @version: 1
 */

/*
    $AC = new AntiCaptcha;
    $AC->Verbose = false;
    $AC->APIKey = '';
    $AC->Recognize('E:\www\vkontakte\regger\captcha.jpg');

    $r = $AC->DecodedCaptcha;

    if (!$r) $AC->MakeAbuse();
*/

class AntiCaptcha {

    var 
$APIKey     = '';
    var 
$Verbose    = true;
    var 
$Numeric  = 0;
    var 
$Phrase   = 0;
    var 
$Regsense = 0;

    var 
$RTimeout   = 2;   // Как часто проверять результат
    
var $MTimeout   = 120; // максимальное время расшифровки
    
    
var $MinLen     = 0;
    var 
$MaxLen     = 0;

    var 
$DecodedCaptcha = false;
    var 
$LastCaptchaID  = '';


    function 
Recognize($file) {
        if (!
is_array($file) && !file_exists($file)) {
            echo 
"File $file not found\n";
            return 
false;
        }
        
        if (
is_array($file)) {
            if (!isset(
$file[0]) || !isset($file[1]) || !isset($file[2]))
                echo 
"Wrong image data!\n";
            
$filedata = Array($file[0], $file[1], $file[2]);
        } else {
            
$filedata = Array(file_get_contents($file));
        }
        
        
$q = new HTTPQuery;
        
$q->ContentType = 'multipart/form-data';
        
$q->Query = Array(
            
'method'    => 'post',
            
'key'       => $this->APIKey,
            
'file'      => $filedata, // Полный путь к файлу
            
'phrase'    => $this->Phrase,
            
'regsense'    => $this->Regsense,
            
'numeric'    => $this->Numeric,
            
'min_len'    => $this->MinLen,
            
'max_len'    => $this->MaxLen
        
);
        
$q->Post('http://ac-service.info/in.php');
        
        if (
strpos($q->Result, "ERROR") !== false) {
            echo 
"Server returned error: {$q->ResultClean}\n";
            
$this->DecodedCaptcha = false;
            return 
false;
        } else {
            
$ex = explode("|", $q->Result);
            
$this->LastCaptchaID = $ex[1];
            
$captcha_id = $ex[1];
            if (!
$this->Verbose) return $captcha_id;
            if (
$this->Verbose) echo "Decoding captcha";
            
            
$waittime = 0;
            if (
$this->Verbose) echo ".";
            
sleep($this->RTimeout);
            while(
true) {
                
$q->Get("http://ac-service.info/res.php?key={$this->APIKey}&action=get&id=$captcha_id");
                
$result = $q->ResultClean;
                if (
strpos($result, 'ERROR') !== false) {
                    if (
$this->Verbose) echo "Server returned error: $result\n";
                    
$this->DecodedCaptcha = false;
                    return 
false;
                }
                if (
$result == "CAPCHA_NOT_READY") {
                    
$waittime += $this->RTimeout;
                    if (
$waittime > $this->MTimeout) {
                        if (
$this->Verbose) echo "Timelimit ({$this->MTimeout} secs) hit\n";
                        break;
                    }
                    if (
$this->Verbose) echo ".";
                    
sleep($this->RTimeout);
                } else {
                    
$ex = explode('|', $result);
                    
$this->DecodedCaptcha = false;
                    if (
trim($ex[0]) == 'OK') $this->DecodedCaptcha = trim($ex[1]);
                    if (
$this->Verbose) echo " ";
                        return 
$this->DecodedCaptcha;
                }
            }
            return 
false;
        }
    }
    
    
    function 
MakeAbuse() {
        
$url = "http://ac-service.info/res.php?key={$this->APIKey}&action=reportbad&id={$this->LastCaptchaID}";
        
$responce = file_get_contents($url);
        return (
$responce == 'OK_REPORT_RECORDED');
    }

}





?>


требует для себя вот это:
PHP код:
<?php

/*
 * @name: HTTPQuery.php
 * @description: Class to work with HTTP protocol
 * @author: NULL_byte
 * @contacts: www.null-byte.info
 * @version: 1.2
 */

class HTTPQuery {
    var 
$URI       = 'http://localhost/';
    var 
$Port      = '80';
    var 
$Method    = 'get';
    var 
$Referer   = null;
    var 
$UserAgent = null;
    var 
$Query     = null;
    var 
$Cookies   = null; 
    var 
$Proxy     = false; // Proxy to use. Format: Array('proxy_host', 'port') or false;
    
var $ContentType = null;
    var 
$Boundary    = '-----NULL-BYTE----NULL-BYTE----NULL-BYTE';

    var 
$Host      = null;
    var 
$Path      = null;

    var 
$Silent    = false; // If it true, wouldn't print any messages
    
var $Debug     = false; // If it true, would print many messages :)
    
    
var $Result    = null;   // Will contain result with headers
    
var $ResultClean = null; // Will contain result without headers
    
var $AddHeaders  = Array();
    var 
$Headers   = Array();

    
    
    
    
    function 
ConstructQuery() {
        if (
is_array($this->Query)) {
            if (
strtolower($this->ContentType) != 'multipart/form-data') {
                
$query_string = '';
                foreach (
$this->Query as $key => $value) {
                    
$query_string .= "$key=$value&";
                    
//$query_string .= $key.'='.urlencode($value);
                
}
                
$this->Query = trim($query_string, '&');
            } else {
                
$query_string = '';
                foreach (
$this->Query as $key => $value) {
                    
$query_string .= "--{$this->Boundary}\r\n";
                    if (!
is_array($value)) {
                        
$query_string .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n$value\r\n";
                    } else {
                        if (!isset(
$value[1]) && !isset($value[2])) {
                            
$value[1] = $value[0];
                            
$value[0] = file_get_contents($value[1]);
                        }
                        if (!isset(
$value[2])) $value[2] = 'application/octet-stream';
                        
//if (!isset($value[2])) $value[2] = 'undefined/undefined';
                        
$query_string .= "Content-Disposition: form-data; name=\"$key\"; ";
                        
$query_string .= "filename=\"{$value[1]}\"\r\n";
                        
$query_string .= "Content-Type: {$value[2]}\r\n\r\n{$value[0]}\r\n";
                    }
                }
                
$query_string .= "--{$this->Boundary}--\r\n";
                
$this->Query = $query_string;
            }
        }
    }
    
    function 
Filter() {
        
$this->Method = strtolower($this->Method);
        
$this->URI = str_replace(Array('\\', 'http://', 'https://'), Array('/', '', ''), $this->URI);
        
$this->URI = preg_replace('#[/]+#', '/', $this->URI);
        if (
is_string($this->Proxy)) $this->Proxy = explode(':', $this->Proxy);
        
$this->ConstructQuery();
    }

    function 
SendRequest($url = false) {
        if (
$url) $this->URI = $url;
        
$this->Filter();

        
$url_parts = explode('/', $this->URI);
        
$this->Host = $url_parts[0];
        
$this->Path = '';
        for (
$i = 1; $i < count($url_parts); $i++)
            
$this->Path .= '/'.$url_parts[$i];
        if (
$this->Path == '') $this->Path = '/';

        
// Creating socket
        
$cur_try = 0; // Current try
        
$max_tries = 5; // Max allowed tries
        
while (true) {
            if (
$this->Proxy) {
                
$fp = @fsockopen($this->Proxy[0], $this->Proxy[1], $errno, $errstr, 10);
            } else {
                
$fp = @fsockopen($this->Host, $this->Port, $errno, $errstr, 5);
            }
            if (
$fp) break; // If everything is ok, going on without stopping
            
            // Else retrying...
            
$cur_try++;
            if (!
$this->Silent) echo "Cannot create socket, will now try again ($cur_try/$max_tries)...\n";
            if (
$cur_try >= $max_tries) {
                if (!
$this->Silent) echo "Too many errors, please check your internet connection!\n";
                return 
false;
            }
            
sleep(3);
        }


        if ((
$this->Method == 'get') && (substr(0, 1, $this->Query) != '?') && ($this->Query != null))
            
$this->Query = '?'.$this->Query;

        
$query_length = strlen($this->Query);
        
        if (!
$this->UserAgent)
            
$this->UserAgent = 'NULL_byte\'s PHP Browser Mozilla/4.0 (compatible; MSIE 3.0; Windows NT 4.0)';

        
$_cookies = $this->CookiesToString($this->Cookies);
        
        
$PostContentType = 'application/x-www-form-urlencoded';
        if (
strtolower($this->ContentType) == 'multipart/form-data')
            
$PostContentType = "multipart/form-data; boundary={$this->Boundary}";
        
        
$out = Array();
        if (
$this->Method == 'get') {
            
$out[] = "GET {$this->Path}{$this->Query} HTTP/1.0";
            
$out[] = "Accept: */*";
            
$out[] = "Accept-Language: ru";
            
$out[] = "User-Agent: {$this->UserAgent}";
            if (
$this->Cookies) $out[] = "Cookie: $_cookies";
            if (
$this->Referer) $out[] = "Referer: {$this->Referer}";
            
$out[] = "Host: {$this->Host}";
        } elseif (
$this->Method == 'post') {
            
$out[] = "POST {$this->Path} HTTP/1.0";
            
$out[] = "Accept: */*";
            
$out[] = "Accept-Language: ru";
            
$out[] = "User-Agent: {$this->UserAgent}";
            if (
$this->Cookies) $out[] = "Cookie: $_cookies";
            if (
$this->Referer) $out[] = "Referer: {$this->Referer}";
            
$out[] = "Host: {$this->Host}";
            if (!isset(
$this->AddHeaders['Content-Type']))
            
$out[] = "Content-Type: $PostContentType";
            
$out[] = "Content-Length: $query_length";
        } else {
            
$out[] = strtoupper($this->Method)." {$this->Path}{$this->Query} HTTP/1.0";
            
$out[] = "Accept: */*";
            
$out[] = "Accept-Language: ru";
            
$out[] = "User-Agent: {$this->UserAgent}";
            if (
$this->Cookies) $out[] = "Cookie: $_cookies";
            if (
$this->Referer) $out[] = "Referer: {$this->Referer}";
            
$out[] = "Host: {$this->Host}:{$this->Port}";
        }
        foreach (
$this->AddHeaders as $key => $value)
            
$out[] = "$key: $value";
        
$out[] = "Connection: Close";
        
//$out[] = "Connection: Keep-Alive";
        
$out = implode("\r\n", $out);

        
$out = str_replace("\n", "\r\n", $out);
        
$out = preg_replace("#[\n]+#", "\n", $out);
        
$out = preg_replace("#[\r]+#", "\r", $out);
        
$out .= "\r\n\r\n";
        if (
$this->Method == 'post') $out .= $this->Query;

        
fwrite($fp, $out);
        
$this->Result = '';
        while (!
feof($fp)) {
            
$line = fgets($fp, 1024);
            
$this->Result .= $line.'';
        }
        
fclose($fp);
        
        if (
$this->Debug) {
            echo 
"----->\n$out\n\n";
            echo 
"<-----\n{$this->Result}\n\n";
        }
        
$this->Referer = $url;
        
$this->Query = NULL;
        
$this->ContentType = NULL;
        
$this->AddHeaders = Array();
        
$this->ParseHeaders();
        
$this->ResultClean = ltrim(substr($this->Result, strpos($this->Result, "\r\n\r\n")));
        return 
$this->Result;
    }

    function 
Get($url = false) {
        
$this->Method = 'get';
        return 
$this->SendRequest($url);
    }

    function 
Post($url = false) {
        
$this->Method = 'post';
        return 
$this->SendRequest($url);
    }

    function 
ParseHeaders() {
        if (!
$this->Result) return false;
        
$server_response = explode("\r\n\r\n", $this->Result);
        
$server_response = $server_response[0];
        
$server_response = str_replace("\r", '', $server_response);
        
$server_response = explode("\n", $server_response);
        
$result = Array();
        foreach(
$server_response as $mixed_headers) {
            if (!(
strpos($mixed_headers, ': ') === false)) {
                
$header = explode(': ', trim($mixed_headers));
                
$result[$header[0]] = isset($header[1]) ? $header[1] : NULL;
            }
        }
        
$this->Headers = $result;
        return 
$result;
    }

    function 
CookiesToString($cookie = false) {
        if (!
$cookie) $cookie = $this->Cookies;
        if (!
is_array($cookie)) return $cookie;
        
$cookie_string = '';
        foreach (
$cookie as $key => $value)
            
$cookie_string .= " $key=$value;";
        
$cookie = trim($cookie_string, '; ');
        return 
$cookie;
    }

    function 
CookiesToArray($cookie = false) {
        if (!
$cookie) $cookie = $this->Cookies;
        if (
is_array($cookie)) return $cookie;
        
$cookie = explode('; ', $cookie);
        
$cookie_array = Array();
        for (
$i = 0; $i < count($cookie); $i++) {
            
$c = explode('=', $cookie[$i]);
            
$cookie_array[$c[0]] = $c[1];
        }
        return 
$cookie_array;
    }

    function 
GetCookies($as_string = false) {
        if (!
$this->Result) return false;
        
$data = explode("\r\n\r\n", $this->Result);
        
$data = $data[0];
        
$data = str_replace("\r", '', $data);
        
$data = explode("\n", $data);
        
$raw_cookies = Array();
        foreach (
$data as $d) {
            
$d = explode(' ', $d);
            if (
strtolower($d[0]) == 'set-cookie:') {
                
$raw_cookies[] = $d[1];
            }
        }
        
$cookies = Array();
        foreach (
$raw_cookies as $cookie) {
            
$cookie = explode('=', $cookie);
            
$cookies[$cookie[0]] = trim($cookie[1], '; ');
        }
        if (
$as_string)
            
$cookies = $this->CookiesToString($cookies);
        return 
$cookies;
    }

}


?>

Последний раз редактировалось NULL_byte; 28.06.2009 в 02:39..
 
Ответить с цитированием
 



Предыдущая тема Следующая тема

Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
 


Быстрый переход




ANTICHAT ™ © 2001- Antichat Kft.