<?php

$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

if (!($request = json_decode($_POST['serialized_post'], true))) {
    header("HTTP/1.0 400 Bad Request");
    $error_message = "Invalid serialized_post param passed.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

$page_type = "";
if (!empty($_GET['page_type'])) {
	$page_type = $_GET['page_type'];
}

$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']);
	if (empty($page->id)) {
		header("HTTP/1.0 409 Conflict");
		$error_message = "The page you attempted to save was not found.";
		ContentManagerPanel::addMessage($error_message);
		die($error_message);
	}
} else {
	header("HTTP/1.0 400 Bad Request");
	$error_message = "page_id missing from save request.";
	ContentManagerPanel::addMessage($error_message);
	die($error_message);
}

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

$content_manager = new ContentManager();
$response = $content_manager->processUpdateRequestPageUpdate($request, null, $page, $force);

//  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));
