[ Index ]
 

Code source de Dolibarr 2.0.1

Accédez au Source d'autres logiciels libres

Classes | Fonctions | Variables | Constantes | Tables

title

Body

[fermer]

/htdocs/includes/magpierss/extlib/ -> Snoopy.class.inc (source)

   1  <?php
   2  
   3  /*************************************************
   4  
   5  Snoopy - the PHP net client
   6  Author: Monte Ohrt <monte@ispi.net>
   7  Copyright (c): 1999-2000 ispi, all rights reserved
   8  Version: 1.0
   9  
  10   * This library is free software; you can redistribute it and/or
  11   * modify it under the terms of the GNU Lesser General Public
  12   * License as published by the Free Software Foundation; either
  13   * version 2.1 of the License, or (at your option) any later version.
  14   *
  15   * This library is distributed in the hope that it will be useful,
  16   * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  18   * Lesser General Public License for more details.
  19   *
  20   * You should have received a copy of the GNU Lesser General Public
  21   * License along with this library; if not, write to the Free Software
  22   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  23  
  24  You may contact the author of Snoopy by e-mail at:
  25  monte@ispi.net
  26  
  27  Or, write to:
  28  Monte Ohrt
  29  CTO, ispi
  30  237 S. 70th suite 220
  31  Lincoln, NE 68510
  32  
  33  The latest version of Snoopy can be obtained from:
  34  http://snoopy.sourceforge.com
  35  
  36  *************************************************/
  37  
  38  class Snoopy
  39  {
  40      /**** Public variables ****/
  41      
  42      /* user definable vars */
  43  
  44      var $host            =    "www.php.net";        // host name we are connecting to
  45      var $port            =    80;                    // port we are connecting to
  46      var $proxy_host        =    "";                    // proxy host to use
  47      var $proxy_port        =    "";                    // proxy port to use
  48      var $agent            =    "Snoopy v1.0";        // agent we masquerade as
  49      var    $referer        =    "";                    // referer info to pass
  50      var $cookies        =    array();            // array of cookies to pass
  51                                                  // $cookies["username"]="joe";
  52      var    $rawheaders        =    array();            // array of raw headers to send
  53                                                  // $rawheaders["Content-type"]="text/html";
  54  
  55      var $maxredirs        =    5;                    // http redirection depth maximum. 0 = disallow
  56      var $lastredirectaddr    =    "";                // contains address of last redirected address
  57      var    $offsiteok        =    true;                // allows redirection off-site
  58      var $maxframes        =    0;                    // frame content depth maximum. 0 = disallow
  59      var $expandlinks    =    true;                // expand links to fully qualified URLs.
  60                                                  // this only applies to fetchlinks()
  61                                                  // or submitlinks()
  62      var $passcookies    =    true;                // pass set cookies back through redirects
  63                                                  // NOTE: this currently does not respect
  64                                                  // dates, domains or paths.
  65      
  66      var    $user            =    "";                    // user for http authentication
  67      var    $pass            =    "";                    // password for http authentication
  68      
  69      // http accept types
  70      var $accept            =    "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*";
  71      
  72      var $results        =    "";                    // where the content is put
  73          
  74      var $error            =    "";                    // error messages sent here
  75      var    $response_code    =    "";                    // response code returned from server
  76      var    $headers        =    array();            // headers returned from server sent here
  77      var    $maxlength        =    500000;                // max return data length (body)
  78      var $read_timeout    =    0;                    // timeout on read operations, in seconds
  79                                                  // supported only since PHP 4 Beta 4
  80                                                  // set to 0 to disallow timeouts
  81      var $timed_out        =    false;                // if a read operation timed out
  82      var    $status            =    0;                    // http request status
  83      
  84      var    $curl_path        =    "/usr/bin/curl";
  85                                                  // Snoopy will use cURL for fetching
  86                                                  // SSL content if a full system path to
  87                                                  // the cURL binary is supplied here.
  88                                                  // set to false if you do not have
  89                                                  // cURL installed. See http://curl.haxx.se
  90                                                  // for details on installing cURL.
  91                                                  // Snoopy does *not* use the cURL
  92                                                  // library functions built into php,
  93                                                  // as these functions are not stable
  94                                                  // as of this Snoopy release.
  95      
  96      // send Accept-encoding: gzip?
  97      var $use_gzip        = true;    
  98      
  99      /**** Private variables ****/    
 100      
 101      var    $_maxlinelen    =    4096;                // max line length (headers)
 102      
 103      var $_httpmethod    =    "GET";                // default http request method
 104      var $_httpversion    =    "HTTP/1.0";            // default http request version
 105      var $_submit_method    =    "POST";                // default submit method
 106      var $_submit_type    =    "application/x-www-form-urlencoded";    // default submit type
 107      var $_mime_boundary    =   "";                    // MIME boundary for multipart/form-data submit type
 108      var $_redirectaddr    =    false;                // will be set if page fetched is a redirect
 109      var $_redirectdepth    =    0;                    // increments on an http redirect
 110      var $_frameurls        =     array();            // frame src urls
 111      var $_framedepth    =    0;                    // increments on frame depth
 112      
 113      var $_isproxy        =    false;                // set if using a proxy server
 114      var $_fp_timeout    =    30;                    // timeout for socket connection
 115  
 116  /*======================================================================*\
 117      Function:    fetch
 118      Purpose:    fetch the contents of a web page
 119                  (and possibly other protocols in the
 120                  future like ftp, nntp, gopher, etc.)
 121      Input:        $URI    the location of the page to fetch
 122      Output:        $this->results    the output text from the fetch
 123  \*======================================================================*/
 124  
 125  	function fetch($URI)
 126      {
 127      
 128          //preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS);
 129          $URI_PARTS = parse_url($URI);
 130          if (!empty($URI_PARTS["user"]))
 131              $this->user = $URI_PARTS["user"];
 132          if (!empty($URI_PARTS["pass"]))
 133              $this->pass = $URI_PARTS["pass"];
 134                  
 135          switch($URI_PARTS["scheme"])
 136          {
 137              case "http":
 138                  $this->host = $URI_PARTS["host"];
 139                  if(!empty($URI_PARTS["port"]))
 140                      $this->port = $URI_PARTS["port"];
 141                  
 142                  // LDR FIX BUG syncronized connect timeout to read timeout, otherwise, read timeout is useless
 143                  if ($this->read_timeout) $this->_fp_timeout=$this->read_timeout;
 144                  
 145                  if($this->_connect($fp))
 146                  {
 147                      if($this->_isproxy)
 148                      {
 149                          // using proxy, send entire URI
 150                          $this->_httprequest($URI,$fp,$URI,$this->_httpmethod);
 151                      }
 152                      else
 153                      {
 154                          $path = $URI_PARTS["path"].(isset($URI_PARTS["query"]) ? "?".$URI_PARTS["query"] : "");
 155                          // no proxy, send only the path
 156                          $this->_httprequest($path, $fp, $URI, $this->_httpmethod);
 157                      }
 158                      
 159                      $this->_disconnect($fp);
 160  
 161                      if($this->_redirectaddr)
 162                      {
 163                          /* url was redirected, check if we've hit the max depth */
 164                          if($this->maxredirs > $this->_redirectdepth)
 165                          {
 166                              // only follow redirect if it's on this site, or offsiteok is true
 167                              if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok)
 168                              {
 169                                  /* follow the redirect */
 170                                  $this->_redirectdepth++;
 171                                  $this->lastredirectaddr=$this->_redirectaddr;
 172                                  $this->fetch($this->_redirectaddr);
 173                              }
 174                          }
 175                      }
 176  
 177                      if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0)
 178                      {
 179                          $frameurls = $this->_frameurls;
 180                          $this->_frameurls = array();
 181                          
 182                          while(list(,$frameurl) = each($frameurls))
 183                          {
 184                              if($this->_framedepth < $this->maxframes)
 185                              {
 186                                  $this->fetch($frameurl);
 187                                  $this->_framedepth++;
 188                              }
 189                              else
 190                                  break;
 191                          }
 192                      }                    
 193                  }
 194                  else
 195                  {
 196                      return false;
 197                  }
 198                  return true;                    
 199                  break;
 200              case "https":
 201                  if(!$this->curl_path || (!is_executable($this->curl_path))) {
 202                      $this->error = "Bad curl ($this->curl_path), can't fetch HTTPS \n";
 203                      return false;
 204                  }
 205                  $this->host = $URI_PARTS["host"];
 206                  if(!empty($URI_PARTS["port"]))
 207                      $this->port = $URI_PARTS["port"];
 208                  if($this->_isproxy)
 209                  {
 210                      // using proxy, send entire URI
 211                      $this->_httpsrequest($URI,$URI,$this->_httpmethod);
 212                  }
 213                  else
 214                  {
 215                      $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : "");
 216                      // no proxy, send only the path
 217                      $this->_httpsrequest($path, $URI, $this->_httpmethod);
 218                  }
 219  
 220                  if($this->_redirectaddr)
 221                  {
 222                      /* url was redirected, check if we've hit the max depth */
 223                      if($this->maxredirs > $this->_redirectdepth)
 224                      {
 225                          // only follow redirect if it's on this site, or offsiteok is true
 226                          if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok)
 227                          {
 228                              /* follow the redirect */
 229                              $this->_redirectdepth++;
 230                              $this->lastredirectaddr=$this->_redirectaddr;
 231                              $this->fetch($this->_redirectaddr);
 232                          }
 233                      }
 234                  }
 235  
 236                  if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0)
 237                  {
 238                      $frameurls = $this->_frameurls;
 239                      $this->_frameurls = array();
 240  
 241                      while(list(,$frameurl) = each($frameurls))
 242                      {
 243                          if($this->_framedepth < $this->maxframes)
 244                          {
 245                              $this->fetch($frameurl);
 246                              $this->_framedepth++;
 247                          }
 248                          else
 249                              break;
 250                      }
 251                  }                    
 252                  return true;                    
 253                  break;
 254              default:
 255                  // not a valid protocol
 256                  $this->error    =    'Invalid protocol "'.$URI_PARTS["scheme"].'"\n';
 257                  return false;
 258                  break;
 259          }        
 260          return true;
 261      }
 262  
 263      
 264  
 265  /*======================================================================*\
 266      Private functions
 267  \*======================================================================*/
 268      
 269      
 270  /*======================================================================*\
 271      Function:    _striplinks
 272      Purpose:    strip the hyperlinks from an html document
 273      Input:        $document    document to strip.
 274      Output:        $match        an array of the links
 275  \*======================================================================*/
 276  
 277  	function _striplinks($document)
 278      {    
 279          preg_match_all("'<\s*a\s+.*href\s*=\s*            # find <a href=
 280                          ([\"\'])?                    # find single or double quote
 281                          (?(1) (.*?)\\1 | ([^\s\>]+))        # if quote found, match up to next matching
 282                                                      # quote, otherwise match up to next space
 283                          'isx",$document,$links);
 284                          
 285  
 286          // catenate the non-empty matches from the conditional subpattern
 287  
 288          while(list($key,$val) = each($links[2]))
 289          {
 290              if(!empty($val))
 291                  $match[] = $val;
 292          }                
 293          
 294          while(list($key,$val) = each($links[3]))
 295          {
 296              if(!empty($val))
 297                  $match[] = $val;
 298          }        
 299          
 300          // return the links
 301          return $match;
 302      }
 303  
 304  /*======================================================================*\
 305      Function:    _stripform
 306      Purpose:    strip the form elements from an html document
 307      Input:        $document    document to strip.
 308      Output:        $match        an array of the links
 309  \*======================================================================*/
 310  
 311  	function _stripform($document)
 312      {    
 313          preg_match_all("'<\/?(FORM|INPUT|SELECT|TEXTAREA|(OPTION))[^<>]*>(?(2)(.*(?=<\/?(option|select)[^<>]*>[\r\n]*)|(?=[\r\n]*))|(?=[\r\n]*))'Usi",$document,$elements);
 314          
 315          // catenate the matches
 316          $match = implode("\r\n",$elements[0]);
 317                  
 318          // return the links
 319          return $match;
 320      }
 321  
 322      
 323      
 324  /*======================================================================*\
 325      Function:    _striptext
 326      Purpose:    strip the text from an html document
 327      Input:        $document    document to strip.
 328      Output:        $text        the resulting text
 329  \*======================================================================*/
 330  
 331  	function _striptext($document)
 332      {
 333          
 334          // I didn't use preg eval (//e) since that is only available in PHP 4.0.
 335          // so, list your entities one by one here. I included some of the
 336          // more common ones.
 337                                  
 338          $search = array("'<script[^>]*?>.*?</script>'si",    // strip out javascript
 339                          "'<[\/\!]*?[^<>]*?>'si",            // strip out html tags
 340                          "'([\r\n])[\s]+'",                    // strip out white space
 341                          "'&(quote|#34);'i",                    // replace html entities
 342                          "'&(amp|#38);'i",
 343                          "'&(lt|#60);'i",
 344                          "'&(gt|#62);'i",
 345                          "'&(nbsp|#160);'i",
 346                          "'&(iexcl|#161);'i",
 347                          "'&(cent|#162);'i",
 348                          "'&(pound|#163);'i",
 349                          "'&(copy|#169);'i"
 350                          );                
 351          $replace = array(    "",
 352                              "",
 353                              "\\1",
 354                              "\"",
 355                              "&",
 356                              "<",
 357                              ">",
 358                              " ",
 359                              chr(161),
 360                              chr(162),
 361                              chr(163),
 362                              chr(169));
 363                      
 364          $text = preg_replace($search,$replace,$document);
 365                                  
 366          return $text;
 367      }
 368  
 369  /*======================================================================*\
 370      Function:    _expandlinks
 371      Purpose:    expand each link into a fully qualified URL
 372      Input:        $links            the links to qualify
 373                  $URI            the full URI to get the base from
 374      Output:        $expandedLinks    the expanded links
 375  \*======================================================================*/
 376  
 377  	function _expandlinks($links,$URI)
 378      {
 379          
 380          preg_match("/^[^\?]+/",$URI,$match);
 381  
 382          $match = preg_replace("|/[^\/\.]+\.[^\/\.]+$|","",$match[0]);
 383                  
 384          $search = array(     "|^http://".preg_quote($this->host)."|i",
 385                              "|^(?!http://)(\/)?(?!mailto:)|i",
 386                              "|/\./|",
 387                              "|/[^\/]+/\.\./|"
 388                          );
 389                          
 390          $replace = array(    "",
 391                              $match."/",
 392                              "/",
 393                              "/"
 394                          );            
 395                  
 396          $expandedLinks = preg_replace($search,$replace,$links);
 397  
 398          return $expandedLinks;
 399      }
 400  
 401  /*======================================================================*\
 402      Function:    _httprequest
 403      Purpose:    go get the http data from the server
 404      Input:        $url        the url to fetch
 405                  $fp            the current open file pointer
 406                  $URI        the full URI
 407                  $body        body contents to send if any (POST)
 408      Output:        
 409  \*======================================================================*/
 410      
 411  	function _httprequest($url,$fp,$URI,$http_method,$content_type="",$body="")
 412      {
 413          if($this->passcookies && $this->_redirectaddr)
 414              $this->setcookies();
 415              
 416          $URI_PARTS = parse_url($URI);
 417          if(empty($url))
 418              $url = "/";
 419          $headers = $http_method." ".$url." ".$this->_httpversion."\r\n";        
 420          if(!empty($this->agent))
 421              $headers .= "User-Agent: ".$this->agent."\r\n";
 422          if(!empty($this->host) && !isset($this->rawheaders['Host']))
 423              $headers .= "Host: ".$this->host."\r\n";
 424          if(!empty($this->accept))
 425              $headers .= "Accept: ".$this->accept."\r\n";
 426          
 427          if($this->use_gzip) {
 428              // make sure PHP was built with --with-zlib
 429              // and we can handle gzipp'ed data
 430              if ( function_exists(gzinflate) ) {
 431                 $headers .= "Accept-encoding: gzip\r\n";
 432              }
 433              else {
 434                 trigger_error(
 435                     "use_gzip is on, but PHP was built without zlib support.".
 436                  "  Requesting file(s) without gzip encoding.", 
 437                  E_USER_NOTICE);
 438              }
 439          }
 440          
 441          if(!empty($this->referer))
 442              $headers .= "Referer: ".$this->referer."\r\n";
 443          if(!empty($this->cookies))
 444          {            
 445              if(!is_array($this->cookies))
 446                  $this->cookies = (array)$this->cookies;
 447      
 448              reset($this->cookies);
 449              if ( count($this->cookies) > 0 ) {
 450                  $cookie_headers .= 'Cookie: ';
 451                  foreach ( $this->cookies as $cookieKey => $cookieVal ) {
 452                  $cookie_headers .= $cookieKey."=".urlencode($cookieVal)."; ";
 453                  }
 454                  $headers .= substr($cookie_headers,0,-2) . "\r\n";
 455              } 
 456          }
 457          if(!empty($this->rawheaders))
 458          {
 459              if(!is_array($this->rawheaders))
 460                  $this->rawheaders = (array)$this->rawheaders;
 461              while(list($headerKey,$headerVal) = each($this->rawheaders))
 462                  $headers .= $headerKey.": ".$headerVal."\r\n";
 463          }
 464          if(!empty($content_type)) {
 465              $headers .= "Content-type: $content_type";
 466              if ($content_type == "multipart/form-data")
 467                  $headers .= "; boundary=".$this->_mime_boundary;
 468              $headers .= "\r\n";
 469          }
 470          if(!empty($body))    
 471              $headers .= "Content-length: ".strlen($body)."\r\n";
 472          if(!empty($this->user) || !empty($this->pass))    
 473              $headers .= "Authorization: BASIC ".base64_encode($this->user.":".$this->pass)."\r\n";
 474  
 475          $headers .= "\r\n";
 476          
 477          // set the read timeout if needed
 478          if ($this->read_timeout > 0)
 479              socket_set_timeout($fp, $this->read_timeout);
 480          $this->timed_out = false;
 481          
 482          fwrite($fp,$headers.$body,strlen($headers.$body));
 483          
 484          $this->_redirectaddr = false;
 485          unset($this->headers);
 486          
 487          // content was returned gzip encoded?
 488          $is_gzipped = false;
 489                          
 490          while($currentHeader = fgets($fp,$this->_maxlinelen))
 491          {
 492              if ($this->read_timeout > 0 && $this->_check_timeout($fp))
 493              {
 494                  $this->status=-100;
 495                  return false;
 496              }
 497                  
 498          //    if($currentHeader == "\r\n")
 499              if(preg_match("/^\r?\n$/", $currentHeader) )
 500                  break;
 501                          
 502              // if a header begins with Location: or URI:, set the redirect
 503              if(preg_match("/^(Location:|URI:)/i",$currentHeader))
 504              {
 505                  // get URL portion of the redirect
 506                  preg_match("/^(Location:|URI:)\s+(.*)/",chop($currentHeader),$matches);
 507                  // look for :// in the Location header to see if hostname is included
 508                  if(!preg_match("|\:\/\/|",$matches[2]))
 509                  {
 510                      // no host in the path, so prepend
 511                      $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port;
 512                      // eliminate double slash
 513                      if(!preg_match("|^/|",$matches[2]))
 514                              $this->_redirectaddr .= "/".$matches[2];
 515                      else
 516                              $this->_redirectaddr .= $matches[2];
 517                  }
 518                  else
 519                      $this->_redirectaddr = $matches[2];
 520              }
 521          
 522              if(preg_match("|^HTTP/|",$currentHeader))
 523              {
 524                  if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$currentHeader, $status))
 525                  {
 526                      $this->status= $status[1];
 527                  }                
 528                  $this->response_code = $currentHeader;
 529              }
 530              
 531              if (preg_match("/Content-Encoding: gzip/", $currentHeader) ) {
 532                  $is_gzipped = true;
 533              }
 534              
 535              $this->headers[] = $currentHeader;
 536          }
 537  
 538          # $results = fread($fp, $this->maxlength);
 539          $results = "";
 540          while ( $data = fread($fp, $this->maxlength) ) {
 541              $results .= $data;
 542              if (
 543                  strlen($results) > $this->maxlength ) {
 544                  break;
 545              }
 546          }
 547          
 548          // gunzip
 549          if ( $is_gzipped ) {
 550              // per http://www.php.net/manual/en/function.gzencode.php
 551              $results = substr($results, 10);
 552              $results = gzinflate($results);
 553          }
 554          
 555          if ($this->read_timeout > 0 && $this->_check_timeout($fp))
 556          {
 557              $this->status=-100;
 558              return false;
 559          }
 560          
 561          // check if there is a a redirect meta tag
 562          
 563          if(preg_match("'<meta[\s]*http-equiv[^>]*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match))
 564          {
 565              $this->_redirectaddr = $this->_expandlinks($match[1],$URI);    
 566          }
 567  
 568          // have we hit our frame depth and is there frame src to fetch?
 569          if(($this->_framedepth < $this->maxframes) && preg_match_all("'<frame\s+.*src[\s]*=[\'\"]?([^\'\"\>]+)'i",$results,$match))
 570          {
 571              $this->results[] = $results;
 572              for($x=0; $x<count($match[1]); $x++)
 573                  $this->_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host);
 574          }
 575          // have we already fetched framed content?
 576          elseif(is_array($this->results))
 577              $this->results[] = $results;
 578          // no framed content
 579          else
 580              $this->results = $results;
 581          
 582          return true;
 583      }
 584  
 585  /*======================================================================*\
 586      Function:    _httpsrequest
 587      Purpose:    go get the https data from the server using curl
 588      Input:        $url        the url to fetch
 589                  $URI        the full URI
 590                  $body        body contents to send if any (POST)
 591      Output:        
 592  \*======================================================================*/
 593      
 594  	function _httpsrequest($url,$URI,$http_method,$content_type="",$body="")
 595      {
 596          if($this->passcookies && $this->_redirectaddr)
 597              $this->setcookies();
 598  
 599          $headers = array();        
 600                      
 601          $URI_PARTS = parse_url($URI);
 602          if(empty($url))
 603              $url = "/";
 604          // GET ... header not needed for curl
 605          //$headers[] = $http_method." ".$url." ".$this->_httpversion;        
 606          if(!empty($this->agent))
 607              $headers[] = "User-Agent: ".$this->agent;
 608          if(!empty($this->host))
 609              $headers[] = "Host: ".$this->host;
 610          if(!empty($this->accept))
 611              $headers[] = "Accept: ".$this->accept;
 612          if(!empty($this->referer))
 613              $headers[] = "Referer: ".$this->referer;
 614          if(!empty($this->cookies))
 615          {            
 616              if(!is_array($this->cookies))
 617                  $this->cookies = (array)$this->cookies;
 618      
 619              reset($this->cookies);
 620              if ( count($this->cookies) > 0 ) {
 621                  $cookie_str = 'Cookie: ';
 622                  foreach ( $this->cookies as $cookieKey => $cookieVal ) {
 623                  $cookie_str .= $cookieKey."=".urlencode($cookieVal)."; ";
 624                  }
 625                  $headers[] = substr($cookie_str,0,-2);
 626              }
 627          }
 628          if(!empty($this->rawheaders))
 629          {
 630              if(!is_array($this->rawheaders))
 631                  $this->rawheaders = (array)$this->rawheaders;
 632              while(list($headerKey,$headerVal) = each($this->rawheaders))
 633                  $headers[] = $headerKey.": ".$headerVal;
 634          }
 635          if(!empty($content_type)) {
 636              if ($content_type == "multipart/form-data")
 637                  $headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary;
 638              else
 639                  $headers[] = "Content-type: $content_type";
 640          }
 641          if(!empty($body))    
 642              $headers[] = "Content-length: ".strlen($body);
 643          if(!empty($this->user) || !empty($this->pass))    
 644              $headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass);
 645              
 646          for($curr_header = 0; $curr_header < count($headers); $curr_header++)
 647              $cmdline_params .= " -H \"".$headers[$curr_header]."\"";
 648          
 649          if(!empty($body))
 650              $cmdline_params .= " -d \"$body\"";
 651          
 652          if($this->read_timeout > 0)
 653              $cmdline_params .= " -m ".$this->read_timeout;
 654          
 655          $headerfile = uniqid(time());
 656  
 657          # accept self-signed certs
 658          $cmdline_params .= " -k";
 659          exec($this->curl_path." -D \"/tmp/$headerfile\"".$cmdline_params." ".$URI,$results,$return);
 660          
 661          if($return)
 662          {
 663              $this->error = "Error: cURL could not retrieve the document, error $return.";
 664              return false;
 665          }
 666              
 667              
 668          $results = implode("\r\n",$results);
 669          
 670          $result_headers = file("/tmp/$headerfile");
 671                          
 672          $this->_redirectaddr = false;
 673          unset($this->headers);
 674                          
 675          for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++)
 676          {
 677              
 678              // if a header begins with Location: or URI:, set the redirect
 679              if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader]))
 680              {
 681                  // get URL portion of the redirect
 682                  preg_match("/^(Location: |URI:)(.*)/",chop($result_headers[$currentHeader]),$matches);
 683                  // look for :// in the Location header to see if hostname is included
 684                  if(!preg_match("|\:\/\/|",$matches[2]))
 685                  {
 686                      // no host in the path, so prepend
 687                      $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port;
 688                      // eliminate double slash
 689                      if(!preg_match("|^/|",$matches[2]))
 690                              $this->_redirectaddr .= "/".$matches[2];
 691                      else
 692                              $this->_redirectaddr .= $matches[2];
 693                  }
 694                  else
 695                      $this->_redirectaddr = $matches[2];
 696              }
 697          
 698              if(preg_match("|^HTTP/|",$result_headers[$currentHeader]))
 699              {
 700                  $this->response_code = $result_headers[$currentHeader];
 701                  if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$this->response_code, $match))
 702                  {
 703                      $this->status= $match[1];
 704                  }
 705              }
 706              $this->headers[] = $result_headers[$currentHeader];
 707          }
 708  
 709          // check if there is a a redirect meta tag
 710          
 711          if(preg_match("'<meta[\s]*http-equiv[^>]*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match))
 712          {
 713              $this->_redirectaddr = $this->_expandlinks($match[1],$URI);    
 714          }
 715  
 716          // have we hit our frame depth and is there frame src to fetch?
 717          if(($this->_framedepth < $this->maxframes) && preg_match_all("'<frame\s+.*src[\s]*=[\'\"]?([^\'\"\>]+)'i",$results,$match))
 718          {
 719              $this->results[] = $results;
 720              for($x=0; $x<count($match[1]); $x++)
 721                  $this->_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host);
 722          }
 723          // have we already fetched framed content?
 724          elseif(is_array($this->results))
 725              $this->results[] = $results;
 726          // no framed content
 727          else
 728              $this->results = $results;
 729  
 730          unlink("/tmp/$headerfile");
 731          
 732          return true;
 733      }
 734  
 735  /*======================================================================*\
 736      Function:    setcookies()
 737      Purpose:    set cookies for a redirection
 738  \*======================================================================*/
 739      
 740  	function setcookies()
 741      {
 742          for($x=0; $x<count($this->headers); $x++)
 743          {
 744          if(preg_match("/^set-cookie:[\s]+([^=]+)=([^;]+)/i", $this->headers[$x],$match))
 745              $this->cookies[$match[1]] = $match[2];
 746          }
 747      }
 748  
 749      
 750  /*======================================================================*\
 751      Function:    _check_timeout
 752      Purpose:    checks whether timeout has occurred
 753      Input:        $fp    file pointer
 754  \*======================================================================*/
 755  
 756  	function _check_timeout($fp)
 757      {
 758          if ($this->read_timeout > 0) {
 759              $fp_status = socket_get_status($fp);
 760              if ($fp_status["timed_out"]) {
 761                  $this->timed_out = true;
 762                  return true;
 763              }
 764          }
 765          return false;
 766      }
 767  
 768  /*======================================================================*\
 769      Function:    _connect
 770      Purpose:    make a socket connection
 771      Input:        $fp    file pointer
 772  \*======================================================================*/
 773      
 774  	function _connect(&$fp)
 775      {
 776          if(!empty($this->proxy_host) && !empty($this->proxy_port))
 777              {
 778                  $this->_isproxy = true;
 779                  $host = $this->proxy_host;
 780                  $port = $this->proxy_port;
 781              }
 782          else
 783          {
 784              $host = $this->host;
 785              $port = $this->port;
 786          }
 787      
 788          $this->status = 0;
 789          
 790          if($fp = fsockopen(
 791                      $host,
 792                      $port,
 793                      $errno,
 794                      $errstr,
 795                      $this->_fp_timeout
 796                      ))
 797          {
 798              // socket connection succeeded
 799  
 800              return true;
 801          }
 802          else
 803          {
 804              // socket connection failed
 805              $this->status = $errno;
 806              switch($errno)
 807              {
 808                  case -3:
 809                      $this->error="socket creation failed (-3)";
 810                  case -4:
 811                      $this->error="dns lookup failure (-4)";
 812                  case -5:
 813                      $this->error="connection refused or timed out (-5)";
 814                  default:
 815                      $this->error="connection failed (".$errno.")";
 816              }
 817              return false;
 818          }
 819      }
 820  /*======================================================================*\
 821      Function:    _disconnect
 822      Purpose:    disconnect a socket connection
 823      Input:        $fp    file pointer
 824  \*======================================================================*/
 825      
 826  	function _disconnect($fp)
 827      {
 828          return(fclose($fp));
 829      }
 830  
 831      
 832  /*======================================================================*\
 833      Function:    _prepare_post_body
 834      Purpose:    Prepare post body according to encoding type
 835      Input:        $formvars  - form variables
 836                  $formfiles - form upload files
 837      Output:        post body
 838  \*======================================================================*/
 839      
 840  	function _prepare_post_body($formvars, $formfiles)
 841      {
 842          settype($formvars, "array");
 843          settype($formfiles, "array");
 844  
 845          if (count($formvars) == 0 && count($formfiles) == 0)
 846              return;
 847          
 848          switch ($this->_submit_type) {
 849              case "application/x-www-form-urlencoded":
 850                  reset($formvars);
 851                  while(list($key,$val) = each($formvars)) {
 852                      if (is_array($val) || is_object($val)) {
 853                          while (list($cur_key, $cur_val) = each($val)) {
 854                              $postdata .= urlencode($key)."[]=".urlencode($cur_val)."&";
 855                          }
 856                      } else
 857                          $postdata .= urlencode($key)."=".urlencode($val)."&";
 858                  }
 859                  break;
 860  
 861              case "multipart/form-data":
 862                  $this->_mime_boundary = "Snoopy".md5(uniqid(microtime()));
 863                  
 864                  reset($formvars);
 865                  while(list($key,$val) = each($formvars)) {
 866                      if (is_array($val) || is_object($val)) {
 867                          while (list($cur_key, $cur_val) = each($val)) {
 868                              $postdata .= "--".$this->_mime_boundary."\r\n";
 869                              $postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n";
 870                              $postdata .= "$cur_val\r\n";
 871                          }
 872                      } else {
 873                          $postdata .= "--".$this->_mime_boundary."\r\n";
 874                          $postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n";
 875                          $postdata .= "$val\r\n";
 876                      }
 877                  }
 878                  
 879                  reset($formfiles);
 880                  while (list($field_name, $file_names) = each($formfiles)) {
 881                      settype($file_names, "array");
 882                      while (list(, $file_name) = each($file_names)) {
 883                          if (!is_readable($file_name)) continue;
 884  
 885                          $fp = fopen($file_name, "r");
 886                          $file_content = fread($fp, filesize($file_name));
 887                          fclose($fp);
 888                          $base_name = basename($file_name);
 889  
 890                          $postdata .= "--".$this->_mime_boundary."\r\n";
 891                          $postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n";
 892                          $postdata .= "$file_content\r\n";
 893                      }
 894                  }
 895                  $postdata .= "--".$this->_mime_boundary."--\r\n";
 896                  break;
 897          }
 898  
 899          return $postdata;
 900      }
 901  }
 902  
 903  ?>


Généré le : Mon Nov 26 12:29:37 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics