Example #1
0
 public function post($body, $type, $id)
 {
     if (!$this->config('enabled')) {
         return false;
     }
     // Find out when the last time an announce was sent for this entity
     $result = $this->Slack->findAllByEntityAndEntityId($type, $id)->first();
     if ($result) {
         $last_update = $result->modified;
     } else {
         $result = $this->Slack->newEntity();
         $result->entity = $type;
         $result->entity_id = $id;
         $last_update = new Time('1 year ago');
     }
     // Prevent sending out an update too soon
     if ($last_update->wasWithinLast($this->config('debounce'))) {
         return false;
     }
     $http = new Client();
     $data = (object) ['text' => $body];
     $response = $http->post($this->config('webhook_url'), ['payload' => json_encode($data, JSON_PRETTY_PRINT)]);
     $result->messages++;
     $this->Slack->save($result);
 }
 public function results()
 {
     $client = new Client();
     $results = json_decode($client->get('http://api.giphy.com/v1/gifs/search?', ['q' => $this->request->data('search'), 'api_key' => $this->api_key])->body());
     $this->set('results', $results->data);
     $this->set('search_string', $this->request->data('search'));
 }
 public function rent($id)
 {
     // no view to render
     $this->autoRender = false;
     $id--;
     $http = new Client();
     $response = $http->get('http://mgautschi.dev.at.sfsu.edu/building_mgmt/properties/api');
     $rental = json_decode($response->body);
     // echo $rental[$id - 1]->address;
     // die;
     $property = $this->Properties->newEntity();
     // Added this line
     $property->user_id = $this->Auth->user('id');
     $property->unitType = $rental[$id]->unitType;
     $property->address = $rental[$id]->address;
     $property->city = $rental[$id]->city;
     $property->state = $rental[$id]->state;
     $property->zip = $rental[$id]->zip;
     $property->building = $rental[$id]->building;
     $property->unitNumber = $rental[$id]->unit;
     $property->beds = $rental[$id]->beds;
     $property->baths = $rental[$id]->baths;
     $property->rent = $rental[$id]->rent;
     $property->square_feet = $rental[$id]->squareFt;
     if ($this->Properties->save($property)) {
         $this->Flash->success(__('You are now renting at ' . $property->address));
         return $this->redirect(['action' => 'search']);
     }
     //return $this->redirect(['action' => 'search']);
     //$this->Flash->error(__('Unable to rent this property.'));
     return $this->redirect(['action' => 'search']);
 }
 public function cep($cep)
 {
     $cep = str_replace('-', '', $cep);
     $this->viewBuilder()->layout('ajax');
     $http = new Client();
     $response = $http->get('http://cep.agenciavoxel.com.br/' . $cep . '.json');
     $this->set('retorno', json_decode($response->body(), true));
 }
 public function main()
 {
     $tick_names_and_values = array();
     $this->authentication();
     $http = new Client();
     $this->loadModel('Stocks');
     $this->loadModel('Devices');
     $token_file = new File("/home/demo/token/token.txt");
     $token = $token_file->read();
     $token_file->close();
     $MyAuthObject = new OAuthObject(array("token_type" => "Bearer", "access_token" => $token));
     $OptionsToast = new WNSNotificationOptions();
     $OptionsToast->SetAuthorization($MyAuthObject);
     $OptionsToast->SetX_WNS_REQUESTFORSTATUS(X_WNS_RequestForStatus::Request);
     $NotifierToast = new WindowsNotificationClass($OptionsToast);
     $OptionsTile = new WNSNotificationOptions();
     $OptionsTile->SetAuthorization($MyAuthObject);
     $OptionsTile->SetX_WNS_REQUESTFORSTATUS(X_WNS_RequestForStatus::Request);
     //NOTE: Set the Tile type
     $OptionsTile->SetX_WNS_TYPE(X_WNS_Type::Tile);
     $NotifierTile = new WindowsNotificationClass($OptionsTile);
     $allStocks = $this->Stocks->find('all')->toArray();
     //$allStocks = $this->Stocks->find('all')->group(['Stocks.device_id'])->toArray();
     //$allStocks = $this->Stocks->Devices->find()->group(['Devices.id'])->toArray();
     Debugger::dump('allStocks: ');
     Debugger::dump($allStocks);
     $allStocksByDeviceId = array();
     for ($i = 0; $i < sizeof($allStocks); $i++) {
         $actualDeviceId = $allStocks[$i]['device_id'];
         $added = false;
         for ($a = 0; $a < sizeof($allStocksByDeviceId); $a++) {
             if ($allStocksByDeviceId[$a]['device_id'] == $actualDeviceId) {
                 $allStocksByDeviceId[$a]['stocks'][] = $allStocks[$i];
                 $added = true;
             }
         }
         if (!$added) {
             $allStocksByDeviceId[] = ['device_id' => $actualDeviceId, 'stocks' => [$allStocks[$i]]];
         }
     }
     Debugger::dump('allStocksByDeviceId: ');
     Debugger::dump($allStocksByDeviceId);
     $someStocks = $this->Stocks->find()->distinct(['tick_name'])->toArray();
     for ($i = 0; $i < sizeof($someStocks); $i++) {
         $response = $http->get('http://download.finance.yahoo.com/d/quotes?f=sl1d1t1v&s=' . $someStocks[$i]['tick_name']);
         $tick_name = explode(",", $response->body())[0];
         $tick_names_and_values[] = [str_replace("\"", "", $tick_name), explode(",", $response->body())[1]];
     }
     Debugger::dump('tick_names_and_values: ');
     Debugger::dump($tick_names_and_values);
     $this->sendAllStocksNotificationsInTileNotifications($NotifierTile, $tick_names_and_values, $allStocksByDeviceId);
     $this->checkMinMaxValuesAndSendToastNotifications($NotifierToast, $tick_names_and_values);
     //$stuff = implode(",", $stuff);
     //$now = Time::now();
     //$this->createFile('/home/demo/files_created_each_minute/'.$now->i18nFormat('yyyy-MM-dd HH:mm:ss').'.txt', $stuff);
 }
 /**
  * Validate a google recaptcha.
  *
  * @param string $value The captcha value.
  * @param array $context The form context.
  * @return bool
  */
 public static function googleRecaptcha($value, $context)
 {
     $httpClient = new Client();
     $googleReponse = $httpClient->post('https://www.google.com/recaptcha/api/siteverify', ['secret' => Configure::read('Google.Recaptcha.secret'), 'response' => $value, 'remoteip' => Router::getRequest()->clientIp()]);
     $result = json_decode($googleReponse->body(), true);
     if (!empty($result['error-codes'])) {
         Log::error('Google Recaptcha: ' . $result['error-codes'][0]);
     }
     return (bool) $result['success'];
 }
 public function getPlayerSummary($steamId = null)
 {
     $this->autoRender = false;
     if ($steamId === null) {
         $steamId = $this->myId;
     }
     $http = new Client();
     $response = $http->get('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/', ['key' => $this->key, 'steamids' => $steamId, 'format' => 'json']);
     $out = json_decode($response->body);
     debug($out);
 }
 /**
  * @param $id
  * @param $data
  * @param $isRejection
  * @return \Cake\Network\Http\Response
  */
 public static function processRequirementApproval($id, $data, $isRejection)
 {
     $queryParams = ['cod_u' => $data->user_code, 'cod_sol' => $data->request_user, 'opt' => $isRejection ? 'no' : 'si', 'id' => $id];
     if ($isRejection) {
         $queryParams['moti'] = $data->reject_reason;
     }
     $http = new Client();
     // Simple get with query string
     $response = $http->get('http://192.168.30.57/mesaayuda/rq_autorizGte_u.php', $queryParams);
     return $response;
 }
