Emalawi19 commited on
Commit
0494aaf
·
verified ·
1 Parent(s): 36d9100

Create api/save.php

Browse files
Files changed (1) hide show
  1. api/save.php +81 -0
api/save.php ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ header('Content-Type: application/json');
3
+ header('Access-Control-Allow-Origin: *');
4
+ header('Access-Control-Allow-Methods: POST, OPTIONS');
5
+ header('Access-Control-Allow-Headers: Content-Type');
6
+
7
+ if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
8
+ http_response_code(204);
9
+ exit;
10
+ }
11
+
12
+ if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
13
+ http_response_code(405);
14
+ echo json_encode(['error' => 'Method not allowed']);
15
+ exit;
16
+ }
17
+
18
+ $input = json_decode(file_get_contents('php://input'), true);
19
+ $username = trim($input['username'] ?? '');
20
+ $filepath = trim($input['filepath'] ?? '');
21
+ $content = $input['content'] ?? '';
22
+
23
+ // Validate username
24
+ if (!preg_match('/^[a-z0-9]{3,32}$/', $username)) {
25
+ http_response_code(400);
26
+ echo json_encode(['error' => 'Invalid username']);
27
+ exit;
28
+ }
29
+
30
+ // Validate filepath — only allow simple filenames, no directory traversal
31
+ $filepath = basename($filepath);
32
+ if (empty($filepath)) {
33
+ http_response_code(400);
34
+ echo json_encode(['error' => 'Invalid filepath']);
35
+ exit;
36
+ }
37
+
38
+ // Allowed extensions
39
+ $allowed = ['php','html','htm','css','js','json','txt','xml','svg'];
40
+ $ext = strtolower(pathinfo($filepath, PATHINFO_EXTENSION));
41
+ if (!in_array($ext, $allowed)) {
42
+ http_response_code(400);
43
+ echo json_encode(['error' => "File type .{$ext} not allowed in editor"]);
44
+ exit;
45
+ }
46
+
47
+ // Check user exists
48
+ $db = new PDO('sqlite:/data/db/platform.sqlite');
49
+ $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
50
+ $stmt = $db->prepare('SELECT id FROM users WHERE username = ?');
51
+ $stmt->execute([$username]);
52
+ if (!$stmt->fetch()) {
53
+ http_response_code(404);
54
+ echo json_encode(['error' => 'User not found']);
55
+ exit;
56
+ }
57
+
58
+ $htdocs = "/data/sites/{$username}/htdocs";
59
+ $dest = "{$htdocs}/{$filepath}";
60
+
61
+ // Write the file
62
+ if (file_put_contents($dest, $content) === false) {
63
+ http_response_code(500);
64
+ echo json_encode(['error' => 'Failed to write file']);
65
+ exit;
66
+ }
67
+
68
+ // Update files table
69
+ $stmt = $db->prepare('
70
+ INSERT INTO files (username, filepath, updated_at)
71
+ VALUES (?, ?, datetime("now"))
72
+ ON CONFLICT(username, filepath) DO UPDATE SET updated_at=datetime("now")
73
+ ');
74
+ $stmt->execute([$username, $filepath]);
75
+
76
+ echo json_encode([
77
+ 'success' => true,
78
+ 'username' => $username,
79
+ 'filepath' => $filepath,
80
+ 'message' => 'File saved successfully'
81
+ ]);