/** * Cleans up the expired tokens after writing */ protected function onAfterWrite() { parent::onAfterWrite(); //Clean up the expired tokens $expiredTokens = KapostPreviewToken::get()->filter('Created:LessThan', date('Y-m-d H:i:s', strtotime('-' . KapostService::config()->preview_token_expiry . ' minutes'))); if ($expiredTokens->count() > 0) { foreach ($expiredTokens as $token) { $token->delete(); } } }
/** * Handles rendering of the preview * @param {mixed} $blog_id Identifier for the current site * @param {array} $content Post details * @param {mixed} $content_id Identifier for the post */ protected function getPreview($blog_id, $content, $content_id) { $results = $this->extend('getPreview', $blog_id, $content, $content_id); if ($results && is_array($results)) { $results = array_filter($results, function ($v) { return !is_null($v); }); if (count($results) > 0) { return array_shift($results); } } //Detect if the record already exists or not so we can decide whether to create a new record or edit an existing $existing = KapostObject::get()->filter('KapostRefID', Convert::raw2sql($content_id))->first(); if (!empty($existing) && $existing !== false && $existing->exists()) { $resultID = $content_id; $this->editPost($content_id, $content, false, true); } else { $resultID = $this->newPost($blog_id, $content, false, true); //Make sure we got the kapost hash back or an id if we got an object back we assume that it's a response if (is_object($resultID)) { return $resultID; } //Find the object $existing = KapostObject::get()->filter('KapostRefID', Convert::raw2sql($resultID))->first(); } //Make sure we got the kapost hash back or an id if we got an object back we assume that it's a response if (is_object($resultID)) { return $resultID; } //Generate a preview token record $token = new KapostPreviewToken(); $token->Code = sha1(uniqid(time() . $resultID)); $token->KapostRefID = $resultID; $token->write(); //Return the details to kapost return array('url' => Controller::join_links(Director::absoluteBaseURL(), 'kapost-service/preview', $resultID, '?auth=' . $token->Code), 'id' => $resultID); }