<?php $EMPTY_SPACE = '{"links":[],"nodes":[]}'; $SPACES_DIR = __DIR__."/spaces/"; 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) { // Cleaning up the space id $space_id = str_replace("/", "-", $space_id); $space_id = str_replace("\\", "-", $space_id); $space_id = str_replace(".", "-", $space_id); global $SPACES_DIR; return $SPACES_DIR.$space_id.".json"; } function kg_get_list_of_spaces() { global $SPACES_DIR; $all_files = scandir($SPACES_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; } // Write empty space to file global $EMPTY_SPACE; file_put_contents($file_path, $EMPTY_SPACE); } function endsWith( $haystack, $needle ) { # Source: https://stackoverflow.com/a/834355/7376120 $length = strlen( $needle ); if( !$length ) { return true; } return substr( $haystack, -$length ) === $needle; }