<?php

/**
 * Script for executing a page version save in the context of the versioning functionality enabled in the cms
 * @author Rihards Siliņš
 * @copyright MTC media Ltd
 */

$cms_root_path = '../../../';
require_once $cms_root_path . 'includes/compatibility_includer.php';

if (!($posted_page = json_decode($_POST['serialized_page'], true))) {
    die('Invalid serialized_page param passed.');
}

$force = false;
if (!empty($_GET['force']) && $_SESSION['content_manager']['is_mtcadmin'] == true) {
    $force = $_GET['force'];
}

$page = new Page();
if (isset($_GET['page_id']) && is_numeric($_GET['page_id'])) {
    if (defined('CMS_MULTI_LANG') && CMS_MULTI_LANG === true && $page->type != 'temp') {
        if (empty($_SESSION['content_manager']['language'])) {
            $_SESSION['content_manager']['language'] = '';
        }
        $page->setLanguage($_SESSION['content_manager']['language']);
    }
    $page->Get($_GET['page_id']);
} else {
    die('Page not found.');
}

// Set author details
if (!empty($_SESSION['content_manager']['username'])) {
    $posted_page['author_name'] = $_SESSION['content_manager']['username'];
}
if (!empty($_SESSION['content_manager']['user_id'])) {
    $posted_page['author_id'] = $_SESSION['content_manager']['user_id'];
}

$content_manager = new ContentManager();
$response = $content_manager->savePageVersion($posted_page, null, $page, $force);

// Drop history pages that have reached there expiry
Page::dropHistoryPages($page->draft_for_page_id);
//  Drop variously corrupt cms pages.
Page::dropCorruptPages();

if ($response['response'] == 2) {
    // rebuild listing cache if relevant
    \Mtc\Cms\Handlers\ListingCacheHandler::triggerAsyncRefresh($page);
}
die(json_encode($response));
