<?php

add_action("wp_ajax_get_space", "get_space"); // Fires only for logged-in-users
add_action("wp_ajax_nopriv_get_space", 'get_space' ); // Fires for everyone
function get_space() {
    $file_path = get_space_file_path($_POST["space"]);
    $content = file_get_contents($file_path);
    echo $content;

    wp_die();
}

add_action("wp_ajax_update_space", "update_space"); // Fires only for logged-in-users
//add_action("wp_ajax_nopriv_update_space", 'update_space' ); // Fires for everyone
function update_space() {
    // Check user capabilities
    if (current_user_can("edit_posts")) {
        // Use json encoding.
        $graph = stripslashes($_POST["graph"]);

        store_new_graph($graph, $_POST["space"]);

        wp_die();
    } else {
        echo "Insufficient permissions!";
    }
}

function store_new_graph($graph, $space_id) {
    $file_path = get_space_file_path($space_id);
    $result = file_put_contents($file_path, $graph);

    //echo print_r($_POST);
    echo "Saved file at ";
    echo $file_path;
    echo " ";
    echo $result;
}

function get_space_file_path($space_id) {
    return __DIR__."/".$space_id.".json";
}