-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
409 lines (349 loc) · 10.7 KB
/
Copy pathfunctions.php
File metadata and controls
409 lines (349 loc) · 10.7 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
<?php
/**
* PHP Directory Explorer - Helper Functions
*
* Este archivo contiene todas las funciones auxiliares de la aplicación
*/
/**
* Obtener ruta absoluta de forma segura
*/
function getAbsolutePath($path)
{
return realpath($path) ?: $path;
}
/**
* Convierte una ruta del sistema de archivos a una URL relativa
*/
function getRelativeUrl($path)
{
global $baseDir, $baseUrl;
$realPath = getAbsolutePath($path);
$realBaseDir = getAbsolutePath($baseDir);
// Si el path está dentro de la base, calcular la URL relativa
if (strpos($realPath, $realBaseDir) === 0) {
$relativePath = substr($realPath, strlen($realBaseDir));
$relativePath = str_replace('\\', '/', $relativePath);
// Normalizar: asegurar que comience con /
if (!empty($relativePath) && $relativePath[0] !== '/') {
$relativePath = '/' . $relativePath;
}
// Combinar con la URL base
return $baseUrl . $relativePath;
}
return null;
}
/**
* Obtener lista de directorios en una ruta dada
*/
function getDirectories($path, $showHidden = false)
{
$directories = [];
if (!is_readable($path)) {
return $directories;
}
try {
$items = scandir($path);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
// Saltamos archivos ocultos si showHidden es false
if (!$showHidden && $item[0] === '.') {
continue;
}
// Excluir directorios configurados
if (in_array($item, EXCLUDED_DIRECTORIES)) {
continue;
}
$fullPath = $path . '/' . $item;
if (is_dir($fullPath) && is_readable($fullPath)) {
$relativeUrl = getRelativeUrl($fullPath);
$perms = getPerms($fullPath);
$size = getDirSize($fullPath, MAX_DIR_DEPTH);
$directories[] = [
'name' => $item,
'path' => $fullPath,
'url' => $relativeUrl,
'perms' => $perms,
'size' => $size,
'formatted_size' => formatSize($size),
'is_hidden' => $item[0] === '.'
];
}
}
} catch (Exception $e) {
// Silenciar errores
if (DEBUG_MODE) {
error_log("Error reading directory $path: " . $e->getMessage());
}
}
return $directories;
}
/**
* Obtener lista de archivos en una ruta dada
*/
function getFiles($path, $showHidden = false)
{
$files = [];
if (!is_readable($path)) {
return $files;
}
try {
$items = scandir($path);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
// Saltamos archivos ocultos si showHidden es false
if (!$showHidden && $item[0] === '.') {
continue;
}
// Excluir archivos configurados
if (in_array($item, EXCLUDED_FILES)) {
continue;
}
$fullPath = $path . '/' . $item;
if (is_file($fullPath) && is_readable($fullPath)) {
$relativeUrl = getRelativeUrl($fullPath);
$perms = getPerms($fullPath);
$size = filesize($fullPath);
$files[] = [
'name' => $item,
'path' => $fullPath,
'url' => $relativeUrl,
'perms' => $perms,
'size' => $size,
'formatted_size' => formatSize($size),
'is_hidden' => $item[0] === '.',
'extension' => pathinfo($item, PATHINFO_EXTENSION)
];
}
}
} catch (Exception $e) {
// Silenciar errores
if (DEBUG_MODE) {
error_log("Error reading files in $path: " . $e->getMessage());
}
}
return $files;
}
/**
* Calcular tamaño de directorio recursivamente (con límite para evitar sobrecarga)
*/
function getDirSize($path, $maxDepth = 3, $currentDepth = 0)
{
if ($currentDepth > $maxDepth) {
return 0; // Limitar profundidad para evitar problemas de rendimiento
}
$size = 0;
if (!is_readable($path)) {
return $size;
}
try {
$items = scandir($path);
foreach ($items as $item) {
if ($item === '.' || $item === '..')
continue;
$fullPath = $path . '/' . $item;
if (is_file($fullPath)) {
$size += filesize($fullPath);
} else if (is_dir($fullPath)) {
$size += getDirSize($fullPath, $maxDepth, $currentDepth + 1);
}
}
} catch (Exception $e) {
// Silenciar errores
if (DEBUG_MODE) {
error_log("Error calculating directory size for $path: " . $e->getMessage());
}
}
return $size;
}
/**
* Obtener permisos en formato legible
*/
function getPerms($path)
{
$perms = fileperms($path);
if (($perms & 0xC000) == 0xC000) {
// Socket
$info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
// Enlace simbólico
$info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
// Regular
$info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
// Especial de bloque
$info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
// Directorio
$info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
// Especial de carácter
$info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
// FIFO
$info = 'p';
} else {
// Desconocido
$info = 'u';
}
// Propietario
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x') :
(($perms & 0x0800) ? 'S' : '-'));
// Grupo
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x') :
(($perms & 0x0400) ? 'S' : '-'));
// Otros
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x') :
(($perms & 0x0200) ? 'T' : '-'));
// Formato numérico
$octal = sprintf('%04o', $perms & 0777);
return ['symbolic' => $info, 'octal' => $octal];
}
/**
* Formatear tamaños de archivo
*/
function formatSize($bytes)
{
$units = SIZE_UNITS;
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, 2) . ' ' . $units[$pow];
}
/**
* Detectar si estamos en modo de acceso root
*/
function detectRootAccess()
{
$requestUri = $_SERVER['REQUEST_URI'] ?? '';
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
// Extraer la parte del path sin parámetros
$requestPath = strtok($requestUri, '?');
$scriptPath = dirname($scriptName);
// Detectar si estamos en modo "root access"
$isRootAccess = false;
if (rtrim($requestPath, '/') !== rtrim($scriptPath, '/')) {
// Si la ruta solicitada es diferente a la ruta del script, estamos en modo rewrite
$isRootAccess = (
str_ends_with($requestPath, '/') ||
str_ends_with($requestPath, '/index.php')
);
}
return [
'isRootAccess' => $isRootAccess,
'requestPath' => $requestPath,
'scriptPath' => $scriptPath,
'requestUri' => $requestUri,
'scriptName' => $scriptName
];
}
/**
* Configurar el directorio base según el contexto
*/
function setupBaseDirectory()
{
$scriptDir = dirname(__FILE__);
$accessInfo = detectRootAccess();
if ($accessInfo['isRootAccess'] && !empty(ROOT_BASE_CONFIG)) {
// Estamos en modo root access, usar la configuración personalizada
if (ROOT_BASE_CONFIG[0] === '/') {
// Ruta absoluta
$baseDir = ROOT_BASE_CONFIG;
} else {
// Ruta relativa al directorio del script
$baseDir = realpath($scriptDir . '/' . ROOT_BASE_CONFIG) ?: $scriptDir;
}
} else {
// Acceso directo al PHPDirExplorer o configuración vacía
$baseDir = $scriptDir;
}
$baseUrl = '';
// Si estamos en un entorno web, intentar determinar la URL base
if ($accessInfo['scriptPath'] !== '/' && $accessInfo['scriptPath'] !== '\\') {
$baseUrl = $accessInfo['scriptPath'];
}
return [
'baseDir' => $baseDir,
'baseUrl' => $baseUrl,
'scriptDir' => $scriptDir,
'accessInfo' => $accessInfo
];
}
/**
* Generar información de debug si está habilitado
*/
function getDebugInfo($baseDir, $baseUrl, $scriptDir, $accessInfo)
{
if (!DEBUG_MODE) {
return '';
}
return "<!-- DEBUG INFO
Request URI: " . $accessInfo['requestUri'] . "
Request Path: " . $accessInfo['requestPath'] . "
Script Name: " . $accessInfo['scriptName'] . "
Script Path: " . $accessInfo['scriptPath'] . "
Script Dir: $scriptDir
Is Root Access: " . ($accessInfo['isRootAccess'] ? 'YES' : 'NO') . "
Base Dir: $baseDir
Base URL: $baseUrl
Root Base Config: " . ROOT_BASE_CONFIG . "
-->";
}
/**
* Validar y sanitizar el path actual
*/
function validateCurrentPath($requestedPath, $baseDir)
{
$currentPath = isset($requestedPath) ? $requestedPath : $baseDir;
$currentPath = getAbsolutePath($currentPath);
// Validar que el directorio existe y es accesible
if (!file_exists($currentPath) || !is_dir($currentPath)) {
$currentPath = $baseDir;
}
// Validar que el path está dentro del directorio base (seguridad)
if (strpos($currentPath, getAbsolutePath($baseDir)) !== 0) {
$currentPath = $baseDir;
}
return $currentPath;
}
/**
* Obtener el path padre validado
*/
function getValidParentPath($currentPath, $baseDir)
{
$parentPath = dirname($currentPath);
if (strpos(getAbsolutePath($parentPath), getAbsolutePath($baseDir)) !== 0) {
$parentPath = $baseDir;
}
return $parentPath;
}
/**
* Generar breadcrumb de navegación
*/
function generatePathBreadcrumb($currentPath, $baseDir)
{
$pathParts = [];
$tempPath = $currentPath;
while (strpos($tempPath, $baseDir) === 0 && $tempPath !== $baseDir) {
array_unshift($pathParts, [
'name' => basename($tempPath),
'path' => $tempPath
]);
$tempPath = dirname($tempPath);
}
return $pathParts;
}