示例#1
1
 protected function emit($channel, $event, $message = null)
 {
     $client = new \Guzzle\Http\Client();
     $apiUrl = "{$this->container->getParameter('socketio_baseurl')}/{$channel}/emit";
     $request = $client->post($apiUrl, array('Content-Type' => 'application/json'), json_encode(array('event' => $event, 'message' => $message)));
     $client->send($request);
 }
 /**
  * Verify a reCAPTCHA submission.
  *
  * @return bool
  */
 public function verify()
 {
     // Get reCAPTCHA value
     $captcha = craft()->request->getPost('g-recaptcha-response');
     // Get reCAPTCHA secret key
     $secretKey = craft()->amForms_settings->getSettingsByHandleAndType('secretKey', AmFormsModel::SettingRecaptcha);
     if (!$secretKey) {
         return false;
     }
     // Google API parameters
     $params = array('secret' => $secretKey->value, 'response' => $captcha);
     // Set request
     $client = new \Guzzle\Http\Client();
     $request = $client->post('https://www.google.com/recaptcha/api/siteverify');
     $request->addPostFields($params);
     $result = $client->send($request);
     // Handle response
     if ($result->getStatusCode() == 200) {
         $json = $result->json();
         if ($json['success']) {
             return true;
         }
     }
     return false;
 }
示例#3
0
 protected function request($methodName, $params = array())
 {
     if ($methodName == 'test') {
         $xml = $this->container->get('templating')->render('SudouxMortgageBundle:LoanApplicationAdmin/formats:testResponse.xml.twig', array());
         $request = $this->client->post('http://httpbin.org/post', array('Content-Type' => 'text/xml'), $xml);
         $response = $request->send();
         $data = $response->json();
     } else {
         $data = null;
         if (isset($this->losConnection)) {
             try {
                 $request = $this->client->post($methodName, array('Content-Type' => 'text/json'), json_encode($params));
                 //  print_r($request);
                 $response = $request->send();
                 $data = $response->json();
             } catch (RequestException $e) {
                 throw $e;
                 /*echo $e->getRequest() . "\n";
                   if ($e->hasResponse()) {
                       echo $e->getResponse() . "\n";
                   }*/
             }
         }
     }
     return $data;
 }
示例#4
0
 protected function request($methodName, $params = array())
 {
     $data = null;
     if (isset($this->losConnection)) {
         try {
             $request = $this->client->post($methodName, array('Content-Type' => 'application/json'), json_encode($params));
             //  print_r($request);
             $response = $request->send();
             $data = $response->json();
         } catch (RequestException $e) {
             throw $e;
             /*echo $e->getRequest() . "\n";
               if ($e->hasResponse()) {
                   echo $e->getResponse() . "\n";
               }*/
         }
     }
     return $data;
 }
