Generic handler for all HTTP verbs

@return void
1038
protected function _handle()
    {
        list($finder, $options) = $this->_extractFinder();
        $query = $this->_table()->find($finder, $options);
        $subject = $this->_subject(['success' => true, 'query' => $query]);

        $this->_trigger('beforePaginate', $subject);
        $items = $this->_controller()->paginate($subject->query);
        $subject->set(['entities' => $items]);

        $this->_trigger('afterPaginate', $subject);
        $this->_trigger('beforeRender', $subject);
    }
217053
public function handleRouter()
	{
		// Load initial/default routes if there're no components or the component wants to merge them
    	if ($this->component === false || $this->component->getMergeDefaultRouting()) {
    		$this->getRouter()->loadRoutes(
    			__APP_CONFIG_ROUTING,
				!$this->getSetting('forcelogin', true),
				$this->getSetting('forcesession', true),
				$this->getSetting('templatebase', true),
				$this->getSetting('templatepath', true)
			);
    	}

		// If there's a component
		if ($this->component !== false) {
			$this->getRouter()->loadRoutes(
				$this->component->hasRouting() ? $this->component->getRoutingPath() : __APP_CONFIG_ROUTING,
				!$this->getSetting('forcelogin'),
				$this->getSetting('forcesession'),
				$this->getSetting('templatebase'),
				$this->getSetting('templatepath')
			);
    	}
    	    	
    	$this->getRouter()->handleRoute(__BASE);
    }
1169636
public function handleRequest(): void
	{
		global $save, $restore;

		$request = $this->getRequest();
		if ((!empty($save) || !empty($restore)) && $request->isPost() && check_bitrix_sessid()) {
			if (!empty($restore)) {
				// Restore defaults
				Option::delete(ADMIN_MODULE_NAME);
				CAdminMessage::showMessage([
					'MESSAGE' => Loc::getMessage('REFERENCES_OPTIONS_RESTORED'),
					'TYPE' => 'OK',
				]);
			} else {
				try {
					// Save options
					foreach ($this->options->getFields() as $id => $opt) {
						switch ($opt['type']) {
							case 'checkbox':
								$value = $request->getPost($id) ? true : false;
								break;

							case 'number':
								$value = (int)$request->getPost($id);
								break;

							case 'text':
							default:
								$value = $request->getPost($id);
								break;
						}

						$event = new Event(ADMIN_MODULE_NAME, 'OnBeforeSetOption_' . $id, ['value' => &$value]);
						$event->send();

						$event = new Event(ADMIN_MODULE_NAME, 'OnBeforeSetOption', ['value' => &$value, 'name' => $id]);
						$event->send();

						Option::set(ADMIN_MODULE_NAME, $id, $value);
					}

					$event = new Event(ADMIN_MODULE_NAME, 'OnAfterSaveOptions');
					$event->send();

					CAdminMessage::showMessage([
						'MESSAGE' => Loc::getMessage('REFERENCES_OPTIONS_SAVED'),
						'TYPE' => 'OK',
					]);
				} catch (\Exception $exception) {
					CAdminMessage::showMessage($exception->getMessage());
				}
			}
		}
	}
61417
protected function checkForAlternateVerbs($request)
	{
		$others = array_diff(Router::$verbs, array($request->getMethod()));

		// Here we will spin through all verbs except for the current request verb and
		// check to see if any routes respond to them. If they do, we will return a
		// proper error response with the correct headers on the response string.
		foreach ($others as $other)
		{
			if ( ! is_null($this->check($this->get($other), $request)))
			{
				$this->methodNotAllowed($other);
			}
		}
	}
1021133
public function dispatch($verb = 'GET')
    {
        $request = Request::create($this->uri, $verb, $this->parameters);

        // Set token authorization header
        $request->headers->set('Authorization', 'Token token="' . config('forum.api.token') . '"');

        // Replace the request input for the duration of the dispatched request
        $input = $this->currentRequest->input();
        $this->currentRequest->replace($request->input());
        $response = Route::dispatch($request);
        $this->currentRequest->replace($input);

        return $this->receiver->handleResponse($request, $response);
    }
