Skip to content
Snippets Groups Projects
datasets.php 1.94 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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"]);
    
        $content = file_get_contents($file_path);
        echo $content;
    
    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 endsWith( $haystack, $needle ) {
        # Source: https://stackoverflow.com/a/834355/7376120
        $length = strlen( $needle );
        if( !$length ) {
            return true;
        }
        return substr( $haystack, -$length ) === $needle;
    }