Esempio n. 1
0
 /**
  * @param Request $wixHiveRequest
  *
  * @return Response
  * @throws WixHiveException
  */
 public function execute(Request $wixHiveRequest)
 {
     $resource = curl_init();
     curl_setopt($resource, CURLOPT_URL, $wixHiveRequest->endpoint);
     $this->setHttpMethod($resource, $wixHiveRequest);
     if ($this->isBodyRequired($wixHiveRequest->httpMethod)) {
         $this->setRequestBody($resource, $wixHiveRequest);
     }
     if (!empty($wixHiveRequest->headers)) {
         $headers = [];
         foreach ($wixHiveRequest->headers as $key => $value) {
             $headers[] = "{$key}: {$value}";
         }
         curl_setopt($resource, CURLOPT_HTTPHEADER, $headers);
     }
     curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($resource, CURLOPT_VERBOSE, 1);
     curl_setopt($resource, CURLOPT_HEADER, 1);
     $result = curl_exec($resource);
     curl_close($resource);
     //TODO process the case when there is no response from the service
     if (false === $result) {
     }
     $response = http_parse_message($result);
     $contentType = explode(";", $response->headers['Content-Type']);
     if (!isset($contentType[0]) || $contentType[0] !== "application/json") {
         throw new WixHiveException("Response content type is not supported", "415");
     }
     return new Response(json_decode($response->body));
 }
Esempio n. 2
0
    /**
     * try three different methods for http request,
     * @param type $url
     * @return type
     */
    function request($url){
        // use curl_get first if it is activated
        if(function_exists('curl_init')) {
            $this->opts = array(
                CURLOPT_HEADER => FALSE,
                CURLOPT_RETURNTRANSFER => TRUE
            );
            $result=$this->curl_get($url);
            return $result['cr'];
        // then try http_get
        }elseif(function_exists('http_get')){
            return http_parse_message(http_get($url))->body;

        // finally we have file_get_contents which is quite often deactivated
        }elseif(ini_get('allow_url_fopen')){
            return file_get_contents($url);
        }else{
            $this->error(__('Your server doesn\'t support remote exchanges.',WYSIJA));
            $this->error(__('Contact your administrator to modify that, it should be configurable.',WYSIJA));
            $this->error('<strong>CURL library</strong> DISABLED');
            $this->error('<strong>allow_url_fopen</strong> DISABLED');
            $this->error('<strong>PECL pecl_http >= 0.1.0</strong> DISABLED');
            return false;
        }
    }
Esempio n. 3
0
 public function parseResponse($message)
 {
     if (!$message) {
         return false;
     }
     $parts = http_parse_message($message);
     return array('protocol' => 'HTTP', 'version' => number_format($parts->httpVersion, 1), 'code' => $parts->responseCode, 'reason_phrase' => $parts->responseStatus, 'headers' => $parts->headers, 'body' => $parts->body);
 }
function get_trusted_ticket($wgserver, $user, $remote_addr)
{
    $params = array('username' => $user, 'client_ip' => $remote_addr);
    $server = PROTOCOL . "://{$wgserver}/trusted";
    $resp = http_parse_message(http_post_fields($server, $params))->body;
    //testing
    // print '<script type="text/javascript">alert("My addy ' . $_SERVER['SERVER_ADDR'] . ' is getting response from server ' . $server . ' for user ' . $user . ' of ' . print_r($resp) . '");</script>';
    //print_r ($resp);
    //actually return it
    return $resp;
}
Esempio n. 5
0
 protected function fetchData(Request $request)
 {
     $this->request = $request;
     include "getUA.php";
     $request_options = array("referer" => "http://api.irail.be/", "timeout" => "30", "useragent" => $irailAgent);
     $id = preg_replace("/.*?(\\d.*)/smi", "\\1", $request->getVehicleId());
     $this->scrapeURL .= "?l=" . $request->getLang() . "&s=1&tid=" . $id . "&da=D&p=2";
     $post = http_post_data($this->scrapeURL, "", $request_options) or die("");
     $body = http_parse_message($post)->body;
     return $body;
 }
 private static function httpcall($url)
 {
     //maybe we should add the method to the config. Some servers have curl, some have this method:
     include "config.php";
     $request_options = array("referer" => "http://iRail.be/", "timeout" => "30", "useragent" => $iRailAgent);
     //echo $url;
     $post = http_post_data($url, "", $request_options) or die("");
     if ($post == "") {
         throw new Exception("Failed to contact the server");
     }
     return http_parse_message($post)->body;
 }
Esempio n. 7
0
     private static function getServerData($id,$lang){
	  include_once("../includes/getUA.php");
	  $request_options = array(
	       "referer" => "http://api.irail.be/",
	       "timeout" => "30",
	       "useragent" => $irailAgent,
	       );
	  $scrapeURL = "http://www.railtime.be/mobile/HTML/TrainDetail.aspx";
	  $id = preg_replace("/.*?(\d.*)/smi", "\\1", $id);
	  $scrapeURL .= "?l=" . $lang . "&tid=" . $id . "&dt=" . date( 'd%2fm%2fY' );
	  $post = http_post_data($scrapeURL, "", $request_options) or die("");
	  return http_parse_message($post)->body;	  
     }
