public function getCausas()
 {
     $cliente = new \Zend\Http\Client('http://civil.poderjudicial.cl', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true));
     $headers = $cliente->getRequest()->getHeaders();
     $cookies = new Zend\Http\Cookies($headers);
     $cliente->setMethod('GET');
     $response = $cliente->send();
     $cliente->setUri('http://civil.poderjudicial.cl/CIVILPORWEB/AtPublicoViewAccion.do?tipoMenuATP=1');
     $cookies->addCookiesFromResponse($response, $cliente->getUri());
     $response = $cliente->send();
     echo '<pre>';
     print_r($response);
     echo '</pre>';
 }
 /**
  * HumHub API
  * 
  * @param string $action
  * @param array $params
  * @return array
  */
 public static function request($action, $params = [])
 {
     if (!Yii::$app->params['humhub']['apiEnabled']) {
         return [];
     }
     $url = Yii::$app->params['humhub']['apiUrl'] . '/' . $action;
     $params['version'] = urlencode(Yii::$app->version);
     $params['installId'] = Setting::Get('installationId', 'admin');
     $url .= '?';
     foreach ($params as $name => $value) {
         $url .= urlencode($name) . '=' . urlencode($value) . "&";
     }
     try {
         $http = new \Zend\Http\Client($url, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => CURLHelper::getOptions(), 'timeout' => 30));
         $response = $http->send();
         $json = $response->getBody();
     } catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $ex) {
         Yii::error('Could not connect to HumHub API! ' . $ex->getMessage());
         return [];
     } catch (Exception $ex) {
         Yii::error('Could not get HumHub API response! ' . $ex->getMessage());
         return [];
     }
     try {
         return Json::decode($json);
     } catch (\yii\base\InvalidParamException $ex) {
         Yii::error('Could not parse HumHub API response! ' . $ex->getMessage());
         return [];
     }
 }
 /**
  * Returns page XML/JSON content from remote web as array
  *
  * CURLOPT_HEADER - Include header in result? (0 = yes, 1 = no)
  * CURLOPT_RETURNTRANSFER - (true = return, false = print) data
  *
  * @param	string	$url	"http://domain.tld"
  * @param	array	$params	GET params
  * @throws	\Exception when cURL us not installed
  * @throws	\Exception when Json cannot be decoded
  * 			or the encoded data is deeper than the recursion limit.
  * @throws	\Exception when response body contains error element
  * @throws	\Exception when reponse status code is not 200
  * @throws	\Exception when content is not JSON neither XML
  * @return	array
  */
 public function getRequestDataResponseAsArray($url, array $params)
 {
     $url = $this->buildQuery($url, $params);
     if (!function_exists('curl_init')) {
         throw new \Exception('cURL is not installed!');
     }
     $curlAdapterConfig = array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true, CURLOPT_USERAGENT => "Mozilla/5.0", CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYHOST => $this->trustSSLHost ? 0 : 2, CURLOPT_SSL_VERIFYPEER => $this->trustSSLHost ? 0 : 1));
     $client = new \Zend\Http\Client($url, $curlAdapterConfig);
     $response = $client->send();
     // Response head error handling
     $responseStatusCode = $response->getStatusCode();
     if ($responseStatusCode !== 200) {
         throw new \Exception("Response status code: " . $responseStatusCode);
     }
     //
     $output = $response->getBody();
     $dataArray = array();
     if ($this->isJson($output)) {
         $dataArray = \Zend\Json\Json::decode($output, \Zend\Json\Json::TYPE_ARRAY);
         if ($dataArray === NULL) {
             throw new \Exception('Json cannot be decoded or the encoded data is deeper than the recursion limit.');
         }
     } elseif ($this->isXml($output)) {
         $xml = simplexml_load_string($output, "SimpleXMLElement", LIBXML_NOCDATA);
         $json = \Zend\Json\Json::encode($xml);
         $dataArray = \Zend\Json\Json::decode($json, \Zend\Json\Json::TYPE_ARRAY);
     } else {
         throw new \Exception('Content is not JSON neither XML');
     }
     return $dataArray;
 }
 /**
  * Get Country User
  *
  * @param EventObserver $observer
  */
 public function execute(EventObserver $observer)
 {
     if (!$this->_customerSession->getLocated()) {
         //$clientIP = $this->_request->getClientIp();
         /*
          * Set static Ip to test
          *
          * DE : 194.55.30.46
          * VN : 123.30.215.27
          * PL : 212.77.98.9
          * SG : 202.157.143.72
          *
          **/
         $clientIP = '123.30.215.27';
         $uri = 'http://freegeoip.net/json/' . $clientIP;
         $httpClient = new \Zend\Http\Client();
         $httpClient->setUri($uri);
         $httpClient->setOptions(array('timeout' => 30));
         try {
             $response = \Zend\Json\Decoder::decode($httpClient->send()->getBody());
             $this->_customerSession->setLocationData($response);
             $this->_customerSession->setLocated(true);
         } catch (\Exception $e) {
             $this->_logger->critical($e);
         }
     }
 }
