Ejemplo n.º 1
0
 /**
  * Returns true if and only if $value meets the validation requirements
  *
  * If $value fails validation, then this method returns false, and
  * getMessages() will return an array of messages that explain why the
  * validation failed.
  *
  * @param mixed $value the value to validate
  *
  * @throws Zend_Valid_Exception If validation of $value is impossible
  * @return boolean
  */
 public function isValid($value)
 {
     $value = (string) $value;
     $this->_setValue($value);
     if (!Zend_Uri_Http::check($value)) {
         $this->_error(self::MALFORMED_URL);
         return false;
     }
     return true;
 }
Ejemplo n.º 2
0
 /**
  * Send a GET HTTP Request
  *
  * @param  int $redirectMax Maximum number of HTTP redirections followed
  * @return Zend_Http_Response
  */
 public function get($redirectMax = 5)
 {
     /**
      * @todo Implement ability to send Query Strings
      */
     // Follow HTTP redirections, up to $redirectMax of them
     for ($redirect = 0; $redirect <= $redirectMax; $redirect++) {
         // Build the HTTP request
         $hostHeader = $this->_uri->getHost() . ($this->_uri->getPort() == 80 ? '' : ':' . $this->_uri->getPort());
         $request = array_merge(array('GET ' . $this->_uri->getPath() . '?' . $this->_uri->getQuery() . ' HTTP/1.0', 'Host: ' . $hostHeader, 'Connection: close'), $this->_headers);
         // Open a TCP connection
         $socket = $this->_openConnection();
         // Make the HTTP request
         fwrite($socket, implode("\r\n", $request) . "\r\n\r\n");
         // Fetch the HTTP response
         $response = $this->_read($socket);
         // If the HTTP response was a redirect, and we are allowed to follow additional redirects
         if ($response->isRedirect() && $redirect < $redirectMax) {
             // Fetch the HTTP response headers
             $headers = $response->getHeaders();
             // Attempt to find the Location header
             foreach ($headers as $headerName => $headerValue) {
                 // If we have a Location header
                 if (strtolower($headerName) == "location") {
                     // Set the URI to the new value
                     if (Zend_Uri_Http::check($headerValue)) {
                         // If we got a well formed absolute URI, set it
                         $this->setUri($headerValue);
                     } else {
                         // Split into path and query and set the query
                         list($headerValue, $query) = explode('?', $headerValue, 2);
                         $this->_uri->setQueryString($query);
                         if (strpos($headerValue, '/') === 0) {
                             // If we got just an absolute path, set it
                             $this->_uri->setPath($headerValue);
                         } else {
                             // Else, assume we have a relative path
                             $path = dirname($this->_uri->getPath());
                             $path .= $path == '/' ? $headerValue : "/{$headerValue}";
                             $this->_uri->setPath($path);
                         }
                     }
                     // Continue with the new redirected request
                     continue 2;
                 }
             }
         }
         // No more looping for HTTP redirects
         break;
     }
     // Return the HTTP response
     return $response;
 }
Ejemplo n.º 3
0
 /**
  * Create a new request object
  * 
  * @param Zend_Uri_Http|string $url    Target URL
  * @param string               $method HTTP request method - default is GET
  */
 public function __construct($uri, $method = 'GET')
 {
     if (!$uri instanceof Zend_Uri_Http) {
         if (!Zend_Uri_Http::check($uri)) {
             require_once 'Spizer/Exception.php';
             throw new Spizer_Exception("'{$uri}' is not a valid HTTP URL");
         }
         $uri = Zend_Uri::factory($uri);
     }
     $this->_uri = $uri;
     $this->_method = $method;
 }
Ejemplo n.º 4
0
 /**
  * Set up the test case
  *
  */
 protected function setUp()
 {
     if (defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') && Zend_Uri_Http::check(TESTS_ZEND_HTTP_CLIENT_BASEURI)) {
         $this->baseuri = TESTS_ZEND_HTTP_CLIENT_BASEURI;
         if (substr($this->baseuri, -1) != '/') {
             $this->baseuri .= '/';
         }
         $uri = $this->baseuri . $this->getName() . '.php';
         $this->client = new Zend_Http_Client($uri, $this->config);
     } else {
         // Skip tests
         $this->markTestSkipped("Zend_Http_Client dynamic tests are not enabled in TestConfiguration.php");
     }
 }
