getUri() public method

Get the URI for the next request
public getUri ( boolean $as_string = false ) : Zend_Uri_Http | string
$as_string boolean If true, will return the URI as a string
return Zend_Uri_Http | string
示例#1
0
 /**
  * Test we can SET and GET a URI as object
  *
  */
 public function testSetGetUriObject()
 {
     $uriobj = Zend_Uri::factory('http://www.zend.com:80/');
     $this->client->setUri($uriobj);
     $uri = $this->client->getUri();
     $this->assertTrue($uri instanceof Zend_Uri_Http, 'Returned value is not a Uri object as expected');
     $this->assertEquals($uri, $uriobj, 'Returned object is not the excepted Uri object');
 }
示例#2
0
 /**
  * Protected method that queries REST service and returns SimpleXML response set
  *
  * @param  string $service name of Audioscrobbler service file we're accessing
  * @param  string $params  parameters that we send to the service if needded
  * @throws Zend_Http_Client_Exception
  * @throws Zend_Service_Exception
  * @return SimpleXMLElement result set
  * @access protected
  */
 protected function _getInfo($service, $params = null)
 {
     $service = (string) $service;
     $params = (string) $params;
     if ($params === '') {
         $this->getHttpClient()->setUri("http://ws.audioscrobbler.com{$service}");
     } else {
         $this->getHttpClient()->setUri("http://ws.audioscrobbler.com{$service}?{$params}");
     }
     $response = $this->getHttpClient()->request();
     $responseBody = $response->getBody();
     if (preg_match('/No such path/', $responseBody)) {
         throw new Zend_Http_Client_Exception('Could not find: ' . $this->_client->getUri());
     } elseif (preg_match('/No user exists with this name/', $responseBody)) {
         throw new Zend_Http_Client_Exception('No user exists with this name');
     } elseif (!$response->isSuccessful()) {
         throw new Zend_Http_Client_Exception('The web service ' . $this->_client->getUri() . ' returned the following status code: ' . $response->getStatus());
     }
     set_error_handler(array($this, '_errorHandler'));
     if (!($simpleXmlElementResponse = simplexml_load_string($responseBody))) {
         restore_error_handler();
         $exception = new Zend_Service_Exception('Response failed to load with SimpleXML');
         $exception->error = $this->_error;
         $exception->response = $responseBody;
         throw $exception;
     }
     restore_error_handler();
     return $simpleXmlElementResponse;
 }
示例#3
0
 /**
  *
  * Private method that queries REST service and returns SimpleXML response set
  * @param string $service name of Audioscrobbler service file we're accessing
  * @param string $params parameters that we send to the service if needded
  * @return SimpleXML result set
  */
 private function getInfo($service, $params = NULL)
 {
     $service = (string) $service;
     $params = (string) $params;
     try {
         if ($params == "") {
             $this->_client->setUri("http://ws.audioscrobbler.com{$service}");
         } else {
             $this->_client->setUri("http://ws.audioscrobbler.com{$service}?{$params}");
         }
         if ($this->testing == TRUE) {
             $adapter = new Zend_Http_Client_Adapter_Test();
             $this->_client->setConfig(array('adapter' => $adapter));
             $adapter->setResponse($this->testing_response);
         }
         $request = $this->_client->request();
         $response = $request->getBody();
         if ($response == 'No such path') {
             throw new Zend_Http_Client_Exception('Could not find: ' . $this->_client->getUri());
         } else {
             if ($response == 'No user exists with this name.') {
                 throw new Zend_Http_Client_Exception('No user exists with this name');
             } else {
                 if ($request->isError()) {
                     throw new Zend_Http_Client_Exception('The web service ' . $this->_client->getUri() . ' returned the following status code: ' . $response->getStatus());
                 } else {
                     return simplexml_load_string($response);
                 }
             }
         }
     } catch (Zend_Http_Client_Exception $e) {
         throw $e;
     }
 }
 public function task(Zend_Http_Response $response, Zend_Http_Client $client)
 {
     $timerStart = microtime(true);
     get_headers($client->getUri());
     $timerEnd = microtime(true);
     $this->totalPages++;
     $this->totalTime += $timerEnd - $timerStart;
 }
