protected function _requireValidSchacHomeOrganization($responseAttributes)
 {
     if (!isset($responseAttributes[self::URN_MACE_TERENA_SCHACHOMEORG])) {
         return self::URN_MACE_TERENA_SCHACHOMEORG . " missing in attributes!";
     }
     $schacHomeOrganizationValues = $responseAttributes[self::URN_MACE_TERENA_SCHACHOMEORG];
     if (count($schacHomeOrganizationValues) === 0) {
         return self::URN_MACE_TERENA_SCHACHOMEORG . " has no values";
     }
     if (count($schacHomeOrganizationValues) > 1) {
         return self::URN_MACE_TERENA_SCHACHOMEORG . " has too many values";
     }
     $schacHomeOrganization = $schacHomeOrganizationValues[0];
     $reservedSchacHomeOrganization = $this->_isReservedSchacHomeOrganization($schacHomeOrganization);
     if ($reservedSchacHomeOrganization === TRUE) {
         return self::URN_MACE_TERENA_SCHACHOMEORG . " is reserved for another IdP!";
     }
     $validHostName = false;
     try {
         $uri = Zend_Uri_Http::fromString('http://' . $schacHomeOrganization);
         $validHostName = $uri->validateHost($schacHomeOrganization);
     } catch (Zend_Validate_Exception $e) {
     }
     if (!$validHostName) {
         return self::URN_MACE_TERENA_SCHACHOMEORG . " is not a valid hostname!";
     }
     // Passed all the checks, valid SHO!
     return false;
 }
 private function _getWechatOAuthUrl($appid, $scope, $callbackurl, $state)
 {
     $client = Zend_Uri_Http::fromString("https://open.weixin.qq.com/connect/oauth2/authorize");
     $client->addReplaceQueryParameters(array("appid" => $appid, "redirect_uri" => $callbackurl, "response_type" => "code", "scope" => $scope, "sate" => $state));
     $client->setFragment("wechat_redirect");
     return $client->getUri();
 }
    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the $value is a valid url that starts with http(s)://
     * and the hostname is a valid TLD
     *
     * @param  string $value
     * @throws Zend_Validate_Exception if a fatal error occurs for validation process
     * @return boolean
     */
    public function isValid($value)
    {
        if (!is_string($value)) {
            $this->_error(self::INVALID_URL);
             return false;
        }
		
        $this->_setValue($value);
        //get a Zend_Uri_Http object for our URL, this will only accept http(s) schemes
        try {
            $uriHttp = Zend_Uri_Http::fromString($value);
        } catch (Zend_Uri_Exception $e) {
            $this->_error(self::INVALID_URL);
            return false;
        }
        
        //if we have a valid URI then we check the hostname for valid TLDs, and not local urls
        $hostnameValidator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_DNS); //do not allow local hostnames, this is the default

        if (!$hostnameValidator->isValid($uriHttp->getHost())) {
            $this->_error(self::INVALID_URL);
            return false;
        }
        return true;
    }
Example #4
0
    public function testSimpleFromString()
    {
        $uri = 'http://www.zend.com';

        $obj = Zend_Uri_Http::fromString($uri);
        $this->assertEquals($uri, $obj->getUri(), 'getUri() returned value that differs from input');
    }
