<?php $EMPTY_SPACE_FILE = kg_get_space_file_path("default").".hidden"; add_action("wp_ajax_get_space", "kg_get_space"); // Fires only for logged-in-users add_action("wp_ajax_nopriv_get_space", 'kg_get_space' ); // Fires for everyone function kg_get_space() { $file_path = kg_get_space_file_path($_POST["space"]); // If it doesn't exist, create new empty space if (!file_exists($file_path)) { kg_create_empty_space($file_path); } $content = file_get_contents($file_path); echo $content; wp_die(); } add_action("wp_ajax_list_spaces", "kg_list_spaces"); // Fires only for logged-in-users function kg_list_spaces() { $spaces = kg_get_list_of_spaces(); $payload = array("spaces" => $spaces); echo json_encode($payload); wp_die(); } add_action("wp_ajax_update_space", "kg_update_space"); // Fires only for logged-in-users //add_action("wp_ajax_nopriv_update_space", 'update_space' ); // Fires for everyone function kg_update_space() { // Check user capabilities if (current_user_can("edit_posts")) { // Use json encoding. $graph = stripslashes($_POST["graph"]); kg_store_new_graph($graph, $_POST["space"]); wp_die(); } else { echo "Insufficient permissions!"; } } function kg_store_new_graph($graph, $space_id) { $file_path = kg_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 kg_get_space_file_path($space_id) { return __DIR__."/".$space_id.".json"; } function kg_get_list_of_spaces() { $all_files = scandir(__DIR__); if ($all_files == false) { return []; } $spaces = []; foreach ($all_files as $file) { if (endsWith($file, ".json")) { $spaces[] = substr($file, 0, -strlen(".json")); } } return $spaces; } function kg_create_empty_space($file_path) { // Don't do anything, if it exists if (file_exists($file_path)) { return; } // Read and copy default empty graph from default file global $EMPTY_SPACE_FILE; $empty_graph = file_get_contents($EMPTY_SPACE_FILE); file_put_contents($file_path, $empty_graph); } function endsWith( $haystack, $needle ) { # Source: https://stackoverflow.com/a/834355/7376120 $length = strlen( $needle ); if( !$length ) { return true; } return substr( $haystack, -$length ) === $needle; }