示例#5
0
 /**
  * Test we can SET and GET a URI as object
  *
  */
 public function testSetGetUriObject()
 {
     $uriobj = new URI\URL('http://www.zend.com:80/');
     $this->_client->setUri($uriobj);
     $uri = $this->_client->getUri();
     $this->assertTrue($uri instanceof URI\URL, 'Returned value is not a Uri object as expected');
     $this->assertEquals($uri, $uriobj, 'Returned object is not the excepted Uri object');
 }
示例#6
0
 /**
  * Make sure we can set an array of object cookies
  *
  */
 public function testSetCookieObjectArray()
 {
     $this->client->setUri($this->baseuri . 'testCookies.php');
     $refuri = $this->client->getUri();
     $cookies = array('chocolate' => 'chips', 'crumble' => 'apple', 'another' => 'cookie');
     $this->client->setCookies($cookies);
     $res = $this->client->send();
     $this->assertEquals($res->getBody(), serialize($cookies), 'Response body does not contain the expected cookies');
 }
 /**
  * Get OpenSocial data for an OpenSocial URI
  *
  * Using the following syntax:
  * /people/{uid}/@all with params array('uid' => 'john.doe')
  * will cause the HTTP client to use the following uri:
  * /people/123%20abc/@all
  *
  * @example $client->get('/people/{uid}/@all', array('uid' => 'john.doe'));
  *
  * @param string $uri    (Prepared) OpenSocial URI
  * @param array  $params Data for prepared URI
  * @return array Models for OpenSocial data (/person returns OpenSocial_Model_Person objects, etc.)
  */
 public function get($uri, $params = array())
 {
     $uri = $this->_getPreparedUri($uri, $params);
     $uri = $this->_prependSlash($uri);
     $serviceType = $this->_getServiceTypeFromUri($uri);
     $uri = $this->_httpClient->getUri(true) . $uri;
     $response = $this->_httpClient->setUri($uri)->request(Zend_Http_Client::GET);
     return $this->_mapResponseToModels($serviceType, $response);
 }
 /**
  * Test that we can handle trailing space in location header
  *
  * @group ZF-11283
  * @link http://framework.zend.com/issues/browse/ZF-11283
  */
 public function testRedirectWithTrailingSpaceInLocationHeaderZF11283()
 {
     $this->_client->setUri('http://example.com/');
     $this->_client->setAdapter('Zend_Http_Client_Adapter_Test');
     $adapter = $this->_client->getAdapter();
     /* @var $adapter Zend_Http_Client_Adapter_Test */
     $response = "HTTP/1.1 302 Redirect\r\n" . "Content-Type: text/html; charset=UTF-8\r\n" . "Location: /test\r\n" . "Server: Microsoft-IIS/7.0\r\n" . "Date: Tue, 19 Apr 2011 11:23:48 GMT\r\n\r\n" . "RESPONSE";
     $adapter->setResponse($response);
     $res = $this->_client->request('GET');
     $lastUri = $this->_client->getUri();
     $this->assertEquals("/test", $lastUri->getPath());
 }
    /**
     * Private method that queries REST service and returns SimpleXML response set
     *
     * @param  string $service name of Audioscrobbler service file we're accessing
     * @param  string $params  parameters that we send to the service if needded
     * @throws Zend_Http_Client_Exception
     * @throws Zend_Service_Exception
     * @return SimpleXMLElement result set
     */
    private function getInfo($service, $params = null)
    {
        $service = (string) $service;
        $params  = (string) $params;

        if ($params === '') {
            $this->_client->setUri("http://ws.audioscrobbler.com{$service}");
        } else {
            $this->_client->setUri("http://ws.audioscrobbler.com{$service}?{$params}");
        }

        if ($this->_testing) {
            /**
             * @see Zend_Http_Client_Adapter_Test
             */
            require_once 'Zend/Http/Client/Adapter/Test.php';
            $adapter = new Zend_Http_Client_Adapter_Test();

            $this->_client->setConfig(array('adapter' => $adapter));

            $adapter->setResponse($this->_testingResponse);
        }

        $request  = $this->_client->request();
        $response = $request->getBody();

        if ($response == 'No such path') {
            throw new Zend_Http_Client_Exception('Could not find: ' . $this->_client->getUri());
        } else if ($response == 'No user exists with this name.') {
            throw new Zend_Http_Client_Exception('No user exists with this name');
        } else if ($request->isError()) {
            throw new Zend_Http_Client_Exception('The web service ' . $this->_client->getUri() . ' returned the following status code: ' . $response->getStatus());
        }

        set_error_handler(array($this, '_errorHandler'));

        if (!$simpleXmlElementResponse = simplexml_load_string($response)) {
            restore_error_handler();
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            $exception = new Zend_Service_Exception('Response failed to load with SimpleXML');
            $exception->error    = $this->_error;
            $exception->response = $response;
            throw $exception;
        }

        restore_error_handler();

        return $simpleXmlElementResponse;
    }
