@param array|null $fields
@param string     $hash
@param string     $method
@param string     $organization

@throws GuzzleException
@throws \RuntimeException

@return bool
518877
private function doUserMetadataRequest($fields, $hash, $method, $organization = '')
    {
        $path = implode('/', [
            self::SOURCEIMAGE_RESOURCE,
            $this->getOrganizationName($organization),
            $hash,
            self::USER_META_RESOURCE,
        ]);
        $data = [];
        if ($fields) {
            $fields = $this->applyValueTransformationsToUserMeta($fields);
            $data = ['json' => $fields];
        }
        $response = $this->call($method, $path, $data);

        return true;
    }
566243
public function callAction($method, $parameters)
    {
        $response = null;
        $this->method = $method;

        $result = parent::callAction($method, $parameters);

        if ($this->returnsArray) {
            if (!is_array($result)) {
                abort(500, 'Bad API response data.');
            }

            // Return JSON for AJAX and GET requests
            if (request()->ajax() || 'index' === $method || 'show' === $method) {
                $response = response()->json($result);

            // Return redirect-back and flash data for normal requests.
            } else {
                $response = empty($this->redirectUrl) ? back() : redirect($this->redirectUrl);
                foreach ($result as $key => $value) {
                    $response->with($key, $value);
                }
                if ('store' !== $method || isset($result['error'])) {
                    $response->withInput();
                }
            }
        } else {
            $response = $result;
        }

        return $response;
    }
1294281
public function execute(TallantoMethodInterface $method)
  {
    // Build options
    $options = [];
    // Is endpoint secured?
    if ($method instanceof AbstractSecuredTallantoMethod) {
      if ($method->isSecured()) {
        $options['auth'] = [$method->getLogin(), $method->getPassword()];
      }
    }
    // Should we supply JSON data in the body?
    if (!is_null($jsonData = $method->getJsonData())) {
      $options['json'] = $jsonData;
    }
    // Get query parameters
    $options['query'] = $method->getQueryParameters();
    // Get request headers
    $options['headers'] = $method->getRequestHeaders();

    // Does endpoint pageable?
    if ($method instanceof PageableTallantoMethodInterface) {
      $options['query']['total_count'] = 'true';
      $options['query']['page_size'] = $method->getPageSize();
      $options['query']['page_number'] = $method->getPageNumber();
    }

    $this->logger->debug(
      'Performing Guzzle {method} request to {uri}',
      [
        'method'  => $method->getMethod(),
        'uri'     => $method->getUri(),
        'options' => $options,
      ]
    );

    // Make request
    try {
      $response = $this->getClient()
        ->request(
          $method->getMethod(),
          $method->getUri(),
          $options
        );
    } catch (RequestException $e) {
      throw new TransportTallantoException(
        'Guzzle request failed: '.$e->getResponse()
          ->getBody()
          ->getContents(), 0, $e
      );
    } catch (\Exception $e) {
      throw new TransportTallantoException('Guzzle request failed.', 0, $e);
    }
    // Assign response
    $method->setResponse($response);
  }