Example #5
0
 /**
  * Delete content of media/js and media/css folders to refresh with updated compressed/minified js/css content
  * If disabled, the updates are done each time an original file is updated. Can be resource overload on live website.
  * 
  * @param Mage_Core_Model_Observer $observer
  */
 public function regenerateMediaFiles($observer)
 {
     if (Mage::getStoreConfigFlag('uioptimization/general/cronupdate') && (Mage::getStoreConfigFlag('uioptimization/csscompression/enabled') || Mage::getStoreConfigFlag('uioptimization/jscompression/enabled'))) {
         // Clean up media/css and media/js folders and recreate the folders if necessary
         try {
             Mage::getModel('core/design_package')->cleanMergedJsCss();
             Mage::dispatchEvent('clean_media_cache_after');
         } catch (Exception $e) {
             Mage::logException($e);
             return;
         }
         $stores = Mage::app()->getStores();
         foreach ($stores as $id => $v) {
             $url = Zend_Uri_Http::fromString(Mage::app()->getStore($id)->getBaseUrl());
             // Recreate the js and css compressed file by using the normal process
             try {
                 $curl = new Zend_Http_Client_Adapter_Curl();
                 $curl->setCurlOption(CURLOPT_SSL_VERIFYPEER, false);
                 $curl->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1);
                 $curl->connect($url->getHost(), $url->getPort(), Mage_Core_Model_Store::isCurrentlySecure());
                 $curl->write(Zend_Http_Client::GET, $url);
                 $curl->close();
                 Mage::log('[Diglin_UIOptimization_Model_Observer] Update media js/css content for the different stores', ZEND_LOG::DEBUG);
             } catch (Exception $e) {
                 Mage::logException($e);
                 return;
             }
         }
     }
 }
Example #6
0
 /**
  * Process oauth related protocol information and return as an array
  *
  * @param string $authHeaderValue
  * @param string $contentTypeHeader
  * @param string $requestBodyString
  * @param string $requestUrl
  * @return array
  * merged array of oauth protocols and request parameters. eg :
  * <pre>
  * array (
  *         'oauth_version' => '1.0',
  *         'oauth_signature_method' => 'HMAC-SHA1',
  *         'oauth_nonce' => 'rI7PSWxTZRHWU3R',
  *         'oauth_timestamp' => '1377183099',
  *         'oauth_consumer_key' => 'a6aa81cc3e65e2960a4879392445e718',
  *         'oauth_signature' => 'VNg4mhFlXk7%2FvsxMqqUd5DWIj9s%3D'
  * )
  * </pre>
  */
 protected function _processRequest($authHeaderValue, $contentTypeHeader, $requestBodyString, $requestUrl)
 {
     $protocolParams = [];
     if (!$this->_processHeader($authHeaderValue, $protocolParams)) {
         return [];
     }
     if ($contentTypeHeader && 0 === strpos($contentTypeHeader, \Zend_Http_Client::ENC_URLENCODED)) {
         $protocolParamsNotSet = !$protocolParams;
         parse_str($requestBodyString, $protocolBodyParams);
         foreach ($protocolBodyParams as $bodyParamName => $bodyParamValue) {
             if (!$this->_isProtocolParameter($bodyParamName)) {
                 $protocolParams[$bodyParamName] = $bodyParamValue;
             } elseif ($protocolParamsNotSet) {
                 $protocolParams[$bodyParamName] = $bodyParamValue;
             }
         }
     }
     $protocolParamsNotSet = !$protocolParams;
     $queryString = \Zend_Uri_Http::fromString($requestUrl)->getQuery();
     $this->_extractQueryStringParams($protocolParams, $queryString);
     if ($protocolParamsNotSet) {
         $this->_fetchProtocolParamsFromQuery($protocolParams, $queryString);
     }
     // Combine request and header parameters
     return $protocolParams;
 }
Example #7
0
 /**
  * Generate a redirect URL from the allowable parameters and configured
  * values.
  *
  * @return string
  */
 public function getUrl()
 {
     $params = $this->assembleParams();
     $uri = Zend_Uri_Http::fromString($this->_consumer->getUserAuthorizationUrl());
     $uri->setQuery($this->_httpUtility->toEncodedQueryString($params));
     return $uri->getUri();
 }
 /**
  * Gets the provided endpoint
  * 
  * @return Zend_Uri_Http
  */
 public function getEndpoint()
 {
     if (empty($this->_endpoint)) {
         $this->_endpoint = Zend_Uri_Http::fromString(self::ENDPOINT_URL);
     }
     return $this->_endpoint;
 }
