| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace UserAccessManager\File; |
| 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 |
$directoryMatch = $this->getDirectoryMatch(); |
| 21 |
return $directoryMatch === null ? $directory : $directoryMatch; |
| 22 |
} |
| 23 |
|
| 24 |
private function getFileContent(string $absolutePath, string $directory, ?string $objectType): string |
| 25 |
{ |
| 26 |
if ($objectType === null) { |
| 27 |
$objectType = ObjectHandler::ATTACHMENT_OBJECT_TYPE; |
| 28 |
} |
| 29 |
|
| 30 |
$location = $this->getLocation(str_replace($absolutePath, '/', $directory)); |
| 31 |
|
| 32 |
$content = "location ~ \"$location\" {\n"; |
| 33 |
$content .= "rewrite ^([^?]*)$ /index.php?uamfiletype=$objectType&uamgetfile=$1 last;\n"; |
| 34 |
$content .= "rewrite ^(.*)\\?(((?!uamfiletype).)*)$ "; |
| 35 |
$content .= "/index.php?uamfiletype=$objectType&uamgetfile=$1&$2 last;\n"; |
| 36 |
$content .= "rewrite ^(.*)\\?(.*)$ /index.php?uamgetfile=$1&$2 last;\n"; |
| 37 |
$content .= "}\n"; |
| 38 |
|
| 39 |
return $content; |
| 40 |
} |
| 41 |
|
| 42 |
public function getFileNameWithPath(?string $directory = null): string |
| 43 |
{ |
| 44 |
return ABSPATH . self::FILE_NAME; |
| 45 |
} |
| 46 |
|
| 47 |
public function create(string $directory, ?string $objectType = null, ?string $absolutePath = ABSPATH): bool |
| 48 |
{ |
| 49 |
$directory = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; |
| 50 |
$absolutePath = rtrim($absolutePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; |
| 51 |
$content = $this->getFileContent($absolutePath, $directory, $objectType); |
| 52 |
|
| 53 |
// save files |
| 54 |
$fileWithPath = $absolutePath . self::FILE_NAME; |
| 55 |
|
| 56 |
try { |
| 57 |
return file_put_contents($fileWithPath, $content) !== false; |
| 58 |
} catch (Exception) { |
| 59 |
// Because file_put_contents can throw exceptions, we use this try catch block |
| 60 |
// to return the success result instead of an exception |
| 61 |
} |
| 62 |
|
| 63 |
return false; |
| 64 |
} |
| 65 |
|
| 66 |
public function delete(string $directory): bool |
| 67 |
{ |
| 68 |
return $this->deleteFiles($directory); |
| 69 |
} |
| 70 |
} |
| 71 |
|