Example #5
0
 public static function send()
 {
     $me = new self("global");
     $sent = array();
     $pastlink = new FutureLink_PastUI();
     $feed = $pastlink->feed();
     $items = array();
     //we send something only if we have something to send
     if (empty($feed->feed->entry) == false) {
         foreach ($feed->feed->entry as &$item) {
             if (empty($item->futurelink->href) || isset($sent[$item->futurelink->hash])) {
                 continue;
             }
             $sent[$item->futurelink->hash] = true;
             $client = new Zend\Http\Client($item->futurelink->href, array('timeout' => 60));
             if (!empty($feed->feed->entry)) {
                 $client->setParameterPost(array('protocol' => 'futurelink', 'metadata' => json_encode($feed)));
                 try {
                     $client->setMethod(Zend\Http\Request::METHOD_POST);
                     $response = $client->send();
                     $request = $client->getLastResponse();
                     $result = $response->getBody();
                     $resultJson = json_decode($response->getBody());
                     //Here we add the date last updated so that we don't have to send it if not needed, saving load time.
                     if (!empty($resultJson->feed) && $resultJson->feed == "success") {
                         $me->addItem(array('dateLastUpdated' => $item->pastlink->dateLastUpdated, 'pastlinklinkHash' => $item->pastlink->hash, 'futurelinkHash' => $item->futurelink->hash));
                     }
                     $items[$item->pastlink->text] = $result;
                 } catch (Exception $e) {
                 }
             }
         }
         return $items;
     }
 }
 {
     return in_array(strtolower($needle), array_map('strtolower', $haystack));
 }
 /**
  Please send me: array( 'uri'=> '', 'method'=>''[, 'curloptions'=> array( ... ) ])
  I will throw an Exception if something goes wrong so no need to validate
  But you can decide whether you wnat me to do it or not
  */
 public static function sendRequest($arrayParms, $throwEx = true)
 {
     Utils::arrayKeyExists(array('url', 'method'), $arrayParms);
     $client = new \Zend\Http\Client($arrayParms['url']);
     $client->setMethod($arrayParms['method']);
     switch ($arrayParms['method']) {
         case POST:
             Utils::arrayKeyExists('payload', $arrayParms);
             $client->setParameterPost($arrayParms['payload']);
             break;
         case GET:
             Utils::arrayKeyExists('payload', $arrayParms);
             $client->setParameterGet($arrayParms['payload']);
             break;
     }
     $adapter = new \Zend\Http\Client\Adapter\Curl();
     $curloptions = array(CURLOPT_POST => 1, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_SSL_VERIFYHOST => FALSE);
     if (array_key_exists('curloptions', $arrayParms)) {
         $curloptions = array_merge($curloptions, $arrayParms['curloptions']);
     }
     $adapter->setOptions(array('curloptions' => $curloptions));
     $client->setAdapter($adapter);
     $response = $client->send();
     if ($response->isSuccess()) {
Example #7
0
 public function __invoke($par)
 {
     $config = $this->getController()->getServiceLocator()->get('config');
     $lang = $this->getController()->getEvent()->getRouteMatch()->getParam('lang', 'en');
     if (empty($config['geocoder_photon_url'])) {
         throw new \InvalidArgumentException('Now Service-Adress for Geo-Service available');
     }
     $client = new \Zend\Http\Client($config['geocoder_photon_url']);
     $client->setMethod('GET');
     $osmTags = ['tourism', 'aeroway', 'railway', 'amenity', 'historic', 'tunnel', 'mountain_pass', 'leisure', 'natural', 'bridge', 'waterway'];
     $osmTags = array_map(function ($i) {
         return urlencode('!' . $i);
     }, $osmTags);
     $uri = sprintf('%s?q=%s&lang=%s&osm_tag=%s', $config['geocoder_photon_url'], urlencode($par), $lang, implode('&osm_tag=', $osmTags));
     $client->setUri($uri);
     $response = $client->send();
     $result = $response->getBody();
     $result = json_decode($result);
     $result = $result->features;
     foreach ($result as $key => $val) {
         $row = ['name' => property_exists($val->properties, 'name') ? $val->properties->name : '', 'postcode' => property_exists($val->properties, 'postcode') ? $val->properties->postcode : '', 'city' => property_exists($val->properties, 'city') ? $val->properties->city : '', 'street' => property_exists($val->properties, 'street') ? $val->properties->street : '', 'state' => property_exists($val->properties, 'state') ? $val->properties->state : '', 'country' => property_exists($val->properties, 'country') ? $val->properties->country : '', 'coordinates' => implode(":", $val->geometry->coordinates), 'osm_key' => property_exists($val->properties, 'osm_key') ? $val->properties->osm_key : '', 'osm_value' => property_exists($val->properties, 'osm_value') ? $val->properties->osm_value : '', 'osm_id' => property_exists($val->properties, 'osm_id') ? $val->properties->osm_id : '', 'data' => json_encode($val)];
         $r[] = $row;
     }
     return $r;
 }
 /**
  * Sends a request and returns a response
  *
  * @param CartRecover_Request $request
  * @return Cart_Recover_Response
  */
 public function sendRequest(CartRecover_Request $request)
 {
     $this->client->setUri($request->getUri());
     $this->client->setParameterGet($request->getParams());
     $this->client->setMethod($request->getMethod());
     $this->client->setHeaders(array('Accept' => 'application/json'));
     $this->response = $this->client->send();
     if ($this->response->getHeaders()->get('Content-Type')->getFieldValue() != 'application/json') {
         throw new CartRecover_Exception_UnexpectedValueException("Unknown response format.");
     }
     $body = json_decode($this->response->getContent(), true);
     $response = new CartRecover_Response();
     $response->setRawResponse($this->response->toString());
     $response->setBody($body);
     $response->setHeaders($this->response->getHeaders()->toArray());
     $response->setStatus($this->response->getReasonPhrase(), $this->response->getStatusCode());
     return $response;
 }
 /**
  * Installs latest compatible module version
  *
  * @param type $moduleId
  */
 public function install($moduleId)
 {
     $modulePath = Yii::getAlias(Yii::$app->params['moduleMarketplacePath']);
     if (!is_writable($modulePath)) {
         throw new HttpException(500, Yii::t('AdminModule.libs_OnlineModuleManager', 'Module directory %modulePath% is not writeable!', array('%modulePath%' => $modulePath)));
     }
     $moduleInfo = $this->getModuleInfo($moduleId);
     if (!isset($moduleInfo['latestCompatibleVersion'])) {
         throw new Exception(Yii::t('AdminModule.libs_OnlineModuleManager', "No compatible module version found!"));
     }
     $moduleDir = $modulePath . DIRECTORY_SEPARATOR . $moduleId;
     if (is_dir($moduleDir)) {
         $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($moduleDir, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
         foreach ($files as $fileinfo) {
             $todo = $fileinfo->isDir() ? 'rmdir' : 'unlink';
             $todo($fileinfo->getRealPath());
         }
         rmdir($moduleDir);
         #throw new HttpException(500, Yii::t('AdminModule.libs_OnlineModuleManager', 'Module directory for module %moduleId% already exists!', array('%moduleId%' => $moduleId)));
     }
     // Check Module Folder exists
     $moduleDownloadFolder = Yii::getAlias("@runtime/module_downloads");
     if (!is_dir($moduleDownloadFolder)) {
         if (!@mkdir($moduleDownloadFolder)) {
             throw new Exception("Could not create module download folder!");
         }
     }
     $version = $moduleInfo['latestCompatibleVersion'];
     // Download
     $downloadUrl = $version['downloadUrl'];
     $downloadTargetFileName = $moduleDownloadFolder . DIRECTORY_SEPARATOR . basename($downloadUrl);
     try {
         $http = new \Zend\Http\Client($downloadUrl, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => CURLHelper::getOptions(), 'timeout' => 30));
         $response = $http->send();
         file_put_contents($downloadTargetFileName, $response->getBody());
     } catch (Exception $ex) {
         throw new HttpException('500', Yii::t('AdminModule.libs_OnlineModuleManager', 'Module download failed! (%error%)', array('%error%' => $ex->getMessage())));
     }
     // Extract Package
     if (file_exists($downloadTargetFileName)) {
         $zip = new ZipArchive();
         $res = $zip->open($downloadTargetFileName);
         if ($res === TRUE) {
             $zip->extractTo($modulePath);
             $zip->close();
         } else {
             throw new HttpException('500', Yii::t('AdminModule.libs_OnlineModuleManager', 'Could not extract module!'));
         }
     } else {
         throw new HttpException('500', Yii::t('AdminModule.libs_OnlineModuleManager', 'Download of module failed!'));
     }
     Yii::$app->moduleManager->flushCache();
     Yii::$app->moduleManager->register($modulePath . DIRECTORY_SEPARATOR . $moduleId);
 }
Example #10
0
 private function getTimeStamp()
 {
     //May be used soon for encrypting futurelinks
     if (isset($_REQUEST['action'], $_REQUEST['hash']) && $_REQUEST['action'] == 'timestamp') {
         $client = new Zend\Http\Client(TikiLib::tikiUrl() . 'tiki-timestamp.php', array('timeout' => 60));
         $client->getRequest()->getQuery()->set('hash', $_REQUEST['hash']);
         $client->getRequest()->getQuery()->set('clienttime', time());
         $response = $client->send();
         echo $response->getBody();
         exit;
     }
 }
function getJsonObject($channelId)
{
    $client = new Zend\Http\Client();
    $url = sprintf('http://api.thingspeak.com/channels/%d/feed.json', $channelId);
    $client->setUri($url)->setMethod(\Zend\Http\Request::METHOD_GET);
    $response = $client->send();
    $responseObject = \Zend\Json\Json::decode($response->getBody());
    if (-1 === $responseObject) {
        exit(sprintf('Nothing found under %s' . PHP_EOL, $url));
    }
    return $responseObject;
}
Example #12
0
 /**
  * @param string $par Query Parameter
  * @param string $geoCoderUrl Url of the geo location service
  * @param string $land language
  *
  * @return array|mixed|string
  */
 public function __invoke($par, $geoCoderUrl, $land)
 {
     $client = new \Zend\Http\Client($geoCoderUrl);
     $client->setMethod('GET');
     // more countries 'country' => 'DE,CH,AT'
     // with countryCode 'zoom' => 2
     $plz = 0 < (int) $par ? 1 : 0;
     $client->setParameterGet(array('q' => $par, 'country' => 'DE', 'plz' => $plz, 'zoom' => 1));
     $response = $client->send();
     $result = $response->getBody();
     $result = json_decode($result);
     $result = (array) $result->result;
     return $result;
 }
 /**
  * This method call Bit.ly to shorten a given URL.
  * @param  unknown_type $url
  * @return unknown
  */
 public function shortenUrl($url)
 {
     if ($this->getOptions()->getBitlyApiKey() && $this->getOptions()->getBitlyUsername()) {
         $client = new \Zend\Http\Client($this->getOptions()->getBitlyUrl());
         $client->setParameterGet(array('format' => 'json', 'longUrl' => $url, 'login' => $this->getOptions()->getBitlyUsername(), 'apiKey' => $this->getOptions()->getBitlyApiKey()));
         $result = $client->send();
         if ($result) {
             $jsonResult = \Zend\Json\Json::decode($result->getBody());
             if ($jsonResult->status_code == 200) {
                 return $jsonResult->data->url;
             }
         }
     }
     return $url;
 }
 /**
  * @param null $id
  * @param array $queryParams
  * @return mixed
  */
 protected function requestGet($id = null, $queryParams = array())
 {
     $uri = $this->getApiPath();
     if (!empty($id)) {
         $uri .= '/' . $id;
     }
     if (!empty($queryParams)) {
         $uri .= '?' . http_build_query($queryParams);
     }
     $request = new Request();
     $request->setMethod(Request::METHOD_GET);
     $request->setUri($uri);
     $request->getHeaders()->addHeaders(array('Accept' => 'application/json', 'Authorization' => $this->getTokenType() . ' ' . $this->getAccessToken()));
     $client = new \Zend\Http\Client(null, array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false)));
     return $client->send($request);
 }
 /**
  * @param Observer $observer
  * @return void
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $clientIP = "115.78.167.37";
     //		$clientIP = $this->_request->getClientIp();
     $httpClient = new \Zend\Http\Client();
     $uri = 'http://freegeoip.net/json/' . $clientIP;
     $httpClient->setUri($uri);
     $httpClient->setOptions(array('timeout' => 30));
     try {
         $response = \Zend\Json\Decoder::decode($httpClient->send()->getBody());
         $this->_customerSession->setLocationData($response);
         $this->_customerSession->setLocated(true);
     } catch (\Exception $e) {
         $this->_logger->critical($e);
     }
     return $this;
 }
Example #16
0
 public function __invoke($par)
 {
     $config = $this->getController()->getServiceLocator()->get('config');
     if (empty($config['geocoder_cross_url'])) {
         throw new \InvalidArgumentException('Now Service-Adress for Geo-Service available');
     }
     $client = new \Zend\Http\Client($config['geocoder_photon_url']);
     $client->setMethod('GET');
     // more countries 'country' => 'DE,CH,AT'
     // with countryCode 'zoom' => 2
     $plz = 0 < (int) $par ? 1 : 0;
     $client->setParameterGet(array('q' => $par, 'country' => 'DE', 'plz' => $plz, 'zoom' => 1));
     $response = $client->send();
     $result = $response->getBody();
     $result = json_decode($result);
     $result = (array) $result->result;
     return $result;
 }
 /**
  * Downloads the update package
  * 
  * @throws Exception
  */
 public function download()
 {
     $targetFile = Yii::$app->getModule('updater')->getTempPath() . DIRECTORY_SEPARATOR . $this->fileName;
     // Unlink download if exists and not matches the md5
     if (is_file($targetFile) && md5_file($targetFile) != $this->md5) {
         unlink($targetFile);
     }
     // Download Package
     if (!is_file($targetFile)) {
         try {
             $http = new \Zend\Http\Client($this->downloadUrl, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => Yii::$app->getModule('updater')->getCurlOptions(), 'timeout' => 300));
             $response = $http->send();
             file_put_contents($targetFile, $response->getBody());
         } catch (Exception $ex) {
             throw new Exception(Yii::t('UpdaterModule.libs_UpdatePackage', 'Update download failed! (%error%)', array('%error%' => $ex->getMessage())));
         }
     }
     if (md5_file($targetFile) != $this->md5) {
         throw new Exception(Yii::t('UpdaterModule.base', 'Update package invalid!'));
     }
 }
 /**
  * Returns all available updates for a given version
  * 
  * @param type $version
  */
 public static function getAvailableUpdate()
 {
     $info = [];
     if (class_exists('\\humhub\\modules\\admin\\libs\\HumHubAPI')) {
         $info = \humhub\modules\admin\libs\HumHubAPI::request('v1/modules/getHumHubUpdates', ['updaterVersion' => Yii::$app->getModule('updater')->version]);
     } else {
         // older Versions
         try {
             $url = Yii::$app->getModule('admin')->marketplaceApiUrl . "getHumHubUpdates?version=" . Yii::$app->version . "&updaterVersion=" . Yii::$app->getModule('updater')->version . "&installId=" . Setting::Get('installationId', 'admin');
             $http = new \Zend\Http\Client($url, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => Yii::$app->getModule('updater')->getCurlOptions(), 'timeout' => 30));
             $response = $http->send();
             $info = Json::decode($response->getBody());
         } catch (Exception $ex) {
             throw new Exception(Yii::t('UpdaterModule.base', 'Could not get update info online! (%error%)', array('%error%' => $ex->getMessage())));
         }
     }
     if (!isset($info['fromVersion'])) {
         return null;
     }
     $package = new UpdatePackage($info['fileName'], $info['fromVersion'], $info['toVersion']);
     $package->md5 = $info['md5'];
     $package->downloadUrl = $info['downloadUrl'];
     return $package;
 }