513262
function request($method, $body = NULL, $header = array()){
        foreach($body as $key => $val) {
            if($val === null) {
                unset($body[$key]);
            }
        }

        ShortPixel::log("REQUEST BODY: " . json_encode($body));

        $retUrls = array("body" => array(), "headers" => array(), "fileMappings" => array());
        $retPend = array("body" => array(), "headers" => array(), "fileMappings" => array());
        $retFiles = array("body" => array(), "headers" => array(), "fileMappings" => array());

        if(isset($body["urllist"])) {
            $retUrls = $this->requestInternal($method, $body, $header);
        }
        if(isset($body["pendingURLs"])) {
            unset($body["urllist"]);
            //some files might have already been processed as relaunches in the given max time
            foreach($retUrls["body"] as $url) {
                //first remove it from the files list as the file was uploaded properly
                if($url->Status->Code != -102 && $url->Status->Code != -106) {
                    $notExpired[] = $url;
                    if(!isset($body["pendingURLs"][$url->OriginalURL])) {
                        $lala = "cucu";
                    } else
                    $unsetPath = $body["pendingURLs"][$url->OriginalURL];
                    if(isset($body["files"]) && ($key = array_search($unsetPath, $body["files"])) !== false) {
                        unset($body["files"][$key]);
                    }
                }
                //now from the pendingURLs if we already have an answer with urllist
                if(isset($body["pendingURLs"][$url->OriginalURL])) {
                    $retUrls["fileMappings"][$url->OriginalURL] = $body["pendingURLs"][$url->OriginalURL];
                    unset($body["pendingURLs"][$url->OriginalURL]);
                }
            }
            if(count($body["pendingURLs"])) {
                $retPend = $this->requestInternal($method, $body, $header);
                if(isset($retPend['body']->Status->Code) && $retPend['body']->Status->Code < 0) { //something's wrong (API key?)
                    throw new ClientException($retPend['body']->Status->Message, $retPend['body']->Status->Code);

                }
                if(isset($body["files"])) {
                    $notExpired = array();
                    foreach($retPend['body'] as $detail) {
                        if($detail->Status->Code != -102) { // -102 is expired, means we need to resend the image through post
                            $notExpired[] = $detail;
                            $unsetPath = $body["pendingURLs"][$detail->OriginalURL];
                            if(($key = array_search($unsetPath, $body["files"])) !== false) {
                                unset($body["files"][$key]);
                            }
                        }
                    }
                    $retPend['body'] = $notExpired;
                }
            }
        }
        if (isset($body["files"]) && count($body["files"]) ||
            isset($body["buffers"]) && count($body["buffers"])) {
            unset($body["pendingURLs"]);
            $retFiles = $this->requestInternal($method, $body, $header);
        }

        if(!isset($retUrls["body"]->Status) && !isset($retPend["body"]->Status) && !isset($retFiles["body"]->Status)
           && (!is_array($retUrls["body"]) || !is_array($retPend["body"]) || !is_array($retFiles["body"]))) {
            throw new Exception("Request inconsistent status. Please contact support.");
        }

        $body = isset($retUrls["body"]->Status)
            ? $retUrls["body"]
            : (isset($retPend["body"]->Status)
                ? $retPend["body"]
                : (isset($retFiles["body"]->Status)
                    ? $retFiles["body"] :
                    array_merge($retUrls["body"], $retPend["body"], $retFiles["body"])));

        $theReturn =  (object) array("body"    => $body,
                     "headers" => array_unique(array_merge($retUrls["headers"], $retPend["headers"], $retFiles["headers"])),
                     "fileMappings" => array_merge($retUrls["fileMappings"], $retPend["fileMappings"], $retFiles["fileMappings"]));
        ShortPixel::log("REQUEST RETURNS: " . json_encode($theReturn));
        return $theReturn;
    }
458688
public function request($method = null)
	{
		# Verifying if was set method.
		if (!is_null($method)) $this->setMethod($method);
		
		# Verifying if URI is setted.
		if (is_null($this->uri)) {
			throw new RuntimeException('URI must be set before calling request method.');
		}
		
		# Setting default CURL options
		$this->setCurlOpts($this->defaultCurlOpts);
		
		# Verifying and preparing request for specified method.
		switch ($this->method) {
			case 'GET' : 
				// Specific routines for GET request.
				break;
			case 'POST' :
				$this->setCurlOpts(CURLOPT_POST, true); 
				
				if ($this->useRawData) {
					$this->setCurlOpts(CURLOPT_POSTFIELDS, $this->dataRaw);
				} else {
					// Verifying if has files to send
					if (count($this->files) > 0) {
						foreach ($this->files as $k => $v) {
							// Verifying if PHP version is over 5.4
							if (PHP_VERSION_ID < 50500) {
								$this->setParameterPost($k, "@$v");
							} else {
								$cFile = new CURLFile($v,mime_content_type($v),$k);
								$this->setParameterPost($k, $cFile);
							}
						} 
					}
					$this->setCurlOpts(CURLOPT_POSTFIELDS, $this->paramsPost);
				}
				break;
			case 'PUT' : 
				$this->setCurlOpts(CURLOPT_CUSTOMREQUEST, "PUT");
				if ($this->useRawData) {
					$this->setCurlOpts(CURLOPT_POSTFIELDS, $this->dataRaw);
				} else {
					$data = http_build_query($this->paramsPost);
					$this->setCurlOpts(CURLOPT_POSTFIELDS, $data);
				}
				break;
			case 'DELETE' : 
				$this->setCurlOpts(CURLOPT_CUSTOMREQUEST, "DELETE");
				break;
		}
		
		# Rendering GET parameters into a query string.
		$queryString = (count($this->paramsGet) > 0) ? '?' . http_build_query($this->paramsGet) : '';
		
		# Preparing and setting URI in CURL options
		$uri = $this->uri . $queryString;
		$this->setCurlOpts(CURLOPT_URL, $uri);
		
		# Parsing headers
		$headers = array();
		foreach ($this->headers as $key => $value) {
			$headers[] = $key . ': ' . $value;
		}
		$this->setCurlOpts(CURLOPT_HTTPHEADER, $headers);
		
		# Setting remaining options in CURL
		$this->setCurlOpts(array(
			CURLOPT_HTTP_VERSION=>$this->httpVersion,
		));
		
		# Initializing Request
		$ch = curl_init();
		curl_setopt_array($ch, $this->curlOpts);
		
		# Performing Request
		$response = curl_exec($ch);
		
		# Verifying if request was successfully executed.
		if (!$response) {
			throw new RuntimeException('cURL Request Error: ' . curl_errno($ch));
		}
		
		# Closing handle
		curl_close($ch);
		
		# Verifying if a custom response handler was set
		if (!is_null($this->responseHandler)) {
			$this->response = $this->responseHandler->fromString($response);
		} else {
			$this->response = Response::fromString($response);
		}
		
		# Saving last instance in Client
		$this->lastRequest = clone $this;
		
		# Verifying noReset control var
		if (!$this->noReset) {
			$this->reset();
		}
		
		return $this->response;
	}
