Execute the Request

@param array 	$action
@param array 	$params

@return self
186114
public function perform() 
	{	
		// set the input
		if ( !is_null( $this->input ) ) 
		{
			CCIn::instance( $this->input );
		} else {
			CCIn::instance( CCServer::instance() );
		}
		
		// set current request
		static::$_current =& $this;
		
		// route is invalid show 404
		if ( !$this->route instanceof CCRoute ) 
		{
			$this->route = CCRouter::resolve( '#404' );
		}
		
		/*
		 * call wake events
		 * if one event returns an response all other calls will be skipped also events!
		 */
		foreach( CCRouter::events_matching( 'wake', $this->route->uri ) as $callback )
		{
			if ( ( $return = CCContainer::call( $callback ) ) instanceof CCResponse )
			{
				$this->response = $return; return $this;
			}
		}
		
		/*
		 * a closure
		 */
		if ( !is_array( $this->route->callback ) && is_callable( $this->route->callback ) ) 
		{	
			// execute and capture the output
			ob_start();
			// run the closure 
			$return = call_user_func_array( $this->route->callback, $this->route->params );
			// catch the output
			$output = ob_get_clean();
			
			// do we got a response?
			if ( !$return instanceof CCResponse ) 
			{
				// if not create one with the captured output
				$return = CCResponse::create( $output );
			}
		}
		/*
		 * a callback
		 */
		elseif ( is_callable( $this->route->callback ) )
		{
			// execute the callback and get the return
			$return = call_user_func_array( $this->route->callback, array( $this->route->action, $this->route->params ) );
			
			// do we got a response?
			if ( !$return instanceof CCResponse ) 
			{
				// if not create one with the return as string
				$return = CCResponse::create( (string) $return );
			}
		}
		/*
		 * 404 error if nothing
		 */
		else 
		{
			$return = CCResponse::error( 404 );
		}
		
		// set the response
		$this->response = $return;
		
		/*
		 * call sleep events
		 * if one event returns an response all other calls will be skipped also events!
		 */
		foreach( CCRouter::events_matching( 'sleep', $this->route->uri ) as $callback )
		{
			if ( $return = CCContainer::call( $callback, $this->response ) instanceof CCResponse )
			{
				$this->response = $return; return $this;
			}
		}
		
		return $this;
	}
1269579
def call(action, params={}, headers={}, options={})
      @api.call(@name, action, params, headers, options)
    end