Example #9
0
 public function sendCodeToNode($id)
 {
     $http = new Client();
     $node = $this->Nodes->get($id, ['fields' => 'node_code']);
     $node_code = $node['node_code'];
     $master_address = \Cake\Core\Configure::read('Master.master_address');
     $master_port = \Cake\Core\Configure::read('Master.master_port');
     $address = $master_address . ':' . $master_port . '/node/link?target=' . $node_code . '&sender=1';
     $response = $http->get((string) $address);
     $this->Flash->success('Code sent');
     return $this->redirect(['action' => 'index']);
 }
 /**
  * Geocodes an address.
  *
  * @param string $address The address or location to geocode
  * @param array $parameters Additional params to pass to the Google Geocoding API
  * @throws GeocoderException if the API return a status code other than 200
  * @return object
  */
 public function geocode($address, $parameters = [])
 {
     $parameters['address'] = $address;
     $parameters['sensor'] = 'false';
     $url = 'http://maps.googleapis.com/maps/api/geocode/json';
     $http = new Client();
     $response = $http->get($url, $parameters);
     if ($response->code != 200) {
         throw new GeocoderException('Google Maps Geocoding API returned status code ' . $response->code);
     }
     $response = json_decode($response->body());
     return $response->results;
 }
Example #11
0
 /**
  * Retuns the full address
  */
 public function getByZipcode($zipcode)
 {
     $http = new Client();
     $response = $http->get('http://www.consultaenderecos.com.br/busca-cep/' . $zipcode);
     $html = str_get_html($response->body());
     $lines = $html->find("table td");
     $data = [];
     $data['street'] = isset($lines[1]) ? $lines[1]->innertext : '';
     $data['neighborhood'] = isset($lines[2]) ? $lines[2]->innertext : '';
     $data['city'] = isset($lines[3]) ? $lines[3]->innertext : '';
     $data['state'] = isset($lines[4]) ? $lines[4]->innertext : '';
     return $data;
 }
 public function send()
 {
     // no view to render
     $this->autoRender = false;
     $message = new Message();
     $http = new Client();
     $response = $http->post('http://spedersen.dev.at.sfsu.edu/renter_mgmt/messages/add', $message->to_json(), ['type' => 'json']);
     // $response = $http->post(
     //     'http://spedersen.dev.at.sfsu.edu/renter_mgmt/messages/add',
     //     $message->to_json(),
     //     ['type' => 'json']);
     $this->Flash->success(__('Your message has been sent.'));
     return $this->redirect(['action' => 'index']);
 }