Example #19
0
 protected function generateVideoInfo()
 {
     if (!$this->getVideoId() && !$this->getVideoUrl()) {
         throw new VideoIdOrVideoUrlRequiredException("Video Id or Video url required.");
     }
     if (empty($this->getVideoId())) {
         $this->setVideoIdFromUrl($this->getVideoUrl());
     }
     $client = new \Zend\Http\Client($this->getVideoInfoUrl() . $this->getVideoId(), array());
     parse_str($client->send(), $response);
     if (isset($response['status']) && $response['status'] == 'fail') {
         throw new GetVideoInfoException($response['reason'], $response['errorcode']);
     }
     $result = array();
     $result['title'] = $response['title'];
     $result['image'] = array('max_resolution' => $this->getThumbnailUrl() . $this->getVideoId() . '/maxresdefault.jpg', 'high_quality' => $this->getThumbnailUrl() . $this->getVideoId() . '/hqdefault.jpg', 'standard' => $this->getThumbnailUrl() . $this->getVideoId() . '/sddefault.jpg', 'thumbnail' => $this->getThumbnailUrl() . $this->getVideoId() . '/default.jpg');
     if (!empty($response['length_seconds'])) {
         $result['length_seconds'] = $response['length_seconds'];
     }
     $filename = $this->pathSafeFilename($result['title']);
     if (isset($response['ps']) && ($response['ps'] = 'live')) {
         if (!isset($response['hlsvp'])) {
             throw new LiveEventIsOverException('This live event is over.', 2);
         }
         $result['stream_url'] = $response['hlsvp'];
     } else {
         if (!empty($response['url_encoded_fmt_stream_map'])) {
             $streamMaps = explode(',', $response['url_encoded_fmt_stream_map']);
             foreach ($streamMaps as $key => $value) {
                 parse_str($value, $streamMaps[$key]);
                 if (!empty($streamMaps[$key]['sig'])) {
                     $streamMaps[$key]['url'] .= '&signature=' . $streamMaps[$key]['sig'];
                     unset($streamMaps[$key]['sig']);
                 }
                 $typeParts = explode(';', $streamMaps[$key]['type']);
                 $streamMaps[$key]['filename'] = $filename . '.' . $this->getExtension(trim($typeParts[0]));
                 $streamMaps[$key] = (object) $streamMaps[$key];
             }
             $result['full_formats'] = $streamMaps;
         }
         $adaptiveFmts = explode(',', $response['adaptive_fmts']);
         foreach ($adaptiveFmts as $key => $value) {
             parse_str($value, $adaptiveFmts[$key]);
             $typeParts = explode(';', $adaptiveFmts[$key]['type']);
             $adaptiveFmts[$key]['filename'] = $filename . '.' . $this->getExtension(trim($typeParts[0]));
             $adaptiveFmts[$key] = (object) $adaptiveFmts[$key];
         }
         $result['adaptive_formats'] = $adaptiveFmts;
     }
     $result['video_url'] = $this->getWatchUrl() . $this->getVideoId();
     $this->setVideoInfo((object) $result);
     return $result;
 }