Esempio n. 8
0
 private function _execute_query($url)
 {
     $response = \http_get($url, array(), $response_info);
     if ($response_info['response_code'] != 200 || !$response) {
         return false;
     }
     $data = http_parse_message($response)->body;
     try {
         $data = json_decode($data, true);
     } catch (Exception $e) {
         return false;
     }
     return $data;
 }
Esempio n. 9
0
 function http_parse_message($res)
 {
     $this->response_raw = $res;
     $this->response_object = http_parse_message($res);
     if ($this->response_object->responseCode == 404) {
         throw new HttpServerException404($this->response_object->responseStatus);
     }
     if ($this->response_object->responseCode >= 400 && $this->response_object->responseCode <= 600) {
         throw new HttpServerException($this->response_object->responseStatus, $this->response_object->responseCode);
     }
     if (!in_array($this->response_object->responseCode, range(200, 207))) {
         throw new RestClientException($this->response_object->responseStatus, $this->response_object->responseCode);
     }
 }
Esempio n. 10
0
 /** Send a query using a specified request-method.
  *
  * @param	string	$query			Query to send. (Required)
  * @param	string	$requestMethod	Request-method for calling (defaults to 'GET'). (Optional)
  * @return	SimpleXMLElement		A SimpleXMLElement object.
  *
  * @access	protected
  * @internal
  */
 protected function internalCall($params, $requestMethod = 'GET')
 {
     /* Create caching hash. */
     $hash = Cache::createHash($params);
     /* Check if response is cached. */
     if ($this->cache != null && $this->cache->contains($hash) && !$this->cache->isExpired($hash)) {
         /* Get cached response. */
         $response = $this->cache->load($hash);
     } else {
         /* Build request query. */
         $query = http_build_str($params, '', '&');
         /* Set request options. */
         $options = array('useragent' => 'PHP last.fm API (PHP/' . phpversion() . ')');
         /* Clear response headers. */
         $this->headers = array();
         /* Get response */
         if ($requestMethod === 'POST') {
             $response = http_post_data(self::API_URL, $query, $options, $info);
         } else {
             $response = http_get(self::API_URL . '?' . $query, $options, $info);
         }
         $response = http_parse_message($response);
         foreach ($response->headers as $header => $value) {
             $this->headers[$header] = $value;
         }
         $response = $response->body;
         /* Cache it. */
         if ($this->cache != null) {
             if (array_key_exists('Expires', $this->headers)) {
                 $this->cache->store($hash, $response, strtotime($this->headers['Expires']));
             } else {
                 $expiration = $this->cache->getPolicy()->getExpirationTime($params);
                 if ($expiration > 0) {
                     $this->cache->store($hash, $response, time() + $expiration);
                 }
             }
         }
     }
     /* Create SimpleXMLElement from response. */
     $response = new SimpleXMLElement($response);
     /* Return response or throw an error. */
     if (Util::toString($response['status']) === 'ok') {
         if ($response->children()->{0}) {
             return $response->children()->{0};
         }
     } else {
         throw new Error(Util::toString($response->error), Util::toInteger($response->error['code']));
     }
 }
Esempio n. 11
0
 private static function fetchData($station, $time, $lang, $timeSel)
 {
     include "../includes/getUA.php";
     $request_options = array("referer" => "http://api.irail.be/", "timeout" => "30", "useragent" => $irailAgent);
     $body = "";
     //we want data for 1 hour. But we can only retrieve 15 minutes per request
     for ($i = 0; $i < 4; $i++) {
         $scrapeUrl = "http://www.railtime.be/mobile/SearchStation.aspx";
         $scrapeUrl .= "?l=EN&tr=" . $time . "-15&s=1&sid=" . stations::getRTID($station, $lang) . "&da=" . $timeSel . "&p=2";
         $post = http_post_data($scrapeUrl, "", $request_options) or die("");
         $body .= http_parse_message($post)->body;
         $time = tools::addQuarter($time);
     }
     return $body;
 }
Esempio n. 12
0
 public static function fetchData($station, $time, $lang, $arrdep)
 {
     include "../includes/getUA.php";
     $request_options = array("referer" => "http://api.irail.be/", "timeout" => "30", "useragent" => $irailAgent);
     if ($arrdep == "A") {
         throw new Exception("Not yet implemented. If you really need this function you can try to implement it yourself in http://github.com/iRail/iRail or you can ask on the mailinglist list.iRail.be", 500);
     }
     //	  $MIVBMODES = array("M", "N", "T", "B");
     $s = explode(".", $station->id);
     $stid = $s[2];
     //stibrt server wants lang in lowercase
     $lang = strtolower($lang);
     $scrapeUrl = "http://stibrt.be/labs/stib/service/getwaitingtimes.php?1=1&iti=1&halt={$stid}&lang={$lang}";
     //	  echo $scrapeUrl . "\n";
     $post = http_post_data($scrapeUrl, "", $request_options) or die("");
     return http_parse_message($post)->body;
 }
