From fd2881ba51e53be63f7624cc48e32c4cdfaed14a Mon Sep 17 00:00:00 2001
From: Max <m.giller.dev@gmail.com>
Date: Fri, 15 Oct 2021 12:46:57 +0200
Subject: [PATCH] Implemented proper authorized save option for editor

---
 datasets/datasets.js  | 44 ++++++++++++++++++++-------------------
 datasets/datasets.php | 48 +++++++++++++++++++++++++------------------
 editor/js/graph.js    | 26 -----------------------
 knowledge-space.php   | 23 ++-------------------
 4 files changed, 53 insertions(+), 88 deletions(-)

diff --git a/datasets/datasets.js b/datasets/datasets.js
index b2bbde0..3b14ee3 100644
--- a/datasets/datasets.js
+++ b/datasets/datasets.js
@@ -1,17 +1,26 @@
 import { PLUGIN_PATH } from "../config";
-
-export const DATASETS_URL = PLUGIN_PATH + "datasets/datasets.php";
+import jQuery from "jquery";
 
 /**
  * Returns the json object from the stored graph as promise.
  *
  * @param {String} spaceId Identification of graph to load.
- * 
+ *
  * @returns Promise returning graph object
  */
 export function loadGraphJson(spaceId) {
-    return fetch(DATASETS_URL + "?space_id=" + spaceId)
-        .then((r) => r.json());
+    let payload = {
+        action: "get_space",
+        space: spaceId,
+    };
+
+    return jQuery
+        .ajax({
+            type: "POST",
+            url: ajax_object.ajax_url,
+            data: payload,
+        })
+        .then((data) => JSON.parse(data));
 }
 
 /**
@@ -21,23 +30,16 @@ export function loadGraphJson(spaceId) {
  * @param {object} json Graph object
  */
 export function saveGraphJson(spaceId, json) {
-    var payload = {
-        space_id: spaceId,
+    let payload = {
+        action: "update_space",
         graph: JSON.stringify(json),
+        space: spaceId,
     };
 
-    var auth = getAuthPayload();
-    if (auth === undefined) {
-        return undefined;
-    }
-
-    return fetch(DATASETS_URL, {
-        method: "POST",
-        body: JSON.stringify(Object.assign(payload, auth)),
-    });
-}
-
-function getAuthPayload() {
-    //! TODO: Implement auth
-    return {};
+    return jQuery
+        .ajax({
+            type: "POST",
+            url: ajax_object.ajax_url,
+            data: payload,
+        });
 }
diff --git a/datasets/datasets.php b/datasets/datasets.php
index cc93dc3..d147b0d 100644
--- a/datasets/datasets.php
+++ b/datasets/datasets.php
@@ -1,34 +1,42 @@
 <?php
 
-function handle_request()
-{
-    if ($_SERVER["REQUEST_METHOD"] == "GET") {
-        handle_get($_GET);
-    } else if ($_SERVER["REQUEST_METHOD"] == "POST") {
-        handle_post(get_post_data());
-    }
-}
+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;
 
-function get_post_data()
-{
-    return json_decode(file_get_contents('php://input'), true);
+    wp_die();
 }
 
-function handle_get($request_data) {
-    $file_path = get_space_file_path($request_data["space_id"]);
+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"]);
 
-    $content = file_get_contents($file_path);
-    echo $content;
+        store_new_graph($graph, $_POST["space"]);
+
+        wp_die();
+    } else {
+        echo "Insufficient permissions!";
+    }
 }
 
-function handle_post($request_data) {
-    $file_path = get_space_file_path($request_data["space_id"]);
+function store_new_graph($graph, $space_id) {
+    $file_path = get_space_file_path($space_id);
+    $result = file_put_contents($file_path, $graph);
 
-    file_put_contents($file_path, $request_data["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";
 }
-
-handle_request();
diff --git a/editor/js/graph.js b/editor/js/graph.js
index 679857f..53a27b5 100644
--- a/editor/js/graph.js
+++ b/editor/js/graph.js
@@ -1,6 +1,5 @@
 import ManagedData from "./manageddata";
 import { PLUGIN_PATH, COLOR_PALETTE } from "../../config";
-import jQuery from "jquery";
 
 const LINK_NAME_CONNECTOR = " → ";
 
@@ -46,31 +45,6 @@ export class Graph extends ManagedData {
 
         this.calculateLinkTypes();
         this.onChangeCallbacks = [];
-
-        let payload = {
-            action: "update_space",
-            graph: JSON.stringify(data),
-            space: space_id,
-        };
-
-        jQuery.ajax({
-            type: "POST",
-            url: ajax_object.ajax_url,
-            // The key needs to match your method's input parameter (case-sensitive).
-            data: payload,
-            // contentType: "application/json; charset=utf-8",
-            // contentType: false,
-            // processData: false,
-            //           dataType: "json",
-            success: function (data) {
-                console.log(data);
-                alert("Success");
-            },
-            error: function (errMsg) {
-                console.log(errMsg);
-                alert("Failure");
-            },
-        });
     }
 
     triggerOnChange() {
diff --git a/knowledge-space.php b/knowledge-space.php
index 6a3e8dc..8b85da0 100644
--- a/knowledge-space.php
+++ b/knowledge-space.php
@@ -84,27 +84,8 @@ function get_space_id_from_atts($atts) {
     }
 }
 
-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")) {
-        $plugin_dir = plugin_dir_path(__FILE__);
-        // Use json encoding.
-        $payload = json_encode($_POST["graph"]);
-        $filename = $plugin_dir . $_POST["space"] . ".json";
-        $result = file_put_contents($filename, $payload);
-
-        //echo print_r($_POST);
-        echo "Saved file at ";
-        echo $filename;
-        echo $result;
-
-        wp_die();
-    } else {
-        echo "Insufficient permissions!";
-    }
-}
+
+require_once(__DIR__ . '/datasets/datasets.php');
 
 add_action('wp_enqueue_scripts', 'kg_load_css');
 add_shortcode('knowledge-space', 'ks_add_graph');
-- 
GitLab