示例#10
0
 /**
  * Make sure we can set cookie objects with a jar
  *
  */
 public function testSetCookieObjectJar()
 {
     $this->client->setUri($this->baseuri . 'testCookies.php');
     $this->client->setCookieJar();
     $refuri = $this->client->getUri();
     $cookies = array(Zend_Http_Cookie::fromString('chocolate=chips', $refuri), Zend_Http_Cookie::fromString('crumble=apple', $refuri));
     $strcookies = array();
     foreach ($cookies as $c) {
         $this->client->setCookie($c);
         $strcookies[$c->getName()] = $c->getValue();
     }
     $res = $this->client->request();
     $this->assertEquals($res->getBody(), serialize($strcookies), 'Response body does not contain the expected cookies');
 }
 /**
  * 
  *
  * @param  $userId
  * @param  $attributes
  * @param  $spMetadata
  * @param  $idpMetadata
  * @return void
  */
 public function provisionUser($userId, $attributes, $spMetadata, $idpMetadata)
 {
     if (!$spMetadata['MustProvisionExternally']) {
         return;
     }
     // https://os.XXX.surfconext.nl/provisioning-manager/provisioning/jit.shtml?
     // provisionDomain=apps.surfnet.nl&provisionAdmin=admin%40apps.surfnet.nl&
     // provisionPassword=xxxxx&provisionType=GOOGLE&provisionGroups=true
     $client = new Zend_Http_Client($this->_url);
     $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json; charset=utf-8')->setParameterGet('provisionType', $spMetadata['ExternalProvisionType'])->setParameterGet('provisionDomain', $spMetadata['ExternalProvisionDomain'])->setParameterGet('provisionAdmin', $spMetadata['ExternalProvisionAdmin'])->setParameterGet('provisionPassword', $spMetadata['ExternalProvisionPassword'])->setParameterGet('provisionGroups', $spMetadata['ExternalProvisionGroups'])->setRawData(json_encode($this->_getData($userId, $attributes)))->request('POST');
     $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($userId, $idpMetadata['EntityId'], $spMetadata['EntityId'], null);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: Sent HTTP request to provision user using " . __CLASS__, $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: URI: " . $client->getUri(true), $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: REQUEST: " . $client->getLastRequest(), $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: RESPONSE: " . $client->getLastResponse(), $additionalInfo);
 }
 /**
  * @return $this
  * @throws Zend_Http_Client_Exception
  */
 protected function _applyFilters()
 {
     if (empty($this->_filters)) {
         return $this;
     }
     $uri = $this->_http->getUri(true);
     foreach ($this->_filters as $key => $value) {
         /** is some filters already applied */
         if (!strpos($uri, '?')) {
             $uri .= '?';
         } else {
             $uri .= '&';
         }
         $uri .= $key . '=' . $value;
     }
     $this->_http->setUri($uri);
     return $this;
 }
示例#13
0
 function post($url = null, $params = null, $config = array())
 {
     $_config = array();
     $arrParams = array();
     //-----------------
     // Установим URL
     if ($url) {
         $this->client->setUri($url);
     } else {
         $url = $this->client->getUri(TRUE);
     }
     // Установим параметры запроса
     if ($params) {
         if (is_string($params)) {
             // Преобразуем строку запроса в массив
             parse_str($params, $arrParams);
             $this->client->setParameterPost($arrParams);
         } else {
             $this->client->setParameterPost($params);
         }
     }
     // Установим заголовок Referer
     if (!empty($this->last_url)) {
         $_config['headers']['Referer'] = $this->last_url;
     }
     // Запомним последний URL
     $this->last_url = $url;
     // Обьединим два массива
     $config = $_config + $config;
     // Сохраним последнюю конфигурацию
     $this->last_config = $this->_setConfig($config);
     // Выполним запрос
     $response = $this->client->request("POST");
     $html = $response->getBody();
     // Запомним последний запрос в виде строки
     $this->last_request = $this->client->getLastRequest();
     // Запомним последний запрос в виде Zend_Http_Response
     $this->last_response = $this->client->getLastResponse();
     // Запомним последние полученные Сookies
     $this->last_cookies = $this->client->getCookieJar()->getAllCookies();
     return new PGPage($this->client->getUri(TRUE), $this->clean($html), $this);
 }
