Handles POST action

@return \DreamFactory\Core\Contracts\ServiceResponseInterface|\DreamFactory\Core\Utility\ServiceResponse|mixed
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception
423282
protected function handlePOST()
    {
        $uploadedFiles = $this->request->getFile('file');
        $importUrl = $this->request->getPayloadData('import_url');
        $storageServiceId = $this->request->input('storage_service_id');
        $storageContainer = $this->request->input('storage_container');

        if (!empty($uploadedFiles)) {
            $package = new Packager($uploadedFiles);
            $results = $package->importAppFromPackage($storageServiceId, $storageContainer);
        } elseif (!empty($importUrl)) {
            $package = new Packager($importUrl);
            $results = $package->importAppFromPackage($storageServiceId, $storageContainer);
        } else {
            $results = parent::handlePOST();
        }

        return $results;
    }
1012639
public function handleRequest()
    {
        try {
            $server = $this->environment->getRequestHelper()->getServerParams();
            $serviceName = preg_replace('/^(.*?)(\?.*)?$/', '$1', $this->getURI($server));
            $className = $this->findServiceClassName($this->services, $serviceName);
            $method = $this->getMethod($server);
            $this->handleAllowedOrigins();

            if ($method != 'options') {
                $this->callService($className, $serviceName, $method);
            }
        } catch (InvalidParameterException $e) {
            $msg = $e->getMessage() ?: "Missing parameter";
            $this->environment->sendResult('400 Bad Request', 'text/plain; charset=utf-8', $msg);
        } catch (DenyException $e) {
            $this->environment->sendResult('403 Forbidden', "text/plain; charset=utf-8", $e->getMessage());
        } catch (\Exception $e) {
            $this->environment->sendResult('500 Server error', "text/plain; charset=utf-8", $e->getMessage());
        }
    }
1260714
public function processUpdateAction()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, Team::getModuleCode(),
                AccessManager::UPDATE)
        ) {
            return $response;
        }

        // Error (Default: false)
        $error_msg = false;

        // Create the Form from the request
        $changeForm = $this->getUpdateForm($this->getRequest());


        $con = Propel::getConnection();
        $con->beginTransaction();

        try {
            // Check the form against constraints violations
            $form = $this->validateForm($changeForm, "POST");

            // Get the form field values
            $data = $form->getData();

            $updatedObject = $this->getService()->updateFromArray($data, $this->getCurrentEditionLocale());

            // Check if object exist
            if (!$updatedObject) {
                throw new \LogicException(
                    $this->getTranslator()->trans("No %obj was updated.", ['%obj' => static::CONTROLLER_ENTITY_NAME])
                );
            }

            $con->commit();
            // If we have to stay on the same page, do not redirect to the successUrl,
            // just redirect to the edit page again.
            if ($this->getRequest()->get('save_mode') == 'stay') {
                return $this->redirectToEditionTemplate($this->getRequest());
            }

            // Redirect to the success URL
            return $this->generateSuccessRedirect($changeForm);

        } catch (FormValidationException $ex) {
            $con->rollBack();
            // Form cannot be validated
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
        } catch (\Exception $ex) {
            $con->rollBack();
            // Any other error
            $error_msg = $ex->getMessage();
        }

        if (false !== $error_msg) {
            // At this point, the form has errors, and should be redisplayed.
            $this->setupFormErrorContext(
                $this->getTranslator()->trans("%obj modification", ['%obj' => static::CONTROLLER_ENTITY_NAME]),
                $error_msg,
                $changeForm,
                $ex
            );

            return $this->getEditRenderTemplate();
        }
    }
665532
public function resourceAction()
    {
        // Handle a request for an OAuth2.0 Access Token and send the response to the client
        if (!$this->server->verifyResourceRequest($this->getOAuth2Request())) {
            $response   = $this->server->getResponse();
            $parameters = $response->getParameters();
            $errorUri   = isset($parameters['error_uri']) ? $parameters['error_uri'] : null;
            return new ApiProblemResponse(
                new ApiProblem(
                    $response->getStatusCode(),
                    $parameters['error_description'],
                    $errorUri,
                    $parameters['error']
                )
            );
        }
        $httpResponse = $this->getResponse();
        $httpResponse->setStatusCode(200);
        $httpResponse->getHeaders()->addHeaders(array('Content-type' => 'application/json'));
        $httpResponse->setContent(
            json_encode(array('success' => true, 'message' => 'You accessed my APIs!'))
        );
        return $httpResponse;
    }