Example #9
0
 /**
  * 初始化趣乐平台地址
  * 
  * @param string $url
  */
 public function __construct($url = null)
 {
     if (empty($url)) {
         $this->_uri = self::$_defaultUri;
     } else {
         $this->_uri = Zend_Uri_Http::fromString($url);
     }
 }
 /**
  * Constructor
  */
 public function __construct()
 {
     $this->_config = new binumi_config();
     // We have to use the fromString method because the 'host' we pass in
     // may actually contain a port (e.g. 'blah.com:8080' not just 'blah.com')
     // so we can't just pass it to Zend_Uri_Http.setHost(), like one might
     // expect
     $url = $this->_config->get_scheme() . '://' . $this->_config->get_host();
     $this->_uri = Zend_Uri_Http::fromString($url);
 }
 public function execute($request)
 {
     $this->forward404Unless($request->hasParameter('url'));
     try {
         $zendUri = Zend_Uri_Http::fromString($request->getParameter('url'));
     } catch (Exception $e) {
         return sfView::ERROR;
     }
     $this->url = $zendUri->getUri();
     $this->proxys = sfConfig::get('op_mobile_proxys');
 }
Example #12
0
 /**
  * Retrieves and parses the charity's Website URL.
  *
  * @return Zend_Uri_Http The parsed URL
  */
 public function getWebsiteUri()
 {
     if ($uri = $this->getModel()->getWebsite()) {
         try {
             return Zend_Uri_Http::fromString($uri);
         } catch (Lucky_Donations_Exception $e) {
             return '';
         }
     } else {
         return false;
     }
 }
Example #13
0
 public function normaliseBaseSignatureUrl($url)
 {
     $uri = Zend_Uri_Http::fromString($url);
     if ($uri->getScheme() == 'http' && $uri->getPort() == '80') {
         $uri->setPort('');
     } elseif ($uri->getScheme() == 'https' && $uri->getPort() == '443') {
         $uri->setPort('');
     }
     $uri->setQuery('');
     $uri->setFragment('');
     $uri->setHost(strtolower($uri->getHost()));
     return $uri->getUri(true);
 }
 /**
  * Test if the Erfurt_Store_Adapter_Sparql resolves the graph URI to the correct service.
  */
 public function testSparqlWithDbPediaEndpoint()
 {
     $options = array('serviceUrl' => 'http://dbpedia.org/sparql', 'graphs' => array('http://dbpedia.org'));
     $adapter = new Erfurt_Store_Adapter_Sparql($options);
     // Use HTTP Client test adapter
     $httpAdapter = new Erfurt_TestHelper_Http_ClientAdapter();
     $httpAdapter->setResponse(new Zend_Http_Response(200, array('Content-type' => 'application/sparql-results+xml'), file_get_contents($this->_dataDir . 'sparqlDBpediaLeipzig.srx')));
     $adapter->setHttpAdapter($httpAdapter);
     $sparql = 'SELECT ?p ?o FROM <http://dbpedia.org> WHERE {<http://dbpedia.org/resource/Leipzig> ?p ?o} LIMIT 10';
     $result = $adapter->sparqlQuery($sparql);
     $serviceUrl = Zend_Uri_Http::fromString('http://dbpedia.org/sparql');
     $requestUrl = $httpAdapter->getLastRequestUri();
     $this->assertTrue(is_array($result));
     $this->assertEquals($serviceUrl->getHost(), $requestUrl->getHost());
     $this->assertEquals($serviceUrl->getPath(), $requestUrl->getPath());
     $this->assertEquals(10, count($result));
 }
 public function routeStartup(\Zend_Controller_Request_Abstract $request)
 {
     /** @var $request \Zend_Controller_Request_Http */
     if (!$request->isGet()) {
         return;
     }
     $host = 'http://' . $request->getHttpHost();
     $uri = \Zend_Uri_Http::fromString($host . $request->getRequestUri());
     $query = $uri->getQueryAsArray();
     if (!isset($query['_escaped_fragment_'])) {
         return;
     }
     $path = $uri->getPath() . ltrim($query['_escaped_fragment_'], '/');
     $uri->setPath($path);
     unset($query['_escaped_fragment_']);
     $uri->setQuery($query);
     $request->setRequestUri(str_replace($host, '', $uri->getUri()));
     $request->setPathInfo();
 }