function getClientUrl(Zend_Http_Client $client)
{
    $string = '';
    try {
        $c = clone $client;
        /*
         * Assume there is nothing on 80 port.
         */
        $c->setUri('http://127.0.0.1');
        $c->getAdapter()->setConfig(array('timeout' => 0));
        $c->request();
    } catch (Exception $e) {
        $string = $c->getLastRequest();
        $string = substr($string, 4, strpos($string, "HTTP/1.1\r\n") - 5);
    }
    return $client->getUri(true) . $string;
}
示例#15
0
 /**
  * @param Zend_Http_Client $xhr
  */
 public static function browserReceive($xhr)
 {
     phpQuery::debug("[WebBrowser] Received from " . $xhr->getUri(true));
     // TODO handle meta redirects
     $body = $xhr->getLastResponse()->getBody();
     // XXX error ???
     if (strpos($body, '<!doctype html>') !== false) {
         $body = '<html>' . str_replace('<!doctype html>', '', $body) . '</html>';
     }
     $pq = phpQuery::newDocument($body);
     $pq->document->xhr = $xhr;
     $pq->document->location = $xhr->getUri(true);
     $refresh = $pq->find('meta[http-equiv=refresh]')->add('meta[http-equiv=Refresh]');
     if ($refresh->size()) {
         //			print htmlspecialchars(var_export($xhr->getCookieJar()->getAllCookies(), true));
         //			print htmlspecialchars(var_export($xhr->getLastResponse()->getHeader('Set-Cookie'), true));
         phpQuery::debug("Meta redirect... '{$refresh->attr('content')}'\n");
         // there is a refresh, so get the new url
         $content = $refresh->attr('content');
         $urlRefresh = substr($content, strpos($content, '=') + 1);
         $urlRefresh = trim($urlRefresh, '\'"');
         // XXX not secure ?!
         phpQuery::ajaxAllowURL($urlRefresh);
         //			$urlRefresh = urldecode($urlRefresh);
         // make ajax call, passing last $xhr object to preserve important stuff
         $xhr = phpQuery::ajax(array('type' => 'GET', 'url' => $urlRefresh, 'dataType' => 'html'), $xhr);
         if ($xhr->getLastResponse()->isSuccessful()) {
             // if all is ok, repeat this method...
             return call_user_func_array(array('phpQueryPlugin_WebBrowser', 'browserReceive'), array($xhr));
         }
     } else {
         return $pq;
     }
 }
