File size: 1,858 Bytes
bb62128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138b22e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
session_start();
$metadataFile = 'data/files.json';

function loadMetadata() {
    global $metadataFile;
    if (!file_exists($metadataFile)) return ['files' => []];
    return json_decode(file_get_contents($metadataFile), true);
}

function saveMetadata($metadata) {
    global $metadataFile;
    file_put_contents($metadataFile, json_encode($metadata, JSON_PRETTY_PRINT));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fileId'])) {
    $fileId = $_POST['fileId'];
    $metadata = loadMetadata();
    foreach ($metadata['files'] as $file) {
        if ($file['id'] === $fileId) {
            $pathInfo = pathinfo($file['name']);
            $copyName = $pathInfo['filename'] . ' (copy)';
            if (isset($pathInfo['extension'])) $copyName .= '.' . $pathInfo['extension'];

            $copyPath = dirname($file['path']) . '/' . $copyName;
            $counter = 1;
            while (file_exists($copyPath)) {
                $copyName = $pathInfo['filename'] . ' (copy ' . $counter . ')';
                if (isset($pathInfo['extension'])) $copyName .= '.' . $pathInfo['extension'];
                $copyPath = dirname($file['path']) . '/' . $copyName;
                $counter++;
            }

            if (file_exists($file['path']) && copy($file['path'], $copyPath)) {
                $newFile = $file;
                $newFile['id'] = uniqid();
                $newFile['name'] = $copyName;
                $newFile['path'] = $copyPath;
                $newFile['created'] = time();
                $newFile['modified'] = time();
                $newFile['starred'] = false;
                $metadata['files'][] = $newFile;
                saveMetadata($metadata);
                echo json_encode(['success' => true]);
                exit;
            }
        }
    }
    echo json_encode(['success' => false]);
}
?>