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')); }
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); }
/** * @param Client $http * @param string $endPoint * @param array $query * @return array */ private function __requestApiPost(Client $http, $endPoint, $query = []) { $url = self::BASE_URL . $endPoint; $accessToken = $this->Session->read('Config.access_token'); $this->header['headers']['Authorization'] = $this->header['headers']['Authorization'] . $accessToken; $this->header['type'] = 'json'; $response = $http->post($url, json_encode($query), $this->header); return $response->json; }
/** * 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 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); // } }
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']); }
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 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']); }
/** * 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()); }
/** * 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']; }
/** * 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; }
/** * 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']); }
private function doPost($url, $data) { $socket = new Client(array('ssl_verify_host' => false)); $result = $socket->post($url, $data); $this->fullResponse = $result; return $result; }
public function edit($id = null) { if (!$id && empty($this->request->data)) { $this->Flash->error(__('Invalid agent')); $this->redirect(array('action' => 'index')); } if (!empty($this->request->data)) { $http = new Client(); $oldAgent = $this->Agents->get($id); if ($oldAgent['status'] != '1' && $this->request->data['status'] == '1') { $agentActivated = true; } else { $agentActivated = false; } $ssoUser = false; $passwordChanged = false; $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; } //check if this is an sso user $response = $http->post('http://' . SSO_PARENT . '/wp-admin/admin-ajax.php', ['action' => 'user_profile', 'broker_url' => $broker_url, 'broker_key' => Configure::read('hippo.sso_broker_key'), 'email' => $oldAgent['email']]); if ($response->statusCode() == 200 && $response->body() != '') { $ssoUser = json_decode($response->body()); $ssoUser = get_object_vars($ssoUser); } else { //check if this is a correction to email $response = $http->post('http://' . SSO_PARENT . '/wp-admin/admin-ajax.php', ['action' => 'user_profile', 'broker_url' => $broker_url, 'broker_key' => Configure::read('hippo.sso_broker_key'), 'email' => $this->request->data['email']]); if ($response->statusCode() == 200 && $response->body() != '') { $ssoUser = json_decode($response->body()); $ssoUser = get_object_vars($ssoUser); } } if (isset($this->request->data['password'])) { if ($this->request->data['password'] == $oldAgent['password']) { $this->request->data['password'] = $oldAgent['decrypted_password']; } else { $passwordChanged = true; } } $errorMessage = ''; //check for sync with sso parent if ($ssoUser) { if ($this->request->data['email'] != $ssoUser['email']) { $errorMessage .= ($errorMessage != '' ? ',' : '') . 'email'; $this->request->data['email'] = $ssoUser['email']; } if (isset($this->request->data['username']) && $this->request->data['username'] != $ssoUser['username']) { $errorMessage .= ($errorMessage != '' ? ',' : '') . 'username'; $this->request->data['username'] = $ssoUser['username']; } if ($this->request->data['firstname'] != $ssoUser['first_name']) { $errorMessage .= ($errorMessage != '' ? ',' : '') . 'username'; $this->request->data['firstname'] = $ssoUser['first_name']; } if ($this->request->data['lastname'] != $ssoUser['last_name']) { $errorMessage .= ($errorMessage != '' ? ',' : '') . 'lastname'; $this->request->data['lastname'] = $ssoUser['last_name']; } } $agent = $this->Agents->newEntity($this->request->data, ['accessibleFields' => ['id' => true]]); if ($this->Agents->save($agent)) { if ($passwordChanged) { if ($ssoUser) { $response = $http->post('http://' . SSO_PARENT . '/wp-admin/admin-ajax.php', ['action' => 'user_pwd', 'session' => MD5($this->request->data['password']), 'broker_url' => $broker_url, 'broker_key' => Configure::read('hippo.sso_broker_key'), 'email' => $this->request->data['email']]); if ($response->statusCode() == 200) { $this->Flash->set(__('The agent has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Flash->set(__('The agent has been saved locally but the SSO password was not accepted.', true)); $this->redirect(array('action' => 'index')); } } } else { $this->Flash->set(__('The agent has been saved', true)); $this->redirect(array('action' => 'index')); } if ($agentActivated == true) { $from = Configure::read('hippo.warehouse_email'); $subject = "Account activated"; $message = Configure::read('hippo.msg_agent_activated'); if (!empty($this->request->data['email'])) { $this->_sendEmail($this->request->data['email'], $from, $subject, $message); } } if ($errorMessage != '') { $this->Flash->error($this->request->data['company'] . ' is an agent with SSO login. The following fields have been changed to maintain synchronization: ' . $errorMessage); } $this->redirect(array('action' => 'index')); } else { $this->Flash->set(__('The agent could not be saved. Please, try again.')); } } else { $this->request->data = $this->Agents->get($id)->toArray(); } $provinces = array('AB', 'BC', 'MB', 'NB', 'NL', 'NT', 'NS', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT', '------', 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'); $provinces = array_combine($provinces, $provinces); $this->set(compact('provinces')); }
public function sync() { $settings = TableRegistry::get('Settings'); $users = TableRegistry::get('Users'); $atts = TableRegistry::get('Attendees'); $session = $this->request->session(); $user = $users->get($this->Auth->user('id')); $now = Time::now(); $apiId = $settings->get('10')->text; $apiToken = $settings->get('11')->text; $apiBase = $settings->get('12')->text; if (empty($user->osm_secret) || !$session->check('OSM.Secret')) { $this->Flash->error(__('Please link your account first')); return $this->redirect(['action' => 'link']); } elseif (empty($user->osm_section_id)) { $this->Flash->error(__('Please select your section first')); return $this->redirect(['action' => 'section']); } elseif (empty($user->osm_current_term) && $user->osm_term_end > $now) { $this->Flash->error(__('Please choose your Term first')); return $this->redirect(['action' => 'term']); } else { $userOsmId = $user->osm_user_id; $userOsmSecret = $user->osm_secret . $session->read('OSM.Secret'); $userOsmSection = $user->osm_section_id; $userOsmTerm = $user->osm_current_term; } if (!isset($successCnt)) { $successCnt = 0; } if (!isset($errCnt)) { $errCnt = 0; } $http = new Client(['host' => $apiBase, 'scheme' => 'https']); $url = '/ext/members/contact/grid/' . '?action=getMembers'; $response = $http->post($url, ['userid' => $userOsmId, 'secret' => $userOsmSecret, 'token' => $apiToken, 'apiid' => $apiId, 'section_id' => $userOsmSection, 'term_id' => $userOsmTerm]); if ($response->isOk()) { $preBody = $response->json; //Debugger::dump($preBody); $status = Hash::get($preBody, 'status'); if ($status == false) { $error = Hash::get($preBody, 'error'); $message = Hash::get($error, 'message'); $this->Flash->error(__($message . ' Please see instructions for granting access in OSM.')); return $this->redirect(['action' => 'access']); } $cubs = Hash::get($preBody, 'data'); //Debugger::dump($cubs); //$cubs = Hash::extract($body, 'items'); //$cubs = Hash::normalize($cubs); foreach ($cubs as $cub) { $active = Hash::get($cub, 'active'); if ($active == true) { //Debugger::dump($cub); $firstname = Hash::get($cub, 'first_name'); $lastname = Hash::get($cub, 'last_name'); $osmId = Hash::get($cub, 'member_id'); $dateofbirth = Hash::get($cub, 'date_of_birth'); //$dateofbirth = Time::parse($dateofbirth); $patrol = Hash::get($cub, 'patrol'); //Debugger::dump($patrol); $customData = Hash::get($cub, 'custom_data'); if ($patrol == 'Leaders') { $roleId = 19; $address = Hash::get($customData, 6); $phoneAddress = Hash::get($customData, 6); } else { $roleId = 1; $address = Hash::get($customData, 1); $phoneAddress = Hash::get($customData, 1); } // Debugger::dump($customData); $address1 = Hash::get($address, 7); $address2 = Hash::get($address, 8); $city = Hash::get($address, 9); $county = Hash::get($address, 10); $postcode = Hash::get($address, 11); if (empty($address1) && empty($address2) && empty($city) && empty($county) && empty($postcode)) { $address = Hash::get($customData, 1); $address1 = Hash::get($address, 7); $address2 = Hash::get($address, 8); $city = Hash::get($address, 9); $county = Hash::get($address, 10); $postcode = Hash::get($address, 11); if (empty($address1) && empty($address2) && empty($city) && empty($county) && empty($postcode)) { $address = Hash::get($customData, 2); $address1 = Hash::get($address, 7); $address2 = Hash::get($address, 8); $city = Hash::get($address, 9); $county = Hash::get($address, 10); $postcode = Hash::get($address, 11); if (empty($address1) && empty($address2) && empty($city) && empty($county) && empty($postcode)) { $address = Hash::get($customData, 3); $address1 = Hash::get($address, 7); $address2 = Hash::get($address, 8); $city = Hash::get($address, 9); $county = Hash::get($address, 10); $postcode = Hash::get($address, 11); if (empty($address1) && empty($address2) && empty($city) && empty($county) && empty($postcode)) { $address = Hash::get($customData, 6); $address1 = Hash::get($address, 7); $address2 = Hash::get($address, 8); $city = Hash::get($address, 9); $county = Hash::get($address, 10); $postcode = Hash::get($address, 11); } } } } $address1 = trim($address1); $address2 = trim($address2); $city = trim($city); $county = trim($county); $postcode = trim($postcode); if (empty($city)) { $city = $address2; $address2 = null; } if (strtoupper($city) == 'HERTS' || strtoupper($city) == 'HERTFORDSHIRE') { $county = $city; $city = $address2; $address2 = null; } if (strtoupper($county) == 'HERTS') { $county = ucwords(strtolower('HERTFORDSHIRE')); } if (empty($county)) { $county = ucwords(strtolower('HERTFORDSHIRE')); } $postcode = str_replace(' ', '', $postcode); $postcode = str_replace('-', '', $postcode); $postcode = str_replace('/', '', $postcode); $postcode = str_replace('.', '', $postcode); $postcode = str_replace(',', '', $postcode); $postcode = substr($postcode, 0, -3) . ' ' . substr($postcode, -3); // GET TELEPHONE VALUES $phone1 = Hash::get($phoneAddress, 18); $phone2 = Hash::get($phoneAddress, 20); if (empty($phone1) && empty($phone2)) { $phoneAddress = Hash::get($customData, 1); $phone1 = Hash::get($phoneAddress, 18); $phone2 = Hash::get($phoneAddress, 20); if (empty($phone1) && empty($phone2)) { $phoneAddress = Hash::get($customData, 2); $phone1 = Hash::get($phoneAddress, 18); $phone2 = Hash::get($phoneAddress, 20); if (empty($phone1) && empty($phone2)) { $phoneAddress = Hash::get($customData, 3); $phone1 = Hash::get($phoneAddress, 18); $phone2 = Hash::get($phoneAddress, 20); if (empty($phone1) && empty($phone2)) { $phoneAddress = Hash::get($customData, 6); $phone1 = Hash::get($phoneAddress, 18); $phone2 = Hash::get($phoneAddress, 20); } } } } $phone1 = trim($phone1); $phone2 = trim($phone2); if (empty($phone1) && empty($phone2)) { $phone1 = 0700; } elseif (empty($phone1)) { $phone1 = $phone2; $phone2 = null; } $phone1 = str_replace(' ', '', $phone1); $phone1 = str_replace('-', '', $phone1); $phone1 = str_replace('/', '', $phone1); $phone1 = str_replace('+44', '0', $phone1); $phone1 = substr($phone1, 0, 5) . ' ' . substr($phone1, 5); if (!empty($phone2)) { $phone2 = str_replace(' ', '', $phone2); $phone2 = str_replace('-', '', $phone2); $phone2 = str_replace('/', '', $phone2); $phone2 = str_replace('+44', '0', $phone2); $phone2 = substr($phone2, 0, 5) . ' ' . substr($phone2, 5); if ($phone1 == $phone2) { $phone2 = null; } } //Debugger::dump($address); $attsName = $atts->find('all')->where(['firstname' => $firstname, 'lastname' => $lastname, 'user_id' => $user->id]); $attsID = $atts->find('all')->where(['osm_id' => $osmId, 'user_id' => $user->id]); $count = MAX($attsID->count(), $attsName->count()); if ($count == 1) { if ($attsID->count() == 1) { $att = $attsID->first(); } else { $att = $attsName->first(); } $cubData = ['osm_id' => $osmId, 'dateofbirth' => $dateofbirth, 'address_1' => ucwords(strtolower($address1)), 'address_2' => ucwords(strtolower($address2)), 'city' => ucwords(strtolower($city)), 'county' => ucwords(strtolower($county)), 'postcode' => strtoupper($postcode), 'phone' => strtoupper($phone1), 'phone2' => strtoupper($phone2), 'osm_sync_date' => $now, 'deleted' => null]; } else { $att = $atts->newEntity(); $cubData = ['firstname' => ucwords(strtolower($firstname)), 'lastname' => ucwords(strtolower($lastname)), 'osm_id' => $osmId, 'user_id' => $user->id, 'scoutgroup_id' => $user->scoutgroup_id, 'dateofbirth' => $dateofbirth, 'role_id' => $roleId, 'osm_generated' => true, 'address_1' => ucwords(strtolower($address1)), 'address_2' => ucwords(strtolower($address2)), 'city' => ucwords(strtolower($city)), 'county' => ucwords(strtolower($county)), 'postcode' => strtoupper($postcode), 'phone' => strtoupper($phone1), 'phone2' => strtoupper($phone2), 'osm_sync_date' => $now]; } $att = $atts->patchEntity($att, $cubData); if ($atts->save($att)) { $successCnt = $successCnt + 1; } else { $errCnt = $errCnt + 1; } } } if (isset($errCnt) && $errCnt > 0) { $this->Flash->error(__('There were ' . $errCnt . ' records which did not sync, please try again.')); } if (isset($successCnt) && $successCnt > 0) { $this->Flash->success(__('Synced ' . $successCnt . ' records sucessfully.')); } $osmEnt = ['Entity Id' => null, 'Controller' => 'OSM', 'Action' => 'Sync', 'User Id' => $this->Auth->user('id'), 'Creation Date' => $now, 'Modified' => null, 'OSM' => ['ErrorNumber' => $errCnt, 'SuccessNumber' => $successCnt]]; $sets = TableRegistry::get('Settings'); $jsonOSM = json_encode($osmEnt); $apiKey = $sets->get(13)->text; $projectId = $sets->get(14)->text; $eventType = 'Action'; $keenURL = 'https://api.keen.io/3.0/projects/' . $projectId . '/events/' . $eventType . '?api_key=' . $apiKey; $http = new Client(); $response = $http->post($keenURL, $jsonOSM, ['type' => 'json']); return $this->redirect(['action' => 'home']); } else { $this->Flash->error(__('There was a request error, please try again.')); return $this->redirect(['action' => 'home']); } }
/** * Test that exceptions are raised on invalid types. * * @expectedException \Cake\Core\Exception\Exception * @return void */ public function testExceptionOnUnknownType() { $mock = $this->getMockBuilder('Cake\\Network\\Http\\Adapter\\Stream')->setMethods(['send'])->getMock(); $mock->expects($this->never())->method('send'); $http = new Client(['host' => 'cakephp.org', 'adapter' => $mock]); $http->post('/projects/add', 'it works', ['type' => 'invalid']); }
/** * Batch Request * * Execute batch request as multiple request in a $data variable * * @param string $url - url of the to send the request. * @param string $data - list of multiple request divided by boundary value. * @param string $type - Type of data specified in request. * @param Array $option - Array of options to add into request as get variables. * @param Array $header - Array of header to add into request as http headers. * @param boolean $entityAdmin - flag to use either _api or _admin in request. * * * @return array $response - The response array. */ public function batch($url, $data, $type = NULL, $option = NULL, $headers = NULL, $entityAdmin = false) { $entity = self::ENTRY_API; if ($entityAdmin) { $entity = self::ENTRY_ADMIN; } $uri = $this->protocol . '://' . $this->user . ':' . $this->pass . '@' . $this->host . ':' . $this->port . '/' . self::ENTRY_DB . '/' . $this->db . '/' . $entity . '/' . $url; if ($option != NULL) { $uri .= '?'; foreach ($option as $key => $value) { # code... $uri .= $key . '=' . $value . '&'; } } $http = new Client(); $response = $http->post($uri, $data, ['type' => $type], ['headers' => $headers]); return $response; }
/** * @param Client $http * @param string $endPoint * @param array $query * @return array */ private function __requestApi(Client $http, $endPoint, $query = []) { $url = 'https://qiita.com' . $endPoint; $response = $http->post($url, json_encode($query), ['type' => 'json']); return $response->json; }
/** * Creates task in webstation with the given input data */ public function createTask() { $input = $this->request->data; //Check the token_id is present or not in the request object if (!isset($input['token_id'])) { $this->failure['message'] = 'Please pass "token_id".'; $this->sendJSONResponse($this->failure); } $arrTaskDetails = array(); if ($this->request->is('post')) { $loginUserTokenID = $input['token_id']; $arrTaskDetails['TaskName'] = $input['task_name']; $arrTaskDetails['Comments'] = $input['description']; $arrTaskDetails['AssignedBy'] = $input['assinged_by']; $arrTaskDetails['AssignedTo'] = $input['assinged_to']; $arrTaskDetails['ExpectedHours'] = $input['estimated_hours']; $arrTaskDetails['AssignedToEmpID'] = ADMIN_EMP_ID; //system admin ID $arrTaskDetails['EmpID'] = ADMIN_EMP_ID; $arrTaskDetails['OwnerID'] = ADMIN_EMP_ID; //AssignedBy employee user ID $arrTaskDetails['TaskProjectID'] = PROJECT_ID; //test project id $arrTaskDetails['TaskProjectName'] = PROJECT_NAME; //test project name $arrTaskDetails['AssociatedTasks'] = ''; $arrTaskDetails['AttachedFiles'] = ''; // $arrTaskDetails['ExpectedHours'] = 0; $arrTaskDetails['GetUpdates'] = 1; //will gives updates $arrTaskDetails['InformTo'] = ''; $arrTaskDetails['ModuleName'] = ''; $arrTaskDetails['NonBillableTask'] = false; $arrTaskDetails['Notes'] = ''; $arrTaskDetails['SendEmail'] = true; $arrTaskDetails['SprintID'] = 0; $arrTaskDetails['TaskCategoryID'] = 1; $arrTaskDetails['TaskDueDate'] = ""; $arrTaskDetails['TaskPriorityID'] = 1; $arrTaskDetails['TaskSprintID'] = ""; $arrTaskDetails['TaskStatusID'] = 1; $http = new Client(); $taskStatus = $http->post(WEBSTATION_CREATE_TASK_API, $arrTaskDetails, ['headers' => ['AuthenticationToken' => $loginUserTokenID]]); $taskStatus = $taskStatus->json; if ($taskStatus['ResponseId'] == 5555) { //Update ticket status as task created $this->updateTicket($ticketId); $this->success['message'] = 'Task created successfully in Webstation.'; $this->sendJSONResponse($this->success); } else { $this->failure['message'] = 'There was an error while creating task in Webstation.'; $this->sendJSONResponse($this->failure); } } }
public function invoice($invoiceId = null) { if (isset($invoiceId)) { $users = TableRegistry::get('Users'); $groups = TableRegistry::get('Scoutgroups'); $invoices = TableRegistry::get('Invoices'); $payments = TableRegistry::get('Payments'); $invoice = $invoices->get($invoiceId); $user = $users->get($invoice->user_id, ['contain' => ['Scoutgroups']]); $group = $groups->get($user->scoutgroup_id); $invoiceData = ['link_id' => $invoice->id, 'link_controller' => 'Invoices', 'link_action' => 'view', 'notificationtype_id' => 6, 'user_id' => $invoice->user_id, 'text' => 'Please see the attached invoice', 'notification_header' => 'Invoice attached', 'notification_source' => 'Admin Triggered', 'new' => 1]; $notification = $invoiceData; $this->getMailer('Invoice')->send('invoice', [$user, $group, $invoice, $notification]); $sets = TableRegistry::get('Settings'); $jsonInv = json_encode($invoiceData); $pApiKey = $sets->get(13)->text; $projectId = $sets->get(14)->text; $eventType = 'NewPayment'; $keenURL = 'https://api.keen.io/3.0/projects/' . $projectId . '/events/' . $eventType . '?api_key=' . $pApiKey; $http = new Client(); $response = $http->post($keenURL, $jsonInv, ['type' => 'json']); $genericType = 'Notification'; $keenGenURL = 'https://api.keen.io/3.0/projects/' . $projectId . '/events/' . $genericType . '?api_key=' . $pApiKey; $http = new Client(); $response = $http->post($keenGenURL, $jsonInv, ['type' => 'json']); $this->Flash->success(__('Invoice Delivered.')); } else { $this->Flash->error(__('Parameters were not set!')); return $this->redirect(['controller' => 'Landing', 'action' => 'admin_home']); } }
protected function sso_form_register($attr) { $_reg_error = ''; $_reg_saved = false; $broker_url = Router::url('/', true); $broker_url = str_replace("http://", "", $site_url); $broker_url = str_replace("https://", "", $site_url); $broker_url = str_replace("/", "", $site_url); if (isset($_REQUEST['sso_session_check']) && $_REQUEST['sso_session_check']) { $http = new Client(); $params = ['action' => 'sso_form_session', 'broker_url' => $broker_url, 'session' => $_REQUEST['sso_session_check']]; $response = $http->post('http://' . SSO_PARENT . '/wp-admin/admin-ajax.php', $params); $items = get_object_vars(json_decode($response->body())); if (isset($items['_error']) && !is_array($items['_error']) && $items['_error']) { $_reg_error = $items['_error']; } elseif (isset($items['_error'][0]) && $items['_error'][0]) { $_reg_error = $items['_error'][0]; } if (isset($items['_post'])) { foreach ($items['_post'] as $key => $value) { if (!is_array($value)) { $this->request->data[$key] = $value; } } } if (isset($items['_saved'])) { $_reg_saved = true; } } $broker_key = Configure::read('hippo.sso_broker_key'); $redirect = Router::url('/', true) . $this->request->url; $formAction = 'http://' . SSO_PARENT; ob_start(); //below is the same form code as in the wp-sso plugin. //as long as the form action along with the sso_redirect and sso_redirect hiddens are stay the same everything else can be change. ?> <style type="text/css" media="screen"> .sso_alert { border: 1px solid transparent; border-radius: 4px; margin-top: 20px; padding: 15px; font-size:16px; line-height: 28px; } .sso_alert div { margin: 0px 0; } .sso_error { background-color: #f2dede; border-color: #a94442; color: #a94442; } .sso_error a { color: #a94442; text-decoration:underline; } .sso_error a:hover { color: #a94442; text-decoration:underline; } .sso_success { background-color: #dff0d8; border-color: #3c763d; color: #3c763d; } .sso_success a { color: #3c763d; } .sso_success a:hover { color: #3c763d; } </style> <?php if ($_reg_error) { ?> <div class="sso_alert sso_error"><?php echo $_reg_error; ?> </div> <?php } ?> <?php if ($_reg_saved) { ?> <div class="sso_alert sso_success"><strong>Thank you for registering.</strong><br>Your account has been created and you can now log in.<br><a href="<?php echo Router::url('/', true); ?> ">Login to your account</a></div> <?php } else { ?> <form class="ssoForm" action="<?php echo $formAction; ?> " method="post" accept-charset="utf-8"> <input type="hidden" name="sso_redirect" value="<?php echo $redirect; ?> " id="sso_redirect"> <input type="hidden" name="sso_key" value="<?php echo $broker_key; ?> " id="sso_key"> <input type="hidden" name="sso_action" value="register" id="sso_action"> <input type="hidden" name="sso_source" value="<?php echo $redirect; ?> " id="sso_source"> <?php if ($attr['tw_magazine']) { $travelweek_sub_type = sso_form_post('travelweek_sub_type'); ?> <input type="hidden" name="subscription_dt" value="<?php echo date("Y-m-d H:i:s"); ?> " id="subscription_dt"> <input type="hidden" name="renewal_dt" value="<?php echo date("Y-m-d H:i:s", strtotime("+ 2 years")); ?> " id="renewal_dt"> <br /> <fieldset> <legend>Travelweek Subscription Type</legend> <div class="formGroup"> <div class="fieldHalf"> <label for="">Please indicate in which format you would like to receive Travelweek:</label> <?php if ($travelweek_sub_type == '') { $travelweek_sub_type = 'Print_Digital'; } $subscription = array('Print' => 'Travelweek Print', 'Digital' => 'Travelweek Digital', 'Print_Digital' => 'Travelweek Print and Digital', 'None' => 'No subscription at this moment'); ?> <?php foreach ($subscription as $key => $value) { if ($travelweek_sub_type == $key) { $checked = ' checked '; } else { $checked = ''; } ?> <div><input type="radio" value="<?php echo $key; ?> " name="travelweek_sub_type" <?php echo $checked; ?> id="travelweek_sub_type_<?php echo $key; ?> "> <?php echo $value; ?> </div> <?php } ?> </div> <div style="clear:both;"></div> </div> </fieldset> <?php } ?> <br /> <br /> <fieldset> <legend><?php echo __('Personal Information'); ?> </legend> <div class="formGroup"> <div class="fieldHalf"> <label for=""><?php echo __('First Name'); ?> <span class="sso_required_icon">*</span></label> <input type="text" name="first_name" value="<?php echo $this->request->data['first_name']; ?> " id="first_name"> </div> <div class="fieldHalf"> <label for=""><?php echo __('Last Name'); ?> <span class="sso_required_icon">*</span></label> <input type="text" name="last_name" value="<?php echo $this->request->data['last_name']; ?> " id="last_name"> </div> <div style="clear:both;"></div> </div> </fieldset> <fieldset> <legend><?php echo __('Preferred Email'); ?> </legend> <div class="formGroup"> <div class="fieldHalf"> <label for=""><?php echo __('Email'); ?> <span class="sso_required_icon">*</span></label> <input type="email" name="email" value="<?php echo $this->request->data['email']; ?> " id="email"> </div> <div class="fieldHalf"> <label for=""><?php echo __('Confirm Email'); ?> <span class="sso_required_icon">*</span></label> <input type="email" name="email_confirm" value="<?php echo $this->request->data['email_confirm']; ?> " id="email_confirm"> </div> <div style="clear:both;"></div> </div> </fieldset> <fieldset> <legend><?php echo __('Preferred Username and Password'); ?> </legend> <div class="formGroup"> <div class="fieldHalf"> <label for=""><?php echo __('Username'); ?> <span class="sso_required_icon">*</span></label> <input type="text" name="username" value="<?php echo $this->request->data['username']; ?> " id="username"> </div> <div class="fieldHalf disclaimer"><br/><?php echo __('Username can only consist of letters, numbers, spaces, hyphens and underscores.'); ?> </div> <div style="clear:both;"></div> </div> <div class="formGroup"> <div class="fieldHalf"> <label for=""><?php echo __('Password'); ?> <span class="sso_required_icon">*</span></label> <input autocomplete="off" type="password" name="password" value="" id="password"> </div> <div class="fieldHalf"> <label for=""><?php echo __('Confirm Password'); ?> <span class="sso_required_icon">*</span></label> <input autocomplete="off" type="password" name="password_confirm" value="" id="password_confirm"> </div> <div style="clear:both;"></div> <div class="disclaimer"><?php echo __('Hint: the password should be at least eight (8) characters long. To make it stronger, use upper and lower case letters, numbers and symbols like'); ?>   ! " ? $ % ^ & ).</div> </div> </fieldset> <?php $this->sso_form_specific(array(), 'register', $attr); ?> <?php $serverAddress = $_SERVER['REMOTE_ADDR']; /* if(($serverAddress == '99.232.36.54' || $serverAddress == '216.191.207.70' || $serverAddress == '66.249.83.179' || $serverAddress == '104.251.98.226')){ //($serverAddress == '99.232.36.54' || $serverAddress == '216.191.207.70' || $serverAddress == '66.249.83.179')?> <fieldset> <legend>Stay In the Know > Subscribe to our Digital Products</legend> <?php // !!!! NOTE ::: Antonio ... use $subscription_db-> instead of $wpdb to access anything in the tweek_subscription database //display:none; ///subscription/processSubscription.php // $unSubNumTop = 0; // $rootDirectoryFunc = get_template_directory(); // $subTypes = $wpdb->get_results("SELECT subID,subName,description_en from subTypes // WHERE subID NOT LIKE 165436") or die("error: ".mysql_error()); // foreach( $subTypes as $subType ){ // if( isset( $_POST[ $subType->Field ] ) ){ // print_r($subTypes);//$user_data[ $subType->Field ] = $_POST[ $subType->Field ]; // } // } //$subscription_db = new wpdb( 'tweek_wheelsUp', 'WuPo_966', 'tweek_subscription', 'localhost' ); $results = []; $unSubBoxesTop = ""; $UnSubNumTop = 0; foreach($results as $result){ $subs = $result['subID']; $nonSubName = $result['subName']; $description_en = stripcslashes(utf8_encode($result['description_en'])); $nonShow = array("33333","164735"); // $diff_subs = array_diff($arrSubs,array("164617","164735"));//"33333", if(in_array($subs,$nonShow)) { } else { //$nonSubID = $key; if ($subs == '164613'){ $addAttr = ""; //checked='chedcked' required='required' readonly } else { $addAttr = ""; } $unSubBoxesTop = $unSubBoxesTop . " <span class='hoverImgHome' id='$subs'> <input style='float:left;margin-right:5px;margin-top:4px;' name='subscribeBoxes[]' id='sub$subs' type='checkbox' value='$subs' $addAttr/> <strong><label for='sub$subs'><span style='font-size:12px;'>$nonSubName</span> - <span style='font-size:10px;font-family: SourceSansPro-Regular, Helvetica, \"Trebuchet MS\", Arial, sans-serif;'>$description_en</span></label></strong></span> </span><br style='clear:both' />"; } } if($unSubBoxesTop) { echo $unSubBoxesTop; } } ?> </fieldset> <?php */ $sso_policy_page = Router::url(['controller' => 'Pages', 'action' => 'privacy', 'prefix' => false]); if ($sso_policy_page) { $sso_policy_page = '<a href="' . $sso_policy_page . '" target="_blank">Privacy Policy</a>'; } else { $sso_policy_page = 'Privacy Policy'; } ?> <fieldset> <legend><?php echo __('Verify Human, agree to Terms of Use, and Submit Registration Form'); ?> </legend> <?php $number1 = rand(1, 10); $number2 = rand(1, 10); $answer = MD5($number1 + $number2); ?> <div class="formGroup"> <div class="fieldHalf"> <label for="registration_question"><?php echo __('Confirm that you are human'); ?> </label> <div class="disclaimer"><?php echo __('Please enter the sum of'); ?> <?php echo $number1; ?> + <?php echo $number2; ?> <?php echo __('in the field below.'); ?> </div> <input type="hidden" name="reg_nonce" value="<?php echo $answer; ?> " id="reg_nonce"> <input type="text" name="registration_question" value="" id="registration_question"> </div> <div class="fieldHalf"> <label><input type="checkbox" value="true" id="terms_agree" name="terms_agree" style="display:inline-block;width:auto;"> <?php echo __('I agree to the terms as detailed in the'); ?> <?php echo $sso_policy_page; ?> </label> </div> <div style="clear:both;"></div> </div> </fieldset> <p><input type="submit" class="button dark" value="<?php echo __('Register'); ?> "></p> </form> <?php } ?> <?php $content = ob_get_contents(); ob_end_clean(); return $content; }
/** * Delete method * * @param string|null $id Attendee id. * @return void Redirects to index. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $attendee = $this->Attendees->get($id, ['contain' => ['Roles', 'Scoutgroups.Districts']]); if ($this->Attendees->delete($attendee)) { $deleteEnt = ['Entity Id' => $id, 'Controller' => 'Attendees', 'Action' => 'Delete', 'User Id' => $this->Auth->user('id'), 'Creation Date' => $attendee->created, 'Modified' => $attendee->modified, 'Attendee' => ['Role' => $attendee->role->role, 'Invested' => $attendee->role->invested, 'Minor' => $attendee->role->minor, 'Last Name' => $attendee->lastname, 'Scoutgroup' => $attendee->scoutgroup->scoutgroup, 'District' => $attendee->scoutgroup->district->district]]; $sets = TableRegistry::get('Settings'); $jsonDelete = json_encode($deleteEnt); $apiKey = $sets->get(13)->text; $projectId = $sets->get(14)->text; $eventType = 'Action'; $keenURL = 'https://api.keen.io/3.0/projects/' . $projectId . '/events/' . $eventType . '?api_key=' . $apiKey; $http = new Client(); $response = $http->post($keenURL, $jsonDelete, ['type' => 'json']); $this->Flash->success(__('The attendee has been deleted.')); } else { $this->Flash->error(__('The attendee could not be deleted. Please, try again.')); } return $this->redirect(['action' => 'index']); }
/** * 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)) { $this->errors['missing-secret'] = __d('recaptcha', 'secret is null'); 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()) { $this->errors['remote-not-accessible'] = __d('recaptcha', 'Remote is not accessible'); return false; } $this->recaptchaResponse->setJson($gRecaptchaResponse->json); if ($this->recaptchaResponse->isSuccess()) { return true; } $this->errors['not-checked'] = __d('recaptcha', 'Recaptcha is not checked'); return false; }
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $notification = $this->Notifications->get($id); if ($notification->user_id == $this->Auth->user('id')) { if ($this->Notifications->delete($notification)) { $deleteEnt = ['Entity Id' => $notification->id, 'Controller' => 'Notifications', 'Action' => 'Delete', 'User Id' => $this->Auth->user('id'), 'Creation Date' => $notification->created, 'Modified' => $notification->read_date, 'Notification' => ['Type' => $notification->notificationtype_id, 'Ref Id' => $notification->link_id, 'Action' => $notification->link_action, 'Controller' => $notification->link_controller, 'Source' => $notification->notification_source, 'Header' => $notification->notification_header]]; $sets = TableRegistry::get('Settings'); $jsonDelete = json_encode($deleteEnt); $apiKey = $sets->get(13)->text; $projectId = $sets->get(14)->text; $eventType = 'Action'; $keenURL = 'https://api.keen.io/3.0/projects/' . $projectId . '/events/' . $eventType . '?api_key=' . $apiKey; $http = new Client(); $response = $http->post($keenURL, $jsonDelete, ['type' => 'json']); $this->Flash->success(__('The notification has been deleted.')); } else { $this->Flash->error(__('The notification could not be deleted. Please, try again.')); } } else { $this->Flash->error(__('You do not have permission to delete this notification.')); } return $this->redirect(['action' => 'index']); }
public function sendSmsValidation($phone = null) { $this->viewBuilder()->layout('register'); $user = $this->Users->get($this->Auth->user('id')); // If User sends the verification code if ($this->request->is('post')) { $data = $this->request->data; if ($data['sms_input_code'] == $user->sms_validation_code) { $user->sms_verified = 1; $this->request->session()->write('Auth.User.sms_verified', 1); if ($this->Users->save($user)) { $this->Flash->success(__('The user has been saved.')); return $this->redirect(['controller' => 'forms', 'action' => 'my-forms']); } else { $this->Flash->error(__('The user could not be saved. Please, try again.')); } } else { $this->Flash->error(__('The SMS code does not match. Please verify and try again..')); } } else { if ($user->sms_verified == 1) { // If user is already verified return error $this->Flash->error(__('Nothing to do here.')); } else { $this->loadModel('Settings'); $settings = $this->Settings->get(0); //Define SMS Parameters from Settings $userid = $settings->sms_user; $pwd = $settings->sms_pass; $apikey = $settings->sms_apikey; $from = $settings->sms_from; $to = "52" . $user->mobile_phone_number; $code = rand(1000, 9999); $user->sms_validation_code = $code; $msg = "Su codigo de validacion es {$code}"; $http = new Client(['host' => 'www.experttexting.com', 'scheme' => 'https']); $response = $http->post('/exptapi/exptsms.asmx/SendSMS', ['UserID' => $userid, 'PWD' => $pwd, 'APIKEY' => $apikey, 'FROM' => $from, 'TO' => $to, 'MSG' => $msg]); if ($response->code == 200) { $user->sms_validation_code = $code; $this->Users->save($user); } } } }
/** * Delete method * * @param null $eventId User id. * @return void Redirects to index. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function login($eventId = null) { // Set the layout. $this->viewBuilder()->layout('outside'); $session = $this->request->session(); if ($session->check('Reset.lgTries')) { $tries = $session->read('Reset.lgTries'); } if (!isset($tries)) { $tries = 0; } if (isset($tries) && $tries < 11) { if ($this->request->is('post')) { $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); $userId = $this->Auth->user('id'); $loggedInUser = $this->Users->get($userId); $now = Time::now(); if (!empty($loggedInUser->logins)) { $logins = $loggedInUser->logins + 1; $previousLogin = $loggedInUser->last_login; $syncRedir = 0; } else { $logins = 1; $previousLogin = $now; $syncRedir = 1; } $loginPass = ['last_login' => $now, 'logins' => $logins]; $loginEnt = ['Entity Id' => $loggedInUser->id, 'Controller' => 'Users', 'Action' => 'Login', 'User Id' => $loggedInUser->id, 'Creation Date' => $loggedInUser->created, 'Modified' => $loggedInUser->modified, 'User' => ['Type' => $loggedInUser->authrole, 'Username' => $loggedInUser->username, 'First Name' => $loggedInUser->firstname, 'Last Name' => $loggedInUser->lastname, 'Number of Logins' => $logins, 'Previous Login' => $previousLogin, 'This Login' => $now]]; $loggedInUser = $this->Users->patchEntity($loggedInUser, $loginPass); $loggedInUser->dirty('modified', true); if ($this->Users->save($loggedInUser)) { $sets = TableRegistry::get('Settings'); $jsonLogin = json_encode($loginEnt); $apiKey = $sets->get(13)->text; $projectId = $sets->get(14)->text; $eventType = 'Login'; $keenURL = 'https://api.keen.io/3.0/projects/' . $projectId . '/events/' . $eventType . '?api_key=' . $apiKey; $http = new Client(); $response = $http->post($keenURL, $jsonLogin, ['type' => 'json']); $this->loadComponent('Progress'); $this->Progress->cacheApps($loggedInUser->id); if (isset($eventId) && $eventId >= 0) { $session->delete('Reset.lgTries'); $session->delete('Reset.rsTries'); return $this->redirect(['prefix' => false, 'controller' => 'Applications', 'action' => 'book', $eventId]); } $session->delete('Reset.lgTries'); $session->delete('Reset.rsTries'); if ($syncRedir == 1) { return $this->redirect(['prefix' => false, 'controller' => 'Users', 'action' => 'sync']); } if ($loggedInUser->authrole == 'admin') { return $this->redirect(['prefix' => 'admin', 'controller' => 'Landing', 'action' => 'admin_home']); } return $this->redirect(['prefix' => false, 'controller' => 'Landing', 'action' => 'user_home']); } else { $this->Flash->error(__('The user could not be saved. Please, try again.')); } } $tries = $tries + 1; $this->Flash->error('Your username or password is incorrect. Please try again.'); $session->write('Reset.lgTries', $tries); } $this->set(compact('eventId')); } else { $this->Flash->error('You have failed entry too many times. Please try again later.'); return $this->redirect(['prefix' => false, 'controller' => 'Users', 'action' => 'reset']); } }
public function acceptOrder($sum) { $this->loadModel('OrdersProducts'); date_default_timezone_set('America/Monterrey'); $products = explode(",", $_SESSION['order']); $newOrder = $this->Orders->newEntity(); $newOrder->set(['user_id' => $_SESSION['Auth']['User']['id'], 'last_modification_date' => date('Y-m-d H:i:s'), 'order_status_id' => 1, 'total_price' => $sum, 'cafeteria_id' => $_SESSION['current_order_cafeteria']]); $result = $this->Orders->save($newOrder); $id = $result->id; foreach ($products as $key => $value) { if ($value > 0) { $order = $this->OrdersProducts->newEntity(); $order->set(['amount' => $value, 'order_id' => $id, 'product_id' => $key]); $this->OrdersProducts->save($order); $http = new Client(); $response = $http->post('https://api.sendgrid.com/api/mail.send.json', ['api_user' => 'raguirre_api', 'api_key' => 'myapikey00', "to" => $this->Auth->user("email"), "from" => "*****@*****.**", "subject" => 'Orden Registrada', "html" => 'La orden #' . $order->id . ' ha sido registrada con éxito.']); } } unset($_SESSION['order']); unset($_SESSION['current_order_cafeteria']); return $this->redirect(['controller' => 'orders', 'action' => 'my_orders']); }
/** * Requisita dados dos Correios * * @param string $url Caminho relativo da página nos Correios * @param string $method Método de requisição (POST/GET) * @param array $query Dados para enviar na página * @return string Página solicitada * @access protected */ protected function _requisitaUrl($url, $method, $query) { $httpClient = new Client(); if ($method === 'get') { $response = $httpClient->get($url . "?" . http_build_query($query)); } else { $response = $httpClient->post($url, $query); } if (!$response->isOk()) { return CorreiosTrait::$ERRO_CORREIOS_FALHA_COMUNICACAO; } return trim($response->body()); }
/** * 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']); }
protected function _sso_logout() { $http = new Client(); $response = $http->post('http://' . SSO_PARENT . '/wp-admin/admin-ajax.php', ['action' => 'broker_logout', 'broker_key' => Configure::read('hippo.sso_broker_key'), 'email' => $this->Auth->user('email')]); }