Esempio n. 13
0
 private static function fetchData($station, $time, $lang, $timeSel)
 {
     include "../includes/getUA.php";
     $request_options = array("referer" => "http://api.irail.be/", "timeout" => "30", "useragent" => $irailAgent);
     $body = "";
     //we want data for 1 hour. But we can only retrieve 15 minutes per request
     for ($i = 0; $i < 4; $i++) {
         $scrapeUrl = "http://www.railtime.be/mobile/HTML/StationDetail.aspx";
         $rt = stations::getRTID($station, $lang);
         $rtname = $rt->rtname;
         $rtid = $rt->rtid;
         $scrapeUrl .= "?sn=" . urlencode($rtname) . "&sid=" . urlencode($rtid) . "&ti=" . urlencode($time) . "&da=" . urlencode($timeSel) . "&l=EN&s=1";
         $post = http_post_data($scrapeUrl, "", $request_options) or die("");
         $body .= http_parse_message($post)->body;
         $time = tools::addQuarter($time);
     }
     return $body;
 }
function get_dyn_pois($fw_dynamic)
{
    $conf_data = file_get_contents("poi_dp_dyn_conf.json");
    $conf = json_decode($conf_data, true);
    $sources = $fw_dynamic["sources"];
    $dyn_data = array();
    $n_sources = count($sources);
    for ($i = 0; $i < $n_sources; $i++) {
        $source = $sources[$i];
        $host = $source["host_type"];
        $type = $source["data_type"];
        if (array_key_exists('host_id', $source)) {
            $ids = $source["host_id"];
            $id = $source["host_id"][0];
        } else {
            $ids = array();
            $id = '';
        }
        switch ($conf["host_type"][$host]["method"]) {
            case "REST_GET":
                $url = $conf["host_type"][$host]["params"]["url"] . $id . $conf["host_type"][$host]["params"]["params"];
                $options = array('headers' => $conf["host_type"][$host]["params"]["headers"]);
                $output = http_get($url, $options);
                break;
            case "REST_POST":
                $i = 0;
                $data = $conf["host_type"][$host]["params"]["params"];
                foreach ($ids as $id) {
                    $data = str_replace('$' . $i++, $id, $data);
                }
                if (is_array($data)) {
                    $data = json_encode($data);
                }
                $output = http_post_data($conf["host_type"][$host]["params"]["url"], $data, array('headers' => $conf["host_type"][$host]["params"]["headers"]));
                break;
        }
        $data = http_parse_message($output)->body;
        // merge separate sources
        $mapped_data = map_data($conf["data_mapping"][$type], $data);
        $dyn_data = array_merge_r2($dyn_data, $mapped_data);
    }
    return $dyn_data;
}
Esempio n. 15
0
 function request($url)
 {
     if (ini_get("allow_url_fopen")) {
         return file_get_contents($url);
     } elseif (function_exists('curl_init')) {
         $this->opts = array(CURLOPT_HEADER => FALSE, CURLOPT_RETURNTRANSFER => TRUE);
         $result = $this->curl_get($url);
         return $result['cr'];
     } elseif (function_exists('http_get')) {
         return http_parse_message(http_get($url))->body;
     } else {
         $this->error(__("Your server doesn't support remote exchanges.", WYSIJA));
         $this->error(__("Contact your administrator to modify that, it should be configurable.", WYSIJA));
         $this->error("<strong>CURL library</strong> DISABLED");
         $this->error("<strong>allow_url_fopen</strong> DISABLED");
         $this->error("<strong>PECL pecl_http >= 0.1.0</strong> DISABLED");
         return false;
     }
 }
Esempio n. 16
0
 protected function fetchData(Request $request)
 {
     include "getUA.php";
     $this->request = $request;
     $scrapeUrl = "http://www.railtime.be/mobile/SearchStation.aspx";
     $request_options = array("referer" => "http://api.irail.be/", "timeout" => "30", "useragent" => $irailAgent);
     $stationname = strtoupper($request->getStation());
     include "includes/railtimeids.php";
     if (array_key_exists($stationname, $railtimeids)) {
         $rtid = $railtimeids[$stationname];
     } else {
         throw new Exception("Station not available for liveboard", 3);
     }
     $this->arrdep = $request->getArrdep();
     $this->name = $request->getStation();
     $scrapeUrl .= "?l=" . $request->getLang() . "&s=1&sid=" . $rtid . "&da=" . substr($request->getArrdep(), 0, 1) . "&p=2";
     $post = http_post_data($scrapeUrl, "", $request_options) or die("");
     $body = http_parse_message($post)->body;
     return $body;
 }