655251
private function doSend($method, array $data, $token = null)
    {
        try {
            $data['token'] = $token ?: $this->token;

            $this->eventDispatcher->dispatch(self::EVENT_REQUEST, new RequestEvent($data));

            $request = $this->createRequest($method, $data);

            /** @var ResponseInterface $response */
            $response = $this->client->send($request);
        } catch (\Exception $e) {
            throw new SlackException('Failed to send data to the Slack API', null, $e);
        }

        try {
            $responseData = json_decode($response->getBody()->getContents(), true);
            if (!is_array($responseData)) {
                throw new \Exception(sprintf(
                    'Expected JSON-decoded response data to be of type "array", got "%s"',
                    gettype($responseData)
                ));
            }

            $this->eventDispatcher->dispatch(self::EVENT_RESPONSE, new ResponseEvent($responseData));

            return $responseData;
        } catch (\Exception $e) {
            throw new SlackException('Failed to process response from the Slack API', null, $e);
        }
    }
629329
public function callAction($method, $parameters)
    {
        $response = $parentResponse = null;

        try {
            $response = $parentResponse = parent::callAction($method, $parameters);
        } catch (\Exception $e) {
            $notFoundExceptions = array(
                'Illuminate\\Database\\Eloquent\\ModelNotFoundException',
                'Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException',
            );
            $errorExceptions = array(
                'Subbly\\Api\\Service\\Exception',
            );

            if (in_array(get_class($e), $notFoundExceptions)) {
                return $this->jsonNotFoundResponse($e->getMessage());
            } elseif (in_array(get_class($e), $errorExceptions)) {
                return $this->jsonErrorResponse($e->getMessage());
            } elseif ($e instanceof \Subbly\Model\Exception\UnvalidModelException) {
                return $this->jsonErrorResponse($e->firstErrorMessage());
            }

            $response = $this->jsonErrorResponse('Fatal error!');
        }

        if (App::environment('local', 'testing')) {
            return $parentResponse ?: parent::callAction($method, $parameters);
        }

        return $response;
    }
1338536
def organization_field_delete(self, id, **kwargs):
        ""
        api_path = "/api/v2/organization_fields/{id}.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, method="DELETE", **kwargs)