示例#16
0
 function processJobFeedsGetPages()
 {
     //print 'asdsadas';
     header("Content-type: text/plain");
     print 'processJobFeedsGetPages';
     require_once 'Zend/Date.php';
     require_once 'Zend/Http/Client.php';
     require_once 'Zend/Http/Response.php';
     require_once 'Zend/Validate.php';
     require_once 'Zend/Validate/EmailAddress.php';
     $table = TABLE_PREFIX . 'cacaomail_mails_to_send';
     $q = "\n\t\tselect * from {$table} where \n\t\tfor_download = 1 \n\t\t\n\t\torder by RAND() DESC limit 30\n\t\t";
     //	$q = "select * from $table where 	feed_id=27 ";
     //print $q;
     //exit;
     $query = CI::db()->query($q);
     $links = $query->result_array();
     foreach ($links as $link) {
         $to_save = array();
         $to_save['id'] = $link['id'];
         $client = new Zend_Http_Client();
         //var_dump($link ["job_link"]);
         $link["job_link"] = str_ireplace(' ', '', $link["job_link"]);
         $link["job_link"] = stripslashes($link["job_link"]);
         //	var_dump($link ["job_link"]);
         $client->setUri($link["job_link"]);
         print "\n\n Getting:  {$link["id"]}  {$link["job_link"]} \n  ";
         $client->setConfig(array('maxredirects' => 300, 'useragent' => 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.4) Gecko/20060612 Firefox/1.5.0.4 Flock/0.7.0.17.1', 'timeout' => 30));
         //$redir_irl = $client->getUri();
         $response = $client->request();
         $the_actual_url = $client->getUri(true);
         $table = TABLE_PREFIX . 'cacaomail_mails_to_send';
         if (md5($link["job_link"]) != md5($the_actual_url)) {
             $the_actual_url = addslashes($the_actual_url);
             $q = " UPDATE  {$table} set job_link='{$the_actual_url}' where id={$link['id']} ";
             $query = CI::db()->query($q);
             $to_save['job_link'] = $the_actual_url;
         }
         //var_dump($client->getUri(true));
         //exit;
         $ctype = $response->getHeader('Content-type');
         if (is_array($ctype)) {
             $ctype = $ctype[0];
         }
         $body = $response->getBody();
         $body = str_ireplace('@recruitireland.com', ' ', $body);
         $body = str_ireplace('@totaljobsgroup.com', ' ', $body);
         $body = str_ireplace('@guardianunlimited.co.uk', ' ', $body);
         $body = str_ireplace('@sempo.org', ' ', $body);
         $body = str_ireplace('@import', ' ', $body);
         $body = str_ireplace('<img title="@" alt="@" src="../img/at.gif"/>', '@', $body);
         //if ($ctype == 'text/html' || $ctype == 'text/xml') {
         $email = CI::model('core')->extractEmailsFromString($body);
         if ($email[0] == '') {
             $body = html_entity_decode($body);
             $body = str_ireplace('@recruitireland.com', ' ', $body);
             $body = str_ireplace('@totaljobsgroup.com', ' ', $body);
             $body = str_ireplace('@sempo.org', ' ', $body);
             $body = str_ireplace('@import', ' ', $body);
             $body = str_ireplace('<img title="@" alt="@" src="../img/at.gif"/>', '@', $body);
             $email = CI::model('core')->extractEmailsFromString($body);
         }
         $email_to_save = false;
         if (!empty($email)) {
             foreach ($email as $eml_to_check) {
                 $validator = new Zend_Validate_EmailAddress();
                 if ($validator->isValid($eml_to_check)) {
                     $email_to_save = $eml_to_check;
                     $to_save['is_active'] = '1';
                 } else {
                 }
             }
             //print $email_to_save;
         } else {
             $email_to_save = false;
         }
         $to_save['job_email'] = $email_to_save;
         $body = htmlentities($body);
         //}
         print $to_save['job_email'] . "\n";
         if (strval($to_save['job_email']) != '') {
             $chexcs = $this->checkIfEmailExits($to_save['job_email']);
             if ($chexcs == false) {
                 print "Saved! \n\n";
                 $to_save['for_download'] = '0';
                 $to_save['job_src'] = $body;
                 //var_dump($to_save);
                 //exit;
                 $table = TABLE_PREFIX . 'cacaomail_mails_to_send';
                 $save = CI::model('core')->saveData($table, $to_save);
             } else {
                 $table = TABLE_PREFIX . 'cacaomail_mails_to_send';
                 $q = "update  {$table} set is_active=0,for_download=0    where job_email='{$to_save['job_email']}' ";
                 //print $q;
                 $query = CI::db()->query($q);
                 //$table2 = TABLE_PREFIX . 'cacaomail_mails_to_send_log';
                 //$q = "update $table2 where mail_id={$to_save['id']} ";
                 //$query = CI::db()->query ( $q );
                 print "Valid email {$to_save['job_email']}. Not saved! Cleaned up id: {$to_save['id']} \n\n";
             }
         } else {
             $table = TABLE_PREFIX . 'cacaomail_mails_to_send';
             $q = "update  {$table} set is_active=0,for_download=0   where id={$to_save['id']} ";
             //print $q;
             $query = CI::db()->query($q);
             //$table2 = TABLE_PREFIX . 'cacaomail_mails_to_send_log';
             //$q = "delete from $table2 where mail_id={$to_save['id']} ";
             //$query = CI::db()->query ( $q );
             print "Email not found at all ! Cleaned up id: {$to_save['id']} \n\n";
         }
         //echo $body;
         //exit;
     }
     //var_dump($links);
 }
示例#17
0
/**
 * For handling the HTTP connection to the phpproxy service
 * @see Zend_Http_Client
 */
require_once 'Zend/Http/Client.php';
/**
 * For handling the HTTP connection through the cURL
 * @see Zend_Http_Client_Adapter_Curl
 */
require_once 'Zend/Http/Client/Adapter/Curl.php';
iconv_set_encoding('input_encoding', 'UTF-8');
iconv_set_encoding('output_encoding', 'UTF-8');
iconv_set_encoding('internal_encoding', 'UTF-8');
$http = new Zend_Http_Client();
$http->setAdapter('Zend_Http_Client_Adapter_Curl');
if ($http->getUri() === null) {
    $result = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
    if ($result) {
        $result = '?' . $result;
    }
    $http->setUri($uri . $result);
}
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: ";
// browsers keep this blank.
示例#18
0
 /**
  * @param Zend_Http_Client $xhr
  */
 public static function browserDownload($xhr)
 {
     phpQuery::debug("[WebBrowser] Received from " . $xhr->getUri(true));
     // TODO handle meta redirects
     $body = $xhr->getLastResponse()->getBody();
     return $body;
 }
示例#19
0
$original_include_path = get_include_path();
$appPath = implode(PS, $paths);
set_include_path($appPath . PS . $original_include_path);
require 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
// config
$config = new Zend_Config_Xml('config.xml', 'production');
$frontendOptions = array('debug_header' => false, 'caching' => true, 'lifetime' => (int) $config->cache->graph->lifetime);
$backendOptions = array('cache_dir' => $config->cache->dir, 'file_name_prefix' => $config->cache->graph->prefix, 'cache_file_umask' => 0777);
$cache = Zend_Cache::factory('Output', 'File', $frontendOptions, $backendOptions);
header('Content-Type: image/png');
$url = $_GET['url'];
$http = new Zend_Http_Client($url);
$http->setConfig(array('timeout' => 5));
$http->setHeaders('User-Agent', $_SERVER['HTTP_USER_AGENT']);
$http->setHeaders('Referer', 'https://' . $http->getUri()->getHost() . '/');
$response = $http->request('GET');
$headers = $response->getHeaders();
if ($response->isSuccessful() !== false && $headers['Content-type'] == 'image/png') {
    $img = $response->getRawBody();
    $cacheID = md5($url);
    if (!$cache->start($cacheID)) {
        imagepng(imagecreatefromstring($img));
        $cache->end();
    }
} else {
    $img = imagecreatefrompng('./graph_unavailable.png');
    $cacheID = md5($url);
    if (!$cache->start($cacheID)) {
        imagepng($img);
        $cache->end();
示例#20
0
 /**
  * Executes render action
  *
  * @param sfWebRequest $request
  */
 public function executeRender(sfWebRequest $request)
 {
     include_once sfConfig::get('sf_lib_dir') . '/vendor/OAuth/OAuth.php';
     $this->memberApplication = Doctrine::getTable('MemberApplication')->findOneByApplicationAndMember($this->application, $this->member);
     $this->redirectUnless($this->memberApplication, '@application_info?id=' . $this->application->getId());
     $views = $this->application->getViews();
     $this->forward404Unless(isset($views['mobile']) && isset($views['mobile']['type']) && isset($views['mobile']['href']) && 'URL' === strtoupper($views['mobile']['type']));
     $method = $request->isMethod(sfWebRequest::POST) ? 'POST' : 'GET';
     $url = $request->getParameter('url', $views['mobile']['href']);
     $zendUri = Zend_Uri_Http::fromString($url);
     $queryString = $zendUri->getQuery();
     $zendUri->setQuery('');
     $zendUri->setFragment('');
     $url = $zendUri->getUri();
     $query = array();
     parse_str($queryString, $query);
     $params = array('opensocial_app_id' => $this->application->getId(), 'opensocial_owner_id' => $this->member->getId());
     $params = array_merge($query, $params);
     unset($params['lat']);
     unset($params['lon']);
     unset($params['geo']);
     if ($request->hasParameter('l') && $this->getUser()->hasFlash('op_opensocial_location')) {
         $method = 'p' == $request->getParameter('l') ? 'POST' : 'GET';
         $location = unserialize($this->getUser()->getFlash('op_opensocial_location'));
         if (isset($location['lat']) && isset($location['lon']) && isset($location['geo'])) {
             $params['lat'] = $location['lat'];
             $params['lon'] = $location['lon'];
             $params['geo'] = $location['geo'];
         }
     }
     $consumer = new OAuthConsumer(opOpenSocialToolKit::getOAuthConsumerKey(), null, null);
     $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin();
     $httpOptions = opOpenSocialToolKit::getHttpOptions();
     // for BC 1.2
     $isAutoConvert = sfConfig::get('op_opensocial_is_auto_convert_encoding', false);
     $client = new Zend_Http_Client();
     if ('POST' !== $method) {
         $client->setMethod(Zend_Http_Client::GET);
         $url .= '?' . OAuthUtil::build_http_query($params);
     } else {
         $postParameters = $isAutoConvert ? $this->getPostParameters() : $_POST;
         $params = array_merge($params, $postParameters);
         $client->setMethod(Zend_Http_Client::POST);
         $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED);
         $client->setRawData(OAuthUtil::build_http_query($params));
     }
     $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, $method, $url, $params);
     $oauthRequest->sign_request($signatureMethod, $consumer, null);
     $client->setConfig($httpOptions);
     $client->setUri($url);
     $client->setHeaders($oauthRequest->to_header());
     $client->setHeaders(opOpenSocialToolKit::getProxyHeaders($request, sfConfig::get('op_opensocial_is_strip_uid', true)));
     if ($isAutoConvert) {
         $client->setHeaders('Accept-Charset: UTF-8');
     } else {
         $client->setHeaders('Accept-Charset: Shift_JIS, UTF-8');
     }
     try {
         $response = $client->request();
     } catch (Zend_Http_Client_Exception $e) {
         $this->logMessage($e->getMessage(), 'err');
         return sfView::ERROR;
     }
     if ($response->isSuccessful()) {
         $contentType = $response->getHeader('Content-Type');
         if (preg_match('#^(text/html|application/xhtml\\+xml|application/xml|text/xml)#', $contentType, $match)) {
             if ($isAutoConvert) {
                 $this->response->setContentType($match[0] . '; charset=Shift_JIS');
             } else {
                 $this->response->setContentType($contentType);
             }
             $rewriter = new opOpenSocialMobileRewriter($this);
             $this->response->setContent($rewriter->rewrite($response->getBody(), $contentType, $isAutoConvert));
         } else {
             $this->response->setContentType($contentType);
             $this->response->setContent($response->getBody());
         }
         if ('test' === $this->context->getConfiguration()->getEnvironment()) {
             return sfView::NONE;
         }
         $this->response->send();
         exit;
     } elseif ($response->isRedirect() && ($location = $response->getHeader('location'))) {
         if (!Zend_Uri_Http::check($location)) {
             $uri = $client->getUri();
             if (strpos($location, '?') !== false) {
                 list($location, $query) = explode('?', $location, 2);
             } else {
                 $query = '';
             }
             $uri->setQuery($query);
             if (strpos($location, '/') === 0) {
                 $uri->setPath($location);
             } else {
                 $path = $uri->getPath();
                 $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
                 $uri->setPath($path . '/' . $location);
             }
             $location = $uri->getUri();
         }
         $this->redirect('@application_render?id=' . $this->application->id . '&url=' . urlencode($location));
     }
     return sfView::ERROR;
 }
示例#21
0
 /**
  *
  * @param Zend_Http_Client $client
  * @param array $client
  * @param boolean $client
  * @return stdClass
  */
 protected function _fetch(Zend_Http_Client $client, array $ids = array(), $useCache = true)
 {
     if ($useCache && $this->hasCache() && ($cache = $this->getCache())) {
         $ids[] = $client->getUri(true);
         $hash = sha1(implode('', $ids));
         if ($cache->contains($hash)) {
             $client->resetParameters(true);
             return Phoursquare_Response::decode($cache->fetch($hash));
         }
     }
     $response = new Phoursquare_Response($client->request());
     if (!$response->isSuccessful()) {
         throw new Exception($response->getErrorMessage());
     }
     $client->resetParameters(true);
     if ($useCache && $this->hasCache()) {
         $cache->save($hash, $response->getResponseBody(), false, $ids);
     }
     return Phoursquare_Response::decode($response->getResponseBody());
 }
 private function _authenticateHttp(Zend_Http_Client $http, $username, $password)
 {
     X_Debug::i("Authenticating HTTP Client");
     $oldUri = $http->getUri(true);
     $loginUri = "http://www.megavideo.com/?s=account";
     $http->setUri($loginUri);
     $response = $http->request();
     //X_Debug::i("Login response1: {$response->getHeadersAsString(true)}");
     $http->setMethod(Zend_Http_Client::POST)->setParameterPost(array('username' => $username, 'password' => $password, 'login' => '1'));
     $response = $http->request(Zend_Http_Client::POST);
     //X_Debug::i("Login response2: {$response->getHeadersAsString(true)}");
     $http->setUri($oldUri)->setMethod(Zend_Http_Client::GET);
     return $response;
 }