/** * susbscribe valid, unique $request['email'] to * boston meshnet mailing list -- thank you finn! **/ public function subscribe($email) { $base_uri = 'https://lists.projectmesh.net/cgi-bin/mailman/subscribe/boston'; $client = new \Guzzle\Service\Client(['base_uri' => 'https://lists.projectmesh.net/cgi-bin/mailman/subscribe/boston', 'timeout' => 7]); $randStrng = str_random(12); error_log(json_encode(['$randStrng' => $randStrng])); $request = $client->post($base_uri, ['content-type' => 'application/x-www-form-urlencoded'], []); $data = ['email' => $email, 'pw' => $randStrng, 'pw-conf' => $randStrng, 'digest' => 0, 'email-button' => 'Subscribe']; $request->setBody($data); $response = $request->send(); /* Pending mailserver install.. $data = (object) [ 'lists' => '*****@*****.**', 'lists_public' => '*****@*****.**', 'from' => $email, 'subject' => 'Mailing List Request from Boston Meshnet (via Bostonmesh.net Website)', 'artisan' => '*****@*****.**', ] ; $success = Mail::send('emails.subscribe', [ 'data' => $data ], function ($message) use($data) { $message->from($data->from); $message->to($data->lists) ->cc($data->artisan) ->cc($data->from) ->subject($data->subject); }); error_log(json_encode(['subscribe' => $success])); */ $success = true; return ['success' => $success]; }
public static function deauthorize($access_token, $url = 'https://runkeeper.com/apps/de-authorize') { $params = array('access_token' => $access_token); $client = new \Guzzle\Service\Client(); $response = $client->post($url, null, $params)->send(); return $response->getStatusCode() == 204 ? true : false; }
/** * Returns PageSpeed score, page statistics, and PageSpeed formatted results for specified URL * * @param string $url * @param string $locale * @param string $strategy * @param optional array $extraParams * @return array * @throws Exception\InvalidArgumentException * @throws Exception\RuntimeException */ public function getResults($url, $locale = 'en_US', $strategy = 'desktop', array $extraParams = null) { if (0 === preg_match('#http(s)?://.*#i', $url)) { throw new InvalidArgumentException('Invalid URL'); } $client = new \Guzzle\Service\Client($this->gateway); /** @var $request \Guzzle\Http\Message\Request */ $request = $client->get('runPagespeed'); $request->getQuery()->set('prettyprint', false)->set('url', $url)->set('locale', $locale)->set('strategy', $strategy); if (isset($extraParams)) { $query = $request->getQuery(); foreach ($extraParams as $key => $value) { $query[$key] = $value; } } try { $response = $request->send(); $response = $response->getBody(); $response = json_decode($response, true); return $response; } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) { $response = $e->getResponse(); $response = $response->getBody(); $response = json_decode($response); throw new RuntimeException($response->error->message, $response->error->code); } }
function getContent() { if (!$this->enabled) { return json_encode(array()); } require_once dirname(__DIR__) . '/vendor/guzzle/guzzle.phar'; $time = time(); $url = $this->getUrl(); $client = new Guzzle\Service\Client($url); $request = $client->get($url); $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, $this->curlConnectTimeout); $request->getCurlOptions()->set(CURLOPT_TIMEOUT, $this->curlTimeout); try { $response = $request->send(); } catch (\Guzzle\Http\Exception\BadResponseException $e) { if ($this->logging) { file_put_contents($this->logFilePath, 'time: ' . (time() - $time) . ', url: ' . $url . ', exception: ' . $e->getMessage() . "\n", FILE_APPEND); } return '[]'; } $content = $response->getBody(true); if ($this->logging) { file_put_contents($this->logFilePath, 'time: ' . (time() - $time) . ', url: ' . $url . ', response: ' . $content . "\n", FILE_APPEND); } return $content; }
/** * Register any application services. * * @return void */ public function register() { $this->app->bind('App\\Helpers\\HeadHunterGrabber', function ($app) { $client = new \Guzzle\Service\Client('https://api.hh.ru'); $client->setUserAgent('SkillPricer/1.0 (vamakin@gmail.com)'); $request = new ApiRequest($client); $grabber = new HeadHunterGrabber($request); return $grabber; }); }
protected function mockClient() { $mockResponse = new \Guzzle\Http\Message\Response(200); $mockResponse->setBody('{"hello":"world","0":[{"alpha":null},{"gamma":3}],"1":{"echo":"foxtrot","\\"quote\\"":true}}', 'application/json'); $mockResponse->setHeaders(array('Host' => 'ms-lib-testrest', 'User-Agent' => 'test', 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Location' => 'hello')); $plugin = new \Guzzle\Plugin\Mock\MockPlugin(); $plugin->addResponse($mockResponse); $client = new \Guzzle\Service\Client(); $client->setDefaultOption('exceptions', false); $client->addSubscriber($plugin); $this->setPropertyValue('client', $client); $this->setPropertyValue('response', $mockResponse); }
public function create($job, $data) { $dropboxClient = new \Guzzle\Service\Client('https://' . Config::get('app.dropbox_host') . '/'); $request = $dropboxClient->get('localize/' . $data['entry']['id']); $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false); // for testing ONLY! $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false); // for testing ONLY! $response = $request->send()->json(); if ($response['success']) { $job->delete(); } else { dd($response); // TODO: logging of error $job->release(); } }
<?php include 'headers.php'; require_once 'guzzle.phar'; // auth good | bWVyc2lhbjpwdDFta3QxbWs= // auth bad | bWVyc2lhbjpib28= // http://localhost:8070/plex/services/login.php?auth=base64encode(username:password) // https://my.plexapp.com/users/sign_in.xml $auth = $_GET['auth']; $client = new Guzzle\Service\Client('https://my.plexapp.com'); $request = $client->post('/users/sign_in.xml', array('Authorization' => 'Basic ' . $auth, HEADER_PLATFORM => VALUE_PLATFORM, HEADER_PLATFORM_VERSION => VALUE_PLATFORM_VERSION, HEADER_PROVIDES => VALUE_PROVIDES, HEADER_PRODUCT => VALUE_PRODUCT, HEADER_VERSION => VALUE_VERSION, HEADER_DEVICE => VALUE_DEVICE, HEADER_CLIENT => VALUE_CLIENT)); $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false); $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false); $response = $client->send($request); echo $response->getBody();
private function registerMwClient() { $key = Config::get('app.key'); $client = new \Guzzle\Service\Client('https://login.microweber.com/api/v1/client/'); $domain = site_url(); $domain = substr($domain, strpos($domain, '://') + 3); $domain = str_replace('/', '', $domain); $request = $client->createRequest('POST', "config/{$domain}"); //dd($request, $request); $request->setPostField('token', $key); $response = $client->send($request); if (200 == $response->getStatusCode()) { $body = (string) $response->getBody(); $body = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $body, MCRYPT_MODE_ECB); $body = trim($body); $body = (array) json_decode($body); Config::set('services.microweber', $body); Config::save(); save_option(['option_value' => 'y', 'option_key' => 'enable_user_microweber_registration', 'option_group' => 'users']); } else { // $reason = $response->getReasonPhrase(); // dd(__FILE__, $reason, $response->getStatusCode()); } }
protected function _callMethod($command, $options) { $client = $this->_client; if (null === $client) { $client = new \Guzzle\Service\Client(static::URL_REST); } /** @var $request \Guzzle\Http\Message\Request */ $request = $client->get($command, array('App-Key' => $this->getToken())); $request->setAuth($this->getUsername(), $this->getPassword()); $response = $request->send(); // Execute the request and decode the json result into an associative array $response = @json_decode($response->getBody(), true); // Check JSON parsing errors if (!$response) { throw new \Exception("Error: Response is not JSON valid"); } // Check for errors returned by the API if (!$response || isset($response['error'])) { throw new \Exception("Error: " . $response['error']['errormessage']); } return $response; }
<?php include 'headers.php'; require_once 'guzzle.phar'; // http://server_ip:server_port/library/sections/sectionID/all - skip the sections and just get them all $server_ip = $_GET['server_ip']; $server_port = $_GET['server_port']; $sectionID = $_GET['sectionID']; $token = $_GET['token']; $client = new Guzzle\Service\Client('http://' . $server_ip); $commandURL = '/library/sections/' . $sectionID . '/all?' . TOKEN_PARAM . '=' . $token; $request = $client->get($commandURL, array('Content-Length' => 0, HEADER_PLATFORM => VALUE_PLATFORM, HEADER_PLATFORM_VERSION => VALUE_PLATFORM_VERSION, HEADER_PROVIDES => VALUE_PROVIDES, HEADER_PRODUCT => VALUE_PRODUCT, HEADER_VERSION => VALUE_VERSION, HEADER_DEVICE => VALUE_DEVICE, HEADER_CLIENT => VALUE_CLIENT)); $request->setPort($server_port); //$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false); //$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false); $response = $client->send($request); echo $response->getBody();
/** * generates a Guzzle client **/ protected function init_client($config) { $default = array('base_url' => '{{scheme}}://api.{{domain}}/{{version}}/?appid={{appid}}&appkey={{appkey}}', 'scheme' => 'https', 'version' => '0.1', 'domain' => \PSU::isDev() ? 'dev.plymouth.edu' : 'plymouth.edu'); $required = array('appid', 'appkey', 'base_url'); $config = \Guzzle\Common\Inspector::prepareConfig($config, $default, $required); $client = new \Guzzle\Service\Client($config->get('base_url'), $config); $client->setConfig($config); return $client; }
private function sendSMS($number, $sender, $msg) { $phonenumber = $number; $phonenumber = str_replace('+', '', $phonenumber); if (strlen($phonenumber) == "11") { $phonenumber = "88" . $phonenumber; } if (strlen($phonenumber) == "13") { if (preg_match("/^88017/i", "{$phonenumber}") or preg_match("/^88016/i", "{$phonenumber}") or preg_match("/^88015/i", "{$phonenumber}") or preg_match("/^88011/i", "{$phonenumber}") or preg_match("/^88018/i", "{$phonenumber}") or preg_match("/^88019/i", "{$phonenumber}")) { $myaccount = urlencode("supersoft"); $mypasswd = urlencode("0qMLQO"); $sendBy = urlencode($sender); $api = "http://api.infobip.com/api/v3/sendsms/plain?user="******"&password="******"&sender=" . $sendBy . "&SMSText=" . $msg . "&GSM=" . $phonenumber . "&type=longSMS"; $client = new \Guzzle\Service\Client($api); // Get your response: $response = $client->get()->send(); $body = $response->xml(); $status = $body->result->status; if ($status == "0") { return "SMS SEND"; } return $status; } else { return "Invalid Number"; } } else { return "Invalid Number"; } }
/** * Get Intervals of Average Response Time and Uptime During a Given Interval * * @param int $checkId * @param string $resolution * @return array */ public function getPerformanceSummary($checkId, $resolution = 'hour') { $client = new \Guzzle\Service\Client('https://api.pingdom.com/api/2.0'); /** @var $request \Guzzle\Http\Message\Request */ $request = $client->get('summary.performance/' . $checkId, array('App-Key' => $this->token)); $request->setAuth($this->username, $this->password); $request->getQuery()->set('resolution', $resolution); $request->getQuery()->set('includeuptime', 'true'); $response = $request->send(); $response = json_decode($response->getBody(), true); return $response['summary'][$resolution . 's']; }
// Getting ready to request an access token for this resource // to the token service. $resource = $provider->getResource(); $tokenServiceUri = $provider->urlAccessToken(); $grant = new \League\OAuth2\Client\Grant\RefreshToken(); echo 'Getting ready to request an access token: ', '<br />', 'Resource: ', $resource, '<br />', 'Token service: ', $tokenServiceUri, '<p />'; $accessToken = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken, 'resource' => $resource]); // We have an access token. // In production scenarios, save the access token in an appropriate // storage mechanism so you can use it during the user's session. echo 'Access token: ', '<br />', $accessToken->accessToken, '<p />'; //This is the REST endpoint that we are sending our request to $apiUrl = $_POST['SPSiteUrl'] . '/_api/web/title'; // Using guzzle to create an http client // pass the access token in the Authorization header $client = new Guzzle\Service\Client(); $request = $client->createRequest('GET', $apiUrl); $request->setHeader('Authorization', 'Bearer ' . $accessToken->accessToken); $request->setHeader('Accept', 'application/json;odata=verbose'); $response = $client->send($request); //Decode the response using the JSON decoder $output = $response->getBody(true); $jsonResult = json_decode($output); if ($jsonResult->d != null) { // Print the result to the page echo '<p>Querying the REST endpoint ', $apiUrl, '<br/>'; echo 'Result: ', $jsonResult->d->Title, '</p>'; } else { // There was a problem with the request echo '<p>There was a problem querying the REST endpoint ' . $apiUrl . '<br/>'; echo 'Error code: ' . $jsonResult->error->code . '<br/>';
public function localize($file_id) { $contentClient = new \Guzzle\Service\Client('http://' . Config::get('app.content_host') . '/'); $entry = Entry::find($file_id); if ($entry->is_dir) { return ['success' => false, 'error_message' => 'Cannot compute SHA1 of directory']; } $this->authenticate($entry->dropbox_id); $tmpfname = tempnam(sys_get_temp_dir(), $file_id); $fd = fopen($tmpfname, "w+"); $meta = $this->active_client->getFile($entry->original_path, $fd); $sha1 = sha1_file($tmpfname); if (strrpos(basename($entry->original_path), '.')) { $extension = substr(basename($entry->original_path), strrpos(basename($entry->original_path), '.')); } else { $extension = ".extensionless"; } $save_path = 'dropbox/' . $sha1 . $extension; // check the byte size of the cached file if it exists on the content server $request = $contentClient->head($save_path); try { $response = $request->send(); $contentLength = $response->getContentLength(); } catch (Guzzle\Http\Exception\BadResponseException $e) { $clientResponseException = $e->getResponse(); $statusCode = $clientResponseException->getStatusCode(); if ($statusCode !== 404) { return ['success' => false, 'error_message' => 'HEAD request from content server path ' . $save_path . ' raised http exception ' . $statusCode . "\n" . print_r($clientResponseException, true)]; } $contentLength = false; } // Raise an exception if we are about to localize this file in place of another file with the same content SHA if ($contentLength && $contentLength > 0 && $contentLength != filesize($tmpfname)) { return ['success' => false, 'error_message' => "File exists on content server with same SHA but different byte count!"]; } // Upload the file if it does not already exist on the content server if (!$contentLength) { $request = $contentClient->put($save_path); $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false); // for testing ONLY! $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false); // for testing ONLY! // TODO: Determine which approach is best of these two: // Having a second pointer on same file, while first pointer is still open // (Temp files are deleted as soon as fclose called) $request->setBody(fopen($tmpfname, 'r')); // Or should we use.... // rewind($fd); // $request->setBody($fd); // I'm not sure if guzzle would support that, // nor if w+ mode supports rewind // (Will it read from start without erasing after a rewind in w+?) $response = $request->send(); } // Close the temp file pointer fclose($fd); // Update the database with the file size information $entry->file_sha = $sha1; $entry->etag = sha1($sha1 . $entry->bytes . $entry->service_updated_at . $entry->client_updated_at); $entry->save(); // TODO: Error handling // TODO: Process abstraction from controller to classes return ['success' => true, 'local_url' => 'http://' . Config::get('app.content_host') . '/' . $save_path]; }
|-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::resource('entity', 'EntitiesController'); Route::get('/', function () { return view('welcome'); }); Route::get('/about', 'PagesController@about'); Route::post('/user/register/', 'UsersController@create'); Route::get('/csrf', function () { return csrf_token(); }); Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]); Route::post('authenticate', 'AuthenticateController@authenticate'); Route::get('authenticate/user', 'AuthenticateController@getAuthenticatedUser'); /*Route::get('/entity/{entityName}', function($entityName){ //$entity_client = new Guzzle\Service\Client('http://en.wikipedia.org/w/api.php?pllimit=2&action=query&prop=extracts&format=jsonfm&formatversion=2&redirects=1&exintro=&explaintext=titles='); //$response = $entity_client->get($entityName)->send(); //echo $response->getBody(); $wikipedia = new \Casinelli\Wikipedia\Wikipedia; return $wikipedia->search("Rome")->getSentences(5); });*/ Route::get('users/{username}', function ($username) { $username_client = new Guzzle\Service\Client('https://api.github.com/'); $response = $username_client->get("users/{$username}")->send(); echo $response->getBody(); });