<?php
//http://fstrange.ru
//update 08.07.2011
require(dirname(__FILE__) . '/Browser.cfg.php');

/**
 * (PHP 4, PHP 5)<br/>
 * получить страницу методом Get или Post с автоматическим сохранением кук
 * @author fStrange http://fstrange.ru
 * @param string  $su url
 * @param string  $suReferrer  Referrer
 * @param array  $aPost  POST data, array or uldecoded string
 * @param bool  $bSaveCookie
 * @return string $sHtml
 */
function Browser($su, $suReferrer = '', $aPost = array(), $bSaveCookie = FALSE){
    global $aBrowser ;
    $aBrowser['su'] = $su;
    $aBrowser['suReferrer'] = $suReferrer ? $suReferrer : $su ;

    $rCurl = curl_init($su);
    curl_setopt($rCurl, CURLOPT_URL, $su);
    curl_setopt($rCurl, CURLOPT_RETURNTRANSFER, TRUE);   //no print
    curl_setopt($rCurl, CURLOPT_USERAGENT, $aBrowser['sUa']);
    curl_setopt($rCurl, CURLOPT_HEADER, true);
    curl_setopt($rCurl, CURLOPT_REFERER,  $aBrowser['suReferrer']);

    curl_setopt($rCurl, CURLOPT_HTTPHEADER, $aBrowser['aHttp']); //our query

    if($aPost){
        curl_setopt($rCurl, CURLOPT_POST, 1);
        curl_setopt($rCurl, CURLOPT_POSTFIELDS, $aPost);  // array or url_encoded str
    }
    if($aBrowser['suReferrer']) curl_setopt($rCurl, CURLOPT_REFERER, $aBrowser['suReferrer']);
    //curl_setopt($rCurl, CURLOPT_SSL_VERIFYPEER, 0);
    //curl_setopt($rCurl, CURLOPT_SSL_VERIFYHOST, 0);


    if($aBrowser['sCookie']){
        curl_setopt($rCurl, CURLOPT_COOKIE , $aBrowser['sCookie']);
    } elseif ($aBrowser['sfBrowserCookie']) {
        $sf = $aBrowser['sfBrowserCookie'];
        if(file_exists($sf) && filemtime($sf) > time() - (24*3600*3)){
            $aBrowser['sCookie'] = file_get_contents($sf);
            curl_setopt($rCurl, CURLOPT_COOKIE , $aBrowser['sCookie']);
        }
    }


    //send HTTP Query
    $sHtml = curl_exec($rCurl);
    if(strpos($sHtml, '"\r\n\r\n"')) list($aBrowser['sHeader'], $sHtml) = explode("\r\n\r\n", $sHtml, 2);
        else $aBrowser['sHeader'] = $sHtml;
    BrowserCookie($bSaveCookie);

    curl_close($rCurl);

    while ( BrowserRedirect() &&  $aBrowser['iLocation']<5){
        $sHtml = Browser($aBrowser['suLocation']);
    }

    return $sHtml;
}

function BrowserCookie($bSaveCookie){
    global $aBrowser;
    if(!$aBrowser['sHeader'] || !strpos($aBrowser['sHeader'], 'Set-Cookie')) return FALSE;
    if(!$bSaveCookie) return FALSE ;

    preg_match_all("/Set-Cookie: (.*?)=(.*?);/i", $aBrowser['sHeader'], $a);
    if(isset($a[1])){
        foreach ($a[1] as $k => $v) $a0[$v] = $a[2][$k];
        if(!empty($a0)) BrowserCookieSave($a0, $aBrowser['sfBrowserCookie']);
    }

    return TRUE;
}
function BrowserRedirect(){
    global $aBrowser;
    if(!$aBrowser['sHeader'] || !strpos($aBrowser['sHeader'], 'Location:')) return FALSE;

    preg_match("#Location: (.*?)[\s\r\n]#is", $aBrowser['sHeader'], $a);
    if(isset($a[1])){
         $su = $a[1];
         if(strpos($su, 'ttp://')) {
             $aBrowser['suLocation'] = $su;
             $aBrowser['iLocation']++;
         } elseif($su){
             $su0 = dirname($aBrowser['su']);
             $aBrowser['suLocation'] = $su0.$su;
             $aBrowser['iLocation']++;
         }
    }  else {
        $aBrowser['suLocation'] = '';
        $aBrowser['iLocation'] = 0;
    }
    return  $aBrowser['suLocation'];
}


function BrowserCookieSave($a){
    global $aBrowser;
    $s = '';
    foreach($a as $k=>$v) $s .= "$k=$v; ";
    $aBrowser['sCookie'] = $s;
    file_put_contents($aBrowser['sfBrowserCookie'], $s);
}
function BrowserCookieDel($i=0){
    global $aBrowser;
    $aBrowser['sCookie'] = '';
    if(1 == $i)
        if(file_exists($aBrowser['sfBrowserCookie'])) unlink($aBrowser['sfBrowserCookie']);
}

function BrowserF($su, $suRef, $sf){
    global $aBrowser;
    $sCookie = ($aBrowser['sCookie']) ?  "Cookie: ".$aBrowser['sCookie']."\r\n" : '';
    $opts = array(
        'http' => array(
            'method' => "GET",
            'header' => "Accept-language: en\r\n" .
                        $sCookie .
                        "Referer: $suRef\r\n"
        )
    );

    $context = stream_context_create($opts);

    $fp = fopen($su, 'r', false, $context);

    $fp2 = fopen($sf, 'w');
    stream_copy_to_stream($fp, $fp2);
    fclose($fp);
    fclose($fp2);
}

function isBrowser200($su){
    $a = get_headers($su);
    if(!isset($a[0])) return FALSE;
    if(strpos($a[0], '200 OK')) return TRUE;
    return FALSE;
}


function PregSimple($sPreg, $s, $i=1){
	preg_match($sPreg, $s, $v);
	$sRet = isset($v[$i]) ? $v[$i] : '' ;
	return $sRet;
}


function SzPreg($sPreg, $s, $sSz = 's,t,m', $i=1){
    $s = PregSimple($sPreg, $s, $i);

    if(!$sSz || !strpos($sSz,',')) return $s;
    $a = explode(',',$sSz);
    foreach($a as  $v) if($v){
        if('s' == $v) $s = strip_tags($s);

        //del spaces
        if('del_s' == $v) $s = preg_replace('~\s+~u',' ',$s);

        if('t' == $v) $s = trim($s);
        if('i' == $v) $s = (int) $s;

        if('m' == $v) $s = mysql_real_escape_string($s);
        if('ps' == $v) $s = PsQuotes($s);

        //url only
        if('!u' == $v) $s = preg_replace("~http://([^\s]+?)[\s\]\)]~i",'',$s."  "); //clear http://
    }

    return $s;
}