Example #16
0
 /**
  * Returns true if the value is a valid url that starts with http(s)://
  * and the hostname is a valid TLD.
  *
  * @param  string $value
  * @return boolean
  */
 public function isValid($value)
 {
     // Invalid if not string.
     if (!is_string($value)) {
         $this->_error(self::INVALID_URL);
         return false;
     }
     $this->_setValue($value);
     try {
         // Try to parse a URL.
         $uriHttp = Zend_Uri_Http::fromString($value);
     } catch (Zend_Uri_Exception $e) {
         // Invalid if not URL.
         $this->_error(self::INVALID_URL);
         return false;
     }
     $hostnameValidator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_LOCAL);
     // Allow local URLs.
     if (!$hostnameValidator->isValid($uriHttp->getHost())) {
         $this->_error(self::INVALID_URL);
         return false;
     }
     return true;
 }
Example #17
0
 /**
  * Checks if the given URL has an accepted hostname.
  *
  * @param string $url
  * @return boolean
  */
 protected function hasAllowedHostname($url)
 {
     if (!$this->hasHostnameRestrictions()) {
         return true;
     }
     $hostname = Zend_Uri_Http::fromString($url)->getHost();
     // Transform the hostname to be able to use fnmatch() and to
     // ensure that the wildcard "*" does not match dots (".").
     $hostname = str_replace('.', '/', $hostname);
     foreach ($this->allowedHostnames as $acceptedHostname) {
         /* @var $acceptedHostname string */
         if (fnmatch(str_replace('.', '/', $acceptedHostname), $hostname, FNM_PATHNAME)) {
             return true;
         }
     }
     return false;
 }
 /**
  * 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']));
     $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);
     $method = $request->isMethod(sfWebRequest::POST) ? 'POST' : 'GET';
     $consumer = new OAuthConsumer(opOpenSocialToolKit::getOAuthConsumerKey(), null, null);
     $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin();
     $httpOptions = opOpenSocialToolKit::getHttpOptions();
     $client = new Zend_Http_Client();
     if ('POST' !== $method) {
         $client->setMethod(Zend_Http_Client::GET);
         $url .= '?' . OAuthUtil::build_http_query($params);
     } else {
         $params = array_merge($params, $request->getPostParameters());
         $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)));
     $response = $client->request();
     if ($response->isSuccessful()) {
         $contentType = $response->getHeader('Content-Type');
         if (preg_match('#^(text/html|application/xhtml\\+xml|application/xml|text/xml)#', $contentType, $match)) {
             header('Content-Type: ' . $match[0] . '; charset=Shift_JIS');
             echo opOpenSocialToolKit::rewriteBodyForMobile($this, $response->getBody());
             exit;
         } else {
             header('Content-Type: ' . $response->getHeader('Content-Type'));
             echo $response->getBody();
             exit;
         }
     }
     return sfView::ERROR;
 }
Example #19
0
 /**
  * @group ZF-11162
  */
 function testClientDoesNotModifyPassedUri()
 {
     $uri = Zend_Uri_Http::fromString('http://example.org/');
     $orig = clone $uri;
     $client = new Zend_Http_Client($uri);
     $this->assertEquals((string) $orig, (string) $uri);
 }
Example #20
0
 protected function _getClient($hostName, $key = null)
 {
     $uri = Zend_Uri_Http::fromString('https://example.com/ccm/admin/api/version/2/&type=json');
     $uri->setHost($hostName);
     $config = array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'curloptions' => array(CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSLVERSION => 3));
     $client = new Zend_Http_Client($uri, $config);
     if ($key) {
         $client->setParameterPost('apiKey', $key);
     }
     return $client;
 }