1185653
protected function _post()
    {
        $subject = $this->_subject([
            'entity' => $this->_entity($this->_request()->getData(), $this->saveOptions()),
            'saveMethod' => $this->saveMethod(),
            'saveOptions' => $this->saveOptions()
        ]);

        $event = $this->_trigger('beforeSave', $subject);
        if ($event->isStopped()) {
            return $this->_stopped($subject);
        }

        $saveCallback = [$this->_table(), $subject->saveMethod];
        if (call_user_func($saveCallback, $subject->entity, $subject->saveOptions)) {
            return $this->_success($subject);
        }

        $this->_error($subject);
    }
274071
public function handler(): Response
    {
        $response = [];
        foreach (Role::all(['createdAt' => 'ASC']) as $role) {
            $response[] = [
                'id' => $role->getId(),
                'name' => $role->getName(),
                'slug' => $role->getSlug(),
                'color' => $role->getColor(),
                'icon' => $role->getIcon()
            ];
        }
        return response($response);
    }
1367175
protected function handlePOST()
    {
        $payload = $this->getPayloadData();
        $login = $this->request->getParameterAsBool('login');
        $registrar = new Registrar();

        $password = array_get($payload, 'new_password', array_get($payload, 'password'));
        $data = [
            'username'              => array_get($payload, 'username'),
            'first_name'            => array_get($payload, 'first_name'),
            'last_name'             => array_get($payload, 'last_name'),
            'name'                  => array_get($payload, 'name'),
            'email'                 => array_get($payload, 'email'),
            'phone'                 => array_get($payload, 'phone'),
            'security_question'     => array_get($payload, 'security_question'),
            'security_answer'       => array_get($payload, 'security_answer'),
            'password'              => $password,
            'password_confirmation' => array_get($payload, 'password_confirmation', $password)
        ];

        if (empty($data['first_name'])) {
            /** @noinspection PhpUnusedLocalVariableInspection */
            list($username, $domain) = explode('@', $data['email']);
            $data['first_name'] = $username;
        }
        if (empty($data['last_name'])) {
            $names = explode('.', $data['first_name']);
            if (isset($names[1])) {
                $data['last_name'] = $names[1];
                $data['first_name'] = $names[0];
            } else {
                $data['last_name'] = $names[0];
            }
        }
        if (empty($data['name'])) {
            $data['name'] = $data['first_name'] . ' ' . $data['last_name'];
        }

        $data = array_filter($data, function ($value) {
            return !is_null($value);
        });

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = $registrar->validator($data);

        if ($validator->fails()) {
            $messages = $validator->errors()->getMessages();

            throw new BadRequestException('Validation failed', null, null, $messages);
        } else {
            $user = $registrar->create($data, $this->getServiceId());

            if ($login) {
                if ($user->confirm_code !== 'y' && !is_null($user->confirm_code)) {
                    return ['success' => true, 'confirmation_required' => true];
                } else {
                    $appId = Session::get('app.id');
                    Session::setUserInfoWithJWT($user, false, $appId);

                    return ['success' => true, 'session_token' => Session::getSessionToken()];
                }
            } else {
                return ['success' => true];
            }
        }
    }
500975
public function handler(): Response
    {
        $mailer = new Mailer([
            'driver' => 'smtp',
            'host' => 'host',
            'port' => 0,
            'encryption' => '',
            'username' => 'username',
            'password' => 'password',
            'sender' => 'sender',
            'remark' => ''
        ]);
        if (Mailer::count() === 0) {
            $mailer->default(true);
        }
        $mailer->save();
        $this->log('info', 'Create a mailer [' . $mailer->getSender() . ']');
        return response([
            'id' => $mailer->getId()
        ]);
    }
1228634
public function httpPostForHtml()
    {
        $id = $this->getRequest()->getParameter('id');
        $operation = $this->getRequest()->getParameter('operation');

        $response = null;
        switch ($operation) {
            case 'remove_selected':
                $response = $this->httpPostDeleteForHtml();
                break;
            case 'store':
            case 'save':
                $response = $this->getUpdatedEntityResponse();
                break;
            default:
                throw new BadRequestException(
                    "Operation '{$operation}' not recognised."
                );
        }

        return $response;
    }
