-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix-permissions.php
More file actions
271 lines (236 loc) · 8.12 KB
/
fix-permissions.php
File metadata and controls
271 lines (236 loc) · 8.12 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
<?php
/**
* Permission Repair Script for Cimaise CMS
*
* Run this script once after uploading via FTP/ZIP to fix file permissions.
* Access: https://your-site.com/fix-permissions.php
*
* DELETE THIS FILE AFTER USE FOR SECURITY!
*/
// Security: Only allow execution from browser (not CLI) with auth and origin checks
if (php_sapi_name() === 'cli') {
die("This script must be run from a web browser.\n");
}
// Token-based auth (works before .env exists)
$expectedToken = '';
$fallbackToken = '';
// Preferred: .env (if present)
$envPath = __DIR__ . '/.env';
if (is_readable($envPath)) {
$envContent = file_get_contents($envPath);
if ($envContent !== false) {
foreach (preg_split('/\r\n|\r|\n/', $envContent) as $line) {
if (str_starts_with($line, 'PERMISSIONS_FIX_TOKEN=')) {
$expectedToken = trim(substr($line, strlen('PERMISSIONS_FIX_TOKEN=')));
break;
}
}
}
}
// Fallback: token file (create manually before first run)
if ($expectedToken === '') {
$tokenFileCandidates = [
__DIR__ . '/storage/tmp/permissions_fix_token.txt',
__DIR__ . '/storage/permissions_fix_token.txt',
];
foreach ($tokenFileCandidates as $tokenFile) {
if (is_readable($tokenFile)) {
$tokenContent = trim((string)file_get_contents($tokenFile));
if ($tokenContent !== '') {
$expectedToken = $tokenContent;
break;
}
}
}
}
// Final fallback: hardcoded token (set manually, then remove)
if ($expectedToken === '' && $fallbackToken !== '') {
$expectedToken = $fallbackToken;
}
if ($expectedToken === '') {
http_response_code(403);
die('Permissions token is not configured');
}
$authToken = '';
if (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
if (preg_match('/Bearer\s+(.+)/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
$authToken = trim($matches[1]);
}
}
if ($authToken === '' && isset($_GET['token'])) {
$authToken = trim((string)$_GET['token']);
}
if (!hash_equals($expectedToken, $authToken)) {
http_response_code(401);
die('Access denied');
}
// Origin/Referer check (same-host)
$host = $_SERVER['HTTP_HOST'] ?? '';
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$referer = $_SERVER['HTTP_REFERER'] ?? '';
$originHost = $origin !== '' ? (parse_url($origin, PHP_URL_HOST) ?? '') : '';
$refererHost = $referer !== '' ? (parse_url($referer, PHP_URL_HOST) ?? '') : '';
// Check origin first, fall back to referer if origin not present
$requestHost = $originHost !== '' ? $originHost : $refererHost;
if ($requestHost !== '' && $requestHost !== $host) {
http_response_code(403);
die('Invalid origin');
}
// Set execution time limit (large sites may need more time)
set_time_limit(300);
$root = __DIR__;
$results = [
'directories' => 0,
'files' => 0,
'writable' => 0,
'errors' => []
];
// Directories that need to be writable (777 or 775)
$writableDirs = [
'storage',
'storage/cache',
'storage/logs',
'storage/tmp',
'storage/translations',
'storage/originals',
'database',
'public/media',
];
// Files that need to be writable (666 or 664)
$writableFiles = [
'.env',
'database/database.sqlite',
];
/**
* Recursively fix permissions
*/
function fixPermissions($path, $root, &$results, $writableDirs, $writableFiles, $depth = 0, $maxDepth = 10) {
if (!file_exists($path)) {
return;
}
$relativePath = (strpos($path, $root . '/') === 0)
? substr($path, strlen($root) + 1)
: basename($path);
if (is_dir($path)) {
if ($depth > $maxDepth) {
$results['errors'][] = "Max depth exceeded for: $relativePath";
return;
}
// Check if this directory should be writable
$isWritable = false;
foreach ($writableDirs as $dir) {
if ($relativePath === $dir || strpos($relativePath, $dir . '/') === 0) {
$isWritable = true;
break;
}
}
$targetPerm = $isWritable ? 0775 : 0755;
if (chmod($path, $targetPerm)) {
$results['directories']++;
if ($isWritable) {
$results['writable']++;
}
} else {
$error = error_get_last();
$results['errors'][] = "Failed to chmod directory: $relativePath" . ($error ? " ({$error['message']})" : '');
}
if ($relativePath === 'vendor' || strpos($relativePath, 'storage/originals') === 0) {
return;
}
// Process contents
$items = scandir($path);
if ($items === false) {
$error = error_get_last();
$results['errors'][] = "Failed to scan directory: $relativePath" . ($error ? " ({$error['message']})" : '');
return;
}
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
fixPermissions($path . '/' . $item, $root, $results, $writableDirs, $writableFiles, $depth + 1, $maxDepth);
}
} else {
// It's a file
$isWritable = in_array($relativePath, $writableFiles, true);
// SQLite files in database/ should be writable
if (strpos($relativePath, 'database/') === 0 && pathinfo($path, PATHINFO_EXTENSION) === 'sqlite') {
$isWritable = true;
}
// Log files should be writable
if (pathinfo($path, PATHINFO_EXTENSION) === 'log') {
$isWritable = true;
}
$targetPerm = $isWritable ? 0664 : 0644;
if (chmod($path, $targetPerm)) {
$results['files']++;
if ($isWritable) {
$results['writable']++;
}
} else {
$error = error_get_last();
$results['errors'][] = "Failed to chmod file: $relativePath" . ($error ? " ({$error['message']})" : '');
}
}
}
// Create missing directories
$requiredDirs = [
'storage/cache',
'storage/logs',
'storage/tmp',
'storage/translations',
'storage/originals',
'public/media',
];
foreach ($requiredDirs as $dir) {
$fullPath = $root . '/' . $dir;
if (!is_dir($fullPath)) {
if (mkdir($fullPath, 0775, true)) {
// Directory will be counted during permission scan
} else {
$error = error_get_last();
$results['errors'][] = "Failed to create directory: $dir" . ($error ? " ({$error['message']})" : '');
}
}
}
// Run the permission fix
fixPermissions($root, $root, $results, $writableDirs, $writableFiles);
// Output results
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
<title>Cimaise - Permission Repair</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
h1 { color: #333; }
.success { color: #22c55e; }
.error { color: #ef4444; }
.warning { color: #f59e0b; background: #fef3c7; padding: 15px; border-radius: 8px; margin: 20px 0; }
ul { background: #f1f5f9; padding: 20px 40px; border-radius: 8px; }
li { margin: 8px 0; }
code { background: #e2e8f0; padding: 2px 6px; border-radius: 4px; }
</style>
</head>
<body>
<h1>🔧 Permission Repair Complete</h1>
<ul>
<li><strong>Directories processed:</strong> <?= $results['directories'] ?></li>
<li><strong>Files processed:</strong> <?= $results['files'] ?></li>
<li><strong>Writable items set:</strong> <?= $results['writable'] ?></li>
</ul>
<?php if (!empty($results['errors'])): ?>
<h2 class="error">Errors (<?= count($results['errors']) ?>)</h2>
<ul>
<?php foreach ($results['errors'] as $error): ?>
<li class="error"><?= htmlspecialchars($error) ?></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p class="success">✅ All permissions fixed successfully!</p>
<?php endif; ?>
<div class="warning">
<strong>⚠️ IMPORTANT:</strong> Delete this file (<code>fix-permissions.php</code>) immediately after use for security!
</div>
<p><a href="/">← Go to homepage</a></p>
</body>
</html>