Ejemplo n.º 5
0
 public static function suite()
 {
     $suite = new PHPUnit_Framework_TestSuite('Zend Framework - Zend');
     $suite->addTestSuite('Zend_Http_Client_StaticTest');
     if (defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') && Zend_Uri_Http::check(TESTS_ZEND_HTTP_CLIENT_BASEURI)) {
         $suite->addTestSuite('Zend_Http_Client_SocketTest');
         $suite->addTestSuite('Zend_Http_Client_SocketKeepaliveTest');
     } else {
         $suite->addTestSuite('Zend_Http_Client_Skip_SocketTest');
     }
     $suite->addTestSuite('Zend_Http_Client_TestAdapterTest');
     if (defined('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY') && TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY) {
         $suite->addTestSuite('Zend_Http_Client_ProxyAdapterTest');
     } else {
         $suite->addTestSuite('Zend_Http_Client_Skip_ProxyAdapterTest');
     }
     //$suite->addTestSuite('Zend_Http_Client_CurlTest');
     return $suite;
 }
 /**
  * Set up the test case
  *
  */
 protected function setUp()
 {
     if (defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') && Zend_Uri_Http::check(TESTS_ZEND_HTTP_CLIENT_BASEURI)) {
         $this->baseuri = TESTS_ZEND_HTTP_CLIENT_BASEURI;
         if (substr($this->baseuri, -1) != '/') {
             $this->baseuri .= '/';
         }
         $name = $this->getName();
         if (($pos = strpos($name, ' ')) !== false) {
             $name = substr($name, 0, $pos);
         }
         $uri = $this->baseuri . $name . '.php';
         $this->_adapter = new $this->config['adapter']();
         $this->client = new Zend_Http_Client($uri, $this->config);
         $this->client->setAdapter($this->_adapter);
     } else {
         // Skip tests
         $this->markTestSkipped("Zend_Http_Client dynamic tests are not enabled in TestConfiguration.php");
     }
 }
Ejemplo n.º 7
0
 public function setUp()
 {
     if (defined('TESTS_Zend_Feed_Pubsubhubbub_BASEURI') && Zend_Uri_Http::check(TESTS_Zend_Feed_Pubsubhubbub_BASEURI)) {
         $this->_baseuri = TESTS_Zend_Feed_Pubsubhubbub_BASEURI;
         if (substr($this->_baseuri, -1) != '/') {
             $this->_baseuri .= '/';
         }
         $name = $this->getName();
         if (($pos = strpos($name, ' ')) !== false) {
             $name = substr($name, 0, $pos);
         }
         $uri = $this->_baseuri . $name . '.php';
         $this->_adapter = new $this->_config['adapter']();
         $this->_client = new Zend_Http_Client($uri, $this->_config);
         $this->_client->setAdapter($this->_adapter);
         Zend_Feed_Pubsubhubbub::setHttpClient($this->_client);
         $this->_subscriber = new Zend_Feed_Pubsubhubbub_Subscriber();
         $this->_subscriber->setStorage(new Zend_Feed_Pubsubhubbub_Storage_Filesystem());
     } else {
         // Skip tests
         $this->markTestSkipped("Zend_Feed_Pubsubhubbub_Subscriber dynamic tests'\n            . ' are not enabled in TestConfiguration.php");
     }
 }
