| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace UserAccessManager\File\Protection; |
| 6 |
|
| 7 |
use Exception; |
| 8 |
use UserAccessManager\Object\ObjectHandler; |
| 9 |
|
| 10 |
class NginxFileProtection extends FileProtection implements FileProtectionInterface |
| 11 |
{ |
| 12 |
public const FILE_NAME = 'uam.conf'; |
| 13 |
|
| 14 |
protected function getLocation(string $directory): string |
| 15 |
{ |
| 16 |
if ($this->mainConfig->getLockedDirectoryType() === 'wordpress') { |
| 17 |
return "^$directory" . $this->getDirectoryMatch(); |
| 18 |
} |
| 19 |
|
| 20 |
return $this->getDirectoryMatch() ?? $directory; |
| 21 |
} |
| 22 |
|
| 23 |
private function getFileContent(string $absolutePath, string $directory, ?string $objectType): string |
| 24 |
{ |
| 25 |
if ($objectType === null) { |
| 26 |
$objectType = ObjectHandler::ATTACHMENT_OBJECT_TYPE; |
| 27 |
} |
| 28 |
|
| 29 |
$location = $this->getLocation(str_replace($absolutePath, '/', $directory)); |
| 30 |
|
| 31 |
return "location ~ \"$location\" {\n" |
| 32 |
. "rewrite ^([^?]*)$ /index.php?uamfiletype=$objectType&uamgetfile=$1 last;\n" |
| 33 |
. "rewrite ^(.*)\\?(((?!uamfiletype).)*)$ " |
| 34 |
. "/index.php?uamfiletype=$objectType&uamgetfile=$1&$2 last;\n" |
| 35 |
. "rewrite ^(.*)\\?(.*)$ /index.php?uamgetfile=$1&$2 last;\n" |
| 36 |
. "}\n"; |
| 37 |
} |
| 38 |
|
| 39 |
public function getFileNameWithPath(?string $directory = null): string |
| 40 |
{ |
| 41 |
return ABSPATH . self::FILE_NAME; |
| 42 |
} |
| 43 |
|
| 44 |
public function create(string $directory, ?string $objectType = null, ?string $absolutePath = ABSPATH): bool |
| 45 |
{ |
| 46 |
$directory = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; |
| 47 |
$absolutePath = rtrim($absolutePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; |
| 48 |
$content = $this->getFileContent($absolutePath, $directory, $objectType); |
| 49 |
|
| 50 |
try { |
| 51 |
return file_put_contents($absolutePath . self::FILE_NAME, $content) !== false; |
| 52 |
} catch (Exception) { |
| 53 |
// file_put_contents may throw, but callers expect a boolean success result. |
| 54 |
} |
| 55 |
|
| 56 |
return false; |
| 57 |
} |
| 58 |
|
| 59 |
public function delete(string $directory): bool |
| 60 |
{ |
| 61 |
return $this->deleteFiles($directory); |
| 62 |
} |
| 63 |
} |
| 64 |
|