1018739
function _doRequest($action,$params,$options){
		$params += array(
			"lang" => $this->lang,
		);
		$params += $this->default_params;

		$options += array(
			"cache" => 0,
			"return_cached_content_on_error" => false,
			"acceptable_error_codes" => array(),
			"file" => array(), // see postFile(),
			"raw_post_data" => null,
			"additional_headers" => array() // array("X-Forwarded-For: 127.0.0.1","X-Logged-User-Id: 123")
		);

		$this->errors = array();
		$this->data = null;

		$timer = new StopWatch();
		$timer->start();

		$lang = $params["lang"];
		unset($params["lang"]);

		$url = $this->base_url;
		if($lang){
			if($this->automatically_add_leading_slash && !preg_match('/\/$/',$url)){
				$url .= "/";
			}
			$url .= "$lang/";
		}
		if($this->automatically_add_leading_slash && !preg_match('/\/$/',$url)){
			$url .= "/";
		}
		$url .= "$action";
		if($this->automatically_add_trailing_slash && !preg_match('/\/$/',$url) && !preg_match('/\?/',$url)){
			$url .= "/";
		}

		$action_url = $url;

		if($options["method"]!="POST" || $options["file"] || !is_null($options["raw_post_data"])){
			$url = $this->_addParamsToUrl($url,$params);
		}
		$this->url = $url;
		$this->method = $options["method"];
		$this->duration = null;

		$cached_ar = null;
		if($options["cache"]>0 && ($ar = $this->_readCache($url,$options["cache"],$cached_ar))){
			return $this->__setCacheAndReturnData($ar);
		}

		// Pro stahovani dat se pouziva UrlFetcher - soucast ATK14
		$headers = $this->additional_headers;
		//if($options["file"]){
		//	$headers["X-FileName"] = $options["name"];
		//}
		$u = new UrlFetcher($url,array(
			"user_agent" => $this->user_agent,
			"additional_headers" => $headers
		));

		if(!is_null($options["raw_post_data"])){
			$u->post($options["raw_post_data"],array(
				"content_type" => $options["mime_type"],
				"additional_headers" => $options["additional_headers"],
			));

		}elseif($options["file"]){
			$content = Files::GetFileContent($options["file"]["path"]);
			$u->post($content,array(
				"content_type" => $options["file"]["mime_type"],
				"additional_headers" => array(
					sprintf('Content-Type: %s',$options["file"]["mime_type"]),
					sprintf('Content-Disposition: attachment; filename="%s"',rawurlencode($options["file"]["name"]))
				)
			));

		}elseif($options["method"]=="POST"){
			// Content-Type: application/x-www-form-urlencoded
			// Content-Length: 244

			$u->post($params);
		}else{
			$u->fetchContent(array(
				"request_method" => $options["method"],
			));
		}
		$this->status_code = $u->getStatusCode();

		$timer->stop();

		$this->duration = $timer->getResult();

		$this->status_code = $u->getStatusCode();

		// TODO: vyresit zalogovani parametru POSTem

		$content = $u->getContent();
		if(!strlen($content) && ($this->status_code!=204)){
			if($options["return_cached_content_on_error"] && $cached_ar){
				return $this->__useOutdatedCache($cached_ar);
			}
			throw new Exception("No content on $url (HTTP $this->status_code)");
		}

		if(strlen($content)>0){

			$d = json_decode($content,true);
			if(is_null($d)){
				trigger_error("ApiDataFetcher:
URL: $url
response code: ".$u->getStatusCode()."
invalid json:\n".$u->getContent()
				);
				if($options["return_cached_content_on_error"] && $cached_ar){
					return $this->__useOutdatedCache($cached_ar);
				}
				throw new Exception("json_decode() failed on $url (HTTP status code: $this->status_code; content: ".$u->getContent().")");
			}

		}else{

			// The $content is empty (HTTP status code is 204).
			// Empty answer means empty JSON.
			$d = array();

		}

		ApiDataFetcher::$QueriesExecuted[] = array(
			"action" => $action,
			"action_url" => $action_url,
			"method" => $options["method"],
			"url" => $url,
			"status_code" => $this->status_code,
			"status_message" => $u->getStatusMessage(),
			"params" => $params,
			"duration" => $timer->getResult(),
			"data" => $d,
		);

		if(preg_match('/^2/',$this->status_code)){
			$this->data = $d;
			$valid_response = true;
		}else{
			$this->errors = $d;
			$valid_response = false;
		}

		if(!$valid_response && !in_array($this->status_code,$options["acceptable_error_codes"])){
			$this->_loggerLog(
				"ApiDataFetcher: $options[method] $url (HTTP $this->status_code, $timer)\n".
				($options["method"] == "POST" ? "params: ".print_r($params,true)."\n" : "").
				"error: ".join(" | ",$this->errors)."\n".
				"requested URL: ".$this->request->getUrl()
			);
			$this->_loggerFlush();
			if($options["return_cached_content_on_error"] && $cached_ar){
				return $this->__useOutdatedCache($cached_ar);
			}
			throw new Exception("HTTP status code $this->status_code (".join(" | ",$this->errors)."), url: $url");
		}else{
			$this->_loggerDebug(
				"ApiDataFetcher: $options[method] $url (HTTP $this->status_code, $timer)".
				($options["method"] == "POST" ? "\nparams: ".print_r($params,true)."\n" : "")
			);
			if($options["cache"]>0){
				$this->_writeCache($url,$this->status_code,$this->data,$this->errors);
			}
		}

		return $this->data;
	}