Loader::helper('mime');
$error = array();
// load all the incoming fields into an array
$incoming_urls = array();
if (!function_exists('iconv_get_encoding')) {
    $errors[] = t('Remote URL import requires the iconv extension enabled on your server.');
}
if (count($errors) == 0) {
    for ($i = 1; $i < 6; $i++) {
        $this_url = trim($_REQUEST['url_upload_' . $i]);
        // did we get anything?
        if (!strlen($this_url)) {
            continue;
        }
        // validate URL
        if (Zend_Uri_Http::check($this_url)) {
            // URL appears to be good... add it
            $incoming_urls[] = $this_url;
        } else {
            $errors[] = Loader::helper('text')->specialchars($this_url) . t(' is not a valid URL.');
        }
    }
    if (!$valt->validate('import_remote')) {
        $errors[] = $valt->getErrorMessage();
    }
    if (count($incoming_urls) < 1) {
        $errors[] = t('You must specify at least one valid URL.');
    }
}
$import_responses = array();
// if we haven't gotten any errors yet then try to process the form
Ejemplo n.º 9
0
 /**
  * Run the crawler until we hit the last URL
  *
  * @param string $url URL to start crawling from
  */
 public function run($url)
 {
     if (!Zend_Uri_Http::check($url)) {
         require_once 'Spizer/Exception.php';
         throw new Spizer_Exception("'{$url}' is not a valid HTTP URI");
     }
     $this->_baseUri = Zend_Uri::factory($url);
     $this->_queue->append($url);
     // Set the default logger if not already set
     if (!$this->logger) {
         require_once 'Spizer/Logger/Xml.php';
         $this->logger = new Spizer_Logger_Xml();
     }
     // Go!
     while ($request = $this->_queue->next()) {
         $this->logger->startPage();
         $this->logger->logRequest($request);
         // Prepare HTTP client for next request
         $this->_httpClient->resetParameters();
         $this->_httpClient->setUri($request->getUri());
         $this->_httpClient->setMethod($request->getMethod());
         $this->_httpClient->setHeaders($request->getAllHeaders());
         $this->_httpClient->setRawData($request->getBody());
         // Send request, catching any HTTP related issues that might happen
         try {
             $response = new Spizer_Response($this->_httpClient->request());
         } catch (Zend_Exception $e) {
             fwrite(STDERR, "Error executing request: {$e->getMessage()}.\n");
             fwrite(STDERR, "Request information:\n");
             fwrite(STDERR, "  {$request->getMethod()} {$request->getUri()}\n");
             fwrite(STDERR, "  Referred by: {$request->getReferrer()}\n");
         }
         $this->logger->logResponse($response);
         // Call handlers
         $this->_callHandlers($request, $response);
         // End page
         $this->logger->endPage();
         ++$this->_requestCounter;
         // Wait if a delay was set
         if (isset($this->_config['delay'])) {
             sleep($this->_config['delay']);
         }
     }
 }
Ejemplo n.º 10
0
 /**
  * Cloud to be notified of updates of the feed
  * Ignored if atom is used
  *
  * @param  string|Zend_Uri_Http $uri
  * @param  string               $procedure procedure to call, e.g. myCloud.rssPleaseNotify
  * @param  string               $protocol  protocol to use, e.g. soap or xml-rpc
  * @return Zend_Feed_Builder_Header
  * @throws Zend_Feed_Builder_Exception
  */
 public function setCloud($uri, $procedure, $protocol)
 {
     if (is_string($uri) && Zend_Uri_Http::check($uri)) {
         $uri = Zend_Uri::factory($uri);
     }
     if (!$uri instanceof Zend_Uri_Http) {
         /**
          * @see Zend_Feed_Builder_Exception
          */
         #require_once 'Zend/Feed/Builder/Exception.php';
         throw new Zend_Feed_Builder_Exception('Passed parameter is not a valid HTTP URI');
     }
     if (!$uri->getPort()) {
         $uri->setPort(80);
     }
     $this->offsetSet('cloud', array('uri' => $uri, 'procedure' => $procedure, 'protocol' => $protocol));
     return $this;
 }
Ejemplo n.º 11
0
 /**
  * Preform a SetExpressCheckout PayPal API call, starting an Express 
  * Checkout process. 
  * 
  * This call is expected to return a token which can be used to redirect
  * the user to PayPal's transaction approval page
  *
  * @param  float  $amount
  * @param  string $returnUrl
  * @param  string $cancelUrl
  * @param  array  $params    Additional parameters
  * @return Zend_Service_PayPal_Response
  */
 public function setExpressCheckout($amount, $returnUrl, $cancelUrl, $params = array())
 {
     $amount = (double) $amount;
     if (!Zend_Uri_Http::check($returnUrl)) {
         require_once 'Zend/Service/PayPal/Exception.php';
         throw new Zend_Service_PayPal_Exception('Return URL is not a valid URL');
     }
     if (!Zend_Uri_Http::check($cancelUrl)) {
         require_once 'Zend/Service/PayPal/Exception.php';
         throw new Zend_Service_PayPal_Exception('Cancel URL is not a valid URL');
     }
     if (!is_array($params)) {
         require_once 'Zend/Service/PayPal/Exception.php';
         throw new Zend_Service_PayPal_Exception('$params is expected to be an array, ' . gettype($params) . ' given');
     }
     $this->prepare('SetExpressCheckout');
     $this->httpClient->setParameterPost(array('AMT' => $amount, 'RETURNURL' => $returnUrl, 'CANCELURL' => $cancelUrl));
     foreach ($params as $k => $v) {
         $this->httpClient->setParameterPost(strtoupper($k), $v);
     }
     return $this->process();
 }
