diff --git a/src/config-sample.php b/src/config-sample.php index 3f0e3faec..e3b658345 100644 --- a/src/config-sample.php +++ b/src/config-sample.php @@ -1,5 +1,6 @@ { - if (enableLoader && loader) { - if (loader._fadeInTimeout) { - clearTimeout(loader._fadeInTimeout); - } - document.body.removeChild(loader); - loader = null; - } - if (response.error) { const error = new Error(response.error.message || 'Unknown API error'); error.code = response.error.code; @@ -417,14 +408,6 @@ const API = { .catch((error) => { clearTimeout(timeoutId); - if (enableLoader && loader) { - if (loader._fadeInTimeout) { - clearTimeout(loader._fadeInTimeout); - } - document.body.removeChild(loader); - loader = null; - } - let errorObj; if (error.name === 'AbortError') { errorObj = { @@ -453,6 +436,17 @@ const API = { normalizedError.code = errorObj.code; throw normalizedError; } + }) + .finally(() => { + if (enableLoader && loader) { + if (loader._fadeInTimeout) { + clearTimeout(loader._fadeInTimeout); + } + if (document.body.contains(loader)) { + document.body.removeChild(loader); + } + loader = null; + } }); }, diff --git a/src/library/Api/Abstract.php b/src/library/Api/Abstract.php index 66ccbf19d..9f5d6c993 100644 --- a/src/library/Api/Abstract.php +++ b/src/library/Api/Abstract.php @@ -1,5 +1,6 @@ listeners[$name] = []; } - return (bool) (is_countable($this->listeners[$name]) ? count($this->listeners[$name]) : 0); + return (bool) \FOSSBilling\Tools::safeCount($this->listeners[$name]); } /** diff --git a/src/library/Box/EventManager.php b/src/library/Box/EventManager.php index fc2dd9a86..3352f5829 100644 --- a/src/library/Box/EventManager.php +++ b/src/library/Box/EventManager.php @@ -1,5 +1,6 @@ maskParams($params); if (($priority = array_search($priority, $this->_priorities)) !== false) { - switch (is_countable($params) ? count($params) : 0) { + switch (\FOSSBilling\Tools::safeCount($params)) { case 0: throw new FOSSBilling\Exception('Missing log message'); case 1: diff --git a/src/library/Box/LogDb.php b/src/library/Box/LogDb.php index 632487d42..6a38a6fa0 100644 --- a/src/library/Box/LogDb.php +++ b/src/library/Box/LogDb.php @@ -1,5 +1,6 @@ - * - * @www.inchoo.net - */ -class Box_Paginator extends Paginator -{ -} - -class Paginator -{ - /** - * @var int total number of pages - */ - protected $numPages; - - /** - * @var int offset - */ - protected $offset; - - /** - * @var array range - */ - protected $range; - - /** - * @var string currentUrl - */ - protected $currentUrl; - - /** - * @param int $itemsCount - * @param int $currentPage - * @param int $limit - * @param int $midRange - */ - public function __construct(protected $itemsCount = 0, protected $currentPage = 1, protected $limit = 20, protected $midRange = 7) - { - // Set defaults - $this->setDefaults(); - - // Calculate number of pages total - $this->getInternalNumPages(); - - // Calculate first shown item on current page - $this->calculateOffset(); - $this->calculateRange(); - } - - private function calculateRange(): void - { - $startRange = $this->currentPage - floor($this->midRange / 2); - $endRange = $this->currentPage + floor($this->midRange / 2); - - if ($startRange <= 0) { - $endRange += abs($startRange) + 1; - $startRange = 1; - } - - if ($endRange > $this->numPages) { - $endRange = $this->numPages; - $startRange = $endRange - $this->numPages + 1; - } - - $this->range = range($startRange, $endRange); - } - - private function setDefaults(): void - { - // If currentPage is set to null or is set to 0 or less - // set it to default (1) - if ($this->currentPage == null || $this->currentPage < 1) { - $this->currentPage = 1; - } - // if limit is set to null set it to default (20) - if ($this->limit == null) { - $this->limit = 20; - // if limit is any number less than 1 then set it to 0 for displaying - // items without limit - } elseif ($this->limit < 1) { - $this->limit = 0; - } - } - - private function getInternalNumPages(): void - { - // If limit is set to 0 or set to number bigger then total items count - // display all in one page - if ($this->limit < 1 || $this->limit > $this->itemsCount) { - $this->numPages = 1; - } else { - // Calculate rest numbers from dividing operation so we can add one - // more page for this items - $restItemsNum = $this->itemsCount % $this->limit; - // if rest items > 0 then add one more page else just divide items - // by limit - $this->numPages = $restItemsNum > 0 ? intval($this->itemsCount / $this->limit) + 1 : intval($this->itemsCount / $this->limit); - } - } - - private function calculateOffset(): void - { - // Calculet offset for items based on current page number - $this->offset = ($this->currentPage - 1) * $this->limit; - } - - /** - * @return int number of pages - */ - public function getNumPages() - { - return $this->numPages; - } - - /** - * @return int current page - */ - public function getCurrentPage() - { - return $this->currentPage; - } - - /** - * @return string current url - */ - public function getCurrentUrl() - { - return $this->currentUrl; - } - - /** - * @return int limit items per page - */ - public function getLimit() - { - return $this->limit; - } - - /** - * @return int offset - */ - public function getOffset() - { - return $this->offset; - } - - /** - * @return array range - */ - public function getRange() - { - return $this->range; - } - - /** - * @return int mid range - */ - public function getMidRange() - { - return $this->midRange; - } - - public function getStartingPoint() - { - $arr = $this->getRange(); - - return reset($arr); - } - - public function getEndingPoint() - { - $arr = $this->getRange(); - - return end($arr); - } - - public function toArray(): array - { - return [ - 'currentpage' => $this->getCurrentPage(), - 'numpages' => $this->getNumPages(), - 'midrange' => $this->getMidRange(), - 'range' => $this->getRange(), - 'start' => $this->getStartingPoint(), - 'end' => $this->getEndingPoint(), - ]; - } -} diff --git a/src/library/Box/Period.php b/src/library/Box/Period.php index 94399b5c9..b130f8480 100644 --- a/src/library/Box/Period.php +++ b/src/library/Box/Period.php @@ -1,5 +1,6 @@ di['request']; + + $page ??= filter_var($request->query->get($pageParam), FILTER_VALIDATE_INT, ['options' => ['default' => 1]]); + $perPage ??= filter_var($request->query->get($perPageParam), FILTER_VALIDATE_INT, ['options' => ['default' => $this->getDefaultPerPage()]]); + + if ($page < 1) { + throw new InformationException("Page number ($pageParam) must be a positive integer."); + } + if ($perPage < 1) { + throw new InformationException("The number of items per page ($perPageParam) must be a positive integer."); + } + if ($perPage > self::MAX_PER_PAGE) { + throw new InformationException("The number of items per page ($perPageParam) is too large. Please specify a smaller number."); + } + + return [(int) $page, (int) $perPage]; + } + + /** + * Build the standard paginated response array. + */ + private function buildPaginatedResponse(int $page, int $perPage, int $total, array $list): array + { + return [ + 'pages' => $total > 0 ? (int) ceil($total / $perPage) : 0, + 'page' => $page, + 'per_page' => $perPage, + 'total' => $total, + 'list' => $list, + ]; + } + /** * Paginate results from a Doctrine QueryBuilder. * @@ -67,23 +106,11 @@ class Pagination implements InjectionAwareInterface */ public function paginateDoctrineQuery(QueryBuilder $qb, ?int $perPage = null, ?int $page = null, string $pageParam = 'page', string $perPageParam = 'per_page'): array { - $request = $this->di['request']; + [$page, $perPage] = $this->resolvePagination($perPage, $page, $pageParam, $perPageParam); + $serializer = new Serializer([new ObjectNormalizer()]); $paginator = new DoctrinePaginator($qb, true); - $page ??= filter_var($request->query->get($pageParam), FILTER_VALIDATE_INT, ['options' => ['default' => 1]]); - $perPage ??= filter_var($request->query->get($perPageParam), FILTER_VALIDATE_INT, ['options' => ['default' => $this->getDefaultPerPage()]]); - - if ($page < 1) { - throw new InformationException("Page number ($pageParam) must be a positive integer."); - } - if ($perPage < 1) { - throw new InformationException("The number of items per page ($perPageParam) must be a positive integer."); - } - if ($perPage > self::MAX_PER_PAGE) { - throw new InformationException("The number of items per page ($perPageParam) is too large. Please specify a smaller number."); - } - $offset = ($page - 1) * $perPage; $qb->setFirstResult($offset) ->setMaxResults($perPage); @@ -95,18 +122,11 @@ class Pagination implements InjectionAwareInterface if ($entity instanceof ApiArrayInterface) { $list[] = $entity->toApiArray(); } else { - // fallback: use serializer to normalize entity $list[] = $serializer->normalize($entity); } } - return [ - 'pages' => $total > 0 ? (int) ceil($total / $perPage) : 0, - 'page' => $page, - 'per_page' => $perPage, - 'total' => $total, - 'list' => $list, - ]; + return $this->buildPaginatedResponse($page, $perPage, $total, $list); } /** @@ -131,27 +151,13 @@ class Pagination implements InjectionAwareInterface */ public function getPaginatedResultSet(string $query, array $params = [], ?int $perPage = null, ?int $page = null, string $pageParam = 'page', string $perPageParam = 'per_page'): array { - $request = $this->di['request']; - - $page ??= filter_var($request->query->get($pageParam), FILTER_VALIDATE_INT, ['options' => ['default' => 1]]); - $perPage ??= filter_var($request->query->get($perPageParam), FILTER_VALIDATE_INT, ['options' => ['default' => $this->getDefaultPerPage()]]); - - if ($page < 1) { - throw new InformationException("Page number ($pageParam) must be a positive integer."); - } - if ($perPage < 1) { - throw new InformationException("The number of items per page ($perPageParam) must be a positive integer."); - } - if ($perPage > self::MAX_PER_PAGE) { - throw new InformationException("The number of items per page ($perPageParam) is too large. Please specify a smaller number."); - } + [$page, $perPage] = $this->resolvePagination($perPage, $page, $pageParam, $perPageParam); $offset = ($page - 1) * $perPage; $paginatedQuery = $query . sprintf(' LIMIT %u, %u', $offset, $perPage); $result = $this->di['db']->getAll($paginatedQuery, $params); - // Attempt to construct count query more reliably $fromPos = stripos($query, 'FROM'); if ($fromPos === false) { throw new InformationException('Invalid SQL query. Missing FROM clause.'); @@ -161,12 +167,6 @@ class Pagination implements InjectionAwareInterface $countQuery = 'SELECT COUNT(1) FROM (' . $query . ') AS sub'; $total = (int) $this->di['db']->getCell($countQuery, $params); - return [ - 'pages' => $total > 0 ? (int) ceil($total / $perPage) : 0, - 'page' => $page, - 'per_page' => $perPage, - 'total' => $total, - 'list' => $result, - ]; + return $this->buildPaginatedResponse($page, $perPage, $total, $result); } } diff --git a/src/library/FOSSBilling/Paginator.php b/src/library/FOSSBilling/Paginator.php new file mode 100644 index 000000000..799b0b039 --- /dev/null +++ b/src/library/FOSSBilling/Paginator.php @@ -0,0 +1,124 @@ +currentPage < 1) { + $this->currentPage = 1; + } + if ($this->limit < 1) { + $this->limit = 0; + } + } + + public function getNumPages(): int + { + if ($this->limit < 1 || $this->limit > $this->itemsCount) { + return 1; + } + + $restItemsNum = $this->itemsCount % $this->limit; + + return $restItemsNum > 0 ? intdiv($this->itemsCount, $this->limit) + 1 : intdiv($this->itemsCount, $this->limit); + } + + public function getCurrentPage(): int + { + return $this->currentPage; + } + + public function getLimit(): int + { + return $this->limit; + } + + public function getOffset(): int + { + return ($this->currentPage - 1) * $this->limit; + } + + public function getMidRange(): int + { + return $this->midRange; + } + + /** + * Returns the range of page numbers to display. + * + * Centers around the current page, bounded by 1 and the total number of pages. + */ + public function getRange(): array + { + $numPages = $this->getNumPages(); + $startRange = $this->currentPage - (int) floor($this->midRange / 2); + $endRange = $this->currentPage + (int) floor($this->midRange / 2); + + if ($startRange <= 0) { + $endRange += abs($startRange) + 1; + $startRange = 1; + } + + if ($endRange > $numPages) { + $endRange = $numPages; + $startRange = max(1, $endRange - $numPages + 1); + } + + return range($startRange, $endRange); + } + + public function getStartingPoint(): int + { + return reset($this->getRange()); + } + + public function getEndingPoint(): int + { + return end($this->getRange()); + } + + /** + * Returns all pagination metadata as an associative array. + * + * Suitable for returning from API endpoints or passing to templates. + */ + public function toArray(): array + { + return [ + 'currentpage' => $this->getCurrentPage(), + 'numpages' => $this->getNumPages(), + 'midrange' => $this->getMidRange(), + 'range' => $this->getRange(), + 'start' => $this->getStartingPoint(), + 'end' => $this->getEndingPoint(), + ]; + } +} diff --git a/src/library/FOSSBilling/Tools.php b/src/library/FOSSBilling/Tools.php index 052f4c1dc..fac6c9601 100644 --- a/src/library/FOSSBilling/Tools.php +++ b/src/library/FOSSBilling/Tools.php @@ -76,47 +76,28 @@ class Tools $charSetLength = strlen($charSet); - // Loop flow-control - $valid = false; - $iterations = 0; - - // Password requirements validation - $hasLowercase = false; - $hasUppercase = false; - $hasNumber = false; - $hasSpecial = false; + // Ensure minimum length for all required character types + $minRequiredLength = $includeSpecial ? 4 : 3; + if ($length < $minRequiredLength) { + throw new InformationException('Password length must be at least ' . $minRequiredLength . ' characters to meet complexity requirements'); + } + // Deterministically build password with one from each required category, then fill the rest $password = ''; - while (!$valid && $iterations < 100) { - // Add a random character to the password from the provided list of acceptable. - $character = substr($charSet, random_int(0, $charSetLength - 1), 1); - $password .= $character; - - // Handle validations - $hasLowercase = $hasLowercase || str_contains($characters, $character); - $hasUppercase = $hasUppercase || str_contains(strtoupper($characters), $character); - $hasNumber = $hasNumber || str_contains($numbers, $character); - $hasSpecial = !$includeSpecial || $hasSpecial || str_contains($specialCharacters, $character); - - // Once we reach the required length, check if the password is valid - if (strlen($password) === $length) { - $valid = $hasLowercase && $hasUppercase && $hasNumber && $hasSpecial; - if (!$valid) { - ++$iterations; - $password = ''; - $hasLowercase = false; - $hasUppercase = false; - $hasNumber = false; - $hasSpecial = false; - } - } + $password .= $characters[random_int(0, strlen($characters) - 1)]; + $password .= strtoupper($characters)[random_int(0, strlen($characters) - 1)]; + $password .= $numbers[random_int(0, strlen($numbers) - 1)]; + if ($includeSpecial) { + $password .= $specialCharacters[random_int(0, strlen($specialCharacters) - 1)]; } - if ($valid) { - return $password; + // Fill remaining length with random characters from the full set + for ($i = strlen($password); $i < $length; ++$i) { + $password .= $charSet[random_int(0, $charSetLength - 1)]; } - throw new InformationException('We were unable to generate a password with the required parameters'); + // Shuffle to avoid predictable positions for required characters + return str_shuffle($password); } public function slug($str): string @@ -192,7 +173,7 @@ class Tools return []; } - $count = is_countable($ids) ? count($ids) : 0; + $count = self::safeCount($ids); $slots = $count ? implode(',', array_fill(0, $count, '?')) : ''; // same as RedBean genSlots() method $rows = $this->di['db']->getAll('SELECT id, title FROM ' . $table . ' WHERE id in (' . $slots . ')', $ids); @@ -237,6 +218,14 @@ class Tools return $email; } + /** + * Safely count a value that may or may not be countable. + */ + public static function safeCount(mixed $value): int + { + return is_countable($value) ? count($value) : 0; + } + public static function isHTTPS(): bool { $protocol = $_SERVER['HTTPS'] ?? $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? $_SERVER['REQUEST_SCHEME'] ?? ''; diff --git a/src/library/FOSSBilling/UpdatePatcher.php b/src/library/FOSSBilling/UpdatePatcher.php index 5968328cb..edf2651d1 100644 --- a/src/library/FOSSBilling/UpdatePatcher.php +++ b/src/library/FOSSBilling/UpdatePatcher.php @@ -266,478 +266,562 @@ class UpdatePatcher implements InjectionAwareInterface private function getPatches($patchLevel = 0): array { $patches = [ - 25 => function (): void { - // Migrate email templates to be compatible with Twig 3.x. - $this->di['dbal']->createQueryBuilder() - ->update('email_template') - ->set('content', 'REPLACE(content, \'{% filter markdown %}\', \'{% apply markdown %}\')') - ->executeStatement(); - - $this->di['dbal']->createQueryBuilder() - ->update('email_template') - ->set('content', 'REPLACE(content, \'{% endfilter %}\', \'{% endapply %}\')') - ->executeStatement(); - }, - 26 => function (): void { - // Migration steps from BoxBilling to FOSSBilling - added favicon settings. - $this->di['dbal']->createQueryBuilder() - ->insert('setting') - ->values([ - 'param' => ':param', - 'value' => ':value', - 'public' => '0', - 'category' => ':category', - 'hash' => ':hash', - 'created_at' => ':created_at', - 'updated_at' => ':updated_at', - ]) - ->setParameter('param', 'company_favicon') - ->setParameter('value', 'themes/huraga/assets/favicon.ico') - ->setParameter('category', null) - ->setParameter('hash', null) - ->setParameter('created_at', '2023-01-08 12:00:00') - ->setParameter('updated_at', '2023-01-08 12:00:00') - ->executeStatement(); - }, - 27 => function (): void { - // Migration steps to create table to allow admin users to do password reset. - $q = 'CREATE TABLE `admin_password_reset` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `admin_id` bigint(20) DEFAULT NULL, `hash` varchar(100) DEFAULT NULL, `ip` varchar(45) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `admin_id_idx` (`admin_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;'; - $this->executeSql($q); - }, - 28 => function (): void { - // Patch to remove .html from email templates action code. - // @see https://github.com/FOSSBilling/FOSSBilling/issues/863 - $this->di['dbal']->createQueryBuilder() - ->update('email_template') - ->set('action_code', 'REPLACE(action_code, \'.html\', \'\')') - ->executeStatement(); - }, - 29 => function (): void { - // Patch to update email templates to use format_date/format_datetime filters - // instead of removed bb_date/bb_datetime filters. - // @see https://github.com/FOSSBilling/FOSSBilling/pull/948 - $this->di['dbal']->createQueryBuilder() - ->update('email_template') - ->set('content', 'REPLACE(content, \'bb_date\', \'format_date\')') - ->executeStatement(); - - $this->di['dbal']->createQueryBuilder() - ->update('email_template') - ->set('content', 'REPLACE(content, \'bb_datetime\', \'format_datetime\')') - ->executeStatement(); - }, - 30 => function (): void { - // Patch to remove the old guzzlehttp package, as we no longer - // use it. Also serves as an example for how to perform file action. - $fileActions = [ - Path::join(PATH_VENDOR, 'guzzlehttp') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 31 => function (): void { - // Patch to remove the old htaccess.txt file, and any old config.php backup. - // @see https://github.com/FOSSBilling/FOSSBilling/pull/1075 - $fileActions = [ - Path::join(PATH_ROOT, 'htaccess.txt') => 'unlink', - Path::join(PATH_ROOT, 'config.php.old') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 32 => function (): void { - // Patch to remove the old phpmailer package, some leftover - // admin_default files, and old Box_ classes we've removed or replaced. - // @see https://github.com/FOSSBilling/FOSSBilling/pull/1091 - // @see https://github.com/FOSSBilling/FOSSBilling/pull/1063 - $fileActions = [ - Path::join(PATH_VENDOR, 'phpmailer') => 'unlink', - Path::join(PATH_THEMES, 'admin_default', 'images') => 'unlink', - Path::join(PATH_THEMES, 'admin_default', 'assets', 'scss', 'bb-deprecated.scss') => 'unlink', - Path::join(PATH_THEMES, 'admin_default', 'assets', 'scss', 'dataTable-deprecated.scss') => 'unlink', - Path::join(PATH_THEMES, 'admin_default', 'assets', 'scss', 'main-deprecated.scss') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Mail.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Ftp.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'FileCacheExcption.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Zip.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Requirements.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Version.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Extension.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Cookie.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'ExceptionAuth.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Response.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Box', 'Config.php') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 33 => function (): void { - // Patch to remove the old FileCache class that was replaced with Symfony's Cache component. - // @see https://github.com/FOSSBilling/FOSSBilling/pull/1184 - $fileActions = [ - Path::join(PATH_LIBRARY, 'FileCache.php') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 34 => function (): void { - // Adds the new "fingerprint" to the session table, to allow us to fingerprint devices and help prevent against attacks such as session hijacking. - $q = 'ALTER TABLE session ADD fingerprint TEXT;'; - $this->executeSql($q); - }, - 35 => function (): void { - // Adds the new "created_at" to the session table, to ensure sessions are destroyed after they reach their maximum age. - $q = 'ALTER TABLE session ADD created_at int(11);'; - $this->executeSql($q); - }, - 36 => function (): void { - // Patch to complete merging the Kb and Support modules. - // @see https://github.com/FOSSBilling/FOSSBilling/pull/1180 - - // Renames the "kb_article" and "kb_article_category" tables to "support_kb_article" and "support_kb_article_category", respectively. - $q = 'RENAME TABLE kb_article TO support_kb_article, kb_article_category TO support_kb_article_category;'; - $this->executeSql($q); - - // An error here can pretty safely be ignore. - try { - // If the Kb extension is currently active, set enabled in Support settings. - $ext_service = $this->di['mod_service']('extension'); - if ($ext_service->isExtensionActive('mod', 'kb')) { - $support_ext_config = $ext_service->getConfig('mod_support'); - $support_ext_config['kb_enable'] = 'on'; - $ext_service->setConfig($support_ext_config); - } - - // If the Kb extension exists, uninstall it. - $kb_ext = $ext_service->findExtension('mod', 'kb'); - if ($kb_ext instanceof \Model_Extension) { - $ext_service->uninstall($kb_ext); - } - } catch (\Exception) { - } - - // Finally, remove old Kb extension files/folders. - $fileActions = [ - Path::join(PATH_MODS, 'Kb') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 37 => function (): void { - // Patch to complete remove the outdated queue module. - // @see https://github.com/FOSSBilling/FOSSBilling/pull/1777 - - try { - $ext_service = $this->di['mod_service']('extension'); - // If the queue extension exists, uninstall it. - $queue_ext = $ext_service->findExtension('mod', 'queue'); - if ($queue_ext instanceof \Model_Extension) { - $ext_service->uninstall($queue_ext); - } - } catch (\Exception) { - } - - // Finally, remove old queue module from the disk. - $fileActions = [ - Path::join(PATH_MODS, 'Queue') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 38 => function (): void { - // We need to remove the old ISPConfig3 and Virtualmin server managers from disk or else the leftover files could prevent the "hosting plans and servers" page from being loaded. - $fileActions = [ - Path::join(PATH_LIBRARY, 'Server', 'Manager', 'Ispconfig3.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Server', 'Manager', 'Virtualmin.php') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 39 => function (): void { - // The Serbian language was incorrectly placed into a folder named `srp` by Crowdin which is now corrected for via the locale repo and as such we need to delete the old directory. - // @see https://github.com/FOSSBilling/locale/issues/212 - $fileActions = [ - Path::join(PATH_LANGS, 'srp') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 40 => function (): void { - // Added `passwordLength` field to server managers - $q = 'ALTER TABLE service_hosting_server ADD COLUMN `password_length` TINYINT DEFAULT NULL;'; - $this->executeSql($q); - }, - 41 => function (): void { - // Remove the `manifest` column from the extensions table since it's no longer used - $q = 'ALTER TABLE extension DROP COLUMN manifest;'; - $this->executeSql($q); - }, - 42 => function (): void { - // This patch will migrate previous currency exchange rate data provider settings to the new ones - // @see https://github.com/FOSSBilling/FOSSBilling/pull/2189 - $ext_service = $this->di['mod_service']('extension'); - - $query = $this->di['dbal']->createQueryBuilder() - ->select('param', 'value') - ->from('setting') - ->executeQuery(); - - $pairs = $query->fetchAllKeyValue(); - - $config = $ext_service->getConfig('mod_currency'); - $config['ext'] = 'mod_currency'; // This should automatically be set, but some appear to be having cache issues that causes it to not be - - // Migrate the old currency exchange rate sync settings - $key = $pairs['currencylayer'] ?? ''; - if ($key) { - $config['provider'] = 'currency_data_api'; - $config['currencydata_key'] = $key; - } - - // Now migrate the cron setting - $cron = $pairs['currency_cron_enabled'] ?? 0; - if ($cron == '1') { - $config['sync_rate'] = 'auto'; - } else { - $config['sync_rate'] = 'never'; - } - - $ext_service->setConfig($config); - }, - 43 => function (): void { - $fileActions = [ - Path::join(PATH_LIBRARY, 'GeoLite2-Country.mmdb') => 'unlink', - ]; - $this->executeFileActions($fileActions); - }, - 44 => function (): void { - // Add ipn_hash column to transaction table and index it for fast duplicate detection. - $q = 'ALTER TABLE `transaction` - ADD COLUMN `ipn_hash` VARCHAR(64) DEFAULT NULL, - ADD INDEX `transaction_ipn_hash_idx` (`gateway_id`, `ipn_hash`(64));'; - $this->executeSql($q); - }, - 45 => function (): void { - // Drop updated_at column from activity tables - // Activity logs are never meant to be updated, only created - $q = 'ALTER TABLE `activity_admin_history` DROP COLUMN `updated_at`;'; - $this->executeSql($q); - - $q = 'ALTER TABLE `activity_client_email` DROP COLUMN `updated_at`;'; - $this->executeSql($q); - - $q = 'ALTER TABLE `activity_client_history` DROP COLUMN `updated_at`;'; - $this->executeSql($q); - - $q = 'ALTER TABLE `activity_system` DROP COLUMN `updated_at`;'; - $this->executeSql($q); - }, - 46 => function (): void { - // Change gender column to ENUM type - $q1 = 'ALTER TABLE `client` - MODIFY COLUMN `gender` ENUM("male", "female", "nonbinary", "other") DEFAULT NULL;'; - - // Change document_type column to ENUM type - $q2 = 'ALTER TABLE `client` - MODIFY COLUMN `document_type` ENUM("passport") DEFAULT NULL;'; - - $this->executeSql($q1); - $this->executeSql($q2); - }, - 47 => function (): void { - // Migrate "membership" product type to "custom" product type - // This is part of removing the Servicemembership module - // @see https://github.com/FOSSBilling/FOSSBilling/pull/3066 - - // Migrate products to the 'custom' product type - $q = 'UPDATE `product` SET `type` = "custom" WHERE `type` = "membership";'; - $this->executeSql($q); - - // Before migrating existing orders to the 'custom' product type, - // set service_id to NULL for orders with service_type = "membership" - $q = 'UPDATE `client_order` SET `service_id` = NULL WHERE `service_type` = "membership";'; - $this->executeSql($q); - // Migrate existing orders to the 'custom' product type - $q = 'UPDATE `client_order` SET `service_type` = "custom" WHERE `service_type` = "membership";'; - $this->executeSql($q); - - // Drop the service_membership table as it's no longer needed - $q = 'DROP TABLE IF EXISTS `service_membership`;'; - $this->executeSql($q); - }, - 48 => function (): void { - $filesystem = new Filesystem(); - $dbal = $this->di['dbal']; - - $oldUploadsPath = Path::join(PATH_ROOT, 'uploads'); - $newUploadsPath = Path::join(PATH_ROOT, 'data', 'uploads'); - - if ($filesystem->exists($oldUploadsPath) && $filesystem->exists($newUploadsPath)) { - foreach (glob($oldUploadsPath . '/*') as $oldFile) { - if (is_file($oldFile)) { - $filename = basename($oldFile); - $newFilePath = Path::join($newUploadsPath, $filename); - if (!$filesystem->exists($newFilePath)) { - $filesystem->rename($oldFile, $newFilePath); - } - } - } - } - - $products = $dbal->executeQuery("SELECT p.id, p.config FROM product p WHERE p.type = 'downloadable'")->fetchAllAssociative(); - - foreach ($products as $product) { - $productConfig = json_decode((string) $product['config'], true) ?: []; - - if (isset($productConfig['filename']) && !empty($productConfig['filename'])) { - continue; - } - - $foundFilename = null; - - $orders = $dbal->executeQuery('SELECT co.id, co.config, co.service_id FROM client_order co WHERE co.product_id = :product_id', ['product_id' => $product['id']])->fetchAllAssociative(); - - foreach ($orders as $order) { - $orderConfig = json_decode($order['config'] ?? '', true); - if (!is_array($orderConfig) || !isset($orderConfig['filename'])) { - continue; - } - - $filePath = Path::join(PATH_UPLOADS, md5((string) $orderConfig['filename'])); - if ($filesystem->exists($filePath)) { - $foundFilename = $orderConfig['filename']; - - break; - } - } - - if ($foundFilename === null) { - $services = $dbal->executeQuery('SELECT sd.id, sd.filename FROM service_downloadable sd INNER JOIN client_order co ON sd.id = co.service_id WHERE co.product_id = :product_id AND sd.filename IS NOT NULL AND sd.filename != ""', ['product_id' => $product['id']])->fetchAllAssociative(); - - foreach ($services as $service) { - $filePath = Path::join(PATH_UPLOADS, md5((string) $service['filename'])); - if ($filesystem->exists($filePath)) { - $foundFilename = $service['filename']; - - break; - } - } - } - - if ($foundFilename !== null) { - $productConfig['filename'] = $foundFilename; - $dbal->executeStatement('UPDATE product SET config = :config, updated_at = :updated_at WHERE id = :id', [ - 'config' => json_encode($productConfig), - 'updated_at' => date('Y-m-d H:i:s'), - 'id' => $product['id'], - ]); - - $dbal->executeStatement('UPDATE service_downloadable sd INNER JOIN client_order co ON sd.id = co.service_id SET sd.filename = :filename WHERE co.product_id = :product_id', ['filename' => $foundFilename, 'product_id' => $product['id']]); - - $ordersToUpdate = $dbal->executeQuery('SELECT id, config FROM client_order WHERE product_id = :product_id AND config LIKE "%filename%"', ['product_id' => $product['id']])->fetchAllAssociative(); - - foreach ($ordersToUpdate as $orderToUpdate) { - $orderConfig = json_decode($orderToUpdate['config'] ?? '', true); - if (is_array($orderConfig) && isset($orderConfig['filename'])) { - $orderConfig['filename'] = $foundFilename; - $dbal->executeStatement('UPDATE client_order SET config = :config, updated_at = :updated_at WHERE id = :id', [ - 'config' => json_encode($orderConfig), - 'updated_at' => date('Y-m-d H:i:s'), - 'id' => $orderToUpdate['id'], - ]); - } - } - } - } - - $orphans = $dbal->executeQuery('SELECT sd.id, co.config as order_config FROM service_downloadable sd INNER JOIN client_order co ON sd.id = co.service_id WHERE sd.filename IS NULL OR sd.filename = ""')->fetchAllAssociative(); - - foreach ($orphans as $orphan) { - $orderConfig = json_decode($orphan['order_config'] ?? '', true); - if (isset($orderConfig['filename']) && !empty($orderConfig['filename'])) { - $filePath = Path::join(PATH_UPLOADS, md5((string) $orderConfig['filename'])); - if ($filesystem->exists($filePath)) { - $dbal->executeStatement('UPDATE service_downloadable SET filename = :filename WHERE id = :id', ['filename' => $orderConfig['filename'], 'id' => $orphan['id']]); - } - } - } - }, - 49 => function (): void { - $q = "UPDATE setting SET value = 'themes/huraga/assets/build/img/logo.svg' WHERE param = 'company_logo' AND value = 'themes/huraga/assets/img/logo.svg';"; - $this->executeSql($q); - - $q = "UPDATE setting SET value = 'themes/huraga/assets/build/img/logo_white.svg' WHERE param = 'company_logo_dark' AND value = 'themes/huraga/assets/img/logo_white.svg';"; - $this->executeSql($q); - - $q = "UPDATE setting SET value = 'themes/huraga/assets/build/favicon.ico' WHERE param = 'company_favicon' AND value = 'themes/huraga/assets/favicon.ico';"; - $this->executeSql($q); - }, - 50 => function (): void { - $this->migrateEncryptedColumn('email_template', 'id', 'vars', "vars IS NOT NULL AND vars != ''"); - $this->migrateEncryptedColumn('extension_meta', 'id', 'meta_value', "meta_key = :meta_key AND meta_value IS NOT NULL AND meta_value != ''", [ - 'meta_key' => 'config', - ]); - }, - 51 => function (): void { - $oldDir = Path::join(PATH_MODS, 'Invoice', 'pdf_template'); - $newDir = Path::join(PATH_MODS, 'Invoice', 'templates', 'pdf'); - - if (!$this->filesystem->exists($oldDir)) { - return; - } - - $fileActions = [ - Path::join($oldDir, 'custom-pdf.twig') => Path::join($newDir, 'custom-invoice.twig'), - Path::join($oldDir, 'custom-pdf.css') => Path::join($newDir, 'custom-invoice.css'), - Path::join($oldDir, 'default-pdf.twig') => 'unlink', - Path::join($oldDir, 'default-pdf.css') => 'unlink', - ]; - $this->executeFileActions($fileActions); - - $finder = new Finder(); - if (!$finder->in($oldDir)->depth('== 0')->hasResults()) { - $this->filesystem->remove($oldDir); - } - }, - 52 => function (): void { - $schemaManager = $this->di['dbal']->createSchemaManager(); - $columns = array_map(static fn ($column) => $column->getName(), $schemaManager->listTableColumns('email_template')); - - if (!in_array('is_custom', $columns, true)) { - $this->executeSql("ALTER TABLE `email_template` ADD COLUMN `is_custom` TINYINT(1) DEFAULT '0' AFTER `enabled`;"); - } - - if (!in_array('is_overridden', $columns, true)) { - $this->executeSql("ALTER TABLE `email_template` ADD COLUMN `is_overridden` TINYINT(1) DEFAULT '0' COMMENT 'Whether subject/content have been customized from file defaults' AFTER `is_custom`;"); - } - - $templates = $this->di['dbal']->executeQuery('SELECT id, action_code, subject, content FROM email_template')->fetchAllAssociative(); - foreach ($templates as $template) { - $default = $this->getDefaultEmailTemplateData((string) ($template['action_code'] ?? '')); - if ($default === null) { - $this->di['dbal']->executeStatement('UPDATE email_template SET is_custom = :is_custom WHERE id = :id', [ - 'is_custom' => 1, - 'id' => $template['id'], - ]); - - continue; - } - - $subject = (string) ($template['subject'] ?? ''); - $content = (string) ($template['content'] ?? ''); - - $isOverridden = (trim($subject) !== trim((string) $default['subject'])) || (trim($content) !== trim((string) $default['content'])); - - if (!$isOverridden) { - $subject = $default['subject']; - $content = $default['content']; - } - - $this->di['dbal']->executeStatement('UPDATE email_template SET is_custom = :is_custom, is_overridden = :is_overridden, subject = :subject, content = :content WHERE id = :id', [ - 'is_custom' => 0, - 'is_overridden' => $isOverridden ? 1 : 0, - 'subject' => $subject, - 'content' => $content, - 'id' => $template['id'], - ]); - } - }, + 25 => 'patch25', + 26 => 'patch26', + 27 => 'patch27', + 28 => 'patch28', + 29 => 'patch29', + 30 => 'patch30', + 31 => 'patch31', + 32 => 'patch32', + 33 => 'patch33', + 34 => 'patch34', + 35 => 'patch35', + 36 => 'patch36', + 37 => 'patch37', + 38 => 'patch38', + 39 => 'patch39', + 40 => 'patch40', + 41 => 'patch41', + 42 => 'patch42', + 43 => 'patch43', + 44 => 'patch44', + 45 => 'patch45', + 46 => 'patch46', + 47 => 'patch47', + 48 => 'patch48', + 49 => 'patch49', + 50 => 'patch50', + 51 => 'patch51', + 52 => 'patch52', ]; ksort($patches, SORT_NATURAL); - return array_filter($patches, fn ($key): bool => $key > $patchLevel, ARRAY_FILTER_USE_KEY); + $patchesToApply = array_filter($patches, fn ($key): bool => $key > $patchLevel, ARRAY_FILTER_USE_KEY); + + return array_map(fn ($method): array => [$this, $method], $patchesToApply); + } + + private function patch25(): void + { + // Migrate email templates to be compatible with Twig 3.x. + $this->di['dbal']->createQueryBuilder() + ->update('email_template') + ->set('content', 'REPLACE(content, \'{% filter markdown %}\', \'{% apply markdown %}\')') + ->executeStatement(); + + $this->di['dbal']->createQueryBuilder() + ->update('email_template') + ->set('content', 'REPLACE(content, \'{% endfilter %}\', \'{% endapply %}\')') + ->executeStatement(); + } + + private function patch26(): void + { + // Migration steps from BoxBilling to FOSSBilling - added favicon settings. + $this->di['dbal']->createQueryBuilder() + ->insert('setting') + ->values([ + 'param' => ':param', + 'value' => ':value', + 'public' => '0', + 'category' => ':category', + 'hash' => ':hash', + 'created_at' => ':created_at', + 'updated_at' => ':updated_at', + ]) + ->setParameter('param', 'company_favicon') + ->setParameter('value', 'themes/huraga/assets/favicon.ico') + ->setParameter('category', null) + ->setParameter('hash', null) + ->setParameter('created_at', '2023-01-08 12:00:00') + ->setParameter('updated_at', '2023-01-08 12:00:00') + ->executeStatement(); + } + + private function patch27(): void + { + // Migration steps to create table to allow admin users to do password reset. + $q = 'CREATE TABLE `admin_password_reset` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `admin_id` bigint(20) DEFAULT NULL, `hash` varchar(100) DEFAULT NULL, `ip` varchar(45) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `admin_id_idx` (`admin_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;'; + $this->executeSql($q); + } + + private function patch28(): void + { + // Patch to remove .html from email templates action code. + // @see https://github.com/FOSSBilling/FOSSBilling/issues/863 + $this->di['dbal']->createQueryBuilder() + ->update('email_template') + ->set('action_code', 'REPLACE(action_code, \'.html\', \'\')') + ->executeStatement(); + } + + private function patch29(): void + { + // Patch to update email templates to use format_date/format_datetime filters + // instead of removed bb_date/bb_datetime filters. + // @see https://github.com/FOSSBilling/FOSSBilling/pull/948 + $this->di['dbal']->createQueryBuilder() + ->update('email_template') + ->set('content', 'REPLACE(content, \'bb_date\', \'format_date\')') + ->executeStatement(); + + $this->di['dbal']->createQueryBuilder() + ->update('email_template') + ->set('content', 'REPLACE(content, \'bb_datetime\', \'format_datetime\')') + ->executeStatement(); + } + + private function patch30(): void + { + // Patch to remove the old guzzlehttp package, as we no longer use it. + $fileActions = [ + Path::join(PATH_VENDOR, 'guzzlehttp') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch31(): void + { + // Patch to remove the old htaccess.txt file, and any old config.php backup. + // @see https://github.com/FOSSBilling/FOSSBilling/pull/1075 + $fileActions = [ + Path::join(PATH_ROOT, 'htaccess.txt') => 'unlink', + Path::join(PATH_ROOT, 'config.php.old') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch32(): void + { + // Patch to remove the old phpmailer package, some leftover admin_default files, and old Box_ classes. + // @see https://github.com/FOSSBilling/FOSSBilling/pull/1091 + // @see https://github.com/FOSSBilling/FOSSBilling/pull/1063 + $fileActions = [ + Path::join(PATH_VENDOR, 'phpmailer') => 'unlink', + Path::join(PATH_THEMES, 'admin_default', 'images') => 'unlink', + Path::join(PATH_THEMES, 'admin_default', 'assets', 'scss', 'bb-deprecated.scss') => 'unlink', + Path::join(PATH_THEMES, 'admin_default', 'assets', 'scss', 'dataTable-deprecated.scss') => 'unlink', + Path::join(PATH_THEMES, 'admin_default', 'assets', 'scss', 'main-deprecated.scss') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Mail.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Ftp.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'FileCacheExcption.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Zip.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Requirements.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Version.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Extension.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Cookie.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'ExceptionAuth.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Response.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Box', 'Config.php') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch33(): void + { + // Patch to remove the old FileCache class that was replaced with Symfony's Cache component. + // @see https://github.com/FOSSBilling/FOSSBilling/pull/1184 + $fileActions = [ + Path::join(PATH_LIBRARY, 'FileCache.php') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch34(): void + { + // Adds the new "fingerprint" to the session table, to allow us to fingerprint devices and help prevent against attacks such as session hijacking. + $q = 'ALTER TABLE session ADD fingerprint TEXT;'; + $this->executeSql($q); + } + + private function patch35(): void + { + // Adds the new "created_at" to the session table, to ensure sessions are destroyed after they reach their maximum age. + $q = 'ALTER TABLE session ADD created_at int(11);'; + $this->executeSql($q); + } + + private function patch36(): void + { + // Patch to complete merging the Kb and Support modules. + // @see https://github.com/FOSSBilling/FOSSBilling/pull/1180 + + // Renames the "kb_article" and "kb_article_category" tables to "support_kb_article" and "support_kb_article_category", respectively. + $q = 'RENAME TABLE kb_article TO support_kb_article, kb_article_category TO support_kb_article_category;'; + $this->executeSql($q); + + // An error here can pretty safely be ignore. + try { + // If the Kb extension is currently active, set enabled in Support settings. + $ext_service = $this->di['mod_service']('extension'); + if ($ext_service->isExtensionActive('mod', 'kb')) { + $support_ext_config = $ext_service->getConfig('mod_support'); + $support_ext_config['kb_enable'] = 'on'; + $ext_service->setConfig($support_ext_config); + } + + // If the Kb extension exists, uninstall it. + $kb_ext = $ext_service->findExtension('mod', 'kb'); + if ($kb_ext instanceof \Model_Extension) { + $ext_service->uninstall($kb_ext); + } + } catch (\Exception) { + } + + // Finally, remove old Kb extension files/folders. + $fileActions = [ + Path::join(PATH_MODS, 'Kb') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch37(): void + { + // Patch to complete remove the outdated queue module. + // @see https://github.com/FOSSBilling/FOSSBilling/pull/1777 + + try { + $ext_service = $this->di['mod_service']('extension'); + // If the queue extension exists, uninstall it. + $queue_ext = $ext_service->findExtension('mod', 'queue'); + if ($queue_ext instanceof \Model_Extension) { + $ext_service->uninstall($queue_ext); + } + } catch (\Exception) { + } + + // Finally, remove old queue module from the disk. + $fileActions = [ + Path::join(PATH_MODS, 'Queue') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch38(): void + { + // We need to remove the old ISPConfig3 and Virtualmin server managers from disk or else the leftover files could prevent the "hosting plans and servers" page from being loaded. + $fileActions = [ + Path::join(PATH_LIBRARY, 'Server', 'Manager', 'Ispconfig3.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Server', 'Manager', 'Virtualmin.php') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch39(): void + { + // The Serbian language was incorrectly placed into a folder named `srp` by Crowdin which is now corrected for via the locale repo and as such we need to delete the old directory. + // @see https://github.com/FOSSBilling/locale/issues/212 + $fileActions = [ + Path::join(PATH_LANGS, 'srp') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch40(): void + { + // Added `passwordLength` field to server managers + $q = 'ALTER TABLE service_hosting_server ADD COLUMN `password_length` TINYINT DEFAULT NULL;'; + $this->executeSql($q); + } + + private function patch41(): void + { + // Remove the `manifest` column from the extensions table since it's no longer used + $q = 'ALTER TABLE extension DROP COLUMN manifest;'; + $this->executeSql($q); + } + + private function patch42(): void + { + // This patch will migrate previous currency exchange rate data provider settings to the new ones + // @see https://github.com/FOSSBilling/FOSSBilling/pull/2189 + $ext_service = $this->di['mod_service']('extension'); + + $query = $this->di['dbal']->createQueryBuilder() + ->select('param', 'value') + ->from('setting') + ->executeQuery(); + + $pairs = $query->fetchAllKeyValue(); + + $config = $ext_service->getConfig('mod_currency'); + $config['ext'] = 'mod_currency'; // This should automatically be set, but some appear to be having cache issues that causes it to not be + + // Migrate the old currency exchange rate sync settings + $key = $pairs['currencylayer'] ?? ''; + if ($key) { + $config['provider'] = 'currency_data_api'; + $config['currencydata_key'] = $key; + } + + // Now migrate the cron setting + $cron = $pairs['currency_cron_enabled'] ?? 0; + if ($cron == '1') { + $config['sync_rate'] = 'auto'; + } else { + $config['sync_rate'] = 'never'; + } + + $ext_service->setConfig($config); + } + + private function patch43(): void + { + $fileActions = [ + Path::join(PATH_LIBRARY, 'GeoLite2-Country.mmdb') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + + private function patch44(): void + { + // Add ipn_hash column to transaction table and index it for fast duplicate detection. + $q = 'ALTER TABLE `transaction` + ADD COLUMN `ipn_hash` VARCHAR(64) DEFAULT NULL, + ADD INDEX `transaction_ipn_hash_idx` (`gateway_id`, `ipn_hash`(64));'; + $this->executeSql($q); + } + + private function patch45(): void + { + // Drop updated_at column from activity tables + // Activity logs are never meant to be updated, only created + $q = 'ALTER TABLE `activity_admin_history` DROP COLUMN `updated_at`;'; + $this->executeSql($q); + + $q = 'ALTER TABLE `activity_client_email` DROP COLUMN `updated_at`;'; + $this->executeSql($q); + + $q = 'ALTER TABLE `activity_client_history` DROP COLUMN `updated_at`;'; + $this->executeSql($q); + + $q = 'ALTER TABLE `activity_system` DROP COLUMN `updated_at`;'; + $this->executeSql($q); + } + + private function patch46(): void + { + // Change gender column to ENUM type + $q1 = 'ALTER TABLE `client` + MODIFY COLUMN `gender` ENUM("male", "female", "nonbinary", "other") DEFAULT NULL;'; + + // Change document_type column to ENUM type + $q2 = 'ALTER TABLE `client` + MODIFY COLUMN `document_type` ENUM("passport") DEFAULT NULL;'; + + $this->executeSql($q1); + $this->executeSql($q2); + } + + private function patch47(): void + { + // Migrate "membership" product type to "custom" product type + // This is part of removing the Servicemembership module + // @see https://github.com/FOSSBilling/FOSSBilling/pull/3066 + + // Migrate products to the 'custom' product type + $q = 'UPDATE `product` SET `type` = "custom" WHERE `type` = "membership";'; + $this->executeSql($q); + + // Before migrating existing orders to the 'custom' product type, + // set service_id to NULL for orders with service_type = "membership" + $q = 'UPDATE `client_order` SET `service_id` = NULL WHERE `service_type` = "membership";'; + $this->executeSql($q); + // Migrate existing orders to the 'custom' product type + $q = 'UPDATE `client_order` SET `service_type` = "custom" WHERE `service_type` = "membership";'; + $this->executeSql($q); + + // Drop the service_membership table as it's no longer needed + $q = 'DROP TABLE IF EXISTS `service_membership`;'; + $this->executeSql($q); + } + + private function patch48(): void + { + $filesystem = new Filesystem(); + $dbal = $this->di['dbal']; + + $oldUploadsPath = Path::join(PATH_ROOT, 'uploads'); + $newUploadsPath = Path::join(PATH_ROOT, 'data', 'uploads'); + + if ($filesystem->exists($oldUploadsPath) && $filesystem->exists($newUploadsPath)) { + foreach (glob($oldUploadsPath . '/*') as $oldFile) { + if (is_file($oldFile)) { + $filename = basename($oldFile); + $newFilePath = Path::join($newUploadsPath, $filename); + if (!$filesystem->exists($newFilePath)) { + $filesystem->rename($oldFile, $newFilePath); + } + } + } + } + + $products = $dbal->executeQuery("SELECT p.id, p.config FROM product p WHERE p.type = 'downloadable'")->fetchAllAssociative(); + + foreach ($products as $product) { + $productConfig = json_decode((string) $product['config'], true) ?: []; + + if (isset($productConfig['filename']) && !empty($productConfig['filename'])) { + continue; + } + + $foundFilename = null; + + $orders = $dbal->executeQuery('SELECT co.id, co.config, co.service_id FROM client_order co WHERE co.product_id = :product_id', ['product_id' => $product['id']])->fetchAllAssociative(); + + foreach ($orders as $order) { + $orderConfig = json_decode($order['config'] ?? '', true); + if (!is_array($orderConfig) || !isset($orderConfig['filename'])) { + continue; + } + + $filePath = Path::join(PATH_UPLOADS, md5((string) $orderConfig['filename'])); + if ($filesystem->exists($filePath)) { + $foundFilename = $orderConfig['filename']; + + break; + } + } + + if ($foundFilename === null) { + $services = $dbal->executeQuery('SELECT sd.id, sd.filename FROM service_downloadable sd INNER JOIN client_order co ON sd.id = co.service_id WHERE co.product_id = :product_id AND sd.filename IS NOT NULL AND sd.filename != ""', ['product_id' => $product['id']])->fetchAllAssociative(); + + foreach ($services as $service) { + $filePath = Path::join(PATH_UPLOADS, md5((string) $service['filename'])); + if ($filesystem->exists($filePath)) { + $foundFilename = $service['filename']; + + break; + } + } + } + + if ($foundFilename !== null) { + $productConfig['filename'] = $foundFilename; + $dbal->executeStatement('UPDATE product SET config = :config, updated_at = :updated_at WHERE id = :id', [ + 'config' => json_encode($productConfig), + 'updated_at' => date('Y-m-d H:i:s'), + 'id' => $product['id'], + ]); + + $dbal->executeStatement('UPDATE service_downloadable sd INNER JOIN client_order co ON sd.id = co.service_id SET sd.filename = :filename WHERE co.product_id = :product_id', ['filename' => $foundFilename, 'product_id' => $product['id']]); + + $ordersToUpdate = $dbal->executeQuery('SELECT id, config FROM client_order WHERE product_id = :product_id AND config LIKE "%filename%"', ['product_id' => $product['id']])->fetchAllAssociative(); + + foreach ($ordersToUpdate as $orderToUpdate) { + $orderConfig = json_decode($orderToUpdate['config'] ?? '', true); + if (is_array($orderConfig) && isset($orderConfig['filename'])) { + $orderConfig['filename'] = $foundFilename; + $dbal->executeStatement('UPDATE client_order SET config = :config, updated_at = :updated_at WHERE id = :id', [ + 'config' => json_encode($orderConfig), + 'updated_at' => date('Y-m-d H:i:s'), + 'id' => $orderToUpdate['id'], + ]); + } + } + } + } + + $orphans = $dbal->executeQuery('SELECT sd.id, co.config as order_config FROM service_downloadable sd INNER JOIN client_order co ON sd.id = co.service_id WHERE sd.filename IS NULL OR sd.filename = ""')->fetchAllAssociative(); + + foreach ($orphans as $orphan) { + $orderConfig = json_decode($orphan['order_config'] ?? '', true); + if (isset($orderConfig['filename']) && !empty($orderConfig['filename'])) { + $filePath = Path::join(PATH_UPLOADS, md5((string) $orderConfig['filename'])); + if ($filesystem->exists($filePath)) { + $dbal->executeStatement('UPDATE service_downloadable SET filename = :filename WHERE id = :id', ['filename' => $orderConfig['filename'], 'id' => $orphan['id']]); + } + } + } + } + + private function patch49(): void + { + $q = "UPDATE setting SET value = 'themes/huraga/assets/build/img/logo.svg' WHERE param = 'company_logo' AND value = 'themes/huraga/assets/img/logo.svg';"; + $this->executeSql($q); + + $q = "UPDATE setting SET value = 'themes/huraga/assets/build/img/logo_white.svg' WHERE param = 'company_logo_dark' AND value = 'themes/huraga/assets/img/logo_white.svg';"; + $this->executeSql($q); + + $q = "UPDATE setting SET value = 'themes/huraga/assets/build/favicon.ico' WHERE param = 'company_favicon' AND value = 'themes/huraga/assets/favicon.ico';"; + $this->executeSql($q); + } + + private function patch50(): void + { + $this->migrateEncryptedColumn('email_template', 'id', 'vars', "vars IS NOT NULL AND vars != ''"); + $this->migrateEncryptedColumn('extension_meta', 'id', 'meta_value', "meta_key = :meta_key AND meta_value IS NOT NULL AND meta_value != ''", [ + 'meta_key' => 'config', + ]); + } + + private function patch51(): void + { + $oldDir = Path::join(PATH_MODS, 'Invoice', 'pdf_template'); + $newDir = Path::join(PATH_MODS, 'Invoice', 'templates', 'pdf'); + + if (!$this->filesystem->exists($oldDir)) { + return; + } + + $fileActions = [ + Path::join($oldDir, 'custom-pdf.twig') => Path::join($newDir, 'custom-invoice.twig'), + Path::join($oldDir, 'custom-pdf.css') => Path::join($newDir, 'custom-invoice.css'), + Path::join($oldDir, 'default-pdf.twig') => 'unlink', + Path::join($oldDir, 'default-pdf.css') => 'unlink', + ]; + $this->executeFileActions($fileActions); + + $finder = new Finder(); + if (!$finder->in($oldDir)->depth('== 0')->hasResults()) { + $this->filesystem->remove($oldDir); + } + } + + private function patch52(): void + { + $schemaManager = $this->di['dbal']->createSchemaManager(); + $columns = array_map(static fn ($column) => $column->getName(), $schemaManager->listTableColumns('email_template')); + + if (!in_array('is_custom', $columns, true)) { + $this->executeSql("ALTER TABLE `email_template` ADD COLUMN `is_custom` TINYINT(1) DEFAULT '0' AFTER `enabled`;"); + } + + if (!in_array('is_overridden', $columns, true)) { + $this->executeSql("ALTER TABLE `email_template` ADD COLUMN `is_overridden` TINYINT(1) DEFAULT '0' COMMENT 'Whether subject/content have been customized from file defaults' AFTER `is_custom`;"); + } + + $templates = $this->di['dbal']->executeQuery('SELECT id, action_code, subject, content FROM email_template')->fetchAllAssociative(); + foreach ($templates as $template) { + $default = $this->getDefaultEmailTemplateData((string) ($template['action_code'] ?? '')); + if ($default === null) { + $this->di['dbal']->executeStatement('UPDATE email_template SET is_custom = :is_custom WHERE id = :id', [ + 'is_custom' => 1, + 'id' => $template['id'], + ]); + + continue; + } + + $subject = (string) ($template['subject'] ?? ''); + $content = (string) ($template['content'] ?? ''); + + $isOverridden = (trim($subject) !== trim((string) $default['subject'])) || (trim($content) !== trim((string) $default['content'])); + + if (!$isOverridden) { + $subject = $default['subject']; + $content = $default['content']; + } + + $this->di['dbal']->executeStatement('UPDATE email_template SET is_custom = :is_custom, is_overridden = :is_overridden, subject = :subject, content = :content WHERE id = :id', [ + 'is_custom' => 0, + 'is_overridden' => $isOverridden ? 1 : 0, + 'subject' => $subject, + 'content' => $content, + 'id' => $template['id'], + ]); + } } /** diff --git a/src/library/FOSSBilling/Validate.php b/src/library/FOSSBilling/Validate.php index 8ff257d28..ef40cac29 100644 --- a/src/library/FOSSBilling/Validate.php +++ b/src/library/FOSSBilling/Validate.php @@ -132,6 +132,22 @@ class Validate return $validTlds[$tld] ?? false; } + /** + * Checks that password and password confirmation match. + * + * @param array $data The data array containing password fields + * @param string $passwordKey The key for the password field (default: 'password') + * @param string $confirmKey The key for the confirmation field (default: 'password_confirm') + * + * @throws InformationException if passwords do not match + */ + public function passwordsMatch(array $data, string $passwordKey = 'password', string $confirmKey = 'password_confirm'): void + { + if (($data[$passwordKey] ?? '') !== ($data[$confirmKey] ?? '')) { + throw new InformationException('Passwords do not match.'); + } + } + public function isPasswordStrong($pwd): bool { if (strlen((string) $pwd) < 8) { @@ -154,11 +170,6 @@ class Validate throw new InformationException('Password must include at least one uppercase letter.'); } - /* - if( !preg_match("#\W+#", $pwd) ) { - $msg = "Password must include at least one symbol!"; - } - */ return true; } diff --git a/src/library/Model/ActivityAdminHistory.php b/src/library/Model/ActivityAdminHistory.php index 9e297f449..edb15f262 100644 --- a/src/library/Model/ActivityAdminHistory.php +++ b/src/library/Model/ActivityAdminHistory.php @@ -1,5 +1,6 @@ getQty(); $free_domain_periods = $addon['config']['free_domain_periods'] ?? []; - if ((is_countable($free_domain_periods) ? count($free_domain_periods) : 0) > 0) { + if (\FOSSBilling\Tools::safeCount($free_domain_periods) > 0) { // if hosting and domain periods are equal, return domain quantity (year) if ($addon_period == $period) { if (in_array($addon_period, $free_domain_periods)) { diff --git a/src/library/Model/ProductDownloadable.php b/src/library/Model/ProductDownloadable.php index 1c75ea792..60bcdf6ed 100644 --- a/src/library/Model/ProductDownloadable.php +++ b/src/library/Model/ProductDownloadable.php @@ -1,5 +1,6 @@ di['db']->getAll($sql, $bindings); - if ((is_countable($rows) ? count($rows) : 0) > 1) { + if (\FOSSBilling\Tools::safeCount($rows) > 1) { return true; } diff --git a/src/library/Payment/Adapter/Stripe.php b/src/library/Payment/Adapter/Stripe.php index 1d94fd729..6a1c524eb 100644 --- a/src/library/Payment/Adapter/Stripe.php +++ b/src/library/Payment/Adapter/Stripe.php @@ -1,5 +1,6 @@ $invoiceItems[0]['title'], ]; $title = __trans('Payment for invoice :serie:id [:title]', $params); - if ((is_countable($invoiceItems) ? count($invoiceItems) : 0) > 1) { + if (\FOSSBilling\Tools::safeCount($invoiceItems) > 1) { $title = __trans('Payment for invoice :serie:id', $params); } diff --git a/src/library/Payment/Exception.php b/src/library/Payment/Exception.php index 01876f550..4c604b877 100644 --- a/src/library/Payment/Exception.php +++ b/src/library/Payment/Exception.php @@ -1,5 +1,6 @@ 0) { + if (\FOSSBilling\Tools::safeCount($ips['exclusive']) > 0) { $ips['exclusive'] = array_values($ips['exclusive']); $rand = array_rand($ips['exclusive']); $account->setIp($ips['exclusive'][$rand]['ip']); diff --git a/src/library/Server/Manager/Whm.php b/src/library/Server/Manager/Whm.php index fbd31dc5e..9aa297d93 100644 --- a/src/library/Server/Manager/Whm.php +++ b/src/library/Server/Manager/Whm.php @@ -1,5 +1,6 @@ di['db']->exec('DELETE FROM `cart_product` WHERE cart_id = :id', [':id' => $id]); $this->di['db']->exec('DELETE FROM `cart` WHERE id = :id', [':id' => $id]); } - $this->di['logger']->info('Removed %s expired shopping carts', is_countable($list) ? count($list) : 0); + $this->di['logger']->info('Removed %s expired shopping carts', \FOSSBilling\Tools::safeCount($list)); } return true; diff --git a/src/modules/Cart/Api/Client.php b/src/modules/Cart/Api/Client.php index 1625de853..da10fdf6f 100644 --- a/src/modules/Cart/Api/Client.php +++ b/src/modules/Cart/Api/Client.php @@ -1,5 +1,6 @@ di['db']->find('CartProduct', 'cart_id = :cart_id', [':cart_id' => $cart->id]); - return (is_countable($cartProducts) ? count($cartProducts) : 0) == 0; + return \FOSSBilling\Tools::safeCount($cartProducts) == 0; } public function rm(\Model_Cart $cart): bool @@ -523,7 +524,7 @@ class Service implements InjectionAwareInterface { $cart = $this->getSessionCart(); $ca = $this->toApiArray($cart); - if ((is_countable($ca['items']) ? count($ca['items']) : 0) == 0) { + if (\FOSSBilling\Tools::safeCount($ca['items']) == 0) { throw new \FOSSBilling\InformationException('Cannot checkout an empty cart'); } diff --git a/src/modules/Client/Api/Admin.php b/src/modules/Client/Api/Admin.php index 940c3a1c2..ce4794c0b 100644 --- a/src/modules/Client/Api/Admin.php +++ b/src/modules/Client/Api/Admin.php @@ -1,5 +1,6 @@ phone); + $phone = $data['phone'] ?? $client->phone; if (!empty($phone) && is_string($phone)) { $client->phone = Tools::validatePhoneNumber($phone); } - $client->email = (!empty($data['email']) ? $data['email'] : $client->email); - $client->first_name = (!empty($data['first_name']) ? $data['first_name'] : $client->first_name); - $client->last_name = (!empty($data['last_name']) ? $data['last_name'] : $client->last_name); - $client->aid = (!empty($data['aid']) ? $data['aid'] : $client->aid); - $client->gender = (!empty($data['gender']) ? $data['gender'] : $client->gender); - $client->birthday = (!empty($data['birthday']) ? $data['birthday'] : $client->birthday); - $client->company = (!empty($data['company']) ? $data['company'] : $client->company); - $client->company_vat = (!empty($data['company_vat']) ? $data['company_vat'] : $client->company_vat); - $client->address_1 = (!empty($data['address_1']) ? $data['address_1'] : $client->address_1); - $client->address_2 = (!empty($data['address_2']) ? $data['address_2'] : $client->address_2); - $client->document_type = (!empty($data['document_type']) ? $data['document_type'] : $client->document_type); - $client->document_nr = (!empty($data['document_nr']) ? $data['document_nr'] : $client->document_nr); - $client->notes = (!empty($data['notes']) ? $data['notes'] : $client->notes); - $client->country = (!empty($data['country']) ? $data['country'] : $client->country); - $client->postcode = (!empty($data['postcode']) ? $data['postcode'] : $client->postcode); - $client->state = (!empty($data['state']) ? $data['state'] : $client->state); - $client->city = (!empty($data['city']) ? $data['city'] : $client->city); + $allowedFields = [ + 'email', 'first_name', 'last_name', 'aid', 'gender', 'birthday', + 'company', 'company_vat', 'address_1', 'address_2', 'document_type', + 'document_nr', 'notes', 'country', 'postcode', 'state', 'city', + 'status', 'email_approved', 'tax_exempt', 'created_at', + 'custom_1', 'custom_2', 'custom_3', 'custom_4', 'custom_5', + 'custom_6', 'custom_7', 'custom_8', 'custom_9', 'custom_10', + 'client_group_id', 'company_number', 'type', 'lang', + ]; - $client->status = (!empty($data['status']) ? $data['status'] : $client->status); - $client->email_approved = (!empty($data['email_approved']) ? $data['email_approved'] : $client->email_approved); - $client->tax_exempt = (!empty($data['tax_exempt']) ? $data['tax_exempt'] : $client->tax_exempt); - $client->created_at = (!empty($data['created_at']) ? $data['created_at'] : $client->created_at); - - $client->custom_1 = (!empty($data['custom_1']) ? $data['custom_1'] : $client->custom_1); - $client->custom_2 = (!empty($data['custom_2']) ? $data['custom_2'] : $client->custom_2); - $client->custom_3 = (!empty($data['custom_3']) ? $data['custom_3'] : $client->custom_3); - $client->custom_4 = (!empty($data['custom_4']) ? $data['custom_4'] : $client->custom_4); - $client->custom_5 = (!empty($data['custom_5']) ? $data['custom_5'] : $client->custom_5); - $client->custom_6 = (!empty($data['custom_6']) ? $data['custom_6'] : $client->custom_6); - $client->custom_7 = (!empty($data['custom_7']) ? $data['custom_7'] : $client->custom_7); - $client->custom_8 = (!empty($data['custom_8']) ? $data['custom_8'] : $client->custom_8); - $client->custom_9 = (!empty($data['custom_9']) ? $data['custom_9'] : $client->custom_9); - $client->custom_10 = (!empty($data['custom_10']) ? $data['custom_10'] : $client->custom_10); - - $client->client_group_id = (!empty($data['group_id']) ? $data['group_id'] : $client->client_group_id); - $client->company_number = (!empty($data['company_number']) ? $data['company_number'] : $client->company_number); - $client->type = (!empty($data['type']) ? $data['type'] : $client->type); - $client->lang = (!empty($data['lang']) ? $data['lang'] : $client->lang); + foreach ($allowedFields as $field) { + $client->{$field} = $data[$field] ?? $client->{$field}; + } $client->updated_at = date('Y-m-d H:i:s'); @@ -303,9 +279,7 @@ class Admin extends \Api_Abstract #[RequiredParams(['id' => 'ID required', 'password' => 'Password required', 'password_confirm' => 'Password confirmation required'])] public function change_password($data): bool { - if ($data['password'] != $data['password_confirm']) { - throw new InformationException('Passwords do not match'); - } + $this->di['validator']->passwordsMatch($data); $this->di['validator']->isPasswordStrong($data['password']); @@ -498,7 +472,7 @@ class Admin extends \Api_Abstract $clients = $this->di['db']->find('Client', 'client_group_id = :group_id', [':group_id' => $data['id']]); - if ((is_countable($clients) ? count($clients) : 0) > 0) { + if (\FOSSBilling\Tools::safeCount($clients) > 0) { throw new InformationException('Group has clients assigned. Please reassign them first.'); } diff --git a/src/modules/Client/Api/Client.php b/src/modules/Client/Api/Client.php index b5ceb3c7e..d33d91761 100644 --- a/src/modules/Client/Api/Client.php +++ b/src/modules/Client/Api/Client.php @@ -1,5 +1,6 @@ di['validator']->passwordsMatch($data); $this->getService()->checkExtraRequiredFields($data); $this->getService()->checkCustomFields($data); @@ -205,9 +204,7 @@ class Guest extends \Api_Abstract { $this->di['events_manager']->fire(['event' => 'onBeforeClientProfilePasswordReset', 'params' => $data['hash']]); - if ($data['password'] != $data['password_confirm']) { - throw new \FOSSBilling\InformationException('Passwords do not match'); - } + $this->di['validator']->passwordsMatch($data); $reset = $this->di['db']->findOne('ClientPasswordReset', 'hash = ?', [$data['hash']]); if (!$reset instanceof \Model_ClientPasswordReset) { diff --git a/src/modules/Client/Controller/Admin.php b/src/modules/Client/Controller/Admin.php index b96024361..e27efeaac 100644 --- a/src/modules/Client/Controller/Admin.php +++ b/src/modules/Client/Controller/Admin.php @@ -1,5 +1,6 @@ di['mod_service']('Order'); $orders = $orderService->getSoonExpiringActiveOrders(); - if ((is_countable($orders) ? count($orders) : 0) == 0) { + if (\FOSSBilling\Tools::safeCount($orders) == 0) { return true; } @@ -1443,7 +1444,7 @@ class Service implements InjectionAwareInterface ->setTax($item['tax']) ->setQuantity($item['quantity']); $items[] = $pi; - if (is_null($first_title) && (is_countable($proforma['lines']) ? count($proforma['lines']) : 0) == 1) { + if (is_null($first_title) && \FOSSBilling\Tools::safeCount($proforma['lines']) == 1) { $first_title = $item['title']; } } diff --git a/src/modules/Invoice/ServiceInvoiceItem.php b/src/modules/Invoice/ServiceInvoiceItem.php index 7696731fb..c96b84dfc 100644 --- a/src/modules/Invoice/ServiceInvoiceItem.php +++ b/src/modules/Invoice/ServiceInvoiceItem.php @@ -1,5 +1,6 @@ di['db']->find('Product', 'type = :type', [':type' => $type]); - if ((is_countable($products) ? count($products) : 0) <= 0) { + if (\FOSSBilling\Tools::safeCount($products) <= 0) { return []; } diff --git a/src/modules/Product/Controller/Admin.php b/src/modules/Product/Controller/Admin.php index 483b0e09d..73d4aca9e 100644 --- a/src/modules/Product/Controller/Admin.php +++ b/src/modules/Product/Controller/Admin.php @@ -1,5 +1,6 @@ di['db']->getAll('SELECT id, title FROM product WHERE id in (' . $slots . ')', $ids); @@ -790,7 +792,8 @@ class Service implements InjectionAwareInterface return []; } - $slots = (is_countable($ids) ? count($ids) : 0) ? implode(',', array_fill(0, is_countable($ids) ? count($ids) : 0, '?')) : ''; // same as RedBean genSlots() method + $count = \FOSSBilling\Tools::safeCount($ids); + $slots = $count ? implode(',', array_fill(0, $count, '?')) : ''; // same as RedBean genSlots() method array_unshift($ids, (int) $model->id); // adding product ID as first param in array return $this->di['db']->find('Product', 'type = "custom" and is_addon= 1 and id != ? and id IN (' . $slots . ')', $ids); diff --git a/src/modules/Profile/Api/Admin.php b/src/modules/Profile/Api/Admin.php index eeaa9930d..47e64e7ca 100644 --- a/src/modules/Profile/Api/Admin.php +++ b/src/modules/Profile/Api/Admin.php @@ -1,5 +1,6 @@ di['validator']->isPasswordStrong($data['new_password']); - - if ($data['new_password'] != $data['confirm_password']) { - throw new \FOSSBilling\InformationException('Passwords do not match'); - } + $this->di['validator']->passwordsMatch($data, 'new_password', 'confirm_password'); $client = $this->getIdentity(); diff --git a/src/modules/Profile/ClientValidator.php b/src/modules/Profile/ClientValidator.php index d56d3ca74..c70d06635 100644 --- a/src/modules/Profile/ClientValidator.php +++ b/src/modules/Profile/ClientValidator.php @@ -1,5 +1,6 @@ di['db']->find('ServiceDomain', 'tld = :tld', [':tld' => $data['tld']]); - $count = is_countable($service_domains) ? count($service_domains) : 0; + $count = \FOSSBilling\Tools::safeCount($service_domains); if ($count > 0) { throw new \FOSSBilling\InformationException('TLD is used by :count: domains', [':count:' => $count], 707); } diff --git a/src/modules/Servicedomain/Api/Client.php b/src/modules/Servicedomain/Api/Client.php index 7d2882c8e..b031cef39 100644 --- a/src/modules/Servicedomain/Api/Client.php +++ b/src/modules/Servicedomain/Api/Client.php @@ -1,5 +1,6 @@ di['db']->find('ServiceDomain', 'tld_registrar_id = :registrar_id', [':registrar_id' => $model->id]); - $count = is_countable($domains) ? count($domains) : 0; + $count = \FOSSBilling\Tools::safeCount($domains); if ($count > 0) { throw new \FOSSBilling\InformationException('Registrar is used by :count: domains', [':count:' => $count], 707); diff --git a/src/modules/Servicedomain/ServiceTld.php b/src/modules/Servicedomain/ServiceTld.php index fa60ca938..f7f4c2c8a 100644 --- a/src/modules/Servicedomain/ServiceTld.php +++ b/src/modules/Servicedomain/ServiceTld.php @@ -1,5 +1,6 @@ di['validator']->passwordsMatch($data); $this->di['validator']->isPasswordStrong($data['password']); diff --git a/src/modules/Staff/Api/Guest.php b/src/modules/Staff/Api/Guest.php index 41b30ccb9..ae256fa46 100644 --- a/src/modules/Staff/Api/Guest.php +++ b/src/modules/Staff/Api/Guest.php @@ -1,5 +1,6 @@ di['db']->findOne('Admin', '1=1')) || count($this->di['db']->findOne('Admin', '1=1')) == 0); + $allow = !\FOSSBilling\Tools::safeCount($this->di['db']->findOne('Admin', '1=1')); if (!$allow) { throw new \FOSSBilling\InformationException('Administrator account already exists', null, 55); } @@ -96,10 +97,7 @@ class Guest extends \Api_Abstract $validator = $this->di['validator']; $validator->checkRequiredParamsForArray($required, $data); - - if ($data['password'] != $data['password_confirm']) { - throw new \FOSSBilling\InformationException('Passwords do not match'); - } + $validator->passwordsMatch($data); $reset = $this->di['db']->findOne('AdminPasswordReset', 'hash = ?', [$data['code']]); if (!$reset instanceof \Model_AdminPasswordReset) { diff --git a/src/modules/Staff/Controller/Admin.php b/src/modules/Staff/Controller/Admin.php index 29b9b44dc..56a218183 100644 --- a/src/modules/Staff/Controller/Admin.php +++ b/src/modules/Staff/Controller/Admin.php @@ -1,5 +1,6 @@ id; $tickets = $this->di['db']->find('SupportTicket', 'support_helpdesk_id = :support_helpdesk_id', [':support_helpdesk_id' => $model->id]); - if ((is_countable($tickets) ? count($tickets) : 0) > 0) { + if (\FOSSBilling\Tools::safeCount($tickets) > 0) { throw new InformationException('Cannot remove helpdesk which has tickets'); } $this->di['db']->trash($model); diff --git a/src/modules/System/Api/Admin.php b/src/modules/System/Api/Admin.php index d5086ec2e..ecdedf4f1 100644 --- a/src/modules/System/Api/Admin.php +++ b/src/modules/System/Api/Admin.php @@ -1,5 +1,6 @@ toArray(); } diff --git a/src/modules/System/Commands/ReleaseNotes.php b/src/modules/System/Commands/ReleaseNotes.php index 7e8864346..5e81f06dc 100644 --- a/src/modules/System/Commands/ReleaseNotes.php +++ b/src/modules/System/Commands/ReleaseNotes.php @@ -1,5 +1,6 @@ { + const titles = { + error: "Error", + warning: "Warning", + success: "Success", + }; + const title = titles[type] || "Info"; let color; switch (type) { case "error": @@ -10,20 +16,22 @@ globalThis.FOSSBilling = { case "warning": color = "warning"; break; + case "success": + color = "success"; + break; default: color = "primary"; } - const container = document.querySelector(".toast-container"); // Get the existing container or create if not present + const container = document.querySelector(".toast-container"); const element = document.createElement("div"); container.appendChild(element); - element.classList.add("toast", "show"); // Add 'show' class to display the toast immediately + element.classList.add("toast", "show"); element.setAttribute("role", "alert"); element.setAttribute("aria-live", "assertive"); element.setAttribute("aria-atomic", "true"); - // Create header div and its children elements const headerDiv = document.createElement("div"); headerDiv.className = "toast-header"; @@ -33,7 +41,7 @@ globalThis.FOSSBilling = { const strongEl = document.createElement("strong"); strongEl.className = "me-auto"; - strongEl.textContent = "System message"; + strongEl.textContent = title; headerDiv.appendChild(strongEl); const closeButton = document.createElement("button"); @@ -45,17 +53,15 @@ globalThis.FOSSBilling = { element.appendChild(headerDiv); - // Create body div and set its text content const bodyDiv = document.createElement("div"); bodyDiv.className = "toast-body"; - bodyDiv.textContent = message; // Safely set the message content + bodyDiv.textContent = message; element.appendChild(bodyDiv); element.addEventListener("hidden.bs.toast", () => { - container.removeChild(element); // Remove the toast element from the container when it's hidden + container.removeChild(element); }); - // Create a new Bootstrap toast instance and show it const toast = new bootstrap.Toast(element); toast.show(); }, @@ -86,25 +92,14 @@ globalThis.FOSSBilling = { //===== Global ajax methods =====// document.addEventListener('DOMContentLoaded', function() { - // Global error handler for unhandled Promise rejections + // Global error handler for unhandled Promise rejections (API-related only) window.addEventListener('unhandledrejection', function(event) { const error = event.reason; - let message = 'An unexpected error occurred'; - if (error && typeof error === 'object') { - message = error.message || error.code || message; - } else if (typeof error === 'string') { - message = error; + if (error && typeof error === 'object' && error.code) { + event.preventDefault(); + const message = error.message || error.code || 'An unexpected error occurred'; + FOSSBilling.message(message, 'error'); } - FOSSBilling.message(message, 'error'); - }); - - // Global error handler for synchronous errors - window.addEventListener('error', function(event) { - let displayMessage = event && event.message ? event.message : 'An unexpected error occurred'; - if (event && event.error && event.error.message) { - displayMessage = event.error.message; - } - FOSSBilling.message(displayMessage, 'error'); }); // Attach event listeners to all forms and links with data-fb-api attribute. diff --git a/src/themes/admin_default/assets/js/ui/modals.js b/src/themes/admin_default/assets/js/ui/modals.js index 59c9fc17b..1d86a9323 100644 --- a/src/themes/admin_default/assets/js/ui/modals.js +++ b/src/themes/admin_default/assets/js/ui/modals.js @@ -179,7 +179,7 @@ globalThis.Modals = { options.type === "small-confirm" ? this.templates.smallConfirm : template; return template.replace(/{{\s?(\w+)\s?}}/g, function (match, key) { - return options[key]; + return options[key] !== undefined ? options[key] : ''; }); }, diff --git a/tests/APIHelper.php b/tests/APIHelper.php index f20dd093e..1c0a45cd0 100644 --- a/tests/APIHelper.php +++ b/tests/APIHelper.php @@ -66,10 +66,12 @@ class Response public function __construct(private readonly int $code, private readonly string $rawResponse) { - $this->decodedResponse = json_decode($this->rawResponse, true); - if (json_last_error() !== JSON_ERROR_NONE) { - throw new \RuntimeException('Invalid JSON response: ' . json_last_error_msg()); + $decoded = json_decode($this->rawResponse, true); + if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) { + $preview = strlen($this->rawResponse) > 500 ? substr($this->rawResponse, 0, 500) . '...' : $this->rawResponse; + throw new \RuntimeException('Invalid JSON response: ' . json_last_error_msg() . ' (HTTP ' . $this->code . '). Response: ' . $preview); } + $this->decodedResponse = $decoded; } public function getHttpCode(): int