Example #20
0
 /**
  * Sends the data via cURL
  * @param array $params
  * @param integer $method
  * @param string $raw_body
  * @return Zend_Http_Response
  */
 private function curl($orig_url, $params = array(), $method = Request::GET, $headers = array(), $remove_unsafe_params = true, $retry_count = 0)
 {
     try {
         if (is_null($orig_url) && defined('MO_API_URL')) {
             $orig_url = MO_API_URL;
         } else {
             if (is_null($orig_url)) {
                 throw new \Exception('No url was provided and MO_API_URL is not defined');
             }
         }
         $url = $orig_url . $this->getFunc();
         if ($method == Request::DELETE || $method == Request::PUT) {
             if (isset($params['_id'])) {
                 $url .= '/' . (isset($params['_id']) ? (int) $params['_id'] : 0);
             }
         }
         // remove any routing to prevent overwritting the url
         if ($remove_unsafe_params) {
             if (isset($params['module'])) {
                 unset($params['module']);
             }
             if (isset($params['controller'])) {
                 unset($params['controller']);
             }
             if (isset($params['action'])) {
                 unset($params['action']);
             }
             if (isset($params['func'])) {
                 unset($params['func']);
             }
         }
         // gots to do this so that transfer-encoding: chunked comes through properly
         $curl_adapter = new \Zend\Http\Client\Adapter\Curl();
         // Enforce a 30 second timeout (default is unlimited)
         if ($this->getTimeout() > 0) {
             $curl_adapter->setCurlOption(CURLOPT_TIMEOUT, $this->getTimeout());
             $curl_adapter->setCurlOption(CURLOPT_CONNECTTIMEOUT, $this->getTimeout());
         }
         //$curl_adapter->setCurlOption(CURLOPT_ENCODING , "gzip");
         $curl_adapter->setCurlOption(CURLOPT_SSL_VERIFYPEER, false);
         $curl_adapter->setCurlOption(CURLOPT_USERAGENT, 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10');
         $http_client = new \Zend\Http\Client();
         $http_client->setAdapter($curl_adapter);
         $http_client->setUri($url);
         $http_client->setArgSeparator('&');
         $request = new \Zend\Http\Request();
         $request->setUri($url);
         //$http_client->setCookieJar($this->getHttpCookieJar());
         // Set the token authentication
         $request->getHeaders()->addHeaderLine('Accept-Encoding', 'gzip,deflate');
         $request->getHeaders()->addHeaderLine('Content-Type', \Zend\Http\Client::ENC_URLENCODED);
         if (is_array($headers)) {
             foreach ($headers as $key => $header) {
                 $request->getHeaders()->addHeaderLine($key, $header);
             }
         }
         if ($request->getUri() === null) {
             throw new \Exception('No URI given. Param \'func\' is required.');
         }
         /* @var $response Zend_Http_Response */
         $response = false;
         if ($method == \Mojavi\Request\Request::GET) {
             if (is_array($params)) {
                 $request->getQuery()->fromArray($params);
             }
             $request->setMethod(\Zend\Http\Request::METHOD_GET);
             $response = $http_client->send($request);
         } else {
             if ($method == \Mojavi\Request\Request::POST) {
                 // If we uploaded files, we have to send them differently
                 if (count($_FILES) > 0) {
                     $request->getFiles()->fromArray($_FILES);
                     $http_client->setEncType(\Zend\Http\Client::ENC_FORMDATA);
                 } else {
                     $http_client->setEncType(\Zend\Http\Client::ENC_URLENCODED);
                 }
                 if (is_array($params)) {
                     $request->getPost()->fromArray($params);
                 }
                 $request->setMethod(\Zend\Http\Request::METHOD_POST);
                 $response = $http_client->send($request);
             } else {
                 if ($method == \Mojavi\Request\Request::DELETE) {
                     $request->setMethod(\Zend\Http\Request::METHOD_DELETE);
                     $response = $http_client->send($request);
                 } else {
                     if ($method == \Mojavi\Request\Request::PUT) {
                         if (count($_FILES) > 0) {
                             $request->getFiles()->fromArray($_FILES);
                             $http_client->setEncType(\Zend\Http\Client::ENC_FORMDATA);
                         } else {
                             $http_client->setEncType(\Zend\Http\Client::ENC_FORMDATA);
                         }
                         if (is_array($params)) {
                             $request->getQuery()->fromArray($params);
                         }
                         $request->setMethod(\Zend\Http\Request::METHOD_PUT);
                         $response = $http_client->send($request);
                     }
                 }
             }
         }
         return $response;
     } catch (\Exception $e) {
         if (strpos($e->getMessage(), 'connect() timed out!') !== false && $retry_count < 3) {
             return $this->curl($orig_url, $params, $method, $headers, $remove_unsafe_params, ++$retry_count);
         } else {
             if (strpos($e->getMessage(), 'couldn\'t connect to host') !== false && $retry_count < 3) {
                 return $this->curl($orig_url, $params, $method, $headers, $remove_unsafe_params, ++$retry_count);
             } else {
                 if (strpos($e->getMessage(), 'Operation timed out') !== false && $retry_count < 3) {
                     return $this->curl($orig_url, $params, $method, $headers, $remove_unsafe_params, ++$retry_count);
                 }
             }
         }
         throw $e;
     }
 }
Example #21
0
/**
 * 构造POST和GET组合的请求 返回相应请求
 *
 * @param string $url            
 * @param array $get            
 * @param array $post            
 * @param boolean $returnObj            
 * @return Zend_Http_Response false
 */
function doRequest($url, $get = array(), $post = array(), $returnObj = false)
{
    try {
        $url = trim($url);
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            throw new Exception('Invalid URL');
            return false;
        }
        $client = new Zend\Http\Client();
        $client->setUri($url);
        if (count($get) > 0 && is_array($get)) {
            $client->setParameterGet($get);
        }
        if (count($post) > 0 && is_array($post)) {
            $client->setParameterPost($post);
        }
        $client->setEncType(Zend\Http\Client::ENC_URLENCODED);
        $client->setOptions(array('maxredirects' => 5, 'strictredirects' => false, 'useragent' => 'Zend\\Http\\Client', 'timeout' => 10, 'adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', 'httpversion' => Request::VERSION_11, 'storeresponse' => true, 'keepalive' => false, 'outputstream' => false, 'encodecookies' => true, 'argseparator' => null, 'rfc3986strict' => false));
        if (!empty($post)) {
            $client->setMethod(Request::METHOD_POST);
        } else {
            $client->setMethod(Request::METHOD_GET);
        }
        $response = $client->send();
        return $returnObj ? $response : $response->getBody();
    } catch (Exception $e) {
        fb(exceptionMsg($e), \FirePHP::LOG);
        return false;
    }
}
Example #22
0
 public function generatePdf()
 {
     $config = $this->getServiceLocator()->get('Config');
     if (!extension_loaded('gd')) {
         throw new \Exception('PHP Extension gd needs to be loaded.');
     }
     /*
      * PDF creation
      */
     $paperSize = 'a4';
     $paperOrientation = 'portrait';
     $pdf = new PdfModel();
     $pdf->setOption("paperSize", $paperSize);
     //Defaults to 8x11
     $pdf->setOption("paperOrientation", $paperOrientation);
     //Defaults to portrait
     $name = $this->getParticipant()->getFirstname() . ' ' . $this->getParticipant()->getSurname();
     $code = $this->getPackage()->getCode()->getValue();
     /*
      * QR-Code creation
      */
     $qr = $this->getServiceLocator()->get('QRCode');
     $qr->isHttps();
     // or $qr->isHttp();
     #$qr->setData('http://prereg.eja.net/onsite/register/'.  \urlencode($code));
     $onsitereg = $config['ERS']['onsitereg'];
     # ensure the url has no trailing slash
     \rtrim($onsitereg, '/\\');
     $qr->setData($onsitereg . '/' . \urlencode($code));
     $qr->setCorrectionLevel('H', 0);
     $qr->setDimensions(200, 200);
     $qr_config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', 'ssltransport' => 'tls', 'sslcapath' => '/etc/ssl/certs/', 'sslverifypeer' => false);
     // Instantiate a client object
     $client = new \Zend\Http\Client($qr->getResult(), $qr_config);
     // The following request will be sent over a TLS secure connection.
     $response = $client->send();
     $qr_content = $response->getContent();
     $base64_qrcode = "data:image/png;base64," . \base64_encode($qr_content);
     #file_put_contents(getcwd().'/public/img/qrcode.png', $qr_content);
     /*
      * Barcode creation
      */
     // Only the text to draw is required
     $barcodeOptions = array('text' => $code, 'barHeight' => 40, 'factor' => 1.1, 'drawText' => false);
     // No required options
     $rendererOptions = array();
     // Draw the barcode in a new image,
     $imageResource = \Zend\Barcode\Barcode::factory('code39', 'image', $barcodeOptions, $rendererOptions)->draw();
     ob_start();
     //Start output buffer.
     imagejpeg($imageResource);
     //This will normally output the image, but because of ob_start(), it won't.
     $contents = ob_get_contents();
     //Instead, output above is saved to $contents
     ob_end_clean();
     //End the output buffer.
     #file_put_contents(getcwd().'/public/img/barcode2.jpg', $contents);
     $base64_barcode = "data:image/png;base64," . \base64_encode($contents);
     /*
      * prepare items
      */
     $items = array();
     foreach ($this->getPackage()->getItems() as $item) {
         if ($item->getStatus() == 'transferred') {
             continue;
         }
         $items[$item->getProductId()][] = $item;
     }
     /* 
      * generate PDF
      */
     $pdfView = new ViewModel();
     $pdfView->setTemplate('pdf/eticket_' . $this->getLanguage());
     $pdfView->setVariables(array('name' => $name, 'package' => $this->getPackage(), 'items' => $items, 'products' => $this->getProducts(), 'agegroup' => $this->getAgegroup(), 'code' => $code, 'qrcode' => $base64_qrcode, 'barcode' => $base64_barcode));
     $pdfRenderer = $this->getServiceLocator()->get('ViewPdfRenderer');
     $html = $pdfRenderer->getHtmlRenderer()->render($pdfView);
     $pdfEngine = $pdfRenderer->getEngine();
     $pdfEngine->set_paper($paperSize, $paperOrientation);
     $pdfEngine->set_base_path(getcwd() . '/');
     $pdfEngine->load_html($html);
     $pdfEngine->render();
     $pdfContent = $pdfEngine->output();
     $filename = $config['ERS']['name_short'] . "_e-Ticket_" . $this->getPackage()->getCode()->getValue() . '_' . $this->getLanguage();
     # TODO: make ticket_path configurable
     $ticket_path = getcwd() . '/data/etickets';
     \rtrim($onsitereg, '/\\');
     if (!is_dir($ticket_path)) {
         mkdir($ticket_path);
     }
     $filePath = $ticket_path . '/' . $filename . '.pdf';
     file_put_contents($filePath, $pdfContent);
     return $filePath;
 }
