diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d862e03 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Apps Dev Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/composer.json b/composer.json index abe235d..0207ae4 100644 --- a/composer.json +++ b/composer.json @@ -5,6 +5,10 @@ "src/" ] }, + "license": "MIT", + "require": { + "nette/utils": "^2.0|^3.0|^4.0" + }, "require-dev": { "guzzlehttp/guzzle": "^6.3|^7.0", "nette/tester": "^2.4" diff --git a/readme.md b/readme.md index fa39d27..0c6ea90 100644 --- a/readme.md +++ b/readme.md @@ -1,15 +1,3 @@ -## CommandLock - -CommandLock is a helper Trait for preventing a command from being ran multiple times at once by creating a lock file for each command. - -The lock files also contain process id of the command which created the lock. -If there is an attempt to run a command that is locked but the process id saved in the lock file doesn't belong to a running process, the lock is reset. - -Class using this Trait also needs to have a property commandLockPathProvider of type CommandLockPathProvider accessible by the Trait. - -CommandLock only runs on Unix and has no required dependencies. However only if Nette SafeStream is registered (either automatically or manually), -atomicity and thread safety of lock and unlock operations can be guaranteed. - ## Installation ```composer require adt/utils``` diff --git a/src/BackgroundQueue.php b/src/BackgroundQueue.php deleted file mode 100644 index 904081a..0000000 --- a/src/BackgroundQueue.php +++ /dev/null @@ -1,47 +0,0 @@ -getRequest()) . ($e instanceof BadResponseException ? Message::toString($e->getResponse()) : $e->getMessage()); - - if ($e instanceof ServerException || $e instanceof ConnectException) { - throw new TemporaryErrorException($message); - } - - throw new BadRequestException($message); - } - - throw $e; - } - - /** - * @throws BadRequestException - * @throws TemporaryErrorException - */ - public static function handleGuzzleResult(Closure $closure) - { - try { - return $closure(); - } catch (Exception $e) { - self::handleException($e); - } - } -} \ No newline at end of file diff --git a/src/BadRequestException.php b/src/BadRequestException.php deleted file mode 100644 index 627722f..0000000 --- a/src/BadRequestException.php +++ /dev/null @@ -1,10 +0,0 @@ -getHelper('container'); - * $this->commandLockPathProvider = $containerHelper->getByType(\ADT\Utils\CommandLockPathProvider::class); - * } - * - * protected function execute(InputInterface $input, OutputInterface $output) { - * $this->tryLock(); - * // Execute command... - * $this->tryUnlock(); - * } - */ - - /** - * Tries to create a lock file with its process id. - * If file exists but process id in it doesn't belong to any running process, overrides the lock. - * If file exists and process id in it belongs to a running process, fails. - * @param bool $strict If true, failure throws an exception - * @param string $identifier If set, adds a "-$identifier" suffix to the name of the lock file. - * @return bool true in case of success, false otherwise - * @throws \Exception - */ - protected function tryLock(bool $strict = true, $identifier = null) { - $folderName = $this->getFolder($identifier); - if (!file_exists($folderName)) { - mkdir($folderName, 0777, true); - } - $pathName = $this->getPath($identifier); - $stream = fopen($pathName, 'a+'); - fseek($stream, 0); - $line = fgets($stream); - // If the file has no characters, it means it either did not exist - // or wasn't owned by any process - // If pgid can't be retrieved, the process that owned the lock - // doesn't exist anymore - if (strlen($line) === 0 || posix_getpgid(intval($line)) === false) { - fseek($stream, 0); - ftruncate($stream, 0); - fwrite($stream, getmypid()); - fclose($stream); - return true; - } - if ($strict) { - throw new \Exception('Error locking: Command already locked by a running process'); - } - else { - return false; - } - } - - /** - * Tries to unlock a lock. - * Can fail if the lock file has id of another running process. - * @param bool $strict If true, failure throws an exception - * @param string $identifier If set, adds a "-$identifier" suffix to the name of the lock file - * @return bool true in case of success, false otherwise - * @throws \Exception - */ - protected function tryUnlock(bool $strict = false, $identifier = null) { - $folderName = $this->getFolder($identifier); - if (!file_exists($folderName)) { - mkdir($folderName, 0777, true); - } - $pathName = $this->getPath($identifier); - $stream = fopen($pathName, 'a+'); - fseek($stream, 0); - // If the file has no characters, it means it either did not exist - // or wasn't owned by any process - // If process id in file matches the current process' id, it is owned - // by the current process and can be safely removed - if ($stream === false || strlen(($line = fgets($stream))) === 0 || intval($line) === getmypid()) { - // Between fclose and unlink calls, the lock is still practically owned by the current process - // and atomicity can still be guaranteed - fclose($stream); - unlink($pathName); - return true; - } - if ($strict) { - throw new \Exception('Error unlocking: Command already locked by a running process'); - } - else { - return false; - } - } - - protected function getPath($identifier = null) { - $fullName = static::getFullName($this->getName(), $identifier); - if (in_array('nette.safe', stream_get_wrappers())) { - return 'nette.safe://' . $this->commandLockPathProvider->getPath($fullName); - } - else { - return $this->commandLockPathProvider->getPath($fullName); - } - } - - protected function getFolder($identifier = null) { - $fullName = static::getFullName($this->getName(), $identifier); - return $this->commandLockPathProvider->getFolder($fullName); - } - - public static function getFullName($name, $identifier) - { - return $name . (is_string($identifier) ? "-$identifier" : ''); - } -} diff --git a/src/CommandLockPathProvider.php b/src/CommandLockPathProvider.php deleted file mode 100644 index 0b17705..0000000 --- a/src/CommandLockPathProvider.php +++ /dev/null @@ -1,44 +0,0 @@ -createPathString($path, $format); - } - - protected function createPathString($path, $format) { - if ($path[strlen($path) - 1] !== '/' && $path[strlen($path) - 1] !== '\\') { - $path .= '/'; - } - if (strpos($path, '$cmd$') !== false) { - throw new \Exception("Path can't include \$cmd\$"); - } - if (strpos($format, '$cmd$') === false) { - $this->lockPath = $path . '.$cmd$.lock'; - } - else { - $this->lockPath = $path . $format; - } - } - - public function getPath(string $commandName = '') { - $commandName = preg_replace('/[^-a-zA-Z0-9]/', '-', $commandName); - return str_replace('$cmd$', $commandName, $this->lockPath); - } - - public function getFolder(string $commandName = '') { - $path = $this->getPath($commandName); - return substr($path, 0, strripos($path, '/') + 1); - } - -} \ No newline at end of file diff --git a/src/CssModule.php b/src/CssModule.php index b533502..6414a6b 100644 --- a/src/CssModule.php +++ b/src/CssModule.php @@ -23,7 +23,7 @@ public function injectCssModule() * @param string|null $dir * @return array */ - private function load(string $moduleName = 'index', string $dir = NULL): array + private function load(string $moduleName = 'index', ?string $dir = NULL): array { $dir = $dir ?? dirname($this->getReflection()->getFileName()); $filePath = $dir . "/$moduleName.module.scss.json"; diff --git a/src/FileSystem.php b/src/FileSystem.php new file mode 100644 index 0000000..679460c --- /dev/null +++ b/src/FileSystem.php @@ -0,0 +1,28 @@ +path = $path; + $this->dir = $dir; + $this->multiplier = $multiplier; + } + + const FormatToExtensions = [ + IMAGETYPE_WEBP => 'webp' + ]; + + const ExtensionsToFormat = [ + 'webp' => IMAGETYPE_WEBP + ]; + + /** + * @throws Exception + */ + public function format(string $url, int $width, int $height, int $mode = \Nette\Utils\Image::OrSmaller, int $format = IMAGETYPE_WEBP): string + { + $originalUrl = $url; + + $isRemoteUrl = $this->isRemoteUrl($url); + + // original file does not exist + if ($isRemoteUrl) { + $contents = @file_get_contents($url); + if (!$contents) { + return $originalUrl; + } + + list($urlWithoutExtension,) = $this->splitUrlOnLastDot($this->removeProtocol($url)); + + } else { + $url = trim($url, '/'); + if (!file_exists($this->path . '/' . $url)) { + return $originalUrl; + } + $contents = file_get_contents($this->path . '/' . $url); + + if ($this->isAnimatedGif($contents)) { + return $originalUrl; + } + + list($urlWithoutExtension,) = $this->splitUrlOnLastDot($url); + } + + $width = $width * $this->multiplier; + $height = $height * $this->multiplier; + $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION); + if ($ext === 'svg') { + return $originalUrl; + } + + $newFile = $this->dir . '/' . $urlWithoutExtension . '_' . $width . '_' . $height . '_' . $mode . '_' . $ext . '.' . self::FormatToExtensions[$format]; + + $this->createImage($contents, $width, $height, $mode, $format, $this->path . '/' . $newFile); + + return '/' . $newFile; + } + + private function isRemoteUrl(string $url): bool + { + $parsedUrl = parse_url($url); + + if (isset($parsedUrl['scheme'])) { + return in_array($parsedUrl['scheme'], ['http', 'https']); + } + + return false; + } + + /** + * Thanks to ZeBadger for original example, and Davide Gualano for pointing me to it + * Original at http://it.php.net/manual/en/function.imagecreatefromgif.php#59787 + **/ + private function isAnimatedGif($fileContents): bool + { + $raw = $fileContents; + + $offset = 0; + $frames = 0; + while ($frames < 2) + { + $where1 = strpos($raw, "\x00\x21\xF9\x04", $offset); + if ( $where1 === false ) + { + break; + } + else + { + $offset = $where1 + 1; + $where2 = strpos( $raw, "\x00\x2C", $offset ); + if ( $where2 === false ) + { + break; + } + else + { + if ( $where1 + 8 == $where2 ) + { + $frames ++; + } + $offset = $where2 + 1; + } + } + } + + return $frames > 1; + } + + private function splitUrlOnLastDot(string $url): array + { + $lastDotPos = strrpos($url, '.'); + + if ($lastDotPos !== false) { + $part1 = substr($url, 0, $lastDotPos); + $part2 = substr($url, $lastDotPos + 1); + return [$part1, $part2]; + } + + return [$url, '']; + } + + private function removeProtocol(string $url): string + { + return preg_replace("/^https?:\/\//", "", $url); + } + + /** + * @throws ImageException + */ + public function createImageFromThumbnailUrl(string $url): bool + { + $info = pathinfo($url); + if (empty($info['extension'])) { + return false; + } + $format = $info['extension']; + if (!array_key_exists($format, static::ExtensionsToFormat)) { + return false; + } + + if (empty($info['filename'])) { + return false; + } + $fileInfo = pathinfo($info['filename']); + + if (empty($fileInfo['filename'])) { + return false; + } + $segments = explode('_', $fileInfo['filename']); + + $extension = array_pop($segments); + $mode = (int)array_pop($segments); + $height = (int)array_pop($segments); + $width = (int)array_pop($segments); + $originalFile = $info['dirname'] . '/' . implode('_', $segments) . '.' . $extension; + if (!file_exists($this->path . '/' . $originalFile)) { + return false; + } + $this->createImage(file_get_contents($this->path . '/' . $originalFile), $width, $height, $mode, static::ExtensionsToFormat[$format], $this->path . '/' . $this->dir . '/' . $url); + + return true; + } + + /** + * @throws ImageException + * @throws Exception + */ + protected function createImage(string $contents, int $width, int $height, int $mode, int $format, string $newFile): void + { + // thumbnail already exists + if (file_exists($newFile)) { + return; + } + + FileSystem::createDirAtomically(dirname($newFile)); + + $prevErrorHandler = set_error_handler(function ($errno, $errstr) use (&$prevErrorHandler) { + if ($errno === E_USER_WARNING && $errstr === 'Nette\Utils\Image::fromString(): gd-png: libpng warning: iCCP: known incorrect sRGB profile') { + return true; + } + return $prevErrorHandler ? $prevErrorHandler(...func_get_args()) : false; + }); + $image = \Nette\Utils\Image::fromString($contents); + set_error_handler($prevErrorHandler); + $image->resize($width, $height, $mode); + $image->save($newFile, 100, $format); + } + + public function getPath(): string + { + return $this->path; + } + + public function getDir(): string + { + return $this->dir; + } +} diff --git a/src/Guzzle.php b/src/Guzzle.php index fd047de..f9d72c0 100644 --- a/src/Guzzle.php +++ b/src/Guzzle.php @@ -2,48 +2,57 @@ namespace ADT\Utils; use Exception; -use GuzzleHttp\Exception\BadResponseException; use GuzzleHttp\Exception\ConnectException; +use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\RequestException; -use GuzzleHttp\Exception\ServerException; use GuzzleHttp\Psr7\Message; +use Throwable; -class Guzzle { +class Guzzle +{ + private const MAX_BODY_LENGTH = 10000; /** - * @deprecated use handleException() instead - * Returns TRUE if everything is allright, FALSE if it's repetable error, otherwise throws exception - * - * \GuzzleHttp\Exception\GuzzleException $guzzleException - * @return boolean|\GuzzleHttp\Exception\GuzzleException + * @throws Throwable */ - public static function handleError(\GuzzleHttp\Exception\GuzzleException $guzzleException) { - - if ($guzzleException instanceof \GuzzleHttp\Exception\ConnectException) { - // HTTP Code 0 - // On Sparkpost or ADT MailApi the request was successfuly processed even if there is no response - // Let's believe it is common behaviour - return TRUE; - } - - if ($guzzleException instanceof \GuzzleHttp\Exception\ServerException) { - // HTTP Code 5xx - return FALSE; + public static function handleException(Throwable $e): ?Exception + { + if ($e instanceof GuzzleException) { + $message = ''; + if ($e instanceof ConnectException || $e instanceof RequestException) { + $message = "--- REQUEST ---\n" . self::sanitizeMessage(Message::toString($e->getRequest())) . "\n --- RESPONSE ---\n"; + } + $message .= ($e instanceof RequestException && $e->getResponse() ? self::sanitizeMessage(Message::toString($e->getResponse())) : $e->getMessage()); + + throw new Exception($message); } - // other exceptions like 3xx (TooManyRedirectsException) or 4xx (\GuzzleHttp\Exception\ClientException) are unrepeatable and we want to throw exception - throw $guzzleException; + throw $e; } - - public static function handleException(Exception $e): ?Exception + private static function sanitizeMessage(string $message): string { - return $e instanceof ServerException || $e instanceof ConnectException - ? null - : ( - $e instanceof RequestException - ? new Exception(Message::toString($e->getRequest()) . ($e instanceof BadResponseException ? Message::toString($e->getResponse()) : $e->getMessage())) - : $e - ); + // Odstraneni binarnich dat (null byty apod.) + if (preg_match('/[^\x20-\x7E\x0A\x0D\t]/u', $message)) { + // Najdeme konec hlavicek (prazdny radek) + $headerEnd = strpos($message, "\r\n\r\n"); + if ($headerEnd === false) { + $headerEnd = strpos($message, "\n\n"); + } + + if ($headerEnd !== false) { + $headers = substr($message, 0, $headerEnd); + return $headers . "\n\n[binary data removed]"; + } + + return '[binary data removed]'; + } + + // Oriznuti prilis dlouhych textovych odpovedi + if (strlen($message) > self::MAX_BODY_LENGTH) { + return substr($message, 0, self::MAX_BODY_LENGTH) . "\n\n... [truncated, total " . strlen($message) . " bytes]"; + } + + return $message; } } diff --git a/src/JsComponents.php b/src/JsComponents.php index 12b9686..2e49c73 100644 --- a/src/JsComponents.php +++ b/src/JsComponents.php @@ -2,17 +2,25 @@ namespace ADT\Utils; +use Nette\Utils\Json; + class JsComponents { protected array $components = []; public function generateConfig(): string { - return json_encode($this->components); + return Json::encode($this->components); } public function setRecaptcha(string $siteKey): string { return $this->components['recaptcha']['siteKey'] = $siteKey; } + + public function setComponents(array $components): self + { + $this->components = array_merge($this->components, $components); + return $this; + } } diff --git a/src/Strings.php b/src/Strings.php index bab2206..e509dd5 100644 --- a/src/Strings.php +++ b/src/Strings.php @@ -2,6 +2,8 @@ namespace ADT\Utils; +use Transliterator; + class Strings { /** @@ -40,6 +42,12 @@ public static function containsCharactersLargerThen(string $s, int $code, string return false; } + + public static function removeDiacritics(string $s): string + { + $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD); + return $transliterator->transliterate($s); + } public static function validateFullName(string $fullName): bool { @@ -70,4 +78,37 @@ public static function validateFullName(string $fullName): bool $ /mx", $fullName); } + + public static function convertToType($str) + { + if (!is_string($str)) { + return $str; + } + + // Pokud řetězec obsahuje pouze číslice + if (ctype_digit($str)) { + // když začíná 0 a má víc jak 1 znak, vratíme string + if (strpos($str, '0') === 0 && strlen($str) > 1) { + return $str; + } + return (int)$str; // jinak vratíme integer + } + + // Pokud řetězec obsahuje číslice a případně jednu desetinnou tečku, vratíme float + if (preg_match('/^\d+\.\d+$/', $str)) { + return (float)$str; + } + + // Pro "true" a "false" vrátíme boolean + if (strtolower($str) === 'true') { + return true; + } + + if (strtolower($str) === 'false') { + return false; + } + + // V opačném případě vratíme původní řetězec + return $str; + } } diff --git a/src/Translatable/TranslatableControlTrait.php b/src/Translatable/TranslatableControlTrait.php index 678bb15..d36670a 100644 --- a/src/Translatable/TranslatableControlTrait.php +++ b/src/Translatable/TranslatableControlTrait.php @@ -43,11 +43,9 @@ public function addTranslation(Form $form, $name, $containerFactory) ->where('e.objectClass = :objectClass') ->andWhere('e.locale NOT IN (:locales)') ->andWhere('e.foreignKey = :foreignKey') - ->setParameters([ - 'objectClass' => get_class($entity), - 'locales' => $locales, - 'foreignKey' => $entity->getId() - ]) + ->setParameter('objectClass', get_class($entity)) + ->setParameter('locales', $locales) + ->setParameter('foreignKey', $entity->getId()) ->delete() ->getQuery() ->execute(); diff --git a/src/Translatable/TranslatableEntityTrait.php b/src/Translatable/TranslatableEntityTrait.php index 526f214..31e6d32 100644 --- a/src/Translatable/TranslatableEntityTrait.php +++ b/src/Translatable/TranslatableEntityTrait.php @@ -2,6 +2,8 @@ namespace ADT\Utils\Translatable; +use Gedmo\Mapping\Annotation\Locale; + trait TranslatableEntityTrait { /** @@ -9,6 +11,7 @@ trait TranslatableEntityTrait * Used locale to override Translation listener`s locale * this is not a mapped field of entity metadata, just a simple property */ + #[Locale] private $locale; public function setTranslatableLocale($locale) diff --git a/src/Translatable/TranslatableSluggableFormTrait.php b/src/Translatable/TranslatableSluggableFormTrait.php index 1f17c35..656f6a3 100644 --- a/src/Translatable/TranslatableSluggableFormTrait.php +++ b/src/Translatable/TranslatableSluggableFormTrait.php @@ -50,13 +50,11 @@ private function generateSlug(TranslatableEntityInterface $entity) ->andWhere('e.content = :content') ->andWhere('e.foreignKey != :foreignKey') ->andWhere('e.field = :field') - ->setParameters([ - 'locale' => $_locale, - 'objectClass' => get_class($entity), - 'content' => $slug, - 'foreignKey' => $entity->getId(), - 'field' => $slugField, - ]) + ->setParameter('locale', $_locale) + ->setParameter('objectClass', get_class($entity)) + ->setParameter('content', $slug) + ->setParameter('foreignKey', $entity->getId()) + ->setParameter('field', $slugField) ->getQuery() ->getSingleResult(); diff --git a/src/Utils.php b/src/Utils.php new file mode 100644 index 0000000..ca2c655 --- /dev/null +++ b/src/Utils.php @@ -0,0 +1,32 @@ +