Webhook handler

@return array
@throws \TelegramBot\Api\InvalidJsonException
354281
public function run()
    {
        if ($data = BotApi::jsonValidate($this->getRawBody(), true)) {
            $this->handle([Update::fromResponse($data)]);
        }
    }
694429
public function getErrorMessage()
    {
        $app = Application::getFacadeApplication();
        $request = $app->make(Request::class);
        $ajax = $app->make(Ajax::class);
        if ($ajax->isAjaxRequest($request)) {
            return t("Invalid token. Please reload the page and retry.");
        } else {
            return t("Invalid form token. Please reload this form and submit again.");
        }
    }
824431
protected function getWebhooks() {
        if (!$this->_webhooks) {
            $this->_webhooks = new WebhookList($this->version, $this->solution['sid']);
        }

        return $this->_webhooks;
    }
177908
public function broadcastWith()
    {
        return [
            'id' => $this->id,
            'webhook' => $this->webhook,
            'request' => $this->request,
            'response' => $this->response,
            'status' => $this->status,
        ];
    }
1348959
public static function getRegisteredHooks()
    {
        $subscribed = array_keys(self::$hooks);
        $called = array_keys(self::$counters);
        $all = array_merge($subscribed, $called);
        return array_unique($all);
    }
389623
protected function handleRequest()
    {
        $message = $this->getMessage();

        if ($this->appId == self::TEST_APP_ID) {
            $response = $this->handleTestMessage($message);
        } else {
            $response = $this->handleMessage($message);
        }

        return [
            'to' => $message['FromUserName'],
            'from' => $message['ToUserName'],
            'response' => $response,
        ];
    }
1299938
protected function execAjaxHandlers()
    {
        if ($handler = $this->getAjaxHandler()) {
            try {
                /*
                 * Validate the handler name
                 */
                if (!preg_match('/^(?:\w+\:{2})?on[A-Z]{1}[\w+]*$/', $handler)) {
                    throw new SystemException(Lang::get('backend::lang.ajax_handler.invalid_name', ['name'=>$handler]));
                }

                /*
                 * Validate the handler partial list
                 */
                if ($partialList = trim(Request::header('X_OCTOBER_REQUEST_PARTIALS'))) {
                    $partialList = explode('&', $partialList);

                    foreach ($partialList as $partial) {
                        if (!preg_match('/^(?!.*\/\/)[a-z0-9\_][a-z0-9\_\-\/]*$/i', $partial)) {
                            throw new SystemException(Lang::get('backend::lang.partial.invalid_name', ['name'=>$partial]));
                        }
                    }
                }
                else {
                    $partialList = [];
                }

                $responseContents = [];

                /*
                 * Execute the handler
                 */
                if (!$result = $this->runAjaxHandler($handler)) {
                    throw new ApplicationException(Lang::get('backend::lang.ajax_handler.not_found', ['name'=>$handler]));
                }

                /*
                 * Render partials and return the response as array that will be converted to JSON automatically.
                 */
                foreach ($partialList as $partial) {
                    $responseContents[$partial] = $this->makePartial($partial);
                }

                /*
                 * If the handler returned a redirect, process the URL and dispose of it so
                 * framework.js knows to redirect the browser and not the request!
                 */
                if ($result instanceof RedirectResponse) {
                    $responseContents['X_OCTOBER_REDIRECT'] = $result->getTargetUrl();
                    $result = null;
                }
                /*
                 * No redirect is used, look for any flash messages
                 */
                elseif (Flash::check()) {
                    $responseContents['#layout-flash-messages'] = $this->makeLayoutPartial('flash_messages');
                }

                /*
                 * Detect assets
                 */
                if ($this->hasAssetsDefined()) {
                    $responseContents['X_OCTOBER_ASSETS'] = $this->getAssetPaths();
                }

                /*
                 * If the handler returned an array, we should add it to output for rendering.
                 * If it is a string, add it to the array with the key "result".
                 * If an object, pass it to Laravel as a response object.
                 */
                if (is_array($result)) {
                    $responseContents = array_merge($responseContents, $result);
                }
                elseif (is_string($result)) {
                    $responseContents['result'] = $result;
                }
                elseif (is_object($result)) {
                    return $result;
                }

                return Response::make()->setContent($responseContents);
            }
            catch (ValidationException $ex) {
                /*
                 * Handle validation error gracefully
                 */
                Flash::error($ex->getMessage());
                $responseContents = [];
                $responseContents['#layout-flash-messages'] = $this->makeLayoutPartial('flash_messages');
                $responseContents['X_OCTOBER_ERROR_FIELDS'] = $ex->getFields();
                throw new AjaxException($responseContents);
            }
            catch (MassAssignmentException $ex) {
                throw new ApplicationException(Lang::get('backend::lang.model.mass_assignment_failed', ['attribute' => $ex->getMessage()]));
            }
            catch (Exception $ex) {
                throw $ex;
            }
        }

        return null;
    }
