Show a particular post

Note that this MAY be triggered directly from a request via 'viewpost' routing, so
don't rely on the $this->data() var to be filled

@return type
429529
public function show() {
		// cast with int here forces the rest of the text to be stripped
		$id = (int) $this->request->param('ID');

		if ($id) {
			$since = $this->request->getVar('since');
			if (!$since) {
				$since = $id - 1;
			} else {
				
			}
			
			$posts = $this->microBlogService->getStatusUpdates(null, array('ID' => 'ASC'), $since, false, false, array(), 0, 1);
			$post = $posts->first();
			
			if (!$post) {
				return Security::permissionFailure();
			}

			$options = $this->getOptions();
			//$options->Replies = true;
			$options->ShowTitlesOnly = false;
			
			$timeline = trim($this->customise(array('Post' => $id, 'ForceContent' => true, 'Posts' => $posts, 'Options' => $options))->renderWith('Timeline'));

			$data = array(
				'Timeline'		=> $timeline,
				'OwnerFeed'		=> $timeline,
				'Post'			=> $id,
			);

			$timeline = $this->customise($data)->renderWith('FullTimeline');
            
            if (Director::is_ajax()) {
				return $timeline;
			}
			
			return $this->customise(array('Title' => $post->Title, 'Content' => $timeline))->renderWith(array('TimelineController_show', 'Page'));
		}
	}
176587
private function _setView()
	{
		if (preg_match('/^[a-z0-9_-]+$/', $this->_requestVars[1])) {
			$this->_view = $this->_requestVars[1];
        } else {
        	$this->_view = $this->_requestVars[1] = self::DEFAULT_VIEW;
        }

        return $this;
	}
189602
public function showAction()
    {
        $id = (int) $this->params()->fromRoute('id', null);

        $service = $this->getService();
        $entity  = $service->getById($id);

        return new ViewModel(array(
            'entity'  => $entity,
            'options' => $this->getOptions(),
        ));
    }
395288
public function getDate()
    {
        global $wpdb;
        return $wpdb->get_var($wpdb->prepare('SELECT post_date FROM ' . $wpdb->prefix . 'posts WHERE ID = %d',
            $this->ID));
    }
665530
public function DispatchRequest () {
		/** @var \MvcCore\IRoute */
		$route = & $this->router->GetCurrentRoute();
		if ($route === NULL) return $this->DispatchException('No route for request', 404);
		list ($ctrlPc, $actionPc) = [$route->GetController(), $route->GetAction()];
		$actionName = $actionPc . 'Action';
		$viewClass = $this->viewClass;
		$viewScriptFullPath = $viewClass::GetViewScriptFullPath(
			$viewClass::GetScriptsDir(),
			$this->request->GetControllerName() . '/' . $this->request->GetActionName()
		);
		if ($ctrlPc == 'Controller') {
			$controllerName = $this->controllerClass;
		} else if ($this->controller !== NULL) {
			$controllerName = '\\'.get_class($this->controller);
		} else {
			// `App_Controllers_<$ctrlPc>`
			$controllerName = $this->CompleteControllerName($ctrlPc);
			if (!class_exists($controllerName)) {
				// if controller doesn't exists - check if at least view exists
				if (file_exists($viewScriptFullPath)) {
					// if view exists - change controller name to core controller, if not let it go to exception
					$controllerName = $this->controllerClass;
				} else {
					return $this->DispatchException("Controller class `$controllerName` doesn't exist.", 404);
				}
			}
		}
		return $this->DispatchControllerAction(
			$controllerName,
			$actionName,
			$viewScriptFullPath,
			function (\Exception & $e) {
				return $this->DispatchException($e);
			}
		);
	}
409964
public function getPostType()
    {
        $called_class_segments = explode('\\', get_called_class());
        $class_name = end($called_class_segments);
        return (is_null($this->post_type))
            ? Str::machine(Str::camelToHuman($class_name), Base::SEPARATOR)
            : $this->post_type;
    }