Example #13
0
 public function desactivateScenario($id)
 {
     $scenariosTable = TableRegistry::get('Scenarios');
     $scenario = $scenariosTable->get($id);
     $http = new Client();
     $master_address = \Cake\Core\Configure::read('Master.master_address');
     $master_port = \Cake\Core\Configure::read('Master.master_port');
     $address = $master_address . ':' . $master_port . '/master/desactivateScript?script_file=' . $scenario->script_file;
     $response = $http->get((string) $address);
     $scenario->status = false;
     $scenariosTable->save($scenario);
     $this->Flash->success('Scenario desactivated');
     return $this->redirect(['action' => 'view' . '/' . $id]);
 }
Example #14
0
 public function index()
 {
     $http = new Client();
     $response = $http->post('http://api.threecms.dev/maj.php', []);
     //        $body = json_decode($response->body);
     //        foreach ($body as $k => $v) {
     //            $ch = curl_init();
     //            curl_setopt($ch, CURLOPT_URL, $v);
     //            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     //            $data = curl_exec($ch);
     //            curl_close($ch);
     //            (new File(TMP . 'maj' . DS . $k . '.zip', true, 0644))->write($data);
     //        }
 }
Example #15
0
File: AppView.php Project: lhas/pep
 public function formatarGrafico($chart = null, $user_id = null, $tab_id = null)
 {
     $default = ["chart_id" => $chart->id, "options" => ["legend" => ["itemStyle" => ["fontWeight" => "normal", "fontSize" => "12px", "fontFamily" => "'Arvo'", "textTransform" => "uppercase"]], "chart" => ["type" => $chart->type], "plotOptions" => ["series" => ["stacking" => "", "cursor" => 'pointer'], "pie" => ["cursor" => "pointer", "dataLabels" => ["enabled" => "true", "format" => '<b>{point.name}</b>: {point.percentage:.1f} %']]], "xAxis" => ["categories" => []]], "series" => [], "title" => ["text" => "Gráfico de Demonstração", "style" => ["fontWeight" => "bold", "fontSize" => "21px", "fontFamily" => "'Arvo'", "textTransform" => "uppercase"]], "subtitle" => ["text" => "", "style" => ["fontSize" => "15px", "fontFamily" => "'Arvo'", "textTransform" => "uppercase"]], "credits" => ["enabled" => false], "loading" => false, "size" => [], "filter_start" => (new \DateTime())->format("01/01/Y"), "filter_end" => (new \DateTime())->format("d/m/Y"), 'format' => 'diario'];
     if (!empty($_GET['inicio'])) {
         $chart->filter_start = $_GET['inicio'];
     }
     if (!empty($_GET['fim'])) {
         $chart->filter_end = $_GET['fim'];
     }
     if (!empty($chart->name)) {
         $default['title']['text'] = $chart->name;
     }
     if (!empty($chart->subname)) {
         $default['subtitle']['text'] = $chart->subname;
     }
     if (!empty($chart->filter_start)) {
         $default['filter_start'] = $chart->filter_start;
     }
     if (!empty($chart->filter_end)) {
         $default['filter_end'] = $chart->filter_end;
     }
     if (!empty($chart->chart_series)) {
         // limpa as series
         $default['series'] = [];
         $http = new Client();
         foreach ($chart->chart_series as $serie) {
             // requisição a API
             $url = $this->Url->build("/", true);
             $dados = ['formato' => $chart->format, 'input' => $serie->input_id, 'materia' => $serie->theme_id];
             $url = $url . 'cms/api/calcular_serie/';
             $payload = ['user_id' => $user_id, 'chart_serie_id' => $serie->id, 'input_id' => $dados['input'], 'formato_grafico' => $dados['formato'], 'theme_id' => $dados['materia']];
             if (!empty($_GET['inicio'])) {
                 $payload['inicio'] = $_GET['inicio'];
             }
             if (!empty($_GET['fim'])) {
                 $payload['fim'] = $_GET['fim'];
             }
             if (!empty($tab_id)) {
                 $payload['tab_id'] = $tab_id;
             }
             $response = $http->post($url, $payload, ['type' => 'json']);
             $response = $response->json;
             if (!empty($response['data'])) {
                 $default['series'][] = ['id' => $serie->id, 'name' => $serie->name, 'color' => $serie->color, 'type' => $serie->type, 'input_id' => strval($serie->input_id), 'theme_id' => strval($serie->theme_id), 'actors_tutors' => $serie->actors_tutors, 'actors_therapists' => $serie->actors_therapists, 'actors_schools' => $serie->actors_schools, 'actors_protectors' => $serie->actors_protectors, 'data' => $response['data']];
             }
         }
     }
     return json_encode($default, JSON_HEX_APOS);
 }
 public function forgot()
 {
     $this->layout = 'default';
     if ($this->request->data) {
         $success = false;
         $http = new Client();
         $broker_url = Router::url('/', true);
         if (substr($broker_url, 0, 7) == 'http://') {
             $broker_url = substr($broker_url, 7);
         } else {
             if (substr($broker_url, 0, 8) == 'https://') {
                 $broker_url = substr($broker_url, 8);
             }
         }
         if (substr($broker_url, -1) == '/') {
             $broker_url = substr($broker_url, 0, strlen($broker_url) - 1);
         }
         if (substr($broker_url, 0, 3) != 'www') {
             $broker_url = 'www.' . $broker_url;
         }
         $broker_url = Router::url('/', true);
         $broker_url = str_replace("http://", "", $broker_url);
         $broker_url = str_replace("https://", "", $broker_url);
         $broker_url = str_replace("/", "", $broker_url);
         $length = 8;
         $randomString = substr(str_shuffle("23456789"), 0, $length);
         //call out to sso parent to verify login
         $params = ['action' => 'user_profile', 'broker_url' => $broker_url, 'broker_key' => Configure::read('hippo.sso_broker_key'), 'email' => $this->request->data['email']];
         $response = $http->post('http://' . SSO_PARENT . '/wp-admin/admin-ajax.php', $params);
         $user_info = $response->body();
         if ($user_info) {
             $params = ['action' => 'broker_pwd', 'hash' => MD5($randomString), 'email' => $this->request->data['email']];
             $http->post('http://' . SSO_PARENT . '/wp-admin/admin-ajax.php', $params);
             $success = true;
             $message = "<html>\n\t\t                  <head>\n\t\t                  </head>\n\t\t                  <body>\n\t\t                    <h1>" . __('Your ENVOY Password Has Been Reset') . "</h1>\n\t\t                    <p>\n\t\t                        " . __('Hello') . ', <br><br>' . __('The password associated with this email address has been reset to the following') . ":<br />" . $randomString . "</p><br>\n\t\t                      <p>\n\t\t                        " . __('For accuracy, it is recommended that you copy and paste the password information into the travel agent login area of the website.') . '<br><br>' . __('You can change your password in the My Profile section of the site once you have logged in.') . "\n\t\t                      </p>\n\t\t                    </body>\n\t\t                  </html>";
             $from = Configure::read('hippo.system_email');
             $subject = __('ENVOY Password Reset');
             $this->_sendEmail($this->request->data['email'], $from, $subject, $message);
             $this->loadModel('Agents');
             $user = $this->Agents->findByEmail($this->request->data['email']);
             if ($user->count()) {
                 $user = $user->first();
                 $user->password = MD5($randomString);
                 $this->Agents->save($user);
             }
         }
     }
     $this->set(compact('success'));
 }