Ejemplo n.º 12
0
 /**
  * Set the URI for the next request
  *
  * @param Zend_Uri_Http|string $uri
  */
 public function setUri($uri)
 {
     if (is_string($uri) && Zend_Uri_Http::check($uri)) {
         $uri = Zend_Uri_Http::factory($uri);
     }
     if ($uri instanceof Zend_Uri_Http) {
         // We have no ports, set the defaults
         if (!$uri->getPort()) {
             $uri->setPort($uri->getScheme() == 'https' ? 443 : 80);
         }
         $this->uri = $uri;
     } else {
         throw new Zend_Http_Exception('Passed parameter is not a valid HTTP URI.');
     }
 }
Ejemplo n.º 13
0
 /**
  * Extract the path, file and query string from the URI
  *
  * @param  string $uri
  * @return void
  */
 protected function setURI($uri)
 {
     $this->uri = $uri;
     if (Zend_Uri_Http::check($uri)) {
         $uri = Zend_Uri::factory($uri);
         $this->query_string = $uri->getQuery();
         $this->path = dirname($uri->getPath());
         $this->file = basename($uri->getPath());
     } else {
         list($this->path, $this->query_string) = explode('?', $uri, 2);
         $this->file = basename($this->path);
         $this->path = dirname($this->path);
     }
     if (!$this->path) {
         $this->path = '/';
     }
     parse_str($this->query_string, $this->get);
 }
Ejemplo n.º 14
0
 /**
  * Send the HTTP request and return an HTTP response object
  *
  * @param string $method
  * @return Zend_Http_Response
  */
 public function request($method = null)
 {
     if (!$this->uri instanceof Zend_Uri_Http) {
         throw new Zend_Http_Client_Exception("No valid URI has been passed to the client");
     }
     if ($method) {
         $this->setMethod($method);
     }
     $this->redirectCounter = 0;
     $response = null;
     // Send the first request. If redirected, continue.
     do {
         // Clone the URI and add the additional GET parameters to it
         $uri = clone $this->uri;
         $uri_params = array();
         parse_str($uri->getQuery(), $uri_params);
         $uri->setQuery(array_merge($uri_params, $this->paramsGet));
         $body = $this->prepare_body();
         $headers = $this->prepare_headers();
         $request = implode("\r\n", $headers) . "\r\n" . $body;
         $this->last_request = $request;
         // Open the connection, send the request and read the response
         $this->adapter->connect($uri->getHost(), $uri->getPort(), $uri->getScheme() == 'https' ? true : false);
         $this->adapter->write($this->method, $uri, $this->config['httpversion'], $headers, $body);
         $response = Zend_Http_Response::factory($this->adapter->read());
         // Load cookies into cookie jar
         if (isset($this->Cookiejar)) {
             $this->Cookiejar->addCookiesFromResponse($response, $uri);
         }
         // If we got redirected, look for the Location header
         if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
             // Check whether we send the exact same request again, or drop the parameters
             // and send a GET request
             if ($response->getStatus() == 303 || !$this->config['strictredirects'] && ($response->getStatus() == 302 || $response->getStatus() == 301)) {
                 $this->resetParameters();
                 $this->setMethod(self::GET);
             }
             // If we got a well formed absolute URI
             if (Zend_Uri_Http::check($location)) {
                 $this->setHeaders('host', null);
                 $this->setUri($location);
             } else {
                 // Split into path and query and set the query
                 list($location, $query) = explode('?', $location, 2);
                 $this->uri->setQueryString($query);
                 // Else, if we got just an absolute path, set it
                 if (strpos($location, '/') === 0) {
                     $this->uri->setPath($location);
                     // Else, assume we have a relative path
                 } else {
                     // Get the current path directory, removing any trailing slashes
                     $path = rtrim(dirname($this->uri->getPath()), "/");
                     $this->uri->setPath($path . '/' . $location);
                 }
             }
             $this->redirectCounter++;
         } else {
             // If we didn't get any location, stop redirecting
             break;
         }
     } while ($this->redirectCounter < $this->config['maxredirects']);
     return $response;
 }