85074
public static function altEncrypt(
        $value,
        $hash = false,
        $method = self::DEFAULT_CHIPPER
    ) {
        /**
         * Serialize Element
         */
        $string = @serialize([
            $value
        ]);
        if (!$string) {
            throw new \ErrorException(
                sprintf(
                    'Could not serialize input of %s',
                    gettype($string)
                )
            );
        }
        $passKey   = self::createPassKey($hash);
        $crypt_arr = self::cryptStandard(
            $passKey[1],
            $string,
            $method
        );

        $microtime = microtime(true);
        $iv = self::safeBase64Encode($method . $crypt_arr[2]);
        $json_value = json_encode([
            'micro'  => $microtime,
            'method' => $crypt_arr[1],
            'iv'     => $iv,
            'value'  => $crypt_arr[0],
        ]);

        // save as bse64 encode safe
        $crypt_text = trim(
            self::safeBase64Encode(
                $json_value .
                json_encode([
                    sha1($microtime . $passKey[1] . $iv)
                ])
            )
        );

        /**
         * ------------------------------------
         * Inject Result of with sign
         * ------------------------------------
         */
        $pos = abs(round(strlen($passKey[0]) / 3));
        $separator = self::safeBase64Encode(sha1($passKey[1]) . self::STANDARD_MIDDLE);
        if (strlen($crypt_text) > $pos) {
            return substr_replace($crypt_text, $separator . $pos, $pos, 0);
        } else {
            return substr_replace($crypt_text, $separator . $pos, 2, 0);
        }
    }
882794
public function runInstall($method, $fields) {
    $checkInstalled = $this->setup->checkInstalled();
    if ($checkInstalled->isDatabaseInstalled() || $checkInstalled->isSettingInstalled()) {
      return $this->createError("CiviCRM is already installed");
    }

    $reqs = $this->setup->checkRequirements();
    if (count($reqs->getErrors())) {
      return $this->runStart($method, $fields);
    }

    $this->setup->installFiles();
    $this->setup->installDatabase();

    $m = $this->setup->getModel();
    $tplFile = $this->getResourcePath('finished.' . $m->cms . '.php');
    if (file_exists($tplFile)) {
      $tplVars = array();
      return array(array(), $this->render($tplFile, $tplVars));
    }
    else {
      return $this->createError("Installation succeeded. However, the final page ($tplFile) was not available.");
    }
  }
44941
public void setMethodHash(XMethod method, byte[] methodHash) {
        methodHashMap.put(method, new MethodHash(method.getName(), method.getSignature(), method.isStatic(), methodHash));
    }
1070011
public function serialize(Organization $organization, array $options = [])
    {
        $data = [
            'id' => $organization->getUuid(),
            'name' => $organization->getName(),
            'code' => $organization->getCode(),
            'email' => $organization->getEmail(),
            'type' => $organization->getType(),
            'parent' => !empty($organization->getParent()) ? [
                'id' => $organization->getParent()->getUuid(),
                'name' => $organization->getParent()->getName(),
            ] : null,
            'meta' => [
                'default' => $organization->getDefault(),
                'position' => $organization->getPosition(),
            ],
            'managers' => array_map(function (User $administrator) {
                return [
                    'id' => $administrator->getId(),
                    'username' => $administrator->getUsername(),
                ];
            }, $organization->getAdministrators()->toArray()),
            'locations' => array_map(function (Location $location) {
                return [
                    'id' => $location->getId(),
                    'name' => $location->getName(),
                ];
            }, $organization->getLocations()->toArray()),
        ];

        if (in_array(Options::IS_RECURSIVE, $options)) {
            $data['children'] = array_map(function (Organization $child) use ($options) {
                return $this->serialize($child, $options);
            }, $organization->getChildren()->toArray());
        }

        return $data;
    }
1323486
public function execute($lineNr = null, $organizationData = null)
    {
        $batch  = $this->getBatch();
        $import = $batch->getVariable('import');

        if (isset($organizationData['gor_id_organization']) && $organizationData['gor_id_organization']) {

            $oldId = $organizationData['gor_id_organization'];

        } else {
            $oldId = false;
            $batch->addToCounter('import_errors');
            $batch->addMessage(sprintf(
                    $this->_('No gor_id_organization not specified for organization at line %d.'),
                    $lineNr
                    ));
        }

        if (isset($organizationData['gor_name']) && $organizationData['gor_name']) {
            if ($oldId) {
                $orgId = $this->db->fetchOne(
                        "SELECT gor_id_organization FROM gems__organizations WHERE gor_name = ?",
                        $organizationData['gor_name']
                        );
                if ($orgId) {
                    $import['organizationIds'][$oldId] = $orgId;
                    $import['formDefaults']['gtr_organizations'][] = $orgId;
                } else {
                    $import['organizationIds'][$oldId] = false;
                }
            }
        } else {
            $orgId = false;
            $batch->addToCounter('import_errors');
            $batch->addMessage(sprintf(
                    $this->_('No gor_name not specified for organization at line %d.'),
                    $lineNr
                    ));
        }
    }