1324389
public function viewAction()
    {
        $id = $this->params()->fromQuery('id');
        $channel = $this->params()->fromRoute('channel', 'default');
        $response = $this->getResponse();
        /* @var \Jobs\Entity\Job $job */
        try {
            $job = $this->initializeJob()->get($this->params(), true);
        } catch (NotFoundException $e) {
            $response->setStatusCode(Response::STATUS_CODE_404);
            return [
                'message' => sprintf($this->translator->translate('Job with id "%s" not found'), $id)
            ];
        }
        
        $mvcEvent             = $this->getEvent();
        $applicationViewModel = $mvcEvent->getViewModel();

        /* @var \Auth\Entity\User $user */
        $user = $this->auth()->getUser();

        /* @var \Zend\View\Model\ViewModel $model */
        $model = $this->viewModelTemplateFilter->getModel($job);

        if (
            Status::ACTIVE == $job->getStatus() or
            Status::WAITING_FOR_APPROVAL == $job->getStatus() or
            $job->getPermissions()->isGranted($user, PermissionsInterface::PERMISSION_VIEW) or
            $this->auth()->isAdmin()
        ) {
            $applicationViewModel->setTemplate('iframe/iFrameInjection');
        } elseif (Status::EXPIRED == $job->getStatus() or  Status::INACTIVE == $job->getStatus()) {
            $response->setStatusCode(Response::STATUS_CODE_410);
            $model->setTemplate('jobs/error/expired');
            $model->setVariables(
                [
                    'job'=>$job,
                    'message', 'the job posting you were trying to open, was inactivated or has expired'
                ]
            );
        } else {
            // there is a special handling for 404 in ZF2
            $response->setStatusCode(Response::STATUS_CODE_404);
            $model->setVariable('message', 'job is not available');
        }
        return $model;
    }
216642
protected function getPostedData()
    {
        $resourcePostedDataMode = $this->getResource()->getPostedDataMethod();
        $endpointPostedDataMode = $this->getEndpoint()->getPostedDataMethod();

        $postedDataMode = $resourcePostedDataMode;
        if ($endpointPostedDataMode != PostedDataMethods::AUTO) {
            $postedDataMode = $endpointPostedDataMode;
        }

        $postedData = null;

        switch ($postedDataMode) {

            case PostedDataMethods::POST:
                $postedData = $this->request->getPost();
                break;

            case PostedDataMethods::JSON_BODY:
                $postedData = $this->request->getJsonRawBody(true);
                break;

            case PostedDataMethods::AUTO:
            default:
                $postedData = $this->request->getPostedData($this->getEndpoint()->getHttpMethod());
        }

        return $postedData;
    }