Example #23
0
 /**
  * Get comments on obalkyknih.cz associated with this record.
  *
  * @return array
  */
 public function getObalkyKnihComments()
 {
     $isbnArray = $this->getBibinfoForObalkyKnihV3();
     $isbnJson = json_encode($isbnArray);
     $client = new \Zend\Http\Client('http://cache.obalkyknih.cz/api/books');
     $client->setParameterGet(array('multi' => '[' . $isbnJson . ']'));
     $response = $client->send();
     $responseBody = $response->getBody();
     $phpResponse = json_decode($responseBody, true);
     if (isset($phpResponse[0]['rating_url'])) {
         echo '<p>Hodnocení knihy:</p><img src="' . $phpResponse[0]['rating_url'] . '"/>';
     }
     $commentArray = array();
     $i = 0;
     foreach ($phpResponse[0]['reviews'] as $review) {
         $com = new \stdClass();
         $com->firstname = $review->library_name;
         $com->created = $review->created;
         $com->comment = $review->html_text;
         $commentArray[$i] = $com;
         $i++;
     }
     return $commentArray;
 }
Example #24
0
 /**
  * Upload inventory data
  *
  * @param string $data Inventory data (XML or zlib-compressed XML)
  * @return \Zend\Http\Response Server response
  */
 public function uploadData($data)
 {
     $client = new \Zend\Http\Client($this->_serverUri, array('adapter' => $this->_adapter, 'strictredirects' => true, 'useragent' => 'Braintacle_local_upload'));
     $client->setMethod('POST')->setHeaders(array('Content-Type' => 'application/x-compress'))->setRawBody($data);
     return $client->send();
 }