926909
public function execute($action) {
        admin_externalpage_setup('tool_usertours/tours');
        // Add the main content.
        switch($action) {
            case self::ACTION_NEWTOUR:
            case self::ACTION_EDITTOUR:
                $this->edit_tour(optional_param('id', null, PARAM_INT));
                break;

            case self::ACTION_MOVETOUR:
                $this->move_tour(required_param('id', PARAM_INT));
                break;

            case self::ACTION_EXPORTTOUR:
                $this->export_tour(required_param('id', PARAM_INT));
                break;

            case self::ACTION_IMPORTTOUR:
                $this->import_tour();
                break;

            case self::ACTION_VIEWTOUR:
                $this->view_tour(required_param('id', PARAM_INT));
                break;

            case self::ACTION_HIDETOUR:
                $this->hide_tour(required_param('id', PARAM_INT));
                break;

            case self::ACTION_SHOWTOUR:
                $this->show_tour(required_param('id', PARAM_INT));
                break;

            case self::ACTION_DELETETOUR:
                $this->delete_tour(required_param('id', PARAM_INT));
                break;

            case self::ACTION_RESETFORALL:
                $this->reset_tour_for_all(required_param('id', PARAM_INT));
                break;

            case self::ACTION_NEWSTEP:
            case self::ACTION_EDITSTEP:
                $this->edit_step(optional_param('id', null, PARAM_INT));
                break;

            case self::ACTION_MOVESTEP:
                $this->move_step(required_param('id', PARAM_INT));
                break;

            case self::ACTION_DELETESTEP:
                $this->delete_step(required_param('id', PARAM_INT));
                break;

            case self::ACTION_LISTTOURS:
            default:
                $this->print_tour_list();
                break;
        }
    }
831831
public function call($entity, $action, $params = array()) {
    $this->log->debug("Send API call: {entity}.{action} over {cxnId}", array(
      'entity' => $entity,
      'action' => $action,
      'cxnId' => $this->cxnId,
    ));
    $cxn = $this->cxnStore->getByCxnId($this->cxnId);
    $req = new StdMessage($cxn['cxnId'], $cxn['secret'],
      array($entity, $action, $params, $this->appMeta['appCert']));

    $http = empty($cxn['viaPort']) ? $this->http : new ViaPortHttp($this->http, $cxn['viaPort']);

    list($respHeaders, $respCiphertext, $respCode) = $http->send('POST', $cxn['siteUrl'], $req->encode(), array(
      'Content-type' => Constants::MIME_TYPE,
    ));
    $respMessage = $this->decode(array(StdMessage::NAME, GarbledMessage::NAME), $respCiphertext);
    if ($respMessage instanceof GarbledMessage) {
      throw new GarbledMessageException($respMessage);
    }
    elseif ($respMessage instanceof StdMessage) {
      if ($respMessage->getCxnId() != $cxn['cxnId']) {
        // Tsk, tsk, Mallory!
        throw new InvalidMessageException('Received response from incorrect connection.');
      }
      return $respMessage->getData();
    }
    else {
      throw new InvalidMessageException('Unrecognized message type.');
    }
  }
876947
public function handleAction($action, $actionParams)
    {
        $response = new b8\Http\Response\JsonResponse();
        try {
            $data = parent::handleAction($action, $actionParams);
            if (isset($data['responseCode'])) {
                $response->setResponseCode($data['responseCode']);
                unset($data['responseCode']);
            }
            $response->setContent($data);
        } catch (Exception $ex) {
            $response->setResponseCode(500);
            $response->setContent(array('status' => 'failed', 'error' => $ex->getMessage()));
        }
        return $response;
    }
1195737
protected function perform($action)
    {
        $this->plugin->io->writeError('running ' . $this->getBin());
        if ($this->passthru([$action])) {
            $this->plugin->io->writeError('<error>failed ' . $this->name . ' ' . $action . '</error>');
        }
    }
1259415
public function execute($action, array $payload)
    {
        $executor = $this->getExecutor($action);

        // dispatch pre event, listeners may change the payload here
        $event = new ExecutionEvent($executor, $action, $payload);
        $this->dispatcher->dispatch(WorkerEvents::PRE_EXECUTE_ACTION, $event);

        try {
            $resolver = $this->getPayloadResolver($executor);
            $payload  = $resolver->resolve($event->getPayload());
        } catch (ExceptionInterface $exception) {
            $this->logger->error(
                sprintf(
                    'Payload %s for "%s" is invalid: %s',
                    json_encode($payload, JSON_UNESCAPED_SLASHES),
                    $action,
                    $exception->getMessage()
                )
            );

            return false;
        }

        $result = $executor->execute($payload);
        // dispatch post event, listeners may change the result here
        $event->setResult($result);
        $this->dispatcher->dispatch(WorkerEvents::POST_EXECUTE_ACTION, $event);

        return $event->getResult();
    }
