-
Notifications
You must be signed in to change notification settings - Fork 5
/
copy-files.php
75 lines (62 loc) · 2.12 KB
/
copy-files.php
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
namespace Kirby\Plugins\CopyFiles;
use Response;
use Dir;
if (!function_exists('panel')) return;
function stripDotSegments($path) {
return preg_replace('#(^|/)\.{1,}/#', '/', $path);
}
// Load widget
kirby()->set('widget', 'copy-files', __DIR__ . DS . 'widgets' . DS . 'copy-files');
// Add routes
panel()->routes([[
'pattern' => 'copy-files/api/copy',
'method' => 'POST',
'action' => function() {
$user = site()->user()->current();
if (!$user || (!$user->permission('panel.page.create') && !$user->isAdmin())) {
return Response::error("Must be authenticated as user with page creation permissions");
}
$sourceUrl = stripDotSegments(get('source'));
$destUrl = preg_replace('/\s+/', '-', stripDotSegments(get('dest')));
// Convert source uri to its proper path
$source = page($sourceUrl);
if ($source) {
$sourceUrl = $source->diruri();
}
// Convert existing page sub-URI of destination to its proper path,
// adding number prefixes where needed (ie. blog -> 4-blog)
$destParts = explode('/', trim($destUrl, '/'));
$destPage = site();
foreach ($destParts as $index => $part) {
$destPage = $destPage->children()->find($part);
if ($destPage == null) {
break;
} else {
$destParts[$index] = $destPage->dirname();
}
}
$sourcePath = kirby()->roots->content() . DS . $sourceUrl;
$destPath = kirby()->roots->content() . DS . implode('/', $destParts);
if (!file_exists($sourcePath)) {
return Response::error("Source doesn't exist");
}
if (file_exists($destPath)) {
return Response::error("Destination already exists");
}
if (is_dir($sourcePath)) {
if (!Dir::copy($sourcePath, $destPath)) {
return Response::error("Failed to copy folder");
}
} else if (!@copy($sourcePath, $destPath)) {
return Response::error("Failed to copy file");
}
// Response data
$data = [];
if ($source) {
$data['url'] = panel()->urls->index . "/pages/$destUrl/edit";
panel()->notify("Page cloned");
}
return Response::success("Copy successful", $data);
},
]]);