Esempio n. 17
0
 function facebookLogin($obj)
 {
     //Facebook Login start
     if (isset($obj->io->input["get"]["code"])) {
         $callback = isset($obj->io->input["get"]["redirect_param"]) ? 'redirect_param=' . $obj->io->input["get"]["redirect_param"] : "";
         $param = http_build_query(array('client_id' => $obj->config->fb["appid"], "client_secret" => $obj->config->fb["secret"], 'redirect_uri' => $obj->openid->realm . '/' . $obj->io->input["get"]["fun"] . '/' . $obj->io->input["get"]["act"] . '/' . $callback, 'code' => $obj->io->input["get"]["code"], 'req_perms' => $obj->config->fb["req_perms"]));
         $token = http_parse_message(http_get('https://graph.facebook.com/oauth/access_token?' . $param))->body;
         if (is_object($error = json_decode($token))) {
             echo "<pre>Facebook login error message\n";
             echo $error->error->type . ":" . $error->error->message;
             exit;
         } else {
             $info = json_decode(http_parse_message(http_get('https://graph.facebook.com/me?' . $token))->body);
             $api_info = array();
             $api_info["openid"] = $info->id;
             $api_info["nickname"] = $info->name;
             if (preg_match("/^([_.0-9a-z-]+)@([0-9a-z][0-9a-z-]+\\.)+[a-z]{2,4}\$/i", $info->email)) {
                 if ($obj->user->checkMemberId($info->email, $obj)) {
                     $api_info["memberid"] = '';
                 } else {
                     $api_info["memberid"] = $info->email;
                 }
                 $api_info["email"] = $info->email;
             }
             $api_info['birthday'] = date('Y-m-d', strtotime($info->birthday));
             $api_info['sex'] = $info->gender == 'female' ? 'g' : 'b';
             $user = array();
             $user = $this->getOpenIdUser($info->id, 'facebook', $obj);
             if (empty($user['openid'])) {
                 $this->registerOpenId($api_info, 'facebook', $obj);
                 $user = $this->getOpenIdUser($info->id, 'facebook', $obj);
             }
             return $this->openIdUserLogin($user, $obj);
         }
         //$obj->http->redirectUrl($obj);
     }
     //Facebook Login end
 }
Esempio n. 18
0
    /**
     * This function will get the data from nmbs we need.
     * @param Request $request
     * @return <type>
     */
    protected function fetchData(Request $request)
    {
        $this->request = $request;
        include "getUA.php";
        $url = "http://hari.b-rail.be/Hafas/bin/extxml.exe";
        $request_options = array("referer" => "http://api.irail.be/", "timeout" => "30", "useragent" => $irailAgent);
        //first request: Getting the id of the right stations
        $postdata = '<?xml version="1.0 encoding="iso-8859-1"?>
<ReqC ver="1.1" prod="iRail API v1.0" lang="EN">
<LocValReq id="from" maxNr="1">
<ReqLoc match="' . $request->getFrom() . '" type="ST"/>
</LocValReq>
<LocValReq id="to" maxNr="1">
<ReqLoc match="' . $request->getTo() . '" type="ST"/>
</LocValReq>
</ReqC>';
        $post = http_post_data($url, $postdata, $request_options) or die("");
        $idbody = http_parse_message($post)->body;
        preg_match_all("/externalId=\"(.*?)\"/si", $idbody, $matches);
        $idfrom = $matches[1][0];
        $idto = $matches[1][1];
        //for now
        $trainsonly = "1111111111111111";
        $timeSel = 0;
        if ($request->getTimeSel() == "depart") {
            $timeSel = 0;
        } else {
            if (strcmp($request->getTimeSel(), "arrive") == 0) {
                $timeSel = 1;
            }
        }
        //now we're going to get the real data
        $postdata = '<?xml version="1.0 encoding="iso-8859-1"?>
<ReqC ver="1.1" prod="irail" lang="' . $request->getLang() . '">
<ConReq>
<Start min="0">
<Station externalId="' . $idfrom . '" distance="0">
</Station>
<Prod prod="' . $trainsonly . '">
</Prod>
</Start>
<Dest min="0">
<Station externalId="' . $idto . '" distance="0">
</Station>
</Dest>
<Via>
</Via>
<ReqT time="' . $request->getTime() . '" date="' . $request->getDate() . '" a="' . $timeSel . '">
</ReqT>
<RFlags b="' . $request->getResults() * $timeSel . '" f="' . $request->getResults() * -($timeSel - 1) . '">
</RFlags>
<GISParameters>
<Front>
</Front>
<Back>
</Back>
</GISParameters>
</ConReq>
</ReqC>';
        $post = http_post_data($url, $postdata, $request_options) or die("<br />NMBS/SNCB website timeout. Please <a href='..'>refresh</a>.");
        return http_parse_message($post)->body;
    }