Example #21
0
 /**
  * Constructor
  *
  * @param  string $returnType
  * @return void
  */
 public function __construct($responseType = 'json')
 {
     $this->setResponseType($responseType);
     $this->_uri = Zend_Uri_Http::fromString("http://search.twitter.com");
     $this->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8');
 }
Example #22
0
 /**
  * @group ZF-11188
  * @see http://www.ietf.org/rfc/rfc2732.txt
  */
 public function testParserSupportsLiteralIpv6AddressesInUri()
 {
     $this->assertTrue(Zend_Uri_Http::fromString('http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html')->valid());
     $this->assertTrue(Zend_Uri_Http::fromString('http://[1080:0:0:0:8:800:200C:417A]/index.html')->valid());
     $this->assertTrue(Zend_Uri_Http::fromString('http://[3ffe:2a00:100:7031::1]')->valid());
     $this->assertTrue(Zend_Uri_Http::fromString('http://[1080::8:800:200C:417A]/foo')->valid());
     $this->assertTrue(Zend_Uri_Http::fromString('http://[::192.9.5.5]/ipng')->valid());
     $this->assertTrue(Zend_Uri_Http::fromString('http://[::FFFF:129.144.52.38]:80/index.html')->valid());
     $this->assertTrue(Zend_Uri_Http::fromString('http://[2010:836B:4179::836B:4179]')->valid());
 }
 /**
  * Uses the adapter to request the given url and returns
  * its response.
  *
  * Example:
  *
  *     $this->request('http://www.example.com/test.html');
  *
  * @param string $url
  * @return Zend_Http_Response
  */
 protected function request($url)
 {
     $this->adapter->connect('');
     $this->adapter->write('GET', Zend_Uri_Http::fromString($url));
     $response = $this->adapter->read();
     $this->adapter->close();
     return Zend_Http_Response::fromString($response);
 }
 public function __construct($uri = null)
 {
     if (null === $uri) {
         $uri = 'http://localhost/foo/bar/baz/2';
     }
     $uri = Zend_Uri_Http::fromString($uri);
     $this->_host = $uri->getHost();
     $this->_port = $uri->getPort();
     parent::__construct($uri);
 }
Example #25
0
 /**
  * Retrieve protocol and request parameters from request object
  *
  * @link http://tools.ietf.org/html/rfc5849#section-3.5
  * @return Mage_Oauth_Model_Server
  */
 protected function _fetchParams()
 {
     $authHeaderValue = $this->_request->getHeader('Authorization');
     if ($authHeaderValue && 'oauth' === strtolower(substr($authHeaderValue, 0, 5))) {
         $authHeaderValue = substr($authHeaderValue, 6);
         // ignore 'OAuth ' at the beginning
         foreach (explode(',', $authHeaderValue) as $paramStr) {
             $nameAndValue = explode('=', trim($paramStr), 2);
             if (count($nameAndValue) < 2) {
                 continue;
             }
             if ($this->_isProtocolParameter($nameAndValue[0])) {
                 $this->_protocolParams[rawurldecode($nameAndValue[0])] = rawurldecode(trim($nameAndValue[1], '"'));
             }
         }
     }
     $contentTypeHeader = $this->_request->getHeader(Zend_Http_Client::CONTENT_TYPE);
     if ($contentTypeHeader && 0 === strpos($contentTypeHeader, Zend_Http_Client::ENC_URLENCODED)) {
         $protocolParamsNotSet = !$this->_protocolParams;
         parse_str($this->_request->getRawBody(), $bodyParams);
         foreach ($bodyParams as $bodyParamName => $bodyParamValue) {
             if (!$this->_isProtocolParameter($bodyParamName)) {
                 $this->_params[$bodyParamName] = $bodyParamValue;
             } elseif ($protocolParamsNotSet) {
                 $this->_protocolParams[$bodyParamName] = $bodyParamValue;
             }
         }
     }
     $protocolParamsNotSet = !$this->_protocolParams;
     $url = $this->_request->getScheme() . '://' . $this->_request->getHttpHost() . $this->_request->getRequestUri();
     if ($queryString = Zend_Uri_Http::fromString($url)->getQuery()) {
         foreach (explode('&', $queryString) as $paramToValue) {
             $paramData = explode('=', $paramToValue);
             if (2 === count($paramData) && !$this->_isProtocolParameter($paramData[0])) {
                 $this->_params[rawurldecode($paramData[0])] = rawurldecode($paramData[1]);
             }
         }
     }
     if ($protocolParamsNotSet) {
         $this->_fetchProtocolParamsFromQuery();
     }
     return $this;
 }