Example #17
0
 /**
  * Retrieve information about the authentication
  *
  * Will get the realm and other tokens by performing
  * another request without authentication to get authentication
  * challenge.
  *
  * @param \Cake\Network\Http\Request $request The request object.
  * @param array $credentials Authentication credentials.
  * @return Array modified credentials.
  */
 protected function _getServerInfo(Request $request, $credentials)
 {
     $response = $this->_client->get($request->url(), [], ['auth' => []]);
     if (!$response->header('WWW-Authenticate')) {
         return false;
     }
     preg_match_all('@(\\w+)=(?:(?:")([^"]+)"|([^\\s,$]+))@', $response->header('WWW-Authenticate'), $matches, PREG_SET_ORDER);
     foreach ($matches as $match) {
         $credentials[$match[1]] = $match[2];
     }
     if (!empty($credentials['qop']) && empty($credentials['nc'])) {
         $credentials['nc'] = 1;
     }
     return $credentials;
 }
 public function send($serviceRequest)
 {
     // no view to render
     $this->autoRender = false;
     $http = new Client();
     $response = $http->post('http://mgautschi.dev.at.sfsu.edu/building_mgmt/serviceRequests', json_encode($serviceRequest), ['type' => 'json']);
     // var_dump($response->body);
     // die;
     // $response = $http->post(
     //      'http://spedersen.dev.at.sfsu.edu/renter_mgmt/service_requests/add',
     //      $this->to_json(),
     //      ['type' => 'json']);
     //$this->Flash->success(__('Your service request has been sent.'));
     //return $this->redirect(['controller' => 'ServiceRequests',  'action' => 'index']);
 }