示例#5
0
 public function addSSHKeyToAccount(Git_RemoteServer_GerritServer $server, Git_Driver_Gerrit_User $user, $ssh_key)
 {
     try {
         $this->logger->info("Gerrit REST driver: Add ssh key for user " . $user->getSSHUserName());
         $this->sendRequest($server, $this->guzzle_client->post($this->getGerritURL($server, '/accounts/' . urlencode($user->getSSHUserName()) . '/sshkeys'), $this->getRequestOptions(array(self::HEADER_CONTENT_TYPE => self::MIME_TEXT)), $this->escapeSSHKey($ssh_key)));
         $this->logger->info("Gerrit REST driver: ssh key successfully added");
         return true;
     } catch (Exception $exception) {
         $this->throwGerritException("Gerrit REST driver: Cannot add ssh key: " . $exception->getMessage());
     }
 }
 public function handleSubmit()
 {
     $data = array_merge(Input::input(), $this->fileDetails('cover_letter'), $this->fileDetails('resume'));
     $client = new Guzzle\Http\Client(Config::get('remote.submit-domain'));
     $request = $client->post('submit', [], $data);
     $response = $request->send();
     if ($response->isSuccessful()) {
         return Redirect::route('app.submit')->withInfo('You have successfully submitted.');
     } else {
         return Redirect::route('app.submit')->withError('Your submission failed - try again, good luck.');
     }
 }
 protected function attemptAuthentication(Request $request)
 {
     $client = new \Guzzle\Http\Client('https://github.com/login/oauth/access_token');
     $req = $client->post('', null, ['client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'code' => $request->query->get('code')])->setHeader('Accept', 'application/json');
     $res = $req->send()->json();
     $access_token = $res['access_token'];
     $client = new \Guzzle\Http\Client('https://api.github.com');
     $req = $client->get('/user');
     $req->getQuery()->set('access_token', $access_token);
     $res = $req->send()->json();
     $email = $res['email'];
     $token = new GithubUserToken();
     $token->setCredentials($email);
     return $this->authenticationManager->authenticate($token);
 }
 public function executeQuery(IDruidQuery $query)
 {
     $generatedQuery = $query->generateQuery();
     $client = new \Guzzle\Http\Client();
     $baseUrl = 'http://' . $this->ip . ':' . $this->port;
     $url = $baseUrl . $this->endpoint;
     // Create a tweet using POST
     $request = $client->post($url, array("content-type" => "application/json"), json_encode($generatedQuery));
     // Send the request and parse the JSON response into an array
     try {
         $response = $request->send();
     } catch (\Guzzle\Http\Exception\CurlException $curlException) {
         throw new $curlException();
     }
     $data = $response->json();
     $formattedResponse = $query->handleResponse($data);
     return $formattedResponse;
 }
 public function verify($data)
 {
     $base = "https://www.google.com/recaptcha/api/siteverify";
     $plugin = craft()->plugins->getPlugin('recaptcha');
     $settings = $plugin->getSettings();
     $params = array('secret' => $settings->attributes['secretKey'], 'response' => $data);
     $client = new \Guzzle\Http\Client();
     $request = $client->post($base);
     $request->addPostFields($params);
     $result = $client->send($request);
     if ($result->getStatusCode() == 200) {
         $json = $result->json();
         if ($json['success']) {
             return true;
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
 /**
  * send request to Youtrack api, dosnt check the cache. Use the rest function in this class instead
  * @param string $url request url
  * @param string $postOrGet get|post|put request type
  * @param array $headers
  * @param string $body
  * @param array $options
  * @return object request object
  */
 function restResponse($url, $postOrGet = 'get', $headers = null, $body = null, $options = null)
 {
     $client = new \Guzzle\Http\Client();
     $authenticationAndSecurity = new authenticationAndSecurity();
     $authentication = $authenticationAndSecurity->getAuthentication();
     if ($authentication['type'] !== 'password' && $authentication['type'] !== 'cookie' && $authentication['type'] !== 'file') {
         echo 'authentication type unknown. please check its set in the customSettings.php file';
         return;
     }
     if (!isset($options)) {
         if ($authentication['type'] === 'password') {
             $options = ['auth' => [$authentication['details']['user'], $authentication['details']['password']]];
         } else {
             $options = [];
         }
     }
     if ($postOrGet === 'get') {
         $request = $client->get($url, $headers, $options);
     } elseif ($postOrGet === 'post') {
         $request = $client->post($url, $headers, $body, $options);
     } elseif ($postOrGet === 'put') {
         $request = $client->put($url, $headers, $body, $options);
     }
     //        if( $postOrGet === 'put' && isset($headers) ){
     //            foreach($headers as $key => $value){
     //                $request->addHeader($key,$value);
     //            }
     //        }
     if ($authentication['type'] === 'cookie' && $authentication['details']) {
         foreach ($authentication['details'] as $singleCookie) {
             foreach ($singleCookie as $cookieName => $cookieValue) {
                 $request->addCookie($cookieName, $cookieValue);
             }
         }
     }
     $request->send();
     return $request;
 }
for ($current = 0; $current < ITERATIONS; $current++) {
    print "#" . $current . "\r\n";
    $type = '';
    $collect = '';
    $user = rand(1, 100);
    $randomType = rand(0, 2);
    $randomCollect = rand(0, $nbOfCollectSources);
    switch ($randomType) {
        case 0:
            $type = 'new';
            $collect = sprintf('collect_type=%s,collect_source=%s', $availableCollectSources[$randomCollect]['mode'], $availableCollectSources[$randomCollect]['source']);
            break;
        case 1:
            $type = 'lost';
            $collect = 'collect_type=unknown,collect_source=unknown';
            break;
        case 2:
            $type = 'revive';
            $collect = sprintf('collect_type=%s,collect_source=%s', $availableCollectSources[$randomCollect]['mode'], $availableCollectSources[$randomCollect]['source']);
            break;
    }
    if ($type != '') {
        try {
            $body = sprintf('bdd_ger,type=%s,userid=%s,%s value=1', $type, $user, $collect);
            $result = $guzzle->post('write?db=' . DATABASE_NAME, $headers, null, array('body' => $body, 'verify' => false))->send();
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        }
    }
    usleep(USLEEP_TIME);
}
示例#12
0
 /**
  * @param string $code
  * @return array
  */
 public function requestAccessToken($code)
 {
     $params = array('client_id' => $this->clientId, 'code' => $code, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->redirectUri);
     try {
         $guzzle = new \Guzzle\Http\Client();
         $response = $guzzle->post($this->token, array(), $params)->send();
         $tokenInfo = $response->json();
         if ($tokenInfo['mapi'] !== $this->clientId) {
             throw new FamilySearchException('Invalid map.');
         }
         return $this->setAccessToken($tokenInfo['access_token']);
     } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
         throw new FamilySearchException('There was a problem while requesting the access token.');
     }
 }
示例#13
0
 /**
  * @throws EtException|\Exception
  * @return EtModel|null
  */
 public function phoneHome()
 {
     try {
         $missingLicenseKey = empty($this->_model->licenseKey);
         // No craft/config/license.key file and we can't write to the config folder. Don't even make the call home.
         if ($missingLicenseKey && !$this->_isConfigFolderWritable()) {
             throw new EtException('Craft needs to be able to write to your “craft/config” folder and it can’t.', 10001);
         }
         if (!craft()->cache->get('etConnectFailure')) {
             $data = JsonHelper::encode($this->_model->getAttributes(null, true));
             $client = new \Guzzle\Http\Client();
             $client->setUserAgent($this->_userAgent, true);
             $options = array('timeout' => $this->getTimeout(), 'connect_timeout' => $this->getConnectTimeout(), 'allow_redirects' => $this->getAllowRedirects());
             $request = $client->post($this->_endpoint, $options);
             $request->setBody($data, 'application/json');
             $response = $request->send();
             if ($response->isSuccessful()) {
                 // Clear the connection failure cached item if it exists.
                 if (craft()->cache->get('etConnectFailure')) {
                     craft()->cache->delete('etConnectFailure');
                 }
                 if ($this->_destinationFileName) {
                     $body = $response->getBody();
                     // Make sure we're at the beginning of the stream.
                     $body->rewind();
                     // Write it out to the file
                     IOHelper::writeToFile($this->_destinationFileName, $body->getStream(), true);
                     // Close the stream.
                     $body->close();
                     return IOHelper::getFileName($this->_destinationFileName);
                 }
                 $etModel = craft()->et->decodeEtModel($response->getBody());
                 if ($etModel) {
                     if ($missingLicenseKey && !empty($etModel->licenseKey)) {
                         $this->_setLicenseKey($etModel->licenseKey);
                     }
                     // Cache the license key status and which edition it has
                     craft()->cache->set('licenseKeyStatus', $etModel->licenseKeyStatus);
                     craft()->cache->set('licensedEdition', $etModel->licensedEdition);
                     craft()->cache->set('editionTestableDomain@' . craft()->request->getHostName(), $etModel->editionTestableDomain ? 1 : 0);
                     if ($etModel->licenseKeyStatus == LicenseKeyStatus::MismatchedDomain) {
                         craft()->cache->set('licensedDomain', $etModel->licensedDomain);
                     }
                     return $etModel;
                 } else {
                     Craft::log('Error in calling ' . $this->_endpoint . ' Response: ' . $response->getBody(), LogLevel::Warning);
                     if (craft()->cache->get('etConnectFailure')) {
                         // There was an error, but at least we connected.
                         craft()->cache->delete('etConnectFailure');
                     }
                 }
             } else {
                 Craft::log('Error in calling ' . $this->_endpoint . ' Response: ' . $response->getBody(), LogLevel::Warning);
                 if (craft()->cache->get('etConnectFailure')) {
                     // There was an error, but at least we connected.
                     craft()->cache->delete('etConnectFailure');
                 }
             }
         }
     } catch (EtException $e) {
         Craft::log('Error in ' . __METHOD__ . '. Message: ' . $e->getMessage(), LogLevel::Error);
         if (craft()->cache->get('etConnectFailure')) {
             // There was an error, but at least we connected.
             craft()->cache->delete('etConnectFailure');
         }
         throw $e;
     } catch (\Exception $e) {
         Craft::log('Error in ' . __METHOD__ . '. Message: ' . $e->getMessage(), LogLevel::Error);
         // Cache the failure for 5 minutes so we don't try again.
         craft()->cache->set('etConnectFailure', true, 300);
     }
     return null;
 }
示例#14
0
 /**
  * 推送消息给到微信服务器
  *
  * @param string $url            
  * @param string $body            
  * @param array $options            
  * @return mixed
  */
 public function post($url, $body, $options = array())
 {
     $client = new \Guzzle\Http\Client();
     $client->setDefaultOption('query', array('access_token' => $this->getAccessToken()));
     $client->setDefaultOption('body', $body);
     $request = $client->post($url, null, null, $options);
     $request->getCurlOptions()->set(CURLOPT_SSLVERSION, 1);
     // CURL_SSLVERSION_TLSv1
     $response = $client->send($request);
     if ($response->isSuccessful()) {
         return $response->getBody(true);
     } else {
         throw new Exception("来伊份服务器未有效的响应请求");
     }
 }
 public function api($method, $params = array())
 {
     // Decide if the call can be cached
     $cached = false;
     $cacheableMethods = array('store_includes_get', 'attribute_list', 'category_list', 'downloadable_list', 'customer_list', 'customer_get', 'customer_address_get', 'transaction_list', 'transaction_get', 'subscription_get', 'subscription_list');
     if (in_array($method, $cacheableMethods)) {
         $cached = true;
         $cacheKey = "foxycart_" . $method;
         if (count($params) > 0) {
             $cacheKey .= "_" . hash('sha256', http_build_query($params));
         }
         $cachedResponse = craft()->cache->get($cacheKey);
         if ($cachedResponse) {
             FoxyCartPlugin::log("[api] Returning cached data for " . $method . "?" . http_build_query($params), LogLevel::Info);
             return simplexml_load_string($cachedResponse, NULL, LIBXML_NOCDATA);
         }
     }
     try {
         $client = new \Guzzle\Http\Client("https://" . $this->storedomain);
         $foxy_data = array_merge(array("api_token" => $this->apikey, "api_action" => $method), $params);
         $request = $client->post("/api", array(), array('verify' => self::$curl_ssl_verifypeer, 'timeout' => self::$curl_timeout, 'connect_timeout' => self::$curl_connecttimeout));
         $request = $request->addPostFields($foxy_data);
         $response = $request->send();
         if (!$response->isSuccessful()) {
             return false;
         }
         $xml = simplexml_load_string($response->getBody(true), NULL, LIBXML_NOCDATA);
         if ($xml->result == "ERROR") {
             $errorMessages = array();
             foreach ($xml->messages->message as $message) {
                 array_push($errorMessages, $message);
             }
             FoxyCartPlugin::log('[api] An API request returned an error: ' . join(", ", $errorMessages), LogLevel::Error);
             return false;
         }
         if ($cached) {
             // Cache this call for 10 minutes
             craft()->cache->set($cacheKey, $response->getBody(true), 600);
         }
         return $xml;
     } catch (\Exception $e) {
         FoxyCartPlugin::log('[api] An API request failed: ' . $e->getMessage(), LogLevel::Error);
         return false;
     }
 }
示例#16
0
 /**
  * @param Topic        $topic
  * @param WampRequest  $request
  * @param array|string $data
  * @param string       $provider The name of pusher who push the data
  */
 public function onPush(Topic $topic, WampRequest $request, $data, $provider)
 {
     $this->logger->info("onPush -> " . $topic->getId());
     /* @var $slack \FourPixelsBundle\Entity\Slack */
     /* @var $slackRequest \FourPixelsBundle\Entity\SlackRequest */
     /* @var $slackTeamTreeHouse \FourPixelsBundle\Entity\SlackTeamTreeHouse */
     $this->em->clear();
     $slackRequest = $this->em->getRepository('FourPixelsBundle:SlackRequest')->find($request->getAttributes()->get('slackRequest'));
     $slack = $this->em->getRepository('FourPixelsBundle:Slack')->find($request->getAttributes()->get('slack'));
     $scoreTable = [];
     if ($slack->getId() === $slackRequest->getSlack()->getId()) {
         $client = new \Guzzle\Http\Client();
         $explode = explode(' ', $slackRequest->getText());
         $globalShowMode = 'in_channel';
         // ephemeral OR in_channel
         switch ($explode[0]) {
             case 'help':
                 $myArray = ['username' => '4pixels', "icon_url" => "https://slack.com/img/icons/app-57.png", "icon_emoji" => ":ghost:", "response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/list", "title" => "LIST", "text" => "/teamtreehouse list \n Displays a list of all the Team Tree House usernames participaiting in the tournament. \n *Example:* _/teamtreehouse list_", "mrkdwn_in" => ['text'], "color" => "#3F2860"], ["fallback" => "please visit https://4pixels.co/api-help/add", "title" => "ADD", "text" => "/teamtreehouse add `TeamTreeHouse username` \n adds a Team Tree House username to the tournament. \n *Example:* _/teamtreehouse add jasoncameron_", "mrkdwn_in" => ['text'], "color" => "#F35A00"], ["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "REMOVE", "text" => "/teamtreehouse remove `TeamTreeHouse username` \n Delete a Team Tree House username from the tournament. \n *Example:* _/teamtreehouse remove jasoncameron_", "mrkdwn_in" => ['text'], "color" => "#B81D18"], ["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "SHOW", "text" => "/teamtreehouse show `TeamTreeHouse username` \n Show a single Team Tree House username score. \n *Example:* _/teamtreehouse show jasoncameron_", "mrkdwn_in" => ['text'], "color" => "#1253A4"], ["fallback" => "please visit https://4pixels.co/api-help/code", "title" => "CODE", "text" => "" . "/teamtreehouse code \n Displays a ranking list of Team Tree House usernames tournament. \n *Example:* _/teamtreehouse code_ \n\n" . "/teamtreehouse code `TeamTreeHouse language` \n Displays a ranking list of Team Tree House usernames tournament based on one lenguage. \n *Example:* _/teamtreehouse code javascript_  \n\n" . "/teamtreehouse code `TeamTreeHouse languages` \n Displays a ranking list of Team Tree House usernames tournament based on many lenguage. \n *Example:* _/teamtreehouse code javascript, php, html_", "mrkdwn_in" => ['text'], "color" => "#75A3D1"]]];
                 break;
             case 'show':
                 //         /teamtreehouse show jasoncameron
                 $username = $explode[1];
                 //MOST VALIDATE THERE ARE NO MORE PARAMETERS THAN 2
                 try {
                     $teamTreeHouseResponse = $client->get('https://teamtreehouse.com/' . $username . '.json')->send();
                     $slackTeamTreeHouse = new \FourPixelsBundle\Entity\SlackTeamTreeHouse();
                     $slackTeamTreeHouse->setContent($teamTreeHouseResponse->json());
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/show", "title" => "SHOW " . $slackTeamTreeHouse->getName() . " (" . $slackTeamTreeHouse->getProfileName() . ")", "color" => "#75A3D1", "thumb_url" => $slackTeamTreeHouse->getGravatarUrl(), "fields" => $slackTeamTreeHouse->getPoints(true)]]];
                 } catch (ClientErrorResponseException $exception) {
                     $responseBody = $exception->getResponse()->getBody(true);
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "SHOW " . $username . " - Ups !!! :panda_face: Panda Trouble", "text" => "Username " . $responseBody . " on Team Tree House", "mrkdwn_in" => ['text'], "color" => "#D40E52"]]];
                 }
                 break;
             case 'code':
                 $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/code", "title" => "Feature CODE", "text" => "The panda is busy right know thinking in other stuff. He will develop this feature soon.", "mrkdwn_in" => ['text'], "color" => "#D40E52"]]];
                 break;
             case 'list':
                 $slackTeamTreeHouseList = $slack->getSlackTeamTreeHouseList();
                 $text = "";
                 foreach ($slackTeamTreeHouseList as $slackTeamTreeHouse) {
                     $text .= $slackTeamTreeHouse->getName() . ' (' . $slackTeamTreeHouse->getProfileName() . ")\n";
                 }
                 $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/list", "title" => "LIST - List size: " . count($slackTeamTreeHouseList), "text" => $text, "color" => "#75A3D1"]]];
                 break;
             case 'add':
                 $username = $explode[1];
                 //MOST VALIDATE THERE ARE NO MORE PARAMETERS THAN 2
                 try {
                     $teamTreeHouseResponse = $client->get('https://teamtreehouse.com/' . $username . '.json')->send();
                     $slackTeamTreeHouse = new \FourPixelsBundle\Entity\SlackTeamTreeHouse();
                     $slackTeamTreeHouse->setContent($teamTreeHouseResponse->json());
                     $slackTeamTreeHouse->setSlack($slack);
                     $this->em->persist($slackTeamTreeHouse);
                     $this->em->flush();
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/add", "title" => "ADD " . $slackTeamTreeHouse->getName() . " (" . $slackTeamTreeHouse->getProfileName() . ")", "text" => "User has been added successfuly", "color" => "#75A3D1", "thumb_url" => $slackTeamTreeHouse->getGravatarUrl()]]];
                 } catch (ClientErrorResponseException $exception) {
                     $responseBody = $exception->getResponse()->getBody(true);
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/add", "title" => "ADD " . $username . " - Ups !!! :panda_face: Panda Trouble ", "text" => "Username " . $responseBody . " on Team Tree House", "color" => "#D40E52"]]];
                 } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
                     $this->em->clear();
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/add", "title" => "ADD " . $username . " - Ups !!! :panda_face: Panda Warning ", "text" => "Username " . $username . " is already added", "color" => "#FF9900"]]];
                 }
                 break;
             case 'remove':
                 $username = $explode[1];
                 $slackTeamTreeHouse = $this->em->getRepository('FourPixelsBundle:SlackTeamTreeHouse')->findOneBy(['slack' => $slack->getId(), 'profile_name' => $username]);
                 if (!is_null($slackTeamTreeHouse)) {
                     try {
                         $name = $slackTeamTreeHouse->getName();
                         $gravatarUrl = $slackTeamTreeHouse->getGravatarUrl();
                         $this->em->remove($slackTeamTreeHouse);
                         $this->em->flush();
                         $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "REMOVE " . $name . " (" . $username . ")", "text" => "User has been removed from the list successfuly", "color" => "#75A3D1", "thumb_url" => $gravatarUrl]]];
                     } catch (\Exception $e) {
                         $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "REMOVE " . $username . " - Ups !!! :panda_face: Panda Warning ", "text" => "The was a problem removing the user from the list. ", "color" => "#FF9900"]]];
                     }
                 } else {
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "REMOVE " . $username . " - Ups !!! :panda_face: Panda Trouble ", "text" => "Username was not found on the list. \n You can view the list with: /teamtreehouse list", "color" => "#D40E52"]]];
                 }
                 break;
             default:
                 $slackTeamTreeHouseList = $slackRequest->getSlack()->getSlackTeamTreeHouseList();
                 foreach ($slackTeamTreeHouseList as $slackTeamTreeHouse) {
                     $teamTreeHouseResponse = $client->get('https://teamtreehouse.com/' . $slackTeamTreeHouse->getProfileName() . '.json')->send();
                     $slackTeamTreeHouse->setContent($teamTreeHouseResponse->json());
                     $this->em->persist($slackTeamTreeHouse);
                     $scoreTable[$slackTeamTreeHouse->getName() . ' (' . $slackTeamTreeHouse->getProfileName() . ')'] = $slackTeamTreeHouse->getTotal();
                 }
                 $this->em->flush();
                 $resultBool = arsort($scoreTable);
                 $text = "";
                 foreach ($scoreTable as $key => $value) {
                     $text .= $value . " \t \t " . $key . " \n ";
                 }
                 $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help", "title" => "RANKING NEWS ", "text" => $text, "color" => "#75A3D1"]]];
                 break;
         }
         $requestForSlack = $client->post($slackRequest->getResponseUrl(), [], ['payload' => json_encode($myArray)]);
         $response = $requestForSlack->send();
     }
     $topic->broadcast(['msg' => 'DONE']);
 }