1096039
public function init(Request $request, $postType, $id)
    {
        // Lets validate if the post type exists and if so, continue.
		$postTypeModel = $this->getPostType($postType);
    	if(!$postTypeModel){
    		$errorMessages = 'You are not authorized to do this.';
    		return $this->abort($errorMessages);
		}

		if(method_exists($postTypeModel, 'override_show_post')){
			return $postTypeModel->override_show_post($id, $request, $postType);
		}

		$config = $this->getConfig($postTypeModel);

    	// Check if the post type has a identifier
    	if(empty($postTypeModel->identifier)){
    		$errorMessages = 'The post type does not have a identifier.';
    		if(array_has($postTypeModel->errorMessages, 'post_type_identifier_does_not_exist')){
    			$errorMessages = $postTypeModel->errorMessages['post_type_identifier_does_not_exist'];
    		}
    		return $this->abort($errorMessages, $config);
		}

		// Validate if we need to validate a other post type before showing this post type
		$validateBefore = $this->validatePostTypeBefore($request, $postTypeModel, $id);
		if($validateBefore['status'] === false){
			$errorMessages = $validateBefore['message'];
    		return $this->abort($errorMessages, $validateBefore['config'], 'post_validation_error');
		}

	    $post = $this->findPostInstance($postTypeModel, $request, $postType, $id, 'show_post');
		if(!$post){
			$errorMessages = 'Post does not exist.';
			if(array_has($postTypeModel->errorMessages, 'post_does_not_exist')){
				$errorMessages = $postTypeModel->errorMessages['post_does_not_exist'];
			}
			return $this->abort($errorMessages, $config);
		}

		// Converting the updated_at to the input picker in the front-end
        $updatedAtCustomField = $this->getCustomFieldObject($postTypeModel, 'updated_at');

        // If we have not set a custom date format, we will not touch this formatting
        if(!empty($updatedAtCustomField['date_format_php'])){
        	$post->created = $post->updated_at->format($updatedAtCustomField['date_format_php']);
        }

		// Converting the created_at to the input picker in the front-end
        $createdAtCustomField = $this->getCustomFieldObject($postTypeModel, 'created_at');

		// If we have not set a custom date format, we will not touch this formatting
		if(!empty($post->created_at)){
			if(!empty($createdAtCustomField['date_format_php'])){
				$post->created = $post->created_at->format($createdAtCustomField['date_format_php']);
			}
		}

		// Retrieve all the post meta's and taxonomies
		$postmeta = $this->retrieveConfigPostMetas($post, $postTypeModel);

        $postArray = $post->toArray();

        $postArraySanitized = [];

        if(array_has($postArray, 'id')){
        	$postArraySanitized['id'] = $postArray['id'];
		}

		if(array_has($postArray, 'post_title')){
        	$postArraySanitized['post_title'] = $postArray['post_title'];
		}

		if(array_has($postArray, 'post_name')){
        	$postArraySanitized['post_name'] = $postArray['post_name'];
		}

		if(array_has($postArray, 'status')){
        	$postArraySanitized['status'] = $postArray['status'];
		}

		if(array_has($postArray, 'post_type')){
        	$postArraySanitized['post_type'] = $postArray['post_type'];
		}

		if(array_has($postArray, 'created_at')){
        	$postArraySanitized['created_at'] = $postArray['created_at'];
		}

		if(array_has($postArray, 'updated_at')){
        	$postArraySanitized['updated_at'] = $postArray['updated_at'];
		}

		// Format the collection
        $collection = [
            'post' => $postArraySanitized,
            'postmeta' => $postmeta,
		];

        // Mergin the collection with the data and custom fields
        $collection['templates'] = $this->mergeCollectionWithView($postTypeModel->view, $collection, $postTypeModel);

		// Setting the config
		$collection['config'] = $config;

        // Lets check if there are any manipulators active
		$collection = $this->showMutator($postTypeModel, $collection, $request);

		if(method_exists($postTypeModel, 'on_show_mutator')){
			$collection = $postTypeModel->on_show_mutator($postTypeModel, $post->id, $postmeta, $collection);
		}

		// Lets check if there are any manipulators active
        $collection = $this->showConditional($postTypeModel, $collection);

        // Cleaning up the output
		unset($collection['postmeta']);

		if(method_exists($postTypeModel, 'on_show_check')){
			$onShowCheck = $postTypeModel->on_show_check($postTypeModel, $post->id, $postmeta);
			if($onShowCheck['continue'] === false){
				$errorMessages = 'You are not authorized to do this.';
				if(array_key_exists('message', $onShowCheck)){
					$errorMessages = $onShowCheck['message'];
				}
				return $this->abort($errorMessages, $config);
			}
		}

		// Lets fire events as registered in the post type
        $this->triggerEvent('on_show_event', $postTypeModel, $post->id, $postmeta);

        $collection['instance'] = [
			'post_type' => $postType,
			'post_identifier' => $id,
		];

        // Returning the full collection
    	return response()->json($collection);
	}
57023
private function register_post_type() {
		$post_type            = $this->get_post_type();
		$this->_post_type_obj = register_post_type( $post_type, $this->get_post_type_args() );
		if ( is_wp_error( $this->_post_type_obj ) ) {
			$this->app->log( $this->_post_type_obj );

			return;
		}
		add_filter( "views_edit-{$post_type}", function ( $views ) {
			unset( $views['mine'] );
			unset( $views['publish'] );

			return $views;
		} );
		add_filter( "bulk_actions-edit-{$post_type}", function ( $actions ) {
			unset( $actions['edit'] );

			return $actions;
		} );
		add_filter( "manage_edit-{$post_type}_sortable_columns", function ( $sortable_columns ) {
			return $this->manage_posts_columns( $sortable_columns, true );
		} );
	}