Esempio n. 19
0
function FetchHTTP($url, $inHeaders = array(), &$outHeaders = array())
{
    static $isRetry = false;
    global $fetchHTTPErrorCaught;
    $wasRetry = $isRetry;
    $isRetry = false;
    $fetchHTTPErrorCaught = false;
    if (!isset($inHeaders['Connection'])) {
        $inHeaders['Connection'] = 'Keep-Alive';
    }
    $inHeaders['Accept-Encoding'] = 'gzip';
    $http_opt = array('timeout' => 60, 'connecttimeout' => 6, 'headers' => $inHeaders, 'compress' => true, 'redirect' => 3);
    //if ($eTag) $http_opt['etag'] = $eTag;
    $http_info = array();
    $fetchHTTPErrorCaught = false;
    $oldErrorReporting = error_reporting(error_reporting() | E_WARNING);
    set_error_handler('FetchHTTPError', E_WARNING);
    $data = http_parse_message(http_get($url, $http_opt, $http_info));
    restore_error_handler();
    error_reporting($oldErrorReporting);
    unset($oldErrorReporting);
    if (!$data) {
        $outHeaders = array();
        return false;
    }
    $outHeaders = array_merge(array('httpVersion' => $data->httpVersion, 'responseCode' => $data->responseCode, 'responseStatus' => $data->responseStatus), $data->headers);
    //if (isset($data->headers['Etag']))
    //    $eTag = $data->headers['Etag'];
    if ($fetchHTTPErrorCaught) {
        return false;
    }
    if (preg_match('/^2\\d\\d$/', $http_info['response_code']) > 0) {
        return $data->body;
    } elseif (!$wasRetry && isset($data->headers['Retry-After'])) {
        $delay = intval($data->headers['Retry-After'], 10);
        DebugMessage("Asked to wait {$delay} seconds for {$url}", E_USER_NOTICE);
        if ($delay > 0 && $delay <= 10) {
            sleep($delay);
        }
        $isRetry = true;
        return FetchHTTP($url, $inHeaders, $outHeaders);
    } else {
        return false;
    }
}
 public function post($url, $data = array())
 {
     $response = http_post($url, $data);
     $parsed = http_parse_message($response);
     return $parsed;
 }
Esempio n. 21
0
 public function getRawData($argsi, $type = 'product')
 {
     $url = $this->getUrl($argsi, $type);
     $body = http_parse_message(http_get($url));
     return $body->body;
 }
Esempio n. 22
0
    public static function getStationFromName($name, $lang)
    {
        //We can do a couple of things here:
        // * Match the name with something in the DB
        // * Give the name to hafas so that it returns us an ID which we can reuse - Doesn't work for external stations
        // * Do a hybrid mode
        // * match from location
        // * match railtime name
        //Let's go wih the hafas solution and get the location from it
        //fallback for wrong hafas information
        if (strtolower($name) == "brussels north" || strtolower($name) == "brussel noord" || strtolower($name) == "bruxelles nord") {
            return stations::getStationFromLocation(4.360854, 50.859658, $lang);
        }
        if (strtolower($name) == "vorst zuid") {
            return stations::getStationFromLocation(4.310025, 50.810158, $lang);
        }
        include "../includes/getUA.php";
        $url = "http://hari.b-rail.be/Hafas/bin/extxml.exe";
        $request_options = array("referer" => "http://api.irail.be/", "timeout" => "30", "useragent" => $irailAgent);
        $postdata = '<?xml version="1.0 encoding="iso-8859-1"?>
<ReqC ver="1.1" prod="iRail API v1.0" lang="' . $lang . '">
<LocValReq id="stat1" maxNr="1">
<ReqLoc match="' . $name . '" type="ST"/>
</LocValReq>
</ReqC>';
        $post = http_post_data($url, $postdata, $request_options) or die("");
        $idbody = http_parse_message($post)->body;
        preg_match("/x=\"(.*?)\".*?y=\"(.*?)\"/si", $idbody, $matches);
        $x = $matches[1];
        $y = $matches[2];
        preg_match("/(.)(.*)/", $x, $m);
        $x = $m[1] . "." . $m[2];
        preg_match("/(..)(.*)/", $y, $m);
        $y = $m[1] . "." . $m[2];
        return stations::getStationFromLocation($x, $y, $lang);
    }
