<?php

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

if (
    empty($_REQUEST['page_id'])
    || !is_numeric($_REQUEST['page_id'])
    || $adminuser->user['id'] != MTCADMIN_USERID
    || !isset($_REQUEST['pagedataTree'])
) {
    exit('false');
}

// Replace insecure PHP serialization with JSON parsing and validation
$raw = $_REQUEST['pagedataTree'];
$new_pagedata = json_decode(is_string($raw) ? $raw : json_encode($raw), true);
if (!is_array($new_pagedata)) {
    exit('false');
}
// Basic shape validation and size guard (prevent abuse)
if (count($new_pagedata) > 10000) { // arbitrary upper bound to avoid abuse
    exit('false');
}

$pagedata = new Pagedata();
if (isset($_POST['merge_pagedata']) && $_POST['merge_pagedata'] === "1") {
    $pagedata->get($_REQUEST['page_id']); // retrieve existing
    $pagedata->merge($new_pagedata, false);
} else {
    $pagedata->page_id = $_REQUEST['page_id'];
    $pagedata->pagedata = $new_pagedata;
}
$pagedata->save();

echo 'true';
