diff --git a/4dev/tests/Combined/CoreLibsCombinedDateTimeTest.php b/4dev/tests/Combined/CoreLibsCombinedDateTimeTest.php index ddc03cad..e2174a41 100644 --- a/4dev/tests/Combined/CoreLibsCombinedDateTimeTest.php +++ b/4dev/tests/Combined/CoreLibsCombinedDateTimeTest.php @@ -309,41 +309,49 @@ final class CoreLibsCombinedDateTimeTest extends TestCase '2020-12-12', '2021-12-12', -1, + null, ], 'dates equal' => [ '2020-12-12', '2020-12-12', 0, + null, ], 'second date smaller' => [ '2021-12-12', '2020-12-12', - 1 + 1, + null, ], 'dates equal with different time' => [ '2020-12-12 12:12:12', '2020-12-12 13:13:13', 0, + null, ], 'invalid dates --' => [ '--', '--', - false + false, + 'UnexpectedValueException', ], 'empty dates' => [ '', '', - false + false, + 'UnexpectedValueException' ], 'invalid dates' => [ 'not a date', 'not a date either', false, + 'UnexpectedValueException' ], 'out of bound dates' => [ '1900-1-1', '9999-12-31', - -1 + -1, + null, ] ]; } @@ -355,51 +363,61 @@ final class CoreLibsCombinedDateTimeTest extends TestCase '2020-12-12', '2021-12-12', -1, + null, ], 'dates equal no timestamp' => [ '2020-12-12', '2020-12-12', 0, + null, ], 'second date smaller no timestamp' => [ '2021-12-12', '2020-12-12', - 1 + 1, + null, ], 'date equal first time smaller' => [ '2020-12-12 12:12:12', '2020-12-12 13:13:13', -1, + null, ], 'date equal time equal' => [ '2020-12-12 12:12:12', '2020-12-12 12:12:12', 0, + null, ], 'date equal second time smaller' => [ '2020-12-12 13:13:13', '2020-12-12 12:12:12', 1, + null, ], 'valid date invalid time' => [ '2020-12-12 13:99:13', '2020-12-12 12:12:99', false, + 'UnexpectedValueException' ], 'invalid datetimes --' => [ '--', '--', false, + 'UnexpectedValueException' ], 'empty datetimess' => [ '', '', false, + 'UnexpectedValueException' ], 'invalid datetimes' => [ 'not a date', 'not a date either', false, + 'UnexpectedValueException' ], ]; } @@ -616,8 +634,11 @@ final class CoreLibsCombinedDateTimeTest extends TestCase * @param int|bool $expected * @return void */ - public function testCompareDate(string $input_a, string $input_b, $expected): void + public function testCompareDate(string $input_a, string $input_b, int|bool $expected, ?string $exception): void { + if ($expected === false) { + $this->expectException($exception); + } $this->assertEquals( $expected, \CoreLibs\Combined\DateTime::compareDate($input_a, $input_b) @@ -636,8 +657,11 @@ final class CoreLibsCombinedDateTimeTest extends TestCase * @param int|bool $expected * @return void */ - public function testCompareDateTime(string $input_a, string $input_b, $expected): void + public function testCompareDateTime(string $input_a, string $input_b, int|bool $expected, ?string $exception): void { + if ($expected === false) { + $this->expectException($exception); + } $this->assertEquals( $expected, \CoreLibs\Combined\DateTime::compareDateTime($input_a, $input_b) diff --git a/4dev/tests/Create/CoreLibsCreateSessionTest.php b/4dev/tests/Create/CoreLibsCreateSessionTest.php index ba97d1a4..90c857ae 100644 --- a/4dev/tests/Create/CoreLibsCreateSessionTest.php +++ b/4dev/tests/Create/CoreLibsCreateSessionTest.php @@ -30,8 +30,9 @@ final class CoreLibsCreateSessionTest extends TestCase // setSessionName: true/false, // checkActiveSession: true/false, [1st call, 2nd call] // getSessionId: string or false - // 3: exepcted name (session) - // 4: expected error string + // 3: exepcted name (session)] + // 4: Exception thrown on error + // 5: expected error string return [ 'session parameter' => [ 'sessionNameParameter', @@ -44,7 +45,8 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => '1234abcd4567' ], 'sessionNameParameter', - '' + null, + '', ], 'session globals' => [ 'sessionNameGlobals', @@ -57,7 +59,8 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => '1234abcd4567' ], 'sessionNameGlobals', - '' + null, + '', ], 'session name default' => [ '', @@ -70,7 +73,8 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => '1234abcd4567' ], '', - '' + null, + '', ], // error checks // 1: we are in cli @@ -85,6 +89,7 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => '1234abcd4567' ], '', + 'RuntimeException', '[SESSION] No sessions in php cli' ], // 2: session disabled @@ -99,6 +104,7 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => '1234abcd4567' ], '', + 'RuntimeException', '[SESSION] Sessions are disabled' ], // 3: invalid session name: string @@ -113,6 +119,7 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => '1234abcd4567' ], '', + 'UnexpectedValueException', '[SESSION] Invalid session name: 1invalid$session#;' ], // 3: invalid session name: only numbers @@ -127,6 +134,7 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => '1234abcd4567' ], '', + 'UnexpectedValueException', '[SESSION] Invalid session name: 123' ], // 3: invalid session name: invalid name short @@ -143,6 +151,7 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => '1234abcd4567' ], '', + 'RuntimeException', '[SESSION] Failed to activate session' ], // 5: get session id return false @@ -157,6 +166,7 @@ final class CoreLibsCreateSessionTest extends TestCase 'getSessionId' => false ], '', + 'UnexpectedValueException', '[SESSION] getSessionId did not return a session id' ], ]; @@ -173,6 +183,7 @@ final class CoreLibsCreateSessionTest extends TestCase * @param string $type * @param array $mock_data * @param string $expected + * @param string|null $exception * @param string $expected_error * @return void */ @@ -181,6 +192,7 @@ final class CoreLibsCreateSessionTest extends TestCase string $type, array $mock_data, string $expected, + ?string $exception, string $expected_error ): void { // override expected @@ -224,6 +236,10 @@ final class CoreLibsCreateSessionTest extends TestCase // regex for session id $ression_id_regex = "/^\w+$/"; + if ($exception !== null) { + $this->expectException($exception); + } + unset($GLOBALS['SET_SESSION_NAME']); $session_id = ''; switch ($type) { @@ -253,13 +269,6 @@ final class CoreLibsCreateSessionTest extends TestCase $expected, $session_mock->getSessionName() ); - } else { - // false checks - $this->assertEquals( - $expected_error, - $session_mock->getErrorStr(), - 'error assert' - ); } } diff --git a/www/admin/class_test.image.php b/www/admin/class_test.image.php index cabc8814..d2be61c6 100644 --- a/www/admin/class_test.image.php +++ b/www/admin/class_test.image.php @@ -109,6 +109,13 @@ foreach ($images as $image) { echo "
"; } +// errros +try { + Image::createThumbnailSimple('', $thumb_width, 0, $cache_folder, $web_folder); +} catch (\UnexpectedValueException $e) { + print "Message:
" . $e->getMessage() . "
" . $e . "
"; +} + print ""; // __END__ diff --git a/www/lib/CoreLibs/Combined/DateTime.php b/www/lib/CoreLibs/Combined/DateTime.php index 27917886..fd6f84ef 100644 --- a/www/lib/CoreLibs/Combined/DateTime.php +++ b/www/lib/CoreLibs/Combined/DateTime.php @@ -105,49 +105,48 @@ class DateTime bool $show_micro = true ): string { // check if the timestamp has any h/m/s/ms inside, if yes skip - if (!preg_match("/(h|m|s|ms)/", (string)$timestamp)) { - list($timestamp, $ms) = array_pad(explode('.', (string)round((float)$timestamp, 4)), 2, null); - // if negative remember - $negative = false; - if ((int)$timestamp < 0) { - $negative = true; - } - $timestamp = abs((float)$timestamp); - $timegroups = [86400, 3600, 60, 1]; - $labels = ['d', 'h', 'm', 's']; - $time_string = ''; - // if timestamp is zero, return zero string - if ($timestamp == 0) { - $time_string = '0s'; - } else { - for ($i = 0, $iMax = count($timegroups); $i < $iMax; $i++) { - $output = floor((float)$timestamp / $timegroups[$i]); - $timestamp = (float)$timestamp % $timegroups[$i]; - // output has days|hours|min|sec - if ($output || $time_string) { - $time_string .= $output . $labels[$i] . (($i + 1) != count($timegroups) ? ' ' : ''); - } - } - } - // only add ms if we have an ms value - if ($ms !== null) { - // if we have ms and it has leading zeros, remove them, but only if it is nut just 0 - $ms = preg_replace("/^0+(\d+)$/", '${1}', $ms); - if (!is_string($ms) || empty($ms)) { - $ms = '0'; - } - // add ms if there - if ($show_micro) { - $time_string .= ' ' . $ms . 'ms'; - } elseif (!$time_string) { - $time_string .= $ms . 'ms'; - } - } - if ($negative) { - $time_string = '-' . $time_string; - } + if (preg_match("/(h|m|s|ms)/", (string)$timestamp)) { + return (string)$timestamp; + } + list($timestamp, $ms) = array_pad(explode('.', (string)round((float)$timestamp, 4)), 2, null); + // if negative remember + $negative = false; + if ((int)$timestamp < 0) { + $negative = true; + } + $timestamp = abs((float)$timestamp); + $timegroups = [86400, 3600, 60, 1]; + $labels = ['d', 'h', 'm', 's']; + $time_string = ''; + // if timestamp is zero, return zero string + if ($timestamp == 0) { + $time_string = '0s'; } else { - $time_string = $timestamp; + for ($i = 0, $iMax = count($timegroups); $i < $iMax; $i++) { + $output = floor((float)$timestamp / $timegroups[$i]); + $timestamp = (float)$timestamp % $timegroups[$i]; + // output has days|hours|min|sec + if ($output || $time_string) { + $time_string .= $output . $labels[$i] . (($i + 1) != count($timegroups) ? ' ' : ''); + } + } + } + // only add ms if we have an ms value + if ($ms !== null) { + // if we have ms and it has leading zeros, remove them, but only if it is nut just 0 + $ms = preg_replace("/^0+(\d+)$/", '${1}', $ms); + if (!is_string($ms) || empty($ms)) { + $ms = '0'; + } + // add ms if there + if ($show_micro) { + $time_string .= ' ' . $ms . 'ms'; + } elseif (!$time_string) { + $time_string .= $ms . 'ms'; + } + } + if ($negative) { + $time_string = '-' . $time_string; } return (string)$time_string; } @@ -162,37 +161,36 @@ class DateTime public static function stringToTime(string|int|float $timestring): string|int|float { $timestamp = 0; - if (preg_match("/(d|h|m|s|ms)/", (string)$timestring)) { - $timestring = (string)$timestring; - // pos for preg match read + multiply factor - $timegroups = [2 => 86400, 4 => 3600, 6 => 60, 8 => 1]; - $matches = []; - // if start with -, strip and set negative - $negative = false; - if (preg_match("/^-/", $timestring)) { - $negative = true; - $timestring = substr($timestring, 1); - } - // preg match: 0: full string - // 2, 4, 6, 8 are the to need values - preg_match("/^((\d+)d ?)?((\d+)h ?)?((\d+)m ?)?((\d+)s ?)?((\d+)ms)?$/", $timestring, $matches); - // multiply the returned matches and sum them up. the last one (ms) is added with . - foreach ($timegroups as $i => $time_multiply) { - if (isset($matches[$i]) && is_numeric($matches[$i])) { - $timestamp += (float)$matches[$i] * $time_multiply; - } - } - if (isset($matches[10]) && is_numeric($matches[10])) { - $timestamp .= '.' . $matches[10]; - } - if ($negative) { - // cast to flaot so we can do a negative multiplication - $timestamp = (float)$timestamp * -1; - } - return $timestamp; - } else { + if (!preg_match("/(d|h|m|s|ms)/", (string)$timestring)) { return $timestring; } + $timestring = (string)$timestring; + // pos for preg match read + multiply factor + $timegroups = [2 => 86400, 4 => 3600, 6 => 60, 8 => 1]; + $matches = []; + // if start with -, strip and set negative + $negative = false; + if (preg_match("/^-/", $timestring)) { + $negative = true; + $timestring = substr($timestring, 1); + } + // preg match: 0: full string + // 2, 4, 6, 8 are the to need values + preg_match("/^((\d+)d ?)?((\d+)h ?)?((\d+)m ?)?((\d+)s ?)?((\d+)ms)?$/", $timestring, $matches); + // multiply the returned matches and sum them up. the last one (ms) is added with . + foreach ($timegroups as $i => $time_multiply) { + if (isset($matches[$i]) && is_numeric($matches[$i])) { + $timestamp += (float)$matches[$i] * $time_multiply; + } + } + if (isset($matches[10]) && is_numeric($matches[10])) { + $timestamp .= '.' . $matches[10]; + } + if ($negative) { + // cast to flaot so we can do a negative multiplication + $timestamp = (float)$timestamp * -1; + } + return $timestamp; } /** @@ -323,21 +321,21 @@ class DateTime * * @param string $start_date start date string in YYYY-MM-DD * @param string $end_date end date string in YYYY-MM-DD - * @return int|bool false on error - * or int -1 (se) as difference + * @return int int -1 (se) as difference + * @throws \UnexpectedValueException On empty start/end values */ public static function compareDate(string $start_date, string $end_date): int|bool { // pre check for empty or wrong - if ($start_date == '--' || $end_date == '--' || !$start_date || !$end_date) { - return false; + if ($start_date == '--' || $end_date == '--' || empty($start_date) || empty($end_date)) { + throw new \UnexpectedValueException('Start or End date not set or are just "--"'); } // if invalid, quit if (($start_timestamp = strtotime($start_date)) === false) { - return false; + throw new \UnexpectedValueException("Error parsing start date through strtotime()"); } if (($end_timestamp = strtotime($end_date)) === false) { - return false; + throw new \UnexpectedValueException("Error parsing end date through strtotime()"); } // convert anything to Y-m-d and then to timestamp // this is to remove any time parts @@ -350,8 +348,6 @@ class DateTime return 0; } elseif ($start_timestamp > $end_timestamp) { return 1; - } else { - return false; } } @@ -366,21 +362,21 @@ class DateTime * * @param string $start_datetime start date/time in YYYY-MM-DD HH:mm:ss * @param string $end_datetime end date/time in YYYY-MM-DD HH:mm:ss - * @return int|bool false for error - * or -1 (se) as difference + * @return int -1 (se) as difference + * @throws \UnexpectedValueException On empty start/end values */ public static function compareDateTime(string $start_datetime, string $end_datetime): int|bool { // pre check for empty or wrong - if ($start_datetime == '--' || $end_datetime == '--' || !$start_datetime || !$end_datetime) { - return false; + if ($start_datetime == '--' || $end_datetime == '--' || empty($start_datetime) || empty($end_datetime)) { + throw new \UnexpectedValueException('Start or end timestamp not set or are just "--"'); } // quit if invalid timestamp if (($start_timestamp = strtotime($start_datetime)) === false) { - return false; + throw new \UnexpectedValueException("Error parsing start timestamp through strtotime()"); } if (($end_timestamp = strtotime($end_datetime)) === false) { - return false; + throw new \UnexpectedValueException("Error parsing end timestamp through strtotime()"); } // compare, or return false if ($start_timestamp < $end_timestamp) { @@ -389,8 +385,6 @@ class DateTime return 0; } elseif ($start_timestamp > $end_timestamp) { return 1; - } else { - return false; } } diff --git a/www/lib/CoreLibs/Create/Session.php b/www/lib/CoreLibs/Create/Session.php index f7a0f7f7..a5ad2309 100644 --- a/www/lib/CoreLibs/Create/Session.php +++ b/www/lib/CoreLibs/Create/Session.php @@ -15,9 +15,6 @@ namespace CoreLibs\Create; class Session { - /** @var string list for errors */ - private string $session_intern_error_str = ''; - /** * init a session, if array is empty or array does not have session_name set * then no auto init is run @@ -71,17 +68,6 @@ class Session return true; } - /** - * Return set error string, empty if none set - * Error strings are only set in the startSession method - * - * @return string Last error string - */ - public function getErrorStr(): string - { - return $this->session_intern_error_str; - } - /** * check if session name is valid * @@ -120,13 +106,11 @@ class Session { // we can't start sessions on command line if ($this->checkCliStatus()) { - $this->session_intern_error_str = '[SESSION] No sessions in php cli'; - return false; + throw new \RuntimeException('[SESSION] No sessions in php cli'); } // if session are OFF if ($this->getSessionStatus() === PHP_SESSION_DISABLED) { - $this->session_intern_error_str = '[SESSION] Sessions are disabled'; - return false; + throw new \RuntimeException('[SESSION] Sessions are disabled'); } // session_status // initial the session if there is no session running already @@ -139,8 +123,7 @@ class Session if (!empty($session_name)) { // invalid session name, abort if (!$this->checkValidSessionName($session_name)) { - $this->session_intern_error_str = '[SESSION] Invalid session name: ' . $session_name; - return false; + throw new \UnexpectedValueException('[SESSION] Invalid session name: ' . $session_name); } $this->setSessionName($session_name); } @@ -149,11 +132,10 @@ class Session } // if we still have no active session if (!$this->checkActiveSession()) { - $this->session_intern_error_str = '[SESSION] Failed to activate session'; - return false; + throw new \RuntimeException('[SESSION] Failed to activate session'); } if (false === ($session_id = $this->getSessionId())) { - $this->session_intern_error_str = '[SESSION] getSessionId did not return a session id'; + throw new \UnexpectedValueException('[SESSION] getSessionId did not return a session id'); } return $session_id; } diff --git a/www/lib/CoreLibs/Debug/FileWriter.php b/www/lib/CoreLibs/Debug/FileWriter.php index c7105bbf..d51f6923 100644 --- a/www/lib/CoreLibs/Debug/FileWriter.php +++ b/www/lib/CoreLibs/Debug/FileWriter.php @@ -63,7 +63,7 @@ class FileWriter * * @param string $string string to write to the file * @param boolean $enter default true, if set adds a linebreak \n at the end - * @return bool True for log written, false for not wirrten + * @return bool True for log written, false for not written */ public static function fdebug(string $string, bool $enter = true): bool { @@ -75,7 +75,7 @@ class FileWriter empty(self::$debug_folder) && defined('BASE') && defined('LOG') ) { - /** @deprecated Do not use this anymore, define path with fsetFolder */ + /** @deprecated Do not use this anymore, define path with festFolder */ trigger_error( 'fsetFolder must be set first. Setting via LOG_FILE_ID and LOG constants is deprecated', E_USER_DEPRECATED diff --git a/www/lib/CoreLibs/Output/Image.php b/www/lib/CoreLibs/Output/Image.php index f530ec01..a7d494fa 100644 --- a/www/lib/CoreLibs/Output/Image.php +++ b/www/lib/CoreLibs/Output/Image.php @@ -8,6 +8,8 @@ declare(strict_types=1); namespace CoreLibs\Output; +use Exception; + class Image { /** @@ -23,7 +25,8 @@ class Image * if empty ROOT is choosen * @param string $cache_source cache path, if not given TMP is used * @param bool $clear_cache if set to true, will create thumb all the tame - * @return string|false thumbnail name, or false for error + * @return string thumbnail name + * @throws \RuntimeException no ImageMagick convert command found */ public static function createThumbnail( string $pic, @@ -33,7 +36,7 @@ class Image string $path = '', string $cache_source = '', bool $clear_cache = false - ): string|false { + ): string { // get image type flags $image_types = [ 0 => 'UNKOWN-IMAGE', @@ -41,7 +44,7 @@ class Image 2 => 'jpg', 3 => 'png' ]; - $return_data = false; + $return_data = ''; $CONVERT = ''; // if CONVERT is not defined, abort /** @phan-suppress-next-line PhanUndeclaredConstant */ @@ -49,7 +52,7 @@ class Image /** @phan-suppress-next-line PhanUndeclaredConstant */ $CONVERT = CONVERT; } else { - return $return_data; + throw new \RuntimeException('CONVERT set binary is not executable or CONVERT is not defined'); } if (!empty($cache_source)) { $tmp_src = $cache_source; @@ -69,72 +72,7 @@ class Image $pic = $tmp[(count($tmp) - 1)]; } // does this picture exist and is it a picture - if (file_exists($filename) && is_file($filename)) { - [$width, $height, $type] = getimagesize($filename) ?: [0, 0, 0]; - $convert_prefix = ''; - $create_file = false; - $delete_filename = ''; - // check if we can skip the PDF creation: if we have size, if do not have type, we assume type png - if (!$type) { - $check_thumb = $tmp_src . 'thumb_' . $pic . '_' . $size_x . 'x' . $size_y . '.' . $image_types[3]; - if (!is_file($check_thumb)) { - $create_file = true; - } else { - $type = 3; - } - } - // if type is not in the list, but returns as PDF, we need to convert to JPEG before - if (!$type) { - $output = []; - $return = null; - // is this a PDF, if no, return from here with nothing - $convert_prefix = 'png:'; - # TEMP convert to PNG, we then override the file name - $convert_string = $CONVERT . ' ' . $filename . ' ' . $convert_prefix . $filename . '_TEMP'; - $status = exec($convert_string, $output, $return); - $filename .= '_TEMP'; - // for delete, in case we need to glob - $delete_filename = $filename; - // find file, if we can't find base name, use -0 as the first one (ignore other pages in multiple ones) - if (!is_file($filename)) { - $filename .= '-0'; - } - [$width, $height, $type] = getimagesize($filename) ?: [0, 0, 0]; - } - // if no size given, set size to original - if (!$size_x || $size_x < 1) { - $size_x = $width; - } - if (!$size_y || $size_y < 1) { - $size_y = $height; - } - $thumb = 'thumb_' . $pic . '_' . $size_x . 'x' . $size_y . '.' . $image_types[$type]; - $thumbnail = $tmp_src . $thumb; - // check if we already have this picture converted - if (!is_file($thumbnail) || $clear_cache == true) { - // convert the picture - if ($width > $size_x) { - $convert_string = $CONVERT . ' -geometry ' . $size_x . 'x ' . $filename . ' ' . $thumbnail; - $status = exec($convert_string, $output, $return); - // get the size of the converted data, if converted - if (is_file($thumbnail)) { - [$width, $height, $type] = getimagesize($thumbnail) ?: [0, 0, 0]; - } - } - if ($height > $size_y) { - $convert_string = $CONVERT . ' -geometry x' . $size_y . ' ' . $filename . ' ' . $thumbnail; - $status = exec($convert_string, $output, $return); - } - } - if (!is_file($thumbnail)) { - copy($filename, $thumbnail); - } - $return_data = $thumb; - // if we have a delete filename, delete here with glob - if ($delete_filename) { - array_map('unlink', glob($delete_filename . '*') ?: []); - } - } else { + if (!file_exists($filename) || !is_file($filename)) { if (!empty($dummy) && strstr($dummy, '/') === false) { // check if we have the "dummy" image flag set $filename = PICTURES . ICONS . strtoupper($dummy) . ".png"; @@ -142,11 +80,77 @@ class Image if (!empty($dummy) && file_exists($filename) && is_file($filename)) { $return_data = $filename; } else { - $return_data = false; + throw new \Exception('Could not set dummy return file: ' . $dummy . ' in ' . $filename); } } else { - $filename = $dummy; + $return_data = $dummy; } + return $return_data; + } + // resize image + [$width, $height, $type] = getimagesize($filename) ?: [0, 0, 0]; + $convert_prefix = ''; + $create_file = false; + $delete_filename = ''; + // check if we can skip the PDF creation: if we have size, if do not have type, we assume type png + if (!$type) { + $check_thumb = $tmp_src . 'thumb_' . $pic . '_' . $size_x . 'x' . $size_y . '.' . $image_types[3]; + if (!is_file($check_thumb)) { + $create_file = true; + } else { + $type = 3; + } + } + // if type is not in the list, but returns as PDF, we need to convert to JPEG before + if (!$type) { + $output = []; + $return = null; + // is this a PDF, if no, return from here with nothing + $convert_prefix = 'png:'; + # TEMP convert to PNG, we then override the file name + $convert_string = $CONVERT . ' ' . $filename . ' ' . $convert_prefix . $filename . '_TEMP'; + $status = exec($convert_string, $output, $return); + $filename .= '_TEMP'; + // for delete, in case we need to glob + $delete_filename = $filename; + // find file, if we can't find base name, use -0 as the first one (ignore other pages in multiple ones) + if (!is_file($filename)) { + $filename .= '-0'; + } + [$width, $height, $type] = getimagesize($filename) ?: [0, 0, 0]; + } + // if no size given, set size to original + if (!$size_x || $size_x < 1) { + $size_x = $width; + } + if (!$size_y || $size_y < 1) { + $size_y = $height; + } + $thumb = 'thumb_' . $pic . '_' . $size_x . 'x' . $size_y . '.' . $image_types[$type]; + $thumbnail = $tmp_src . $thumb; + // check if we already have this picture converted + if (!is_file($thumbnail) || $clear_cache == true) { + // convert the picture + if ($width > $size_x) { + $convert_string = $CONVERT . ' -geometry ' . $size_x . 'x ' . $filename . ' ' . $thumbnail; + $status = exec($convert_string, $output, $return); + // get the size of the converted data, if converted + if (is_file($thumbnail)) { + [$width, $height, $type] = getimagesize($thumbnail) ?: [0, 0, 0]; + } + } + if ($height > $size_y) { + $convert_string = $CONVERT . ' -geometry x' . $size_y . ' ' . $filename . ' ' . $thumbnail; + $status = exec($convert_string, $output, $return); + } + } + if (!is_file($thumbnail)) { + copy($filename, $thumbnail); + } + $return_data = $thumb; + // if we have a delete filename, delete here with glob + if ($delete_filename) { + array_map('unlink', glob($delete_filename . '*') ?: []); } return $return_data; } @@ -173,7 +177,9 @@ class Image * set to false to not use (default true) * to use quick but less nice version * @param int $jpeg_quality default 80, set image quality for jpeg only - * @return string|false thumbnail with path + * @return string thumbnail with path + * @throws \UnexpectedValueException input values for filename or cache_folder are wrong + * @throws \RuntimeException convert (gd) failed */ public static function createThumbnailSimple( string $filename, @@ -185,8 +191,9 @@ class Image bool $use_cache = true, bool $high_quality = true, int $jpeg_quality = 80 - ): string|false { + ): string { $thumbnail = false; + $exception_message = 'Could not create thumbnail'; // $this->debug('IMAGE PREPARE', "FILE: $filename (exists " // .(string)file_exists($filename)."), WIDTH: $thumb_width, HEIGHT: $thumb_height"); if ( @@ -210,12 +217,17 @@ class Image } // check that input image exists and is either jpeg or png // also fail if the basic CACHE folder does not exist at all - if ( - !file_exists($filename) || - !is_dir($cache_folder) || - !is_writable($cache_folder) - ) { - return $thumbnail; + if (!file_exists($filename)) { + // return $thumbnail; + throw new \UnexpectedValueException('Missing image file: ' . $filename); + } + if (!is_dir($cache_folder)) { + // return $thumbnail; + throw new \UnexpectedValueException('Cache folder is not a directory: ' . $cache_folder); + } + if (!is_writable($cache_folder)) { + // return $thumbnail; + throw new \UnexpectedValueException('Cache folder is not writeable: ' . $cache_folder); } // $this->debug('IMAGE PREPARE', "FILENAME OK, THUMB WIDTH/HEIGHT OK"); [$inc_width, $inc_height, $img_type] = getimagesize($filename) ?: [0, 0, null]; @@ -347,6 +359,7 @@ class Image imagedestroy($source); imagedestroy($thumb); } else { + $exception_message = 'Invalid source image file. Only JPEG/PNG are allowed: ' . $filename; $thumbnail = false; } } @@ -430,7 +443,11 @@ class Image // add web path $thumbnail = $thumbnail_web_path . $thumbnail; } - // either return false or the thumbnail name + output path web + // if still false -> throw exception + if ($thumbnail === false) { + throw new \RuntimeException($exception_message); + } + // else return the thumbnail name + output path web return $thumbnail; } diff --git a/www/lib/CoreLibs/Security/SymmetricEncryption.php b/www/lib/CoreLibs/Security/SymmetricEncryption.php index b106cea1..2586e94a 100644 --- a/www/lib/CoreLibs/Security/SymmetricEncryption.php +++ b/www/lib/CoreLibs/Security/SymmetricEncryption.php @@ -27,6 +27,7 @@ class SymmetricEncryption * @param string $message Message to encrypt * @param string $key Encryption key (as hex string) * @return string + * @throws \Exception * @throws \RangeException */ public static function encrypt(string $message, string $key): string @@ -34,7 +35,7 @@ class SymmetricEncryption try { $key = CreateKey::hex2bin($key); } catch (SodiumException $e) { - throw new \Exception('Invalid hex key'); + throw new \UnexpectedValueException('Invalid hex key'); } if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { throw new \RangeException( @@ -84,10 +85,10 @@ class SymmetricEncryption $key ); } catch (SodiumException $e) { - throw new \Exception('Invalid ciphertext (too short)'); + throw new \UnexpectedValueException('Invalid ciphertext (too short)'); } if (!is_string($plain)) { - throw new \Exception('Invalid Key'); + throw new \UnexpectedValueException('Invalid Key'); } sodium_memzero($ciphertext); sodium_memzero($key);