Esempio n. 23
0
//echo $data . "<br>";
//echo $request_options . "<br>";
$body = http_parse_message($post)->body;
//This code fixes most hated issue #2 →→ You can buy me a beer in Ghent at anytime if you leave me a message at +32484155429
$dummy = preg_match("/(query\\.exe\\/..\\?seqnr=1&ident=.*?).OK.focus\" id=\"formular\"/si", $body, $matches);
if ($matches[1] != "") {
    //DEBUG:echo $matches[1];
    //scrape the date & time layout from $body
    preg_match("/value=\"(.., ..\\/..\\/..)\" onblur=\"checkWeekday/si", $body, $datelay);
    $datelay[1] = urlencode($datelay[1]);
    preg_match("/name=\"REQ0JourneyTime\" value=\"(..:..)\"/si", $body, $timelay);
    $timelay[1] = urlencode($timelay[1]);
    $passthrough_url = "http://hari.b-rail.be/HAFAS/bin/" . $matches[1] . "&queryPageDisplayed=yes&REQ0JourneyStopsS0A=1%26fromTypeStation%3Dhidden&REQ0JourneyStopsS0K=S-0N1&REQ0JourneyStopsZ0A=1%26toTypeStation%3Dhidden&REQ0JourneyStopsZ0K=S-1N1&REQ0JourneyDate=" . $datelay[1] . "&wDayExt0=Ma|Di|Wo|Do|Vr|Za|Zo&REQ0JourneyTime=" . $timelay[1] . "&REQ0HafasSearchForw=1&REQ0JourneyProduct_prod_list=" . $trainsonly . "&start=Submit";
    //DEBUG:echo "\n". $passthrough_url;
    $post = http_post_data($passthrough_url, null, $request_options);
    $body = http_parse_message($post)->body;
}
// check if nmbs planner is down
if (strstr($body, "[Serverconnection]") && strstr($body, "[Server]")) {
    $down = 1;
} else {
    $down = 0;
}
$body = strstr($body, '<table CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%" BGCOLOR="#FFFFFF">');
if ($body == "" && $down == 0) {
    header('Location: noresults');
} else {
    $body = str_replace('<table CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%" BGCOLOR="#FFFFFF">', '<table CELLSPACING="0" CELLPADDING="0" BORDER="0" BGCOLOR="#FFFFFF">', $body);
    $body = str_replace("<img ", "<img border=\"0\" ", $body);
    $body = str_replace("<td ", "<td NOWRAP ", $body);
    $body = str_replace("type=\"checkbox\"", "type=\"HIDDEN\"", $body);
Esempio n. 24
0
 protected function sendSocket($method, $url, $body = array())
 {
     $bodyString = "";
     if ($body) {
         $bodyString = json_encode($body, JSON_FORCE_OBJECT);
     }
     $length = strlen($bodyString);
     $data = '';
     $fp = fsockopen($this->url, null, $errno, $errstr, 30);
     if (!$fp) {
         echo "{$errstr} ({$errno})<br />\n";
     } else {
         $out = "{$method} {$url} HTTP/1.1\r\n";
         $out .= "Content-Length: {$length}\r\n";
         $out .= "Connection: Close\r\n\r\n{$bodyString}";
         fwrite($fp, $out);
         while (!feof($fp)) {
             $data .= fgets($fp, 1024);
         }
         fclose($fp);
     }
     $data = http_parse_message($data);
     if ($data->responseCode >= 200 && $data->responseCode < 300) {
         return $data->body;
     } else {
         throw new \Exception($data->body, $data->responseCode);
     }
 }
Esempio n. 25
0
/**
 * @param $url
 * @param bool $use_tidy
 * @return array
 */
function verif_url($url, $use_tidy = TRUE)
{
    global $cookies;
    static $purifier;
    static $loaded = false;
    $smarty = TikiLib::lib('smarty');
    $result = array();
    $get = get_from_dom($url->getElementsByTagName('get')->item(0));
    $post = get_from_dom($url->getElementsByTagName('post')->item(0));
    $xpath = $url->getElementsByTagName('xpath')->item(0)->textContent;
    $data = $url->getElementsByTagName('data')->item(0)->textContent;
    $urlstr = $url->getAttribute('src');
    if (extension_loaded('http')) {
        $options['timeout'] = 2;
        $options['connecttimeout'] = 2;
        $options['url'] = $url->getAttribute('src');
        $options['referer'] = $url->getAttribute('referer');
        $options['redirect'] = 0;
        $options['cookies'] = $cookies;
        $options['cookiestore'] = tempnam('/tmp/', 'tiki-tests');
        // Close the session to avoid timeout
        session_write_close();
        switch (strtolower($url->getAttribute('method'))) {
            case 'get':
                $buffer = http_get($urlstr, $options, $info);
                break;
            case 'post':
                $buffer = http_post_fields($urlstr, $post, NULL, $options, $info);
        }
        $headers = http_parse_headers($buffer);
        if (isset($headers['Set-Cookie'])) {
            foreach ($headers['Set-Cookie'] as $c) {
                TikiLib::parse_str($c, $cookies);
            }
        }
        $buffer = http_parse_message($buffer)->body;
    } elseif (extension_loaded('curl')) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $urlstr);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($curl, CURLOPT_TIMEOUT, 2);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_REFERER, $url->getAttribute('referer'));
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($curl, CURLOPT_USERAGENT, 'TikiTest');
        // We deal with the cookies
        $cookies_string = '';
        foreach ($cookies as $c => $v) {
            $cookies_string .= "{$c}={$v}; path=/;";
        }
        curl_setopt($curl, CURLOPT_COOKIE, $cookies_string);
        switch (strtolower($url->getAttribute('method'))) {
            case 'get':
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                break;
            case 'post':
                curl_setopt($curl, CURLOPT_POST, true);
                $post_string = '';
                foreach ($post as $p => $v) {
                    if ($post_string != '') {
                        $post_string .= '&';
                    }
                    $post_string .= "{$p}={$v}";
                }
                curl_setopt($curl, CURLOPT_POSTFIELDS, $post_string);
        }
        // Close the session to avoid timeout
        session_write_close();
        $http_response = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($http_response, 0, $header_size);
        $body = substr($http_response, $header_size);
        preg_match_all('|Set-Cookie: (.*);|U', $header, $cookies_array);
        foreach ($cookies_array[1] as $c) {
            $cookies_tmp .= "&{$c}";
        }
        TikiLib::parse_str($cookies_tmp, $cookies_titi);
        if (!is_array($cookies)) {
            $cookies = array();
        }
        $cookies = array_merge($cookies, $cookies_titi);
        $buffer = $body;
        curl_close($curl);
    }
    if (extension_loaded('tidy')) {
        $data = tidy_parse_string($data, array(), 'utf8');
        $buffer = tidy_parse_string($buffer, array(), 'utf8');
        if ($use_tidy) {
            tidy_diagnose($data);
            $result['ref_error_count'] = tidy_error_count($data);
            $result['ref_error_msg'] = tidy_get_error_buffer($data);
            tidy_diagnose($buffer);
            $result['replay_error_count'] = tidy_error_count($buffer);
            $result['replay_error_msg'] = tidy_get_error_buffer($buffer);
        }
    } else {
        if (!$loaded) {
            require_once 'lib/htmlpurifier_tiki/HTMLPurifier.tiki.php';
            $config = getHTMLPurifierTikiConfig();
            $purifier = new HTMLPurifier($config);
            $loaded = true;
        }
        if ($purifier) {
            $data = '<html><body>' . $purifier->purify($data) . '</body></html>';
            $buffer = '<html><body>' . $purifier->purify($buffer) . '</body></html>';
        }
        $result['ref_error_msg'] = tra('The Tidy extension is not present');
        $result['replay_error_msg'] = tra('The Tidy extension is not present');
    }
    // If we have a XPath then we extract the new DOM and print it in HTML
    if (trim($xpath) != '') {
        $dom_ref = DOMDocument::loadHTML($data);
        $xp_ref = new DomXPath($dom_ref);
        $res_ref = $xp_ref->query($xpath);
        $new_data = new DOMDocument('1.0');
        $root = $new_data->createElement('html');
        $root = $new_data->appendChild($root);
        $body = $new_data->createElement('html');
        $body = $root->appendChild($body);
        foreach ($res_ref as $ref) {
            $tmp = $new_data->importNode($ref, TRUE);
            $body->appendChild($tmp);
        }
        $data = $new_data->saveHTML();
        $dom_buffer = DOMDocument::loadHTML($buffer);
        $xp_buffer = new DomXPath($dom_buffer);
        $res_buffer = $xp_buffer->query($xpath);
        $new_buffer = new DOMDocument('1.0');
        $root = $new_buffer->createElement('html');
        $root = $new_buffer->appendChild($root);
        $body = $new_buffer->createElement('html');
        $body = $root->appendChild($body);
        foreach ($res_buffer as $ref) {
            $tmp = $new_buffer->importNode($ref, TRUE);
            $body->appendChild($tmp);
        }
        $buffer = $new_buffer->saveHTML();
    }
    $tmp = diff2($data, $buffer, "htmldiff");
    if (trim($xpath) != '') {
        $result['html'] = preg_replace(array("/<html>/", "/<\\/html>/"), array("<div style='overflow: auto; width:500px; text-align: center'> ", "</div>"), $tmp);
    } else {
        $result['html'] = preg_replace(array("/<html.*<body/U", "/<\\/body><\\/html>/U"), array("<div style='overflow: auto; width:500px; text-align: center' ", "</div>"), $tmp);
    }
    $result['url'] = $urlstr;
    $result['method'] = $url->getAttribute('method');
    if (strtolower($result['method']) == 'post') {
        $result['post'] = $post;
    }
    return $result;
}
Esempio n. 26
0
$password = $_POST['password'];
$client = $_POST['client'];
$fedid = array();
// connect to ldap server
global $ldap_connection_string;
$ldapconn = ldap_connect($ldap_connection_string) or die("Could not connect to LDAP server.");
if ($ldapconn) {
    #if (true) {
    $ldapbind = ldap_bind($ldapconn, $username, $password);
    #    $ldapbind = true;
    if ($ldapbind) {
        $authenticated = true;
        $fedid = generate_fedid($client, $username);
        $sessionString = urlencode('{"sessionId":"' . $fedid['sessionId'] . '","sessionKey":"' . $fedid['sessionKey'] . '","sessionToken":"' . $fedid['sessionToken'] . '"}');
        $url = "https://signin.aws.amazon.com/federation?Action=getSigninToken&Session={$sessionString}";
        $json_response = http_parse_message(http_get($url))->body;
        if (preg_match("/{\"SigninToken\":\"(.*)\"}/", $json_response, $matches)) {
            $signinToken = $matches[1];
            $loginurl = "https://signin.aws.amazon.com/federation?Action=login&Issuer=" . urlencode("http://www.appliedtrust.com") . "&Destination=" . urlencode("https://console.aws.amazon.com") . "&SigninToken=" . $signinToken;
        }
    } else {
        $authenticated = false;
    }
}
?>