284073
public function getRequestInputByType()
    {
        $data = $this->instance->getRealMethod() == 'GET' ? HttpFoundation::createFromGlobals()->query :
            HttpFoundation::createFromGlobals()->request;

        if ($data) {
            foreach ($data->all() as $key => $value) {
                session()->createFlashMessage($key, $value);
            }

            session()->createFlashMessage('request', $data);
        }

        return $data;
    }
184611
public function removePostPostType()
    {
        global $wp_post_types;

        if (isset($wp_post_types['post'])) {
            if (function_exists('get_field') && get_field('disable_default_blog_post_type', 'option')) {
                add_action('admin_menu', function () {
                    remove_menu_page('edit.php');
                });

                add_action('wp_before_admin_bar_render', function () {
                    global $wp_admin_bar;
                    $wp_admin_bar->remove_menu('new-post');
                });
            }
        }

        if (isset($wp_post_types['page'])) {
            if (function_exists('get_field') && get_field('disable_default_page_post_type', 'option')) {
                add_action('admin_menu', function () {
                    remove_menu_page('edit.php?post_type=page');
                });

                add_action('wp_before_admin_bar_render', function () {
                    global $wp_admin_bar;
                    $wp_admin_bar->remove_menu('new-page');
                });
            }
        }

        return null;
    }
646183
public function pageAction()
    {
        $path = $this->params()->fromRoute('path');
        $page = $this->queryService->findPublishedPageByPath(trim($path, '/'));

        if ($page instanceof NullPage) {
            /** @var Response $response */
            $response = $this->getResponse();
            $response->setStatusCode(Response::STATUS_CODE_404);
            return null;
        }

        return new ViewModel(array('page' => $page));
    }
4665
public function viewWithPayload()
    {
        return function (string $view, PayloadContract $payload, string $key = 'payload') {
            return ResponseFactory::view($view, [$key => $payload->getUnwrappedOutput()], $payload->getStatus());
        };
    }
826634
private function makePayload()
    {
        $payload = [];
        switch ($this->type) {
            case self::TYPE_POSTBACK:
            case self::TYPE_CALL:
                $payload = ['payload' => $this->payload];
                break;
            case self::TYPE_WEB:
                $payload = ['url' => $this->payload];
                break;
            default:
                throw new UnknownTypeException;
        }

        return array_merge($payload, $this->extra);
    }
1018025
public function setPost(){

		//populate the post array
		$postArray = (isset($_POST)) ? $_POST : array();

		//set the postInputData
		$this->postInputData = $postArray;

		//add this to the inputData
		$this->inputData = $this->Merge($this->inputData, $this->postInputData);

		//set the postInputDataSet to true
		$this->postInputDataSet = true;

		//return this object instance
		return $this;

	}
627040
public function editAction()
    {
        $id = $this->params()->fromRoute('id');
        if (! is_numeric($id)) {
            $this->flashMessenger()->addMessage(
                $this->scTranslate('The category ID was not specified.')
            );
            return $this->redirect()
                ->toRoute('sc-admin/content-manager')
                ->setStatusCode(303);
        }

        try {
            $category = $this->getCategoryService()->getCategory($id);
        } catch (RuntimeException $e) {
            $this->flashMessenger()->addMessage($e->getMessage());
            return $this->redirect()
                ->toRoute('sc-admin/content-manager')
                ->setStatusCode(303);
        }
        $form = $this->getCategoryForm();
        $form->setAttribute(
            'action',
            $this->url()->fromRoute('sc-admin/category/edit', ['id' => $id])
        );
        $form->bind($category);

        if ($this->getRequest()->isPost()) {
            $form->setData($this->getRequest()->getPost());
            if ($form->isValid()) {
                $this->getCategoryService()->saveContent($form->getData());
            }
        }

        return new ViewModel([
            'content' => $category,
            'form' => $form,
        ]);
    }