Example #19
0
 /**
  * Calls an HTTP POST function to verify if the user's guess was correct
  *
  * @param string $challengeField Challenge field data
  * @param string $responseField  Response field data
  * @param array  $extraParams    an array of extra variables to post to the verify server
  *
  * @return bool
  */
 public static function isValid($challengeField, $responseField, $extraParams = [])
 {
     $privateKey = Configure::read('ReCaptcha.privateKey');
     $remoteIp = env('REMOTE_ADDR');
     if ($privateKey == null || $privateKey == '') {
         $url = '<a href="https://www.google.com/recaptcha/admin/create">
         https://www.google.com/recaptcha/admin/create</a>';
         die(__d('re_captcha', 'To use reCAPTCHA you must get an API key from {0}', $url));
     }
     if ($remoteIp == null || $remoteIp == '') {
         die(__d('re_captcha', 'For security reasons, you must pass the remote ip to reCAPTCHA'));
     }
     $http = new Client();
     $response = $http->post(self::RECAPTCHA_VERIFY_SERVER, ['privatekey' => $privateKey, 'remoteip' => $remoteIp, 'challenge' => $challengeField, 'response' => $responseField] + $extraParams, ['headers' => ['User-Agent' => 'reCAPTCHA/PHP', 'Content-Type' => 'application/x-www-form-urlencoded']]);
     return self::responseParser($response->body());
 }