<html>
</body>
<?php 
if ($authenticated === true) {
    echo "<h3>authentication successful</h3>";
Esempio n. 27
0
    private static function requestHafasXml($idfrom, $idto, $lang, $time, $date, $results, $timeSel, $typeOfTransport)
    {
        include "../includes/getUA.php";
        $url = "http://hari.b-rail.be/Hafas/bin/extxml.exe";
        $request_options = array("referer" => "http://api.irail.be/", "timeout" => "30", "useragent" => $irailAgent);
        if ($typeOfTransport == "trains") {
            $trainsonly = "0111111000000000";
        } else {
            if ($typeOfTransport == "all") {
                $trainsonly = "1111111111111111";
            } else {
                $trainsonly = "0111111000000000";
            }
        }
        if ($timeSel == "depart") {
            $timeSel = 0;
        } else {
            if ($timeSel == "arrive") {
                $timeSel = 1;
            } else {
                $timeSel = 1;
            }
        }
        //now we're going to get the real data
        $postdata = '<?xml version="1.0 encoding="iso-8859-1"?>
<ReqC ver="1.1" prod="iRail" lang="' . $lang . '">
<ConReq>
<Start min="0">
<Station externalId="' . $idfrom . '" distance="0">
</Station>
<Prod prod="' . $trainsonly . '">
</Prod>
</Start>
<Dest min="0">
<Station externalId="' . $idto . '" distance="0">
</Station>
</Dest>
<Via>
</Via>
<ReqT time="' . $time . '" date="' . $date . '" a="' . $timeSel . '">
</ReqT>
<RFlags b="' . $results * $timeSel . '" f="' . $results * -($timeSel - 1) . '">
</RFlags>
<GISParameters>
<Front>
</Front>
<Back>
</Back>
</GISParameters>
</ConReq>
</ReqC>';
        $post = http_post_data($url, $postdata, $request_options) or die("<br />NMBS/SNCB website timeout. Please <a href='..'>refresh</a>.");
        return http_parse_message($post)->body;
    }
Esempio n. 28
0
    function request($uri, $method="GET", $headers=null, $body='') {

	if (!isset($headers))
	    $headers = array();

	if ($method == "POST") {
	    if (!isset($header['Content-Type']))
		$headers['Content-Type'] = self::DEFAULT_POST_CONTENT_TYPE;
	}
	$is_form_encoded = (isset($headers) and
	    $headers['Content-Type'] == self::DEFAULT_POST_CONTENT_TYPE);

	$parameters = null;

	if ($is_form_encoded and isset($body))
	    parse_str($body,$parameters);

	$req = Request::from_consumer_and_token($this->consumer,
		$this->token, $method, $uri,
		$parameters, $body, $is_form_encoded);
	$req->sign_request($this->method, $this->consumer, $this->token);
	$headers = array_merge($headers, $req->to_header());

	$parsed = parse_url($uri);
	$realm = http_build_url(
	    array(
		"scheme" => $parsed['scheme'],
		"host"   => $parsed['host'],
		)
	    );

	if ($is_form_encoded) {
	    return http_parse_message(
		http_post_fields($uri, $parameters, null, array(headers => $headers))
	    )->body;
	} elseif ($method == "GET")  {
	    $uri = $req->to_url();
	    return http_get($uri, array(headers => $headers));
	} else {
	    $headers = $req->to_header($realm);
	    return http_head($uri, array(headers => $headers));
	}

	return http_request($method, $uri, $body, array(headers => $headers));
    }
Esempio n. 29
0
<?php

$clientId = Symphony::Configuration()->get('client_id', 'githuboauth');
$secret = Symphony::Configuration()->get('secret', 'githuboauth');
$redirectUrl = Symphony::Configuration()->get('token_redirect', 'githuboauth');
if (isset($_REQUEST['code'])) {
    $code = $_REQUEST['code'];
    $url = 'https://github.com/login/oauth/access_token';
    $post = 'client_id=' . $clientId . '&client_secret=' . $secret . '&code=' . $code;
    if (function_exists('http_post_data')) {
        $result = http_post_data($url, $post);
        $result = http_parse_message($result);
        $result = $result->body;
    } else {
        if (function_exists('curl_version')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $result = curl_exec($ch);
            curl_close($ch);
        } else {
            echo 'Failed to post HTTP.';
            exit;
        }
    }
    $headers = explode('&', trim($result));
    foreach ($headers as $item) {
        $header = explode('=', $item);
        if ($header[0] == 'access_token') {
            $token = $header[1];
Esempio n. 30
0
<?php 
echo $method;
?>
 Host Response:<br>
</b>
<pre>
<?php 
// Main function:
switch ($method) {
    case "GET":
        $response = http_get($url);
        break;
    case "POST":
        $response = http_post_data($url, $data);
        break;
    case "PUT":
        $response = http_put_data($url, $data);
        break;
    case "DELETE":
        echo "DELETE NOT SUPPORTED: {$url}";
        exit;
}
//list($head,$body) = explode("{",$response);
echo $response;
echo "<b><h3><br>JSon pretty print:<br></h3></b>";
$json = http_parse_message($response)->body;
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
?>
</pre>
</body>
</html>