925913
public function handleRequest(): self
    {
        if ($this->params->getBotParam('webhook.url')) {
            return $this->handleWebhook();
        }

        if ($loop_time = $this->getLoopTime()) {
            return $this->handleGetUpdatesLoop($loop_time, $this->getLoopInterval());
        }

        return $this->handleGetUpdates();
    }
113037
public function handleRequest()
    {
        $sequence = $this->bootstrap->buildRuntimeSequence();
        $sequence->invoke($this->bootstrap);

        $objectManager = $this->bootstrap->getObjectManager();
        /** @var LoggerInterface $logger */
        $logger = $objectManager->get(PsrLoggerFactoryInterface::class)->get('systemLogger');

        $logger->debug('Running sub process loop.');
        echo "\nREADY\n";

        try {
            while (true) {
                $commandLine = trim(fgets(STDIN));
                $trimmedCommandLine = trim($commandLine);
                $logger->info(sprintf('Received command "%s".', $trimmedCommandLine), LogEnvironment::fromMethodName(__METHOD__));
                if ($commandLine === "QUIT\n") {
                    break;
                }
                /** @var Request $request */
                $request = $objectManager->get(RequestBuilder::class)->build($trimmedCommandLine);
                $response = new Response();
                if ($this->bootstrap->isCompiletimeCommand($request->getCommand()->getCommandIdentifier())) {
                    echo "This command must be executed during compiletime.\n";
                } else {
                    $objectManager->get(Dispatcher::class)->dispatch($request, $response);
                    $response->send();

                    $this->emitDispatchedCommandLineSlaveRequest();
                }
                echo "\nREADY\n";
            }

            $logger->debug('Exiting sub process loop.');
            $this->bootstrap->shutdown(Bootstrap::RUNLEVEL_RUNTIME);
            exit($response->getExitCode());
        } catch (\Exception $exception) {
            $this->handleException($exception);
        }
    }