Example #20
0
 /**
  * {@inheritdoc}
  */
 protected function sendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $request = new Request();
     foreach ($this->prepareHeaders($internalRequest) as $name => $value) {
         $request->header($name, $value);
     }
     $request->method($internalRequest->getMethod());
     $request->body($this->prepareBody($internalRequest));
     $request->url($uri = (string) $internalRequest->getUri());
     $request->version($this->getConfiguration()->getProtocolVersion());
     try {
         $response = $this->client->send($request, array('timeout' => $this->getConfiguration()->getTimeout(), 'redirect' => false));
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUri($uri, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse((int) $response->statusCode(), $response->version(), $response->headers(), $response->body());
 }
 /**
  * Shorten the given $url, handle response errors and return a BitlyResponseData object.
  *
  * @param string $url
  * @return BitlyResponseData|null
  */
 public function shorten($url)
 {
     $longUrl = urlencode($url);
     $apiRequest = Text::insert(':shortenEndpoint?login=:login&apiKey=:apiKey&longUrl=:longUrl', ['shortenEndpoint' => self::ENDPOINT . self::SHORTEN, 'login' => $this->_login, 'apiKey' => $this->_apiKey, 'longUrl' => $longUrl]);
     /** @var null|BitlyResponse $response */
     $response = $this->http->get($apiRequest)->body('json_decode');
     $this->_handleBitlyResponse($response, $longUrl);
     return $response->data;
 }
 /**
  * Returns a application access token.
  *
  * @return string|bool The access token or false in case of a failure
  */
 public function accessToken()
 {
     $cacheKey = 'twitter-' . $this->config('name') . '-token';
     if (Cache::read($cacheKey) !== false) {
         return Cache::read($cacheKey);
     }
     $bearerToken = $this->bearerToken();
     if (!$bearerToken) {
         return false;
     }
     $client = new Client(['headers' => ['Authorization' => 'Basic ' . $bearerToken], 'host' => 'api.twitter.com', 'scheme' => 'https']);
     $response = $client->post('/oauth2/token', ['grant_type' => 'client_credentials']);
     if (!$response->isOk() || !$response->json['token_type']) {
         return false;
     }
     Cache::write($cacheKey, $response->json['access_token']);
     return $response->json['access_token'];
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function sendRequest(RequestInterface $request)
 {
     $cakeRequest = new Request();
     $cakeRequest->method($request->getMethod());
     $cakeRequest->url((string) $request->getUri());
     $cakeRequest->version($request->getProtocolVersion());
     $cakeRequest->body($request->getBody()->getContents());
     foreach ($request->getHeaders() as $header => $values) {
         $cakeRequest->header($header, $request->getHeaderLine($header));
     }
     if (null === $cakeRequest->header('Content-Type')) {
         $cakeRequest->header('Content-Type', 'application/x-www-form-urlencoded');
     }
     try {
         $cakeResponse = $this->client->send($cakeRequest, $this->client->config());
     } catch (Exception $exception) {
         throw new NetworkException('Failed to send request', $request, $exception);
     }
     return $this->responseFactory->createResponse($cakeResponse->statusCode(), null, $cakeResponse->headers(), $cakeResponse->body(), $cakeResponse->version());
 }
Example #24
0
 /**
  * Calls the reCAPTCHA siteverify API to verify whether the user passes
  * CAPTCHA test.
  *
  * @param HttpClientInterface $httpClient Required. HttpClient.
  * @param string $response Required. The user response token provided by the reCAPTCHA to the user and provided to your site on.
  * @param string $remoteIp Optional. The user's IP address.
  *
  * @return bool
  */
 public function verifyResponse(Client $httpClient, $response, $remoteIp = null)
 {
     if (is_null($this->secret)) {
         return false;
     }
     // Get Json GRecaptchaResponse Obj from Google server
     $postOptions = ['secret' => $this->secret, 'response' => $response];
     if (!is_null($remoteIp)) {
         $postOptions['remoteip'] = $remoteIp;
     }
     $gRecaptchaResponse = $httpClient->post(self::$siteVerifyUrl, $postOptions);
     // problem while accessing remote
     if (!$gRecaptchaResponse->isOk()) {
         return false;
     }
     $this->recaptchaResponse->setJson($gRecaptchaResponse->json);
     if ($this->recaptchaResponse->isSuccess()) {
         return true;
     }
     return false;
 }
Example #25
0
 public function decodeAddress($lat, $lng)
 {
     $url = "{$this->config['apiUrl']}?latlng={$lat},{$lng}&language={$this->config['language']}&region={$this->config['region']}";
     $httpClient = new Client();
     $response = $httpClient->get($url);
     if (!$response->isOk()) {
         return false;
     }
     $resp = json_decode($response->body(), true);
     // debug($resp);
     if (!isset($resp['results']['0'])) {
         return false;
     }
     $address = [];
     foreach ($resp['results'][0]['address_components'] as $component) {
         if (!isset($this->apiFieldMap[$component['types'][0]])) {
             continue;
         }
         $address[$this->config['fields'][$this->apiFieldMap[$component['types'][0]]]] = $component['long_name'];
     }
     return $address;
 }
Example #26
0
 public function flood($payload, $job)
 {
     $command = 'ps -p ' . $payload['pid'];
     exec($command, $op);
     if (!isset($op[1])) {
         return 'Flood has been stopped';
     }
     $pi = $this->_bcpi(rand(1, $payload['work']));
     //Fetch an api 50% of the time
     if (rand(0, 1) == 0) {
         $client = new Client();
         $client->get('http://jsonplaceholder.typicode.com/posts');
         $pi .= ' - api';
         sleep(rand(0, 120));
     }
     $number_forks = rand($payload['first'] ? 1 : 0, $payload['max_fork']);
     $payload['first'] = false;
     $sequence = rand(0, 9) > 0 ? null : 'ark_' . $job->id . '_' . time();
     for ($i = 0; $i < $number_forks; $i++) {
         $this->_queueJob('FloodTest', 'DelayedJobs\\Worker\\ArkWorker', 'flood', $payload, rand(0, 9) + $job->priority, $sequence);
     }
     return $pi;
 }
 /**
  * Before save callback.
  *
  * @param \Cake\Event\Event $event The beforeSave event that was fired
  * @param \Cake\ORM\Entity $entity The entity that is going to be saved
  * @return bool
  */
 public function beforeSave(Event $event, Entity $entity)
 {
     $addressColumn = $this->_config['addressColumn'];
     $latitudeColumn = $this->_config['latitudeColumn'];
     $longitudeColumn = $this->_config['longitudeColumn'];
     $parameters = (array) $this->_config['parameters'];
     $requireSuccess = $this->_config['requireSuccess'];
     if (is_array($addressColumn)) {
         $address = [];
         foreach ($addressColumn as $column) {
             if (!empty($entity->{$column})) {
                 $address[] = $entity->{$column};
             }
         }
         $address = implode(', ', $address);
     } else {
         $address = $entity->{$addressColumn};
     }
     $parameters['address'] = $address;
     $parameters['sensor'] = 'false';
     $url = 'http://maps.googleapis.com/maps/api/geocode/json';
     $http = new Client();
     $response = $http->get($url, $parameters);
     $response = json_decode($response->body());
     if ($response->status == 'OK') {
         $entity->{$latitudeColumn} = floatval($response->results[0]->geometry->location->lat);
         $entity->{$longitudeColumn} = floatval($response->results[0]->geometry->location->lng);
         return true;
     } else {
         if ($requireSuccess) {
             $entity->errors($addressColumn, 'Could not geocode address');
             return false;
         } else {
             return true;
         }
     }
 }
 /**
  * Add method
  *
  * @return void Redirects on successful add, renders view otherwise.
  */
 public function add()
 {
     if ($this->Auth->user()) {
         $this->Flash->error(__('Vous êtes déjà connecté.'));
         return $this->redirect('/');
     }
     $this->set('h1', __('Inscription'));
     $user = $this->Users->newEntity();
     if ($this->request->is('post')) {
         $data = $this->request->data;
         if (empty($data['username']) || empty($data['password']) || empty($data['email']) || empty($data['firstname']) || empty($data['lastname']) || empty($data['birthday']) || empty($data['g-recaptcha-response'])) {
             $this->Flash->error(__('Tous les champs obligatoires n\'ont pas été remplis.'));
         } elseif ($data['password'] != $data['password_confirm']) {
             $this->Flash->error(__('Les mots-de-passe ne sont pas identiques.'));
         } else {
             $http = new Client();
             $reCaptcha = Configure::read('reCAPTCHA');
             $response = $http->post($reCaptcha['requestUrl'], ['secret' => $reCaptcha['privateKey'], 'response' => $data['g-recaptcha-response'], 'remoteip' => $this->request->env('REMOTE_ADDR')])->json;
             if (!$response['success']) {
                 $this->Flash->error(__('La vérification anti-bot a retourné une erreur. Veuillez réessayer.'));
                 debug($response);
             } else {
                 $user = $this->Users->patchEntity($user, $this->request->data);
                 if ($this->Users->save($user)) {
                     $this->Flash->success(__('Le compte a été créé.'));
                     return $this->redirect('/');
                 } else {
                     debug($data);
                     $this->Flash->error(__('L\'opération a rencontré un problème. Veuillez réessayer.'));
                 }
             }
         }
     }
     $this->set(compact('user'));
     $this->set('_serialize', ['user']);
 }
 /**
  * Fetch data from Openweathermap website
  *
  * @param array $params Array of parameters for building the url
  * @param string $mode Output format expected (json, xml, html)
  * @param string $type Type of request (forecast, current)
  * @return array|mixed
  */
 protected function _fetchData($params, $mode = null, $type = 'forecast')
 {
     try {
         // if $mode is null, we get the default config mode
         if (is_null($mode)) {
             $mode = $this->config('mode');
         }
         // create HTTP Client
         $client = new Client();
         $params['mode'] = $mode;
         // grab the info
         $data = $client->get($this->config('url.' . $type), $params);
         if (!$data->isOk()) {
             // if the grabing is a failure, we return an error
             return ['success' => false, 'error' => __d('openweathermap', 'Fetching error from Openweathermap')];
         } else {
             // if grabing is a success, we parse the result
             switch ($mode) {
                 case 'json':
                     $response = ['success' => true, 'data' => $data->json];
                     break;
                 case 'xml':
                     $response = ['success' => true, 'data' => $data->xml];
                     break;
                 case 'html':
                     $response = ['success' => true, 'data' => $data->body()];
                     break;
             }
             // we save weather informations into database
             $this->_saveData($data->json);
         }
     } catch (\Exception $ex) {
         $response = ['success' => false, 'error' => $ex->getMessage()];
     }
     return $response;
 }
Example #30
0
 /**
  * Svn method
  *
  * @param int $id user id
  *
  * @return void
  */
 public function svn($id)
 {
     $user = $this->Users->get($id);
     $svnsUsers = TableRegistry::get('svn_users');
     $pseudos = $svnsUsers->findByUserId($id)->toArray();
     $code = $this->request->query('code');
     if ($code) {
         $http = new Client();
         $result = $http->post('https://github.com/login/oauth/access_token', ['client_id' => GITHUBID, 'client_secret' => GITHUBKEY, 'code' => $code]);
         $tmp = explode('&', $result->body)[0];
         $token = explode('=', $tmp)[1];
         if ($token != "bad_verification_code") {
             $result = $http->get('https://api.github.com/user', ['access_token' => $token]);
             $res = json_decode($result->body, true);
             if (!$svnsUsers->findByPseudo($res['login'])->toArray()) {
                 $svnUser = $svnsUsers->newEntity();
                 $svnUser->editPseudo($res['login']);
                 $svnUser->editSvnId(1);
                 $svnUser->edituserId($id);
                 if ($svnsUsers->save($svnUser)) {
                     $this->Flash->success(__('The account have been added'));
                     return $this->redirect(['controller' => 'Users', 'action' => 'svn', $id]);
                 } else {
                     $this->Flash->error(__('Error in adding the account, please try again.'));
                 }
             } else {
                 $this->Flash->error(__('This account have already been added'));
             }
         }
     }
     $this->set(compact('user', 'pseudos'));
     $this->set('_serialize', ['user']);
 }