Example #26
0
 /**
  * @param Zend_Uri_Http $uri
  * @param $relative
  * @return Zend_Uri_Http
  */
 function http_get_uri(Zend_Uri_Http $uri, $relative)
 {
     if (strpos($relative, 'http://') === 0 || strpos($relative, 'https://') === 0) {
         $uri = Zend_Uri_Http::fromString($relative);
     } else {
         $uri = clone $uri;
         $uri->setQuery(array());
         $parts = explode('?', $relative, 2);
         $relative = $parts[0];
         if ($relative[0] === '/') {
             $uri->setPath($relative);
         } else {
             $path = dirname($uri->getPath());
             if ($path === '/') {
                 $path = '';
             }
             $uri->setPath("{$path}/{$relative}");
         }
         if (isset($parts[1])) {
             $uri->setQuery($parts[1]);
         }
     }
     return $uri;
 }
        $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
        $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 {
 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;
     }
 }
Example #29
0
 /**
  * Performs a HTTP request using the specified method
  *
  * @param string $method The HTTP method for the request - 'GET', 'POST',
  *                       'PUT', 'DELETE'
  * @param string $url The URL to which this request is being performed
  * @param array $headers An associative array of HTTP headers
  *                       for this request
  * @param string $body The body of the HTTP request
  * @param string $contentType The value for the content type
  *                                of the request body
  * @param int $remainingRedirects Number of redirects to follow if request
  *                              s results in one
  * @return Zend_Http_Response The response object
  */
 public function performHttpRequest($method, $url, $headers = null, $body = null, $contentType = null, $remainingRedirects = null)
 {
     require_once 'Zend/Http/Client/Exception.php';
     if ($remainingRedirects === null) {
         $remainingRedirects = self::getMaxRedirects();
     }
     if ($headers === null) {
         $headers = array();
     }
     // Append a Gdata version header if protocol v2 or higher is in use.
     // (Protocol v1 does not use this header.)
     $major = $this->getMajorProtocolVersion();
     $minor = $this->getMinorProtocolVersion();
     if ($major >= 2) {
         $headers['GData-Version'] = $major + ($minor === null ? '.' + $minor : '');
     }
     // check the overridden method
     if (($method == 'POST' || $method == 'PUT') && $body === null && $headers['x-http-method-override'] != 'DELETE') {
         require_once 'Zend/Gdata/App/InvalidArgumentException.php';
         throw new Zend_Gdata_App_InvalidArgumentException('You must specify the data to post as either a ' . 'string or a child of Zend_Gdata_App_Entry');
     }
     if ($url === null) {
         require_once 'Zend/Gdata/App/InvalidArgumentException.php';
         throw new Zend_Gdata_App_InvalidArgumentException('You must specify an URI to which to post.');
     }
     $headers['Content-Type'] = $contentType;
     if (Zend_Gdata_App::getGzipEnabled()) {
         // some services require the word 'gzip' to be in the user-agent
         // header in addition to the accept-encoding header
         if (strpos($this->_httpClient->getHeader('User-Agent'), 'gzip') === false) {
             $headers['User-Agent'] = $this->_httpClient->getHeader('User-Agent') . ' (gzip)';
         }
         $headers['Accept-encoding'] = 'gzip, deflate';
     } else {
         $headers['Accept-encoding'] = 'identity';
     }
     // Make sure the HTTP client object is 'clean' before making a request
     // In addition to standard headers to reset via resetParameters(),
     // also reset the Slug and If-Match headers
     $this->_httpClient->resetParameters();
     $this->_httpClient->setHeaders(array('Slug', 'If-Match'));
     // Set the params for the new request to be performed
     $this->_httpClient->setHeaders($headers);
     require_once 'Zend/Uri/Http.php';
     $uri = Zend_Uri_Http::fromString($url);
     preg_match("/^(.*?)(\\?.*)?\$/", $url, $matches);
     $this->_httpClient->setUri($matches[1]);
     $queryArray = $uri->getQueryAsArray();
     foreach ($queryArray as $name => $value) {
         $this->_httpClient->setParameterGet($name, $value);
     }
     $this->_httpClient->setConfig(array('maxredirects' => 0));
     // Set the proper adapter if we are handling a streaming upload
     $usingMimeStream = false;
     $oldHttpAdapter = null;
     if ($body instanceof Zend_Gdata_MediaMimeStream) {
         $usingMimeStream = true;
         $this->_httpClient->setRawDataStream($body, $contentType);
         $oldHttpAdapter = $this->_httpClient->getAdapter();
         if ($oldHttpAdapter instanceof Zend_Http_Client_Adapter_Proxy) {
             require_once 'Zend/Gdata/HttpAdapterStreamingProxy.php';
             $newAdapter = new Zend_Gdata_HttpAdapterStreamingProxy();
         } else {
             require_once 'Zend/Gdata/HttpAdapterStreamingSocket.php';
             $newAdapter = new Zend_Gdata_HttpAdapterStreamingSocket();
         }
         $this->_httpClient->setAdapter($newAdapter);
     } else {
         $this->_httpClient->setRawData($body, $contentType);
     }
     try {
         $response = $this->_httpClient->request($method);
         // reset adapter
         if ($usingMimeStream) {
             $this->_httpClient->setAdapter($oldHttpAdapter);
         }
     } catch (Zend_Http_Client_Exception $e) {
         // reset adapter
         if ($usingMimeStream) {
             $this->_httpClient->setAdapter($oldHttpAdapter);
         }
         require_once 'Zend/Gdata/App/HttpException.php';
         throw new Zend_Gdata_App_HttpException($e->getMessage(), $e);
     }
     if ($response->isRedirect() && $response->getStatus() != '304') {
         if ($remainingRedirects > 0) {
             $newUrl = $response->getHeader('Location');
             $response = $this->performHttpRequest($method, $newUrl, $headers, $body, $contentType, $remainingRedirects);
         } else {
             require_once 'Zend/Gdata/App/HttpException.php';
             throw new Zend_Gdata_App_HttpException('Number of redirects exceeds maximum', null, $response);
         }
     }
     if (!$response->isSuccessful()) {
         require_once 'Zend/Gdata/App/HttpException.php';
         $exceptionMessage = 'Expected response code 200, got ' . $response->getStatus();
         if (self::getVerboseExceptionMessages()) {
             $exceptionMessage .= "\n" . $response->getBody();
         }
         $exception = new Zend_Gdata_App_HttpException($exceptionMessage);
         $exception->setResponse($response);
         throw $exception;
     }
     return $response;
 }
Example #30
0
 /**
  * Prepare valid uri.
  *
  * @param string $path
  * @return Zend_Uri_Http
  */
 public function prepareUri($path)
 {
     $uri = trim($this->getUrl(), '/') . '/' . ltrim($path, '/');
     $uriHttp = Zend_Uri_Http::fromString($uri);
     return $uriHttp;
 }