1088544
public function doAction( $action, $params = array() )
    {
        if ( isset( $this->actions[ $action ] ) )
        {
            foreach( $this->actions[ $action ] as $callback )
            {
                call_user_func_array( $callback[ 'callback' ], $params );

                if ( $this->debug )
                {
                    echo PHP_EOL . '->ACTION: ' . $action . ' -> '
                            . $this->_serializeCallback( $callback[ 'callback' ] )
                            . ' + Priority: ' . $callback[ 'priority' ]
                            . PHP_EOL;
                }
            }
        }
    }
964556
protected function performRequest(array $params)
    {
        $this->setRawResponse($this->rawResponse);
        $response = explode("\n", $this->rawResponse);

        return $response;
    }
168059
public function invokeAction($controller, $action, $params)
    {
        $actionMethod = $action . 'Action';

        if (!method_exists($controller, $actionMethod)) {
            throw new NotFoundActionException([
                '`:controller:::action` method does not exist',
                'action' => $actionMethod,
                'controller' => get_class($controller)
            ]);
        }

        $this->eventsManager->fireEvent('request:authorize', $this);

        $this->eventsManager->fireEvent('request:validate', $this, ['controller' => get_class($controller), 'action' => $action]);

        $this->eventsManager->fireEvent('request:ready', $this);

        $this->eventsManager->fireEvent('request:invoke', $this, $action);

        $args = $this->_buildActionArgs($controller, $action, $params);

        switch (count($args)) {
            case 0:
                $r = $controller->$actionMethod();
                break;
            case 1:
                $r = $controller->$actionMethod($args[0]);
                break;
            case 2:
                $r = $controller->$actionMethod($args[0], $args[1]);
                break;
            case 3:
                $r = $controller->$actionMethod($args[0], $args[1], $args[2]);
                break;
            default:
                $r = call_user_func_array([$controller, $actionMethod], $args);
                break;
        }

        $this->eventsManager->fireEvent('request:invoked', $this, ['action' => $action, 'return' => $r]);

        return $r;
    }
146695
public function handleController(
        $controller, $action = null, array $params = null, $model = null
    ) {

        ! $model || $model = $this->modelFactory->create(null, $model);

        $this->setController(
            $this->controllerFactory->create($params, $controller, $model)
        );

        if (!is_null($action)) {
            $this->setControllerResult(
                $this->executeMethod($this->getController(), $action, $params, $model)
            );
        }
    }
936285
protected function executeCliAction(Config\Action $action) : void
    {
        // since the cli has no straight way to communicate back to php
        // cli hooks have to handle sync stuff by them self
        // so no 'beforeAction' or 'afterAction' is called here
        $runner = new Action\Cli();
        $runner->execute($this->io, $action, $this->arguments);
    }
1151066
public function execute($params = [])
    {
        return $this->getDb()
            ->createCommand()
            ->setText($this->buildSql())
            ->execute(array_merge($this->getParams(), $params));
    }
836017
public function url($action, $params=[]) {
		if(is_array($action))
			return $this->resolver->url($action, $params);
		else
			return $this->resolver->url([get_called_class(), $action], $params);
	}
696452
protected function resolve($action, $params)
    {
        if ($action instanceof Closure) {

            return $action($params);
        }

        list($controller, $method) = $action;

        $reflect = new ReflectionClass($controller);

        foreach (array_filter($reflect->getMethod($method)->getParameters(), $this->getParams()) as $param) {
            array_unshift($params, $this->registry->make(
                $param->getClass()->getName()
            ));
        }

        return $reflect->getMethod($method)->invokeArgs(
            $this->registry->make($controller),
            $params
        );
    }
323382
protected function soap(string $service, string $action, array $params = [])
    {
        $params["ObjectID"] = $this->id;

        if ($action === "Browse") {
            $params["Filter"] = "";
            $params["SortCriteria"] = "";
        }

        return $this->controller->soap($service, $action, $params);
    }