Ejemplo n.º 15
0
 /**
  * Checks if the given value is a valid URL.
  *
  * @param string $value
  * @return boolean True if a valid URL was passed, false otherwise.
  */
 protected function isUrl($value)
 {
     return Zend_Uri_Http::check($value);
 }
Ejemplo n.º 16
0
 /**
  * Send the HTTP request and return an HTTP response object
  *
  * @param string $method
  * @return Zend_Http_Response
  */
 public function request($method = null)
 {
     $this->redirectCounter = 0;
     $response = null;
     // Send the first request. If redirected, continue.
     do {
         $response = parent::request($method);
         // Load cookies into cookie jar
         if (isset($this->Cookiejar)) {
             $this->Cookiejar->addCookiesFromResponse($response, $this->uri);
         }
         // If we got redirected, look for the Location header
         if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
             // Check whether we send the exact same request again, or drop the parameters
             // and send a GET request
             if ($response->getStatus() == 303 || !$this->doStrictRedirects && ($response->getStatus() == 302 || $response->getStatus() == 301)) {
                 $this->resetParameters();
                 $this->setMethod(self::METHOD_GET);
             }
             // If we got a well formed absolute URI
             if (Zend_Uri_Http::check($location)) {
                 $this->setUri($location);
             } else {
                 // Split into path and query and set the query
                 list($location, $query) = explode('?', $location, 2);
                 $this->uri->setQueryString($query);
                 // Else, if we got just an absolute path, set it
                 if (strpos($location, '/') === 0) {
                     $this->uri->setPath($location);
                     // Else, assume we have a relative path
                 } else {
                     // Get the current path directory, removing any trailing slashes
                     $path = rtrim(dirname($this->uri->getPath()), "/");
                     $this->uri->setPath($path . '/' . $location);
                 }
             }
             $this->redirectCounter++;
         } else {
             // If we didn't get any location, stop redirecting
             break;
         }
     } while ($this->redirectCounter < $this->maxRedirects);
     return $response;
 }
Ejemplo n.º 17
0
 /**
  * Send the HTTP request and return an HTTP response object
  *
  * @param string $method
  * @return Zend_Http_Response
  * @throws Zend_Http_Client_Exception
  */
 public function request($method = null)
 {
     if (!$this->uri instanceof Zend_Uri_Http) {
         /** @see Zend_Http_Client_Exception */
         require_once 'Zend/Http/Client/Exception.php';
         throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
     }
     if ($method) {
         $this->setMethod($method);
     }
     $this->redirectCounter = 0;
     $response = null;
     // Make sure the adapter is loaded
     if ($this->adapter == null) {
         $this->setAdapter($this->config['adapter']);
     }
     // Send the first request. If redirected, continue.
     do {
         // Clone the URI and add the additional GET parameters to it
         $uri = clone $this->uri;
         if (!empty($this->paramsGet)) {
             $query = $uri->getQuery();
             if (!empty($query)) {
                 $query .= '&';
             }
             $query .= http_build_query($this->paramsGet, null, '&');
             $uri->setQuery($query);
         }
         $body = $this->_prepareBody();
         $headers = $this->_prepareHeaders();
         // Open the connection, send the request and read the response
         $this->adapter->connect($uri->getHost(), $uri->getPort(), $uri->getScheme() == 'https' ? true : false);
         $this->last_request = $this->adapter->write($this->method, $uri, $this->config['httpversion'], $headers, $body);
         $response = $this->adapter->read();
         if (!$response) {
             /** @see Zend_Http_Client_Exception */
             require_once 'Zend/Http/Client/Exception.php';
             throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
         }
         $response = Zend_Http_Response::fromString($response);
         if ($this->config['storeresponse']) {
             $this->last_response = $response;
         }
         // Load cookies into cookie jar
         if (isset($this->cookiejar)) {
             $this->cookiejar->addCookiesFromResponse($response, $uri);
         }
         // If we got redirected, look for the Location header
         if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
             // Check whether we send the exact same request again, or drop the parameters
             // and send a GET request
             if ($response->getStatus() == 303 || !$this->config['strictredirects'] && ($response->getStatus() == 302 || $response->getStatus() == 301)) {
                 $this->resetParameters();
                 $this->setMethod(self::GET);
             }
             // If we got a well formed absolute URI
             if (Zend_Uri_Http::check($location)) {
                 $this->setHeaders('host', null);
                 $this->setUri($location);
             } else {
                 // Split into path and query and set the query
                 if (strpos($location, '?') !== false) {
                     list($location, $query) = explode('?', $location, 2);
                 } else {
                     $query = '';
                 }
                 $this->uri->setQuery($query);
                 // Else, if we got just an absolute path, set it
                 if (strpos($location, '/') === 0) {
                     $this->uri->setPath($location);
                     // Else, assume we have a relative path
                 } else {
                     // Get the current path directory, removing any trailing slashes
                     $path = $this->uri->getPath();
                     $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
                     $this->uri->setPath($path . '/' . $location);
                 }
             }
             ++$this->redirectCounter;
         } else {
             // If we didn't get any location, stop redirecting
             break;
         }
     } while ($this->redirectCounter < $this->config['maxredirects']);
     return $response;
 }