962782
protected function makeRequest()
    {
        $requestType = trim(strtolower($this->getService('type')));
        if($this->getService('endpoint'))
            $this->requestUrl->appendPathSegment($this->getEndpoint());
        if($requestType != 'post' && $this->getParam())
            $this->requestUrl->setQueryFromArray($this->getParam());
        $this->requestUrl->setQueryParameter('key',$this->getApiKey());
        switch ($requestType){
            case 'POST':
                $postData = json_encode($this->getParam());
                break;
            case 'GET':
            default:
                break;
        }
        $request        = StreamClient::make()->{$requestType}($this->requestUrl->write());
        $responseBody   = $this->unserializeResponse($request->getBody());
        $responseStatus = $request->getStatusCode();
        switch($responseStatus){
            case 200:
                if($responseBody['status'] != self::STATUS_SUCCESS)
                    throw new \ErrorException($responseBody['status'].':'.$responseBody['error_message']);
                break;
            default:
                throw new \ErrorException($responseStatus.' '.$request->getReasonPhrase().':'.$responseBody['error_message']);
        }
        $checkClass = __NAMESPACE__."\Services\\".ucfirst($this->service);
        $this->responseBody = (Arr::has($responseBody,$this->getService(self::$responseKey))) ? Arr::get($responseBody,$this->getService(self::$responseKey)) : $responseBody;
        return (class_exists($checkClass)) ? new $checkClass($this) : $responseBody;
    }
283757
protected function getResponse(){

        $post = false;

        // use output parameter if required by the service
        $this->requestUrl.= $this->service['endpoint']
                            ? $this->endpoint
                            : '';

        // set API Key
        $this->requestUrl.= 'key='.urlencode( $this->key );


        switch( $this->service['type'] ){

            case 'POST':

                    $post =  json_encode( $this->service['param'] );

                break;


            case 'GET':
            default:
                    $this->requestUrl.='&'. Parameters::getQueryString( $this->service['param'] );
                break;
        }


        return $this->make( $post );

    }
844508
public function handler(): Response
    {
        $response = [];
        foreach (Bulletin::all() as $bulletin) {
            $response[] = [
                'id' => $bulletin->getId(),
                'createdAt' => $bulletin->getCreatedAt()->getTimestamp(),
                'title' => $bulletin->getTitle(),
                'abstract' => $bulletin->getAbstract(),
                'isDraft' => $bulletin->isDraft(),
                'statistics' => $bulletin->getStatistics()
            ];
        }
        return response($response);
    }
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;
    }
784777
public function handler(): Response
    {
        $member = $this->getAuth();
        return response([
            'id' => $member->getId(),
            'username' => $member->getUsername(),
            'role' => [
                'id' => $member->getRole()->getId(),
                'name' => $member->getRole()->getName()
            ],
            'name' => $member->getName()
        ]);
    }
653743
public function handler(): Response
    {
        $bulletin = Bulletin::find($this->getParameter('id'));
        if (!$bulletin) {
            throw new HttpNotFoundException();
        }
        if (!$bulletin->isDraft()) {
            throw new HttpForbiddenException();
        }
        $data = $this->validate([
            'title' => [
                new NotBlank()
            ],
            'content' => [
                new NotBlank()
            ],
            'receivers' => []
        ]);
        $bulletin->update($data);
        $this->log('info', 'Update bulletin [' . $bulletin->getId() . ']');
        return response();
    }
753210
public function handler(): Response
    {
        $member = $this->getAuth();
        if ($member) {
            $this->log('info', 'Logout');
        }
        $this->auth(null);
        return response();
    }
709450
public function handler(): Response
    {
        $response = [];
        $roles = [];
        $role_slugs = $this->request->get('roles', '');
        if (!$role_slugs) {
            $members = Member::all(['createdAt' => 'ASC']);
        } else {
            foreach (explode(',', $role_slugs) as $role_slug) {
                $roles[] = Role::findBy(['slug' => $role_slug]);
            }
            $members = Member::where(['role' => $roles], ['createdAt' => 'ASC']);
        }
        foreach ($members as $member) {
            $r = $member->getRole();
            $response[] = [
                'id' => $member->getId(),
                'username' => $member->getUsername(),
                'email' => $member->getEmail(),
                'phone' => $member->getPhone(),
                'name' => $member->getName(),
                'gender' => $member->getGender(),
                'role' => [
                    'slug' => $r->getSlug(),
                    'name' => $r->getName(),
                    'color' => $r->getColor(),
                    'icon' => $r->getIcon()
                ]
            ];
        }
        return response($response);
    }