246221
public function handleRequest() {
		$files = array();
		$supportsGzip = false;
		$expiresOffset = $this->parseTime($this->settings["expires"]);
		$tinymceDir = dirname(__FILE__);

		// Plugins
		$plugins = self::getParam("plugins");
		if ($plugins) {
			$this->settings["plugins"] = $plugins;
		}

		$plugins = array_unique(preg_split('/,/', $this->settings["plugins"], -1, PREG_SPLIT_NO_EMPTY));

		// Themes
		$themes = self::getParam("themes");
		if ($themes) {
			$this->settings["themes"] = $themes;
		}

		$themes = array_unique(preg_split('/,/', $this->settings["themes"], -1, PREG_SPLIT_NO_EMPTY));

		// Languages
		$languages = self::getParam("languages");
		if ($languages) {
			$this->settings["languages"] = $languages;
		}

		$languages = array_unique(preg_split('/,/', $this->settings["languages"], -1, PREG_SPLIT_NO_EMPTY));

		// Files
		$tagFiles = self::getParam("files");
		if ($tagFiles) {
			$this->settings["files"] = $tagFiles;
		}

		// Diskcache option
		$diskCache = self::getParam("diskcache");
		if ($diskCache) {
			$this->settings["disk_cache"] = ($diskCache === "true");
		}

		// Source or minified version
		$src = self::getParam("src");
		if ($src) {
			$this->settings["source"] = ($src === "true");
		}

		// Add core js
		if (self::getParam("core", "true") === "true") {
			$files[] = "tinymce";
		}

		// Add core languages
		foreach ($languages as $language) {
			$files[] = "langs/" . $language;
		}

		// Add plugins
		foreach ($plugins as $plugin) {
			$files[] = "plugins/" . $plugin . "/plugin";

			foreach ($languages as $language) {
				$files[] = "plugins/" . $plugin . "/langs/" . $language;
			}
		}

		// Add themes
		foreach ($themes as $theme) {
			$files[] = "themes/" . $theme . "/theme";

			foreach ($languages as $language) {
				$files[] = "themes/" . $theme . "/langs/" . $language;
			}
		}

		// Add any specified files.
		$allFiles = array_merge($files, array_unique(preg_split('/,/', $this->settings['files'], -1, PREG_SPLIT_NO_EMPTY)));

		// Process source files
		for ($i = 0; $i < count($allFiles); $i++) {
			$file = $allFiles[$i];

			if ($this->settings["source"] && file_exists($file . ".js")) {
				$file .= ".js";
			} else if (file_exists($file . ".min.js"))  {
				$file .= ".min.js";
			} else {
				$file = "";
			}

			$allFiles[$i] = $file;
		}

		// Generate hash for all files
		// CUSTOM SilverStripe Webroot-specific caches
		$hash = md5(implode('', $allFiles) . $_SERVER['SCRIPT_NAME']);
		// CUSTOM END

		// Check if it supports gzip
		$zlibOn = ini_get('zlib.output_compression') || (ini_set('zlib.output_compression', 0) === false);
		$encodings = (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) ? strtolower($_SERVER['HTTP_ACCEPT_ENCODING']) : "";
		$encoding = preg_match( '/\b(x-gzip|gzip)\b/', $encodings, $match) ? $match[1] : "";

		// Is northon antivirus header
		if (isset($_SERVER['---------------'])) {
			$encoding = "x-gzip";
		}

		$supportsGzip = $this->settings['compress'] && !empty($encoding) && !$zlibOn && function_exists('gzencode');

		// Set cache file name
		$cacheFile = $this->settings["cache_dir"] . "/tinymce.gzip-" . $hash . ($supportsGzip ? ".gz" : ".js");

 		// Set headers
		header("Content-type: text/javascript");
		header("Vary: Accept-Encoding");  // Handle proxies
		header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expiresOffset) . " GMT");
		header("Cache-Control: public, max-age=" . $expiresOffset);

		if ($supportsGzip) {
			header("Content-Encoding: " . $encoding);
		}

		// Use cached file
		if ($this->settings['disk_cache'] && file_exists($cacheFile)) {
			readfile($cacheFile);
			return;
		}

		// Set base URL for where tinymce is loaded from
		$buffer = "var tinyMCEPreInit={base:'" . dirname($_SERVER["SCRIPT_NAME"]) . "',suffix:'.min'};";

		// Load all tinymce script files into buffer
		foreach ($allFiles as $file) {
			if ($file) {
				$fileContents = $this->getFileContents($tinymceDir . "/" . $file);
//				$buffer .= "\n//-FILE-$tinymceDir/$file (". strlen($fileContents) . " bytes)\n";
				$buffer .= $fileContents;
			}
		}

		// Mark all themes, plugins and languages as done
		$buffer .= 'tinymce.each("' . implode(',', $files) . '".split(","),function(f){tinymce.ScriptLoader.markDone(tinyMCE.baseURL+"/"+f+".js");});';

		// Compress data
		if ($supportsGzip) {
			$buffer = gzencode($buffer, 9, FORCE_GZIP);
		}

		// Write cached file
		if ($this->settings["disk_cache"]) {
			@file_put_contents($cacheFile, $buffer);
		}

		// Stream contents to client
		echo $buffer;
	}