1145810
private function getCachedResponse($method, $url, array $data, array $headers)
    {
        if ($this->cache)
        {
            return $this->cache->findResponse($method, $url, $data, $headers, $this->basicAuthCredentials);
        }

        return false;
    }
412928
public function callAction($method, $parameters)
    {
        $result = null;
        $this->setupLayout($method);

        // Call the action if $this->general() doesn't suggest otherwise
        if (method_exists($this, 'general'))
            $result = $this->general();
        if (!$result)
            $result = parent::callAction($method, $parameters);

        return isset($result) ? $result : $this->layout; // must use isset() for case of empty array in AJAX response
    }
1368579
public function processInvitationByHash(User $user, $hash)
    {
        $invitation = $this->dm->getRepository('WobbleCodeUserBundle:Invitation')->findOneBy(
            [
                'hash'   => $hash,
                'status' => 'pending'
            ]
        );

        if (!$invitation) {
            return false;
        }

        $organization = $invitation->getOrganization();
        $this->addMemberByInvitation($organization, $user, $invitation);

        return $organization;
    }
344951
public function execute($method, $apiCall, array $parameters = array(), $headers = array())
    {
        // Check if the access token needs to be added
        if ($this->access_token != null) {
            $headers = array_merge($headers, array(
                "Authorization: Bearer " . $this->access_token,
            ));
        }

        // Force cURL to not send Expect header to workaround bug with Akamai CDN not handling
        // this type of requests correctly
        $headers = array_merge($headers, array(
            "Expect:",
        ));

        // Setup CURL
        $ch = $this->curlbuilder->create();

        // Set default options
        $ch->setOptions(array(
            CURLOPT_URL             => $apiCall,
            CURLOPT_HTTPHEADER      => $headers,
            CURLOPT_CONNECTTIMEOUT  => 20,
            CURLOPT_TIMEOUT         => 90,
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_HEADER          => false,
            CURLINFO_HEADER_OUT     => true
        ));

        switch ($method) {
            case 'POST':
                $ch->setOptions(array(
                    CURLOPT_CUSTOMREQUEST   => "POST",
                    CURLOPT_POST            => count($parameters),
                    CURLOPT_POSTFIELDS      => $parameters
                ));

                if (!class_exists('\CURLFile') && defined('CURLOPT_SAFE_UPLOAD')) {
                    $ch->setOption(CURLOPT_SAFE_UPLOAD, false);
                }
                elseif (class_exists('\CURLFile') && defined('CURLOPT_SAFE_UPLOAD')) {
                    $ch->setOption(CURLOPT_SAFE_UPLOAD, true);
                }

                break;
            case 'DELETE':
                $ch->setOption(CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
            case 'PATCH':
                $ch->setOptions(array(
                    CURLOPT_CUSTOMREQUEST   => "PATCH",
                    CURLOPT_POST            => count($parameters),
                    CURLOPT_POSTFIELDS      => $parameters
                ));
                break;
            default:
                $ch->setOption(CURLOPT_CUSTOMREQUEST, "GET");
                break;
        }

        // Execute request and catch response
        $response_data = $ch->execute();

        if ($response_data === false && !$ch->hasErrors()) {
            throw new CurlException("Error: Curl request failed");
        }
        else if($ch->hasErrors()) {
            throw new PinterestException('Error: execute() - cURL error: ' . $ch->getErrors(), $ch->getErrorNumber());
        }

        // Initiate the response
        $response = new Response($response_data, $ch);

        // Check the response code
        if ($response->getResponseCode() >= 400) {
            throw new PinterestException('Pinterest error (code: ' . $response->getResponseCode() . ') with message: ' . $response->getMessage(), $response->getResponseCode());
        }

        // Get headers from last request
        $this->headers = $ch->getHeaders();

        // Close curl resource
        $ch->close();

        // Return the response
        return $response;
    }