/**
 * Check for whether code and/or state params are being passed back from GitHub after
 * user authorizes the regsitered app. If so, exchange for token and save.
 */
function wpghpl_handle_authentication_redirection()
{
    #check if we're receiving the GitHub temporary code
    $code = !empty($_GET['code']) ? $_GET['code'] : false;
    $state = !empty($_GET['state']) ? $_GET['state'] : false;
    if (!$code) {
        return;
    }
    $saved_state = get_option('wpghpl_auth_state');
    if ($state != $saved_state) {
        return;
    }
    //TODO: This should throw an error!
    update_option('wpghpl_auth_code', $code);
    //TODO: The php-githup-api library can probably do this easier
    //TODO: This should handle non-success scenarios, like user NOT granting access
    $guzzle = new \Guzzle\Http\Client('https://github.com');
    $guzzle->setDefaultOption('headers', array('Accept' => 'application/json'));
    $body = array('client_id' => get_option('wpghpl_client_id'), 'client_secret' => get_option('wpghpl_client_secret'), 'code' => $code, 'redirect_uri' => admin_url('options-general.php?page=wpghpl'), 'state' => $state);
    $request = $guzzle->post('https://github.com/login/oauth/access_token', null, $body);
    $response = $request->send();
    $data = $response->json();
    if (!empty($data['access_token'])) {
        update_option('wpghpl_token', $data['access_token']);
    }
}
示例#18
0
 /**
  * @Route("/github")
  */
 public function ghloginAction(Request $request)
 {
     // https://github.com/login/oauth/authorize?client_id=f77f000b2dfc717ade2a&redirect_uri=http://extending.loc/app_dev.php/github_login&scope=user,user:email
     $client = new \Guzzle\Http\Client('https://github.com/login/oauth/access_token');
     $req = $client->post('', null, ['client_id' => 'f77f000b2dfc717ade2a', 'client_secret' => '42967a6f718a83e5f85ad609292a78fce81dd46d', 'code' => $request->query->get('code')])->setHeader('Accept', 'application/json');
     $res = $req->send()->json();
     $token = $res['access_token'];
     $client = new \Guzzle\Http\Client('https://api.github.com');
     $req = $client->get('/user');
     $req->getQuery()->set('access_token', $token);
     $username = $req->send()->json()['email'];
     return new Response($username);
 }
 public function cancelPending($address)
 {
     $query = ['address' => $address];
     return $this->httpClient->post('/cancelpending/', $query);
 }
示例#20
0
 /**
  * 推送消息给到微信服务器
  *
  * @param string $url            
  * @param array $params            
  * @return mixed
  */
 public function post($url, $params = array())
 {
     $client = new \Guzzle\Http\Client($this->_url);
     $client->setDefaultOption('body', $params);
     $request = $client->post($url);
     $request->getCurlOptions()->set(CURLOPT_SSLVERSION, 1);
     // CURL_SSLVERSION_TLSv1
     $response = $client->send($request);
     if ($response->isSuccessful()) {
         return $response->json();
     } else {
         throw new \Exception("云片短信服务器未有效的响应请求");
     }
 }