1010043
protected function preProcess(): void
    {
        Router::process();

        // disable Layout for XmlHttpRequests
        if (Request::isXmlHttpRequest()) {
            $this->layoutFlag = false;
        }

        // switch to JSON response based on Accept header
        if (Request::checkAccept([Request::TYPE_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON) {
            $this->layoutFlag = false;
            Response::setType('JSON');
        }
    }
229371
public function handleRequest()
    {
        try {
            $rtn = parent::handleRequest();

            if (extension_loaded('newrelic')) {
                $site = $this->toPhpName($this->config->get('site.name'));
                $controller = $this->toPhpName($this->route['controller']);
                $action = $this->toPhpName($this->route['action']);

                newrelic_name_transaction($site . '.' . $controller . '.' . $action);
            }
        } catch (HttpException\NotFoundException $ex) {
            $rtn = $this->handleHttpError($ex->getErrorCode());
        } catch (HttpException $ex) {
            if ((defined('CMS_ENV') && CMS_ENV == 'development') || array_key_exists('ex', $_GET)) {
                throw $ex;
            }

            $rtn = $this->handleHttpError($ex->getErrorCode());
        } catch (Exception $ex) {
            if ((defined('CMS_ENV') && CMS_ENV == 'development') || array_key_exists('ex', $_GET)) {
                throw $ex;
            }

            $rtn = $this->handleHttpError(500);
        }

        return $rtn;
    }
363892
public function execute(): void
    {
        if ($this->oLocaleService::ENABLE_SNIFF_URL) {

            /**
             * Manipulate the URL
             * Remove the /{language} element from the URL once the Locale service has initialsied
             * so that this doesn't affect normal routing of the application.
             *
             * @todo (Pablo - 2019-03-08) - Check if this breaks on systems where the app isn't at the root of the domain
             */

            $oUrl = $this->parseUrl($this->getUrl());

            //  If the detected language is the same as the default language then remove it form the URL and repeat
            if ($oUrl->language === $this->oLocaleService::DEFAULT_LANGUAGE) {
                header(
                    'Location: /' . $oUrl->url,
                    true,
                    HttpCodes::STATUS_TEMPORARY_REDIRECT
                );
                exit(0);
            }

            //  Save the original URL, should it be needed
            $_SERVER['ORIGINAL_URL'] = $this->getUrl();

            //  Update the $_SERVER values so the rest of the system continues as normal
            if (array_key_exists('PATH_INFO', $_SERVER)) {
                $_SERVER['PATH_INFO'] = '/' . $oUrl->path;
            }
            if (array_key_exists('REQUEST_URI', $_SERVER)) {
                $_SERVER['REQUEST_URI'] = '/' . $oUrl->url;
            }
        }
    }
171997
public function handler()
    {
        if ($this->allow_public_access) {
            Container::resolve_method($this, 'handle');
            return;
        }

        if (empty($this->restrict_to_roles) || \in_array(User_Utils::get_user_role()->name, $this->restrict_to_roles)) {
            Container::resolve_method($this, 'handle');
            return;
        }

        \wp_send_json_error('You do not have sufficient permissions to perform this action', 403);
    }
490304
public function execute()
    {
        $ch = curl_init();
        $this->setAuth($ch);
        try {
            switch (strtoupper($this->verb)) {
                case 'GET':
                    $this->executeGet($ch);
                    break;
                case 'POST':
                    $this->executePost($ch);
                    break;
                case 'PUT':
                    $this->executePut($ch);
                    break;
                case 'DELETE':
                    $this->executeDelete($ch);
                    break;
                default:
                    throw new \InvalidArgumentException(
                        'Current verb (' . $this->verb
                        . ') is an invalid REST verb.'
                    );
            }
        } catch (\InvalidArgumentException $e) {
            curl_close($ch);
            throw $e;
        } catch (\Exception $e) {
            curl_close($ch);
            throw $e;
        }

        /*
         * check and debug api request total time
         */
        $this->processDebugApi();

        return $this->responseBody;
    }
997014
public function handleRequest()
    {
        $request = $this->prepareRequest();
        $version = $request['version'];
        $queryConfiguration = $request['queryConfiguration'];

        $data = $this->provider->process();
        return $version->createResponse($data, $queryConfiguration, $this->columnConfigurations);
    }
814804
protected function handlePATCH()
    {
        if (!empty($this->resource)) {
            if ($this->request->getParameterAsBool(ApiOptions::REGENERATE)) {
                /** @var AppModel $appClass */
                $appClass = static::$model;
                $app = $appClass::find($this->resource)->first();
                $app->api_key = $appClass::generateApiKey($app->name);
                $app->save();
            }
        }

        return parent::handlePATCH();
    }
1037498
public function generic_exception_handler( $exception ) {
		// Paulus - Handle all of our "ApiException"s
		if ( $exception instanceOf ApiException ) {
			// Handle our ApiException interface exceptions from Paulus
			$this->api_exception_handler( $exception );
		}
		// All other exceptions
		else {
			// Log the error
			$this->error_log( $exception->getMessage() );

			// Let's handle the exception gracefully (RESTfully)
			$this->abort( 500, 'EXCEPTION_THROWN', $exception->getMessage() );
		}
	}
1710
protected function handleRequest()
    {
        $message = $this->getMessage();
        $response = $this->handleMessage($message);

        return [
            'to'       => $message['FromUserName'],
            'from'     => $message['ToUserName'],
            'response' => $response,
        ];
    }