1342749
public function getHandlers()
    {
        $handlers = [];
        foreach ($this->handlers as $key => $handler) {
            $handlers[$key] = $handler->getCallable();
        }

        return $handlers;
    }
1264366
public static function handleRequest()
    {
        // save static class
        static::$calledClass = get_called_class();

        // handle JSON requests
        if (static::peekPath() == 'json') {
            // check access for API response modes
            static::$responseMode = static::shiftPath();
            if (in_array(static::$responseMode, ['json','jsonp'])) {
                if (!static::checkAPIAccess()) {
                    return static::throwAPIUnAuthorizedError();
                }
            }
        }

        return static::handleRecordsRequest();
    }
62593
public function listHooks(): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/repos/:owner/:repo/hooks',
            $this->getRepositories()->getOwner(), $this->getRepositories()->getRepo()));
    }
1283297
function listHookData() {
    // We may come here several times, so cache this.
    if (!empty($this->hook_data)) {
      return $this->hook_data;
    }

    $this->hook_data = $this->environment->getStorage()->retrieve('hooks');
    return $this->hook_data;
  }
1136866
public function listen()
    {
        $input     = null;
        $inputJSON = file_get_contents('php://input');
        if (strlen($inputJSON)) {
            $input     = json_decode($inputJSON, TRUE); //convert JSON into array
            $lastError = json_last_error();
            if ($lastError) {
                $this->addStatusMessage(json_last_error_msg(), 'warning');
            }
        }
        return $input;
    }
294681
private function handleWebhook() {
        $identifier = $this->field('identifier');

        if ($identifier !== $this->identifier) {
            return;
        }

        $event_id = $this->field('event_id');
        $webhook_id = $this->field('webhook_id');

        if (!$event_id || !$webhook_id) {
            Log::info($this->patrol, 'Webhook ' . $this->identifier . ' has no event_id or webhook_id');
            return;
        }

        $httpClient = new HttpClient($this->patrol, 'GET', 'webhooks/' . $webhook_id . '/events/' . $event_id);
        $response = $httpClient->response();

        if (!$response) {
            Log::info($this->patrol, 'Retrieving webhook from ' . $httpClient->getUrl() . ' failed');
            return;
        }

        $data = $this->field($response, 'data');

        if (!$data) {
            Log::info($this->patrol, 'Event has invalid format to be processed: ' . print_r($response, true));
        }

        $callable = $this->callback;

        if (is_callable($callable)) {
            $callable($data);
        }
    }
1223077
public function getThread(): array
    {
        \set_error_handler(static function () {});

        /** @var array|false $tree */
        $tree = \imap_thread($this->resource->getStream());

        \restore_error_handler();

        return false !== $tree ? $tree : [];
    }