Ejemplo n.º 18
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;
 }
Ejemplo n.º 19
0
 /**
  * Delete a cookie according to it's name and domain. If no name is specified,
  * all cookies from this domain will be cleared out.
  *
  * @param string|Zend_Uri_Http $domain
  * @param string $cookie_name 
  * @return boolean true if cookie was deleted.
  */
 public function deleteCookies($domain, $cookie_name = null)
 {
     $ret = false;
     $path = '/';
     if ($domain instanceof Zend_Uri_Http) {
         $path = dirname($domain->getPath());
         $domain = $domain->getHost();
     } elseif (is_string($domain) && Zend_Uri_Http::check($domain)) {
         $domain = Zend_Uri_Http::factory($domain);
         $path = dirname($domain->getPath());
         $domain = $domain->getHost();
     }
     // If we have a cookie's name, delete only this one
     if (isset($cookie_name) && isset($this->cookies[$domain][$path][$cookie_name])) {
         unset($this->cookies[$domain][$path][$cookie_name]);
         $ret = true;
         // If we only got a URI, clear all cookies matching this URI.
     } else {
         $cookies = $this->_matchPath($this->_matchDomain($domain), $path);
         foreach ($cookies as $cookie) {
             if (isset($this->cookies[$cookie->getDomain()][$cookie->getPath])) {
                 unset($this->cookies[$cookie->getDomain()][$cookie->getPath]);
                 $ret = true;
                 if (count($this->cookies[$cookie->getDomain()]) == 0) {
                     unset($this->cookies[$cookie->getDomain()]);
                 }
             }
         }
     }
     return $ret;
 }
 function importFile($fileUrl)
 {
     $u = new User();
     $cf = Loader::helper('file');
     $fp = FilePermissions::getGlobal();
     if (!$fp->canAddFiles()) {
         die(t("Unable to add files."));
     }
     //$valt = Loader::helper('validation/token');
     Loader::library("file/importer");
     Loader::library('3rdparty/Zend/Http/Client');
     Loader::library('3rdparty/Zend/Uri/Http');
     $file = Loader::helper('file');
     Loader::helper('mime');
     $error = array();
     // load all the incoming fields into an array
     $this_url = $fileUrl;
     // validate URL
     if (Zend_Uri_Http::check($this_url)) {
         // URL appears to be good... add it
         $incoming_urls[] = $this_url;
     } else {
         $errors[] = '"' . $this_url . '"' . t(' is not a valid URL.');
     }
     //}
     //if (!$valt->validate('import_remote')) {
     //	$errors[] = $valt->getErrorMessage();
     //}
     if (count($incoming_urls) < 1) {
         $errors[] = t('You must specify at least one valid URL.');
     }
     $import_responses = array();
     // if we haven't gotten any errors yet then try to process the form
     if (count($errors) < 1) {
         // itterate over each incoming URL adding if relevant
         foreach ($incoming_urls as $this_url) {
             // try to D/L the provided file
             // This all sets up the CURL actions to check the page
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $this_url);
             curl_setopt($ch, CURLOPT_HEADER, true);
             curl_setopt($ch, CURLOPT_NOBODY, true);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
             curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
             //follow up to 10 redirections - avoids loops
             $data = curl_exec($ch);
             $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
             // Get the HTTP Code
             // Get final redirected URL, will be the same if URL is not redirected
             $new_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
             curl_close($ch);
             // Array of HTTP status codes. Trim down if you would like to.
             $codes = array(0 => 'Domain Not Found', 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported');
             if (isset($codes[$http_code])) {
                 if ($codes[$http_code] == "OK") {
                     $client = new Zend_Http_Client($this_url);
                     $response = $client->request();
                     if ($response->isSuccessful()) {
                         $uri = Zend_Uri_Http::fromString($this_url);
                         $fname = '';
                         $fpath = $file->getTemporaryDirectory();
                         // figure out a filename based on filename, mimetype, ???
                         if (preg_match('/^.+?[\\/]([-\\w%]+\\.[-\\w%]+)$/', $uri->getPath(), $matches)) {
                             // got a filename (with extension)... use it
                             $fname = $matches[1];
                         } else {
                             if (!is_null($response->getHeader('Content-Type'))) {
                                 // use mimetype from http response
                                 $fextension = MimeHelper::mimeToExtension($response->getHeader('Content-Type'));
                                 if ($fextension === false) {
                                     $errors[] = t('Unknown mime-type: ') . $response->getHeader('Content-Type');
                                 } else {
                                     // make sure we're coming up with a unique filename
                                     do {
                                         // make up a filename based on the current date/time, a random int, and the extension from the mime-type
                                         $fname = date('d-m-Y_H:i_') . mt_rand(100, 999) . '.' . $fextension;
                                     } while (file_exists($fpath . '/' . $fname));
                                 }
                             }
                         }
                         //else {
                         // if we can't get the filename from the file itself OR from the mime-type I'm not sure there's much else we can do
                         //}
                         if (strlen($fname)) {
                             // write the downloaded file to a temporary location on disk
                             $handle = fopen($fpath . '/' . $fname, "w");
                             fwrite($handle, $response->getBody());
                             fclose($handle);
                             // import the file into concrete
                             if ($fp->canAddFileType($cf->getExtension($fname))) {
                                 $fi = new FileImporter();
                                 $resp = $fi->import($fpath . '/' . $fname, $fname, $fr);
                             } else {
                                 $resp = FileImporter::E_FILE_INVALID_EXTENSION;
                             }
                             if (!$resp instanceof FileVersion) {
                                 $errors[] .= $fname . ': ' . FileImporter::getErrorMessage($resp) . "\n";
                             } else {
                                 $import_responses[] = $resp;
                             }
                             // clean up the file
                             unlink($fpath . '/' . $fname);
                         } else {
                             // could not figure out a file name
                             $errors[] = t('Could not determine the name of the file at ') . $this_url;
                         }
                     } else {
                         // warn that we couldn't download the file
                         $errors[] = t('There was an error downloading ') . $this_url;
                     }
                 }
             } else {
                 $errors[] = t("Error connecting to file's server, file skipped");
             }
         }
     }
     //print_r($errors);
     if ($resp instanceof FileVersion) {
         return $resp;
     }
 }
Ejemplo n.º 21
0
 /**
  * Magic method to validate google map link
  * @param mixed $mValue
  * @return string
  * @throws AM_Model_Db_Element_Data_Exception
  */
 protected function _addGoogleLinkToMap($mValue)
 {
     $mValue = (string) $mValue;
     if (!Zend_Uri_Http::check($mValue)) {
         throw new AM_Model_Db_Element_Data_Exception(sprintf('Wrong parameter "%s" given. It must be an valid URL.', self::DATA_KEY_HTML5_GOOGLE_LINK_TO_MAP));
     }
     return $mValue;
 }