Example #25
0
 /**
  * Fetches and sets data from the remote system via {@link $this->uri}.
  */
 protected function fetchData()
 {
     $uri = $this->getUri();
     if (!$uri) {
         return;
     }
     $client = new \Zend\Http\Client($this->getUri());
     $client->setMethod('GET');
     try {
         $response = $client->send();
     } catch (\Exception $e) {
         return;
     }
     $status = $response->getStatusCode();
     if ($status == 200) {
         $result = $response->getBody();
         $result = (array) json_decode($result);
         if (0 < count($result)) {
             $name = array_pop($result);
             $this->setName($name);
         }
     }
 }
Example #26
0
 public function testPutRoleResources()
 {
     $client = new \Zend\Http\Client(self::HOST . '/roles/1/resources/ZfeggAdmin\\V1\\Rest\\AdminRole\\Controller::collection');
     $client->setMethod('PUT');
     $client->setHeaders(['Accept' => 'application/hal+json', 'Content-Type' => 'application/json']);
     $client->setRawBody(json_encode(['resource' => 'ZfeggAdmin\\V1\\Rest\\AdminRole\\Controller::collection', 'privileges' => ['GET', 'post', 'Put', 'delete']]));
     $response = $client->send();
     echo Json::prettyPrint($response->getBody());
 }
$config = getConfig();
$token = $config['token'];
// Github API token
$user = $config['user'];
// Your user or organization
$repo = $config['repo'];
// The repository you're getting the changelog for
$milestone = $config['milestone'];
// The milestone ID
$client = new Zend\Http\Client();
$client->setOptions(array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl'));
$request = $client->getRequest();
$headers = $request->getHeaders();
$headers->addHeaderLine("Authorization", "token {$token}");
$client->setUri("https://api.github.com/repos/{$user}/{$repo}/milestones/{$milestone}");
$milestoneResponseBody = $client->send()->getBody();
$milestonePayload = json_decode($milestoneResponseBody, true);
if (!isset($milestonePayload['title'])) {
    file_put_contents('php://stderr', sprintf("Provided milestone ID [%s] does not exist: %s\n", $milestone, $milestoneResponseBody));
}
$client->setUri('https://api.github.com/search/issues?q=' . urlencode('milestone:' . $milestonePayload['title'] . ' repo:' . $user . '/' . $repo . ' state:closed'));
$client->setMethod('GET');
$issues = array();
$error = false;
do {
    $response = $client->send();
    $json = $response->getBody();
    $payload = json_decode($json, true);
    if (!(is_array($payload) && isset($payload['items']))) {
        file_put_contents('php://stderr', sprintf("Github API returned error message [%s]\n", is_object($payload) ? $payload['message'] : $json));
        exit(1);
Example #28
0
 /**
  * {@inheritdoc}
  *
  *
  * @see \Zend\Authentication\Adapter\AdapterInterface::authenticate()
  */
 public function authenticate()
 {
     $hybridAuth = $this->getHybridAuth();
     /* @var $adapter \Hybrid_Provider_Model */
     $adapter = $hybridAuth->authenticate($this->_provider);
     $userProfile = $adapter->getUserProfile();
     $email = isset($userProfile->emailVerified) && !empty($userProfile->emailVerified) ? $userProfile->emailVerified : $userProfile->email;
     $forceSave = false;
     $user = $this->getRepository()->findByProfileIdentifier($userProfile->identifier);
     if (!$user) {
         $forceSave = true;
         $user = $this->getRepository()->create();
     }
     $currentInfo = $user->getProfile();
     $newInfo = (array) $userProfile;
     if ($forceSave || $currentInfo != $newInfo) {
         /*  */
         $dm = $this->getRepository()->getDocumentManager();
         if ('' == $user->getInfo()->email) {
             $user->getInfo()->email = $email;
         }
         $user->getInfo()->firstName = $userProfile->firstName;
         $user->getInfo()->lastName = $userProfile->lastName;
         $user->getInfo()->birthDay = $userProfile->birthDay;
         $user->getInfo()->birthMonth = $userProfile->birthMonth;
         $user->getInfo()->birthYear = $userProfile->birthYear;
         $user->getInfo()->postalcode = $userProfile->zip;
         $user->getInfo()->city = $userProfile->city;
         $user->getInfo()->street = $userProfile->address;
         $user->getInfo()->phone = $userProfile->phone;
         $user->getInfo()->gender = $userProfile->gender;
         $user->setLogin($email);
         $user->setProfile($newInfo);
         $dm->persist($user);
         // make sure all ids are generated and user exists in database.
         $dm->flush();
         /*
          * This must be after flush because a newly created user has no id!
          */
         if ($forceSave || !$user->getInfo()->image && $userProfile->photoURL) {
             // get user image
             if ('' != $userProfile->photoURL) {
                 $client = new \Zend\Http\Client($userProfile->photoURL, array('sslverifypeer' => false));
                 $response = $client->send();
                 $file = new GridFSFile();
                 $file->setBytes($response->getBody());
                 $userImage = new UserImage();
                 $userImage->setName($userProfile->lastName . $userProfile->firstName);
                 $userImage->setType($response->getHeaders()->get('Content-Type')->getFieldValue());
                 $userImage->setUser($user);
                 $userImage->setFile($file);
                 $user->getInfo()->setImage($userImage);
                 $dm->persist($userImage);
                 //$this->getRepository()->store($user->info);
             }
             // We have to flush again
             $dm->flush();
         }
     }
     return new Result(Result::SUCCESS, $user->getId(), array('firstLogin' => $forceSave, 'user' => $user));
 }
Example #29
0
        }
    }
    if ($last) {
        list($last, $last_version) = explode('|', $last);
        if ($last > time() - 60 * 60 * 24) {
            $doit = false;
        }
    }
}
if ($doit) {
    ini_set('include_path', CAT_PATH . '/modules/lib_zendlite');
    include CAT_PATH . '/modules/lib_zendlite/library.php';
    $client = new Zend\Http\Client($current['source'], array('timeout' => $current['timeout'], 'adapter' => 'Zend\\Http\\Client\\Adapter\\Proxy', 'proxy_host' => $current['proxy_host'], 'proxy_port' => $current['proxy_port']));
    $client->setHeaders(array('Pragma' => 'no-cache', 'Cache-Control' => 'no-cache'));
    try {
        $response = $client->send();
        if ($response->getStatusCode() != '200') {
            $error = "Unable to load source " . "(using Proxy: " . (isset($current['proxy_host']) && $current['proxy_host'] != '' ? 'yes' : 'no') . ")<br />" . "Status: " . $response->getStatus() . " - " . $response->getMessage() . ($debug ? "<br />" . var_dump($client->getLastRequest()) : NULL) . "<br />";
            $version = 'unknown';
        } else {
            $version = $response->getBody();
        }
    } catch (Exception $e) {
        $error = "Unable to load source " . "(using Proxy: " . (isset($current['proxy_host']) && $current['proxy_host'] != '' ? 'yes' : 'no') . ")<br />" . $e->getMessage() . "<br />";
        $version = 'unknown';
    }
    if ($version && $version != 'unknown') {
        if (CAT_Helper_Addons::getInstance()->versionCompare($version, CAT_VERSION, '>')) {
            $newer = true;
        }
    }
 /**
  * Returns latest HumHub Version
  */
 public function getLatestHumHubVersion()
 {
     $url = Yii::$app->getModule('admin')->marketplaceApiUrl . "getLatestVersion?version=" . Yii::$app->version . "&installId=" . Setting::Get('installationId', 'admin');
     try {
         $http = new \Zend\Http\Client($url, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => $this->getCurlOptions(), 'timeout' => 30));
         $response = $http->send();
         $json = \yii\helpers\Json::decode($response->getBody());
         if (isset($json['latestVersion'])) {
             return $json['latestVersion'];
         }
     } catch (Exception $ex) {
         Yii::error('Could not get latest HumHub Version!' . $ex->getMessage());
     }
     return "";
 }