701119
private function waitNextInvocation(): array
    {
        if ($this->handler === null) {
            $this->handler = curl_init("http://{$this->apiUrl}/2018-06-01/runtime/invocation/next");
            curl_setopt($this->handler, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($this->handler, CURLOPT_FAILONERROR, true);
        }

        // Retrieve invocation ID
        $contextBuilder = new ContextBuilder;
        curl_setopt($this->handler, CURLOPT_HEADERFUNCTION, function ($ch, $header) use ($contextBuilder) {
            if (! preg_match('/:\s*/', $header)) {
                return strlen($header);
            }
            [$name, $value] = preg_split('/:\s*/', $header, 2);
            $name = strtolower($name);
            $value = trim($value);
            if ($name === 'lambda-runtime-aws-request-id') {
                $contextBuilder->setAwsRequestId($value);
            }
            if ($name === 'lambda-runtime-deadline-ms') {
                $contextBuilder->setDeadlineMs(intval($value));
            }
            if ($name === 'lambda-runtime-invoked-function-arn') {
                $contextBuilder->setInvokedFunctionArn($value);
            }
            if ($name === 'lambda-runtime-trace-id') {
                $contextBuilder->setTraceId($value);
            }

            return strlen($header);
        });

        // Retrieve body
        $body = '';
        curl_setopt($this->handler, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) use (&$body) {
            $body .= $chunk;

            return strlen($chunk);
        });

        curl_exec($this->handler);
        if (curl_errno($this->handler) > 0) {
            $message = curl_error($this->handler);
            $this->closeHandler();
            throw new \Exception('Failed to fetch next Lambda invocation: ' . $message);
        }
        if ($body === '') {
            throw new \Exception('Empty Lambda runtime API response');
        }

        $context = $contextBuilder->buildContext();

        if ($context->getAwsRequestId() === '') {
            throw new \Exception('Failed to determine the Lambda invocation ID');
        }

        $event = json_decode($body, true);

        return [$event, $context];
    }
715071
public function linkAccountCallback() {
    $sdk = $this->getSdk();

    if ($sdk instanceof RedirectResponse) {
      return $sdk;
    }

    $network_manager = $this->networkManager->createInstance('social_auth_twitter');
    $data_handler = $network_manager->getDataHandler();

    // Get the Twitter OAuth token from storage.
    if (!($oauth_token = $data_handler->get('oauth_token')) || !($oauth_token_secret = $data_handler->get('oauth_token_secret'))) {
      drupal_set_message($this->t('Twitter login failed. Token or Token Secret is not valid.'), 'error');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    $this->authManager->setSdk($sdk);
    $this->authManager->setAccessToken([
      'oauth_token' => $oauth_token,
      'oauth_token_secret' => $oauth_token_secret,
    ]);

    // Get the permanent access token.
    $access_token = $sdk->oauth('oauth/access_token', [
      'oauth_verifier' => $this->request->get('oauth_verifier'),
    ]);

    $this->authManager->setAccessToken([
      'oauth_token' => $access_token['oauth_token'],
      'oauth_token_secret' => $access_token['oauth_token_secret'],
    ]);

    // Get user's profile from Twitter API.
    if (!($this->authManager->getProfile()) || !($account_id = $this->authManager->getAccountId())) {
      drupal_set_message($this->t('@network login failed, could not load @network profile. Contact site administrator.', [
        '@network' => $this->t('Twitter'),
      ]), 'error');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    // Check whether any another user account already connected.
    $account = $this->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties(['twitter_id' => $account_id]);
    $account = current($account);

    // Check whether another account was connected to this Twitter account.
    if ($account && (int) $account->id() !== (int) $this->currentUser()->id()) {
      drupal_set_message($this->t('Your @network account has already connected to another account on this site.', [
        '@network' => $this->t('Twitter'),
      ]), 'warning');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    $account = User::load($this->currentUser()->id());
    $account->get('twitter_id')->setValue($account_id);
    $account->save();

    drupal_set_message($this->t('You are now able to log in with @network', [
      '@network' => $this->t('Twitter'),
    ]));
    return $this->redirect('entity.user.edit_form', [
      'user' => $account->id(),
    ]);
  }
1063179
public static function ensureJsonSuffix(): callable
    {
        return function (callable $handler) {
            return function (RequestInterface $request, array $options = null) use ($handler) {
                $uri = $request->getUri();
                $path = $uri->getPath();

                if (substr($path, -5) !== '.json') {
                    $uri = $uri->withPath($path.'.json');
                    $request = $request->withUri($uri);
                }

                return $handler($request, $options ?? []);
            };
        };
    }