diff --git a/.github/workflows/syntax.yml b/.github/workflows/syntax.yml index 7d6c51366b..fd7d75ee43 100644 --- a/.github/workflows/syntax.yml +++ b/.github/workflows/syntax.yml @@ -161,6 +161,21 @@ jobs: sudo chmod 777 ${{ github.workspace }}/include/config.php cat ${{ github.workspace}}/include/config.php + - name: Validate composer.json and composer.lock + run: composer validate --strict + + - name: Cache Composer packages + id: composer-cache + uses: actions/cache@v3 + with: + path: include/vendor + key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-php- + + - name: Install dependencies + run: composer install --prefer-dist --no-progress + - name: Check install code for validity run: | cd ${{ github.workspace }} @@ -190,21 +205,6 @@ jobs: - name: View contents of logs run: sudo cat ${{ github.workspace }}/log/cacti.log -# - name: Validate composer.json and composer.lock -# run: composer validate --strict - -# - name: Cache Composer packages -# id: composer-cache -# uses: actions/cache@v3 -# with: -# path: vendor -# key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} -# restore-keys: | -# ${{ runner.os }}-php- -# -# - name: Install dependencies -# run: composer install --prefer-dist --no-progress - # Add a test script to composer.json, for instance: "test": "vendor/bin/phpunit" # Docs: https://getcomposer.org/doc/articles/scripts.md diff --git a/composer.json b/composer.json index 94095b4eab..9d75a05596 100644 --- a/composer.json +++ b/composer.json @@ -1,30 +1,30 @@ { - "_copyright": { - "01": "+-------------------------------------------------------------------------+", - "02": "| Copyright (C) 2004-2023 The Cacti Group |", - "03": "| |", - "04": "| This program is free software; you can redistribute it and/or |", - "05": "| modify it under the terms of the GNU General Public License |", - "06": "| as published by the Free Software Foundation; either version 2 |", - "07": "| of the License, or (at your option) any later version. |", - "08": "| |", - "09": "| This program is distributed in the hope that it will be useful, |", - "10": "| but WITHOUT ANY WARRANTY; without even the implied warranty of |", - "11": "| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |", - "12": "| GNU General Public License for more details. |", - "13": "+-------------------------------------------------------------------------+", - "14": "| Cacti: The Complete RRDtool-based Graphing Solution |", - "15": "+-------------------------------------------------------------------------+", - "16": "| This code is designed, written, and maintained by the Cacti Group. See |", - "17": "| about.php and/or the AUTHORS file for specific developer information. |", - "18": "+-------------------------------------------------------------------------+", - "19": "| http://www.cacti.net/ |", - "20": "+-------------------------------------------------------------------------+" - }, + "_comment": [ + "+-------------------------------------------------------------------------+", + "| Copyright (C) 2004-2025 The Cacti Group |", + "| |", + "| This program is free software; you can redistribute it and/or |", + "| modify it under the terms of the GNU General Public License |", + "| as published by the Free Software Foundation; either version 2 |", + "| of the License, or (at your option) any later version. |", + "| |", + "| This program is distributed in the hope that it will be useful, |", + "| but WITHOUT ANY WARRANTY; without even the implied warranty of |", + "| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |", + "| GNU General Public License for more details. |", + "+-------------------------------------------------------------------------+", + "| Cacti: The Complete RRDtool-based Graphing Solution |", + "+-------------------------------------------------------------------------+", + "| This code is designed, written, and maintained by the Cacti Group. See |", + "| about.php and/or the AUTHORS file for specific developer information. |", + "+-------------------------------------------------------------------------+", + "| http://www.cacti.net/ |", + "+-------------------------------------------------------------------------+" + ], "name": "cacti/cacti", "description": "Cacti Network Monitoring Framework", "type": "composer-plugin", - "license": "GPL2", + "license": "GPL-2.0-only", "require": { "php": ">=8.0", "ext-PDO": "*", @@ -79,5 +79,8 @@ "lint": "phplint --no-cache src/", "phpcsfixer": "php-cs-fixer fix --diff --dry-run --ansi", "phpcsfixit": "php-cs-fixer fix --ansi" + }, + "require-dev": { + "rector/rector": "^2.0" } } diff --git a/composer.lock b/composer.lock index c983a5aa0d..0556599b4d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "34f1ae13f314fa0628a505258127079e", + "content-hash": "1d63b984f64281347a203d389a46d52d", "packages": [ { "name": "firebase/php-jwt", @@ -1293,10 +1293,128 @@ "time": "2024-09-25T14:20:29+00:00" } ], - "packages-dev": [], + "packages-dev": [ + { + "name": "phpstan/phpstan", + "version": "2.1.6", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan.git", + "reference": "6eaec7c6c9e90dcfe46ad1e1ffa5171e2dab641c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/6eaec7c6c9e90dcfe46ad1e1ffa5171e2dab641c", + "reference": "6eaec7c6c9e90dcfe46ad1e1ffa5171e2dab641c", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "docs": "https://phpstan.org/user-guide/getting-started", + "forum": "https://github.com/phpstan/phpstan/discussions", + "issues": "https://github.com/phpstan/phpstan/issues", + "security": "https://github.com/phpstan/phpstan/security/policy", + "source": "https://github.com/phpstan/phpstan-src" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + } + ], + "time": "2025-02-19T15:46:42+00:00" + }, + { + "name": "rector/rector", + "version": "2.0.9", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "4393230e478c0006795770fe74c223b5c64ed68c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/4393230e478c0006795770fe74c223b5c64ed68c", + "reference": "4393230e478c0006795770fe74c223b5c64ed68c", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0", + "phpstan/phpstan": "^2.1.3" + }, + "conflict": { + "rector/rector-doctrine": "*", + "rector/rector-downgrade-php": "*", + "rector/rector-phpunit": "*", + "rector/rector-symfony": "*" + }, + "suggest": { + "ext-dom": "To manipulate phpunit.xml via the custom-rule command" + }, + "bin": [ + "bin/rector" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/2.0.9" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "time": "2025-02-10T08:14:01+00:00" + } + ], "aliases": [], "minimum-stability": "dev", - "stability-flags": [], + "stability-flags": {}, "prefer-stable": true, "prefer-lowest": false, "platform": { @@ -1319,6 +1437,6 @@ "ext-sqlite3": "*", "ext-xml": "*" }, - "platform-dev": [], - "plugin-api-version": "2.3.0" + "platform-dev": {}, + "plugin-api-version": "2.6.0" } diff --git a/include/auth.php b/include/auth.php index a9a5895083..6aa2db8455 100644 --- a/include/auth.php +++ b/include/auth.php @@ -74,7 +74,7 @@ */ if ($auth_method != AUTH_METHOD_BASIC) { if (isset($_SESSION[SESS_CHANGE_PASSWORD])) { - header('Location: ' . CACTI_PATH_URL . 'auth_changepassword.php?ref=' . (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'index.php')); + header('Location: ' . CACTI_PATH_URL . 'auth_changepassword.php?ref=' . ($_SERVER['HTTP_REFERER'] ?? 'index.php')); exit; } diff --git a/include/global.php b/include/global.php index 69930cf119..9833b39e7a 100644 --- a/include/global.php +++ b/include/global.php @@ -165,9 +165,9 @@ foreach ($db_var_defaults as $db_var_name => $db_var_default) { $db_var_full = $db_var_prefix . $db_var_name; - if (!isset($$db_var_full)) { + if (!isset(${$db_var_full})) { if ($db_var_default !== null) { - $$db_var_full = $db_var_default; + ${$db_var_full} = $db_var_default; } else { $db_missing_vars .= (($db_missing_vars == '') ? 'missing ' : ', ') . $db_var_full; } @@ -225,7 +225,7 @@ /* define any additional paths as constants */ foreach ($config as $key => $value) { - if (substr($key, -5) == '_path') { + if (str_ends_with($key, '_path')) { $path_name = substr($key, 0, -5); $constant_name = 'CACTI_PATH_' . strtoupper($path_name); @@ -596,7 +596,7 @@ foreach ($input as $var => $val) { if (!in_array($var, $not_unset, true)) { - unset($$var); + unset(${$var}); } } diff --git a/include/global_languages.php b/include/global_languages.php index cb1dd6e944..a793a08252 100644 --- a/include/global_languages.php +++ b/include/global_languages.php @@ -299,7 +299,7 @@ function get_src_language_files($i18n_handler) { ); } - $i18n_handler_text = ($i18n_handler === null) ? 'null' : $i18n_handler; + $i18n_handler_text = $i18n_handler ?? 'null'; foreach ($i18n_providers as $i18n_provider) { $found = true; @@ -566,7 +566,7 @@ function set_language_constants(array $constants) { function __gettext(?string $text, string $domain = 'cacti') { global $i18n; - $text = $text ?? ''; + $text ??= ''; // Assume translation fails or is not defined if (isset($i18n[$domain])) { @@ -594,8 +594,8 @@ function __gettext(?string $text, string $domain = 'cacti') { function __n(?string $singular, ?string $plural, $number, string $domain = 'cacti') { global $i18n; - $singular = $singular ?? ''; - $plural = $plural ?? ''; + $singular ??= ''; + $plural ??= ''; if (isset($i18n[$domain])) { return __uf($i18n[$domain]->ngettext($singular, $plural, $number)); @@ -931,12 +931,12 @@ function number_format_i18n($number, $decimals = null, $baseu = 1024) { $number = 0; } elseif ($decimals == -1 || $decimals == null) { $number = number_format($number, 0, $locale['decimal_point'], $locale['thousands_sep']); - } elseif ($number >= pow($baseu, 4)) { - $number = number_format($number / pow($baseu, 4), $decimals, $locale['decimal_point'], $locale['thousands_sep']) . __(' T'); - } elseif ($number >= pow($baseu, 3)) { - $number = number_format($number / pow($baseu, 3), $decimals, $locale['decimal_point'], $locale['thousands_sep']) . __(' G'); - } elseif ($number >= pow($baseu, 2)) { - $number = number_format($number / pow($baseu, 2), $decimals, $locale['decimal_point'], $locale['thousands_sep']) . __(' M'); + } elseif ($number >= $baseu ** 4) { + $number = number_format($number / $baseu ** 4, $decimals, $locale['decimal_point'], $locale['thousands_sep']) . __(' T'); + } elseif ($number >= $baseu ** 3) { + $number = number_format($number / $baseu ** 3, $decimals, $locale['decimal_point'], $locale['thousands_sep']) . __(' G'); + } elseif ($number >= $baseu ** 2) { + $number = number_format($number / $baseu ** 2, $decimals, $locale['decimal_point'], $locale['thousands_sep']) . __(' M'); } elseif ($number >= $baseu) { $number = number_format($number / $baseu, $decimals, $locale['decimal_point'], $locale['thousands_sep']) . __(' K'); } else { @@ -944,8 +944,8 @@ function number_format_i18n($number, $decimals = null, $baseu = 1024) { } foreach ($origlocales as $locale_setting) { - if (strpos($locale_setting, '=') !== false) { - list($category, $locale) = explode('=', $locale_setting); + if (str_contains($locale_setting, '=')) { + [$category, $locale] = explode('=', $locale_setting); } else { $category = LC_ALL; $locale = $locale_setting; @@ -980,7 +980,7 @@ function get_new_user_default_language() { function i18n_debug($text, $mode = FILE_APPEND, $eol = PHP_EOL) { global $config; - if (!empty($config['i18n_log']) && is_writeable($config['i18n_log'])) { + if (!empty($config['i18n_log']) && is_writable($config['i18n_log'])) { file_put_contents($config['i18n_log'], $text . $eol, $mode); } } @@ -988,7 +988,7 @@ function i18n_debug($text, $mode = FILE_APPEND, $eol = PHP_EOL) { function i18n_text_debug($text, $mode = FILE_APPEND, $eol = PHP_EOL) { global $config; - if (!empty($config['i18n_text_log']) && is_writeable($config['i18n_log'])) { + if (!empty($config['i18n_text_log']) && is_writable($config['i18n_log'])) { file_put_contents($config['i18n_text_log'], $text . $eol, $mode); } } diff --git a/include/global_session.php b/include/global_session.php index abc9131898..c4254a1cf5 100644 --- a/include/global_session.php +++ b/include/global_session.php @@ -89,7 +89,7 @@ $myrefresh['seconds'] = 99999999; $myrefresh['page'] = 'index.php'; $refreshIsLogout = 'false'; -} elseif (!isset($_SESSION[SESS_USER_ID]) && isset($_SERVER['REQUEST_URL']) && strpos($_SERVER['REQUEST_URI'], 'index.php') !== false) { +} elseif (!isset($_SESSION[SESS_USER_ID]) && isset($_SERVER['REQUEST_URL']) && str_contains($_SERVER['REQUEST_URI'], 'index.php')) { $myrefresh['seconds'] = 99999999; $myrefresh['page'] = sanitize_uri($_SERVER['REQUEST_URI']); $refreshIsLogout = 'false'; diff --git a/include/session.php b/include/session.php index a69bce7e26..84eb11d3ef 100644 --- a/include/session.php +++ b/include/session.php @@ -93,7 +93,7 @@ function cacti_db_session_write($id, $data) { } $client_addr = get_client_addr(); - $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT']:'Unknown'; + $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'; if ($user_id > 0) { db_execute_prepared('INSERT INTO sessions @@ -105,7 +105,7 @@ function cacti_db_session_write($id, $data) { user_agent = VALUES(user_agent), transactions = transactions + 1', array($id, $client_addr, $access, $data, $user_id, $user_agent)); - } elseif (strpos($data, 'ses_user_id') !== false) { + } elseif (str_contains($data, 'ses_user_id')) { db_execute_prepared('INSERT INTO sessions (id, remote_addr, access, data, user_agent) VALUES (?, ?, ?, ?, ?) diff --git a/include/vendor/autoload.php b/include/vendor/autoload.php index 13b2175214..69f821b111 100644 --- a/include/vendor/autoload.php +++ b/include/vendor/autoload.php @@ -3,8 +3,21 @@ // autoload.php @generated by Composer if (PHP_VERSION_ID < 50600) { - echo 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; - exit(1); + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, $err); + } elseif (!headers_sent()) { + echo $err; + } + } + trigger_error( + $err, + E_USER_ERROR + ); } require_once __DIR__ . '/composer/autoload_real.php'; diff --git a/include/vendor/composer/ClassLoader.php b/include/vendor/composer/ClassLoader.php index afef3fa2ad..7824d8f7ea 100644 --- a/include/vendor/composer/ClassLoader.php +++ b/include/vendor/composer/ClassLoader.php @@ -42,35 +42,37 @@ */ class ClassLoader { - /** @var ?string */ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var string|null */ private $vendorDir; // PSR-4 /** - * @var array[] - * @psalm-var array> + * @var array> */ private $prefixLengthsPsr4 = array(); /** - * @var array[] - * @psalm-var array> + * @var array> */ private $prefixDirsPsr4 = array(); /** - * @var array[] - * @psalm-var array + * @var list */ private $fallbackDirsPsr4 = array(); // PSR-0 /** - * @var array[] - * @psalm-var array> + * List of PSR-0 prefixes + * + * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) + * + * @var array>> */ private $prefixesPsr0 = array(); /** - * @var array[] - * @psalm-var array + * @var list */ private $fallbackDirsPsr0 = array(); @@ -78,8 +80,7 @@ class ClassLoader private $useIncludePath = false; /** - * @var string[] - * @psalm-var array + * @var array */ private $classMap = array(); @@ -87,29 +88,29 @@ class ClassLoader private $classMapAuthoritative = false; /** - * @var bool[] - * @psalm-var array + * @var array */ private $missingClasses = array(); - /** @var ?string */ + /** @var string|null */ private $apcuPrefix; /** - * @var self[] + * @var array */ private static $registeredLoaders = array(); /** - * @param ?string $vendorDir + * @param string|null $vendorDir */ public function __construct($vendorDir = null) { $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); } /** - * @return string[] + * @return array> */ public function getPrefixes() { @@ -121,8 +122,7 @@ public function getPrefixes() } /** - * @return array[] - * @psalm-return array> + * @return array> */ public function getPrefixesPsr4() { @@ -130,8 +130,7 @@ public function getPrefixesPsr4() } /** - * @return array[] - * @psalm-return array + * @return list */ public function getFallbackDirs() { @@ -139,8 +138,7 @@ public function getFallbackDirs() } /** - * @return array[] - * @psalm-return array + * @return list */ public function getFallbackDirsPsr4() { @@ -148,8 +146,7 @@ public function getFallbackDirsPsr4() } /** - * @return string[] Array of classname => path - * @psalm-return array + * @return array Array of classname => path */ public function getClassMap() { @@ -157,8 +154,7 @@ public function getClassMap() } /** - * @param string[] $classMap Class to filename map - * @psalm-param array $classMap + * @param array $classMap Class to filename map * * @return void */ @@ -175,24 +171,25 @@ public function addClassMap(array $classMap) * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * - * @param string $prefix The prefix - * @param string[]|string $paths The PSR-0 root directories - * @param bool $prepend Whether to prepend the directories + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories * * @return void */ public function add($prefix, $paths, $prepend = false) { + $paths = (array) $paths; if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( - (array) $paths, + $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, - (array) $paths + $paths ); } @@ -201,19 +198,19 @@ public function add($prefix, $paths, $prepend = false) $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { - $this->prefixesPsr0[$first][$prefix] = (array) $paths; + $this->prefixesPsr0[$first][$prefix] = $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( - (array) $paths, + $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], - (array) $paths + $paths ); } } @@ -222,9 +219,9 @@ public function add($prefix, $paths, $prepend = false) * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * - * @param string $prefix The prefix/namespace, with trailing '\\' - * @param string[]|string $paths The PSR-4 base directories - * @param bool $prepend Whether to prepend the directories + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException * @@ -232,17 +229,18 @@ public function add($prefix, $paths, $prepend = false) */ public function addPsr4($prefix, $paths, $prepend = false) { + $paths = (array) $paths; if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( - (array) $paths, + $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, - (array) $paths + $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { @@ -252,18 +250,18 @@ public function addPsr4($prefix, $paths, $prepend = false) throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; - $this->prefixDirsPsr4[$prefix] = (array) $paths; + $this->prefixDirsPsr4[$prefix] = $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( - (array) $paths, + $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], - (array) $paths + $paths ); } } @@ -272,8 +270,8 @@ public function addPsr4($prefix, $paths, $prepend = false) * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * - * @param string $prefix The prefix - * @param string[]|string $paths The PSR-0 base directories + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 base directories * * @return void */ @@ -290,8 +288,8 @@ public function set($prefix, $paths) * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * - * @param string $prefix The prefix/namespace, with trailing '\\' - * @param string[]|string $paths The PSR-4 base directories + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException * @@ -425,7 +423,8 @@ public function unregister() public function loadClass($class) { if ($file = $this->findFile($class)) { - includeFile($file); + $includeFile = self::$includeFile; + $includeFile($file); return true; } @@ -476,9 +475,9 @@ public function findFile($class) } /** - * Returns the currently registered loaders indexed by their corresponding vendor directories. + * Returns the currently registered loaders keyed by their corresponding vendor directories. * - * @return self[] + * @return array */ public static function getRegisteredLoaders() { @@ -555,18 +554,26 @@ private function findFileWithExtension($class, $ext) return false; } -} -/** - * Scope isolated include. - * - * Prevents access to $this/self from included files. - * - * @param string $file - * @return void - * @private - */ -function includeFile($file) -{ - include $file; + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } } diff --git a/include/vendor/composer/InstalledVersions.php b/include/vendor/composer/InstalledVersions.php index c6b54af7ba..6a465a5d18 100644 --- a/include/vendor/composer/InstalledVersions.php +++ b/include/vendor/composer/InstalledVersions.php @@ -32,6 +32,11 @@ class InstalledVersions */ private static $installed; + /** + * @var bool + */ + private static $installedIsLocalDir; + /** * @var bool|null */ @@ -98,7 +103,7 @@ public static function isInstalled($packageName, $includeDevRequirements = true) { foreach (self::getInstalled() as $installed) { if (isset($installed['versions'][$packageName])) { - return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; } } @@ -119,7 +124,7 @@ public static function isInstalled($packageName, $includeDevRequirements = true) */ public static function satisfies(VersionParser $parser, $packageName, $constraint) { - $constraint = $parser->parseConstraints($constraint); + $constraint = $parser->parseConstraints((string) $constraint); $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); return $provided->matches($constraint); @@ -266,7 +271,7 @@ public static function getRawData() if (null === self::$installed) { // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 - if (substr(__DIR__, -8, 1) !== 'C') { + if (substr(__DIR__, -8, 1) !== 'C' && is_file(__DIR__ . '/installed.php')) { self::$installed = include __DIR__ . '/installed.php'; } else { self::$installed = array(); @@ -309,6 +314,12 @@ public static function reload($data) { self::$installed = $data; self::$installedByVendor = array(); + + // when using reload, we disable the duplicate protection to ensure that self::$installed data is + // always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not, + // so we have to assume it does not, and that may result in duplicate data being returned when listing + // all installed packages for example + self::$installedIsLocalDir = false; } /** @@ -322,30 +333,45 @@ private static function getInstalled() } $installed = array(); + $copiedLocalDir = false; if (self::$canGetVendors) { + $selfDir = strtr(__DIR__, '\\', '/'); foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + $vendorDir = strtr($vendorDir, '\\', '/'); if (isset(self::$installedByVendor[$vendorDir])) { $installed[] = self::$installedByVendor[$vendorDir]; } elseif (is_file($vendorDir.'/composer/installed.php')) { - $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; - if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { - self::$installed = $installed[count($installed) - 1]; + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + self::$installedByVendor[$vendorDir] = $required; + $installed[] = $required; + if (self::$installed === null && $vendorDir.'/composer' === $selfDir) { + self::$installed = $required; + self::$installedIsLocalDir = true; } } + if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) { + $copiedLocalDir = true; + } } } if (null === self::$installed) { // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 - if (substr(__DIR__, -8, 1) !== 'C') { - self::$installed = require __DIR__ . '/installed.php'; + if (substr(__DIR__, -8, 1) !== 'C' && is_file(__DIR__ . '/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; } else { self::$installed = array(); } } - $installed[] = self::$installed; + + if (self::$installed !== array() && !$copiedLocalDir) { + $installed[] = self::$installed; + } return $installed; } diff --git a/include/vendor/composer/LICENSE b/include/vendor/composer/LICENSE index f27399a042..62ecfd8d00 100644 --- a/include/vendor/composer/LICENSE +++ b/include/vendor/composer/LICENSE @@ -1,4 +1,3 @@ - Copyright (c) Nils Adermann, Jordi Boggiano Permission is hereby granted, free of charge, to any person obtaining a copy @@ -18,4 +17,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/include/vendor/composer/autoload_files.php b/include/vendor/composer/autoload_files.php index ed57677c47..a632c69f4c 100644 --- a/include/vendor/composer/autoload_files.php +++ b/include/vendor/composer/autoload_files.php @@ -9,4 +9,6 @@ '7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', + '9b38cf48e83f5d8f60375221cd213eee' => $vendorDir . '/phpstan/phpstan/bootstrap.php', + '38143a9afc50997d55e4815db8489d1c' => $vendorDir . '/rector/rector/bootstrap.php', ); diff --git a/include/vendor/composer/autoload_psr4.php b/include/vendor/composer/autoload_psr4.php index 41fe7b7d62..bb272ef168 100644 --- a/include/vendor/composer/autoload_psr4.php +++ b/include/vendor/composer/autoload_psr4.php @@ -6,14 +6,14 @@ $baseDir = dirname(dirname($vendorDir)); return array( - 'Stevenmaguire\\OAuth2\\Client\\' => array($vendorDir . '/stevenmaguire/oauth2-keycloak/src', $vendorDir . '/stevenmaguire/oauth2-microsoft/src'), + 'Stevenmaguire\\OAuth2\\Client\\' => array($vendorDir . '/stevenmaguire/oauth2-microsoft/src', $vendorDir . '/stevenmaguire/oauth2-keycloak/src'), 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'), 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), 'PhpMqtt\\Client\\' => array($vendorDir . '/php-mqtt/client/src'), 'PHPMailer\\PHPMailer\\' => array($vendorDir . '/phpmailer/phpmailer/src'), 'MyCLabs\\Enum\\' => array($vendorDir . '/myclabs/php-enum/src'), - 'League\\OAuth2\\Client\\' => array($vendorDir . '/league/oauth2-client/src', $vendorDir . '/league/oauth2-google/src'), + 'League\\OAuth2\\Client\\' => array($vendorDir . '/league/oauth2-google/src', $vendorDir . '/league/oauth2-client/src'), 'Hayageek\\OAuth2\\Client\\' => array($vendorDir . '/hayageek/oauth2-yahoo/src'), 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), diff --git a/include/vendor/composer/autoload_real.php b/include/vendor/composer/autoload_real.php index 8c7175fb9f..7e37079fd7 100644 --- a/include/vendor/composer/autoload_real.php +++ b/include/vendor/composer/autoload_real.php @@ -33,25 +33,18 @@ public static function getLoader() $loader->register(true); - $includeFiles = \Composer\Autoload\ComposerStaticInit4457df976b6743d4cf060b8bfc645118::$files; - foreach ($includeFiles as $fileIdentifier => $file) { - composerRequire4457df976b6743d4cf060b8bfc645118($fileIdentifier, $file); + $filesToLoad = \Composer\Autoload\ComposerStaticInit4457df976b6743d4cf060b8bfc645118::$files; + $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + + require $file; + } + }, null, null); + foreach ($filesToLoad as $fileIdentifier => $file) { + $requireFile($fileIdentifier, $file); } return $loader; } } - -/** - * @param string $fileIdentifier - * @param string $file - * @return void - */ -function composerRequire4457df976b6743d4cf060b8bfc645118($fileIdentifier, $file) -{ - if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { - $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; - - require $file; - } -} diff --git a/include/vendor/composer/autoload_static.php b/include/vendor/composer/autoload_static.php index 30fdd1503d..f53948dc3f 100644 --- a/include/vendor/composer/autoload_static.php +++ b/include/vendor/composer/autoload_static.php @@ -10,6 +10,8 @@ class ComposerStaticInit4457df976b6743d4cf060b8bfc645118 '7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', + '9b38cf48e83f5d8f60375221cd213eee' => __DIR__ . '/..' . '/phpstan/phpstan/bootstrap.php', + '38143a9afc50997d55e4815db8489d1c' => __DIR__ . '/..' . '/rector/rector/bootstrap.php', ); public static $prefixLengthsPsr4 = array ( @@ -53,8 +55,8 @@ class ComposerStaticInit4457df976b6743d4cf060b8bfc645118 public static $prefixDirsPsr4 = array ( 'Stevenmaguire\\OAuth2\\Client\\' => array ( - 0 => __DIR__ . '/..' . '/stevenmaguire/oauth2-keycloak/src', - 1 => __DIR__ . '/..' . '/stevenmaguire/oauth2-microsoft/src', + 0 => __DIR__ . '/..' . '/stevenmaguire/oauth2-microsoft/src', + 1 => __DIR__ . '/..' . '/stevenmaguire/oauth2-keycloak/src', ), 'Psr\\Log\\' => array ( @@ -83,8 +85,8 @@ class ComposerStaticInit4457df976b6743d4cf060b8bfc645118 ), 'League\\OAuth2\\Client\\' => array ( - 0 => __DIR__ . '/..' . '/league/oauth2-client/src', - 1 => __DIR__ . '/..' . '/league/oauth2-google/src', + 0 => __DIR__ . '/..' . '/league/oauth2-google/src', + 1 => __DIR__ . '/..' . '/league/oauth2-client/src', ), 'Hayageek\\OAuth2\\Client\\' => array ( diff --git a/include/vendor/composer/installed.json b/include/vendor/composer/installed.json index 2361860343..c59137f996 100644 --- a/include/vendor/composer/installed.json +++ b/include/vendor/composer/installed.json @@ -886,6 +886,67 @@ ], "install-path": "../phpmailer/phpmailer" }, + { + "name": "phpstan/phpstan", + "version": "2.1.6", + "version_normalized": "2.1.6.0", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan.git", + "reference": "6eaec7c6c9e90dcfe46ad1e1ffa5171e2dab641c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/6eaec7c6c9e90dcfe46ad1e1ffa5171e2dab641c", + "reference": "6eaec7c6c9e90dcfe46ad1e1ffa5171e2dab641c", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "time": "2025-02-19T15:46:42+00:00", + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "docs": "https://phpstan.org/user-guide/getting-started", + "forum": "https://github.com/phpstan/phpstan/discussions", + "issues": "https://github.com/phpstan/phpstan/issues", + "security": "https://github.com/phpstan/phpstan/security/policy", + "source": "https://github.com/phpstan/phpstan-src" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + } + ], + "install-path": "../phpstan/phpstan" + }, { "name": "psr/http-client", "version": "1.0.3", @@ -1155,6 +1216,68 @@ }, "install-path": "../ralouphie/getallheaders" }, + { + "name": "rector/rector", + "version": "2.0.9", + "version_normalized": "2.0.9.0", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "4393230e478c0006795770fe74c223b5c64ed68c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/4393230e478c0006795770fe74c223b5c64ed68c", + "reference": "4393230e478c0006795770fe74c223b5c64ed68c", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0", + "phpstan/phpstan": "^2.1.3" + }, + "conflict": { + "rector/rector-doctrine": "*", + "rector/rector-downgrade-php": "*", + "rector/rector-phpunit": "*", + "rector/rector-symfony": "*" + }, + "suggest": { + "ext-dom": "To manipulate phpunit.xml via the custom-rule command" + }, + "time": "2025-02-10T08:14:01+00:00", + "bin": [ + "bin/rector" + ], + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/2.0.9" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "install-path": "../rector/rector" + }, { "name": "stevenmaguire/oauth2-keycloak", "version": "5.1.0", @@ -1348,5 +1471,8 @@ } ], "dev": true, - "dev-package-names": [] + "dev-package-names": [ + "phpstan/phpstan", + "rector/rector" + ] } diff --git a/include/vendor/composer/installed.php b/include/vendor/composer/installed.php index ead32e2490..d66cbd6fbd 100644 --- a/include/vendor/composer/installed.php +++ b/include/vendor/composer/installed.php @@ -1,9 +1,9 @@ array( 'name' => 'cacti/cacti', - 'pretty_version' => '1.0.0+no-version-set', - 'version' => '1.0.0.0', - 'reference' => NULL, + 'pretty_version' => 'dev-develop', + 'version' => 'dev-develop', + 'reference' => 'fb05ea4a451ebb5766d82bfd4962130e546e76bf', 'type' => 'composer-plugin', 'install_path' => __DIR__ . '/../../../', 'aliases' => array(), @@ -11,9 +11,9 @@ ), 'versions' => array( 'cacti/cacti' => array( - 'pretty_version' => '1.0.0+no-version-set', - 'version' => '1.0.0.0', - 'reference' => NULL, + 'pretty_version' => 'dev-develop', + 'version' => 'dev-develop', + 'reference' => 'fb05ea4a451ebb5766d82bfd4962130e546e76bf', 'type' => 'composer-plugin', 'install_path' => __DIR__ . '/../../../', 'aliases' => array(), @@ -127,6 +127,15 @@ 'aliases' => array(), 'dev_requirement' => false, ), + 'phpstan/phpstan' => array( + 'pretty_version' => '2.1.6', + 'version' => '2.1.6.0', + 'reference' => '6eaec7c6c9e90dcfe46ad1e1ffa5171e2dab641c', + 'type' => 'library', + 'install_path' => __DIR__ . '/../phpstan/phpstan', + 'aliases' => array(), + 'dev_requirement' => true, + ), 'psr/http-client' => array( 'pretty_version' => '1.0.3', 'version' => '1.0.3.0', @@ -190,6 +199,15 @@ 'aliases' => array(), 'dev_requirement' => false, ), + 'rector/rector' => array( + 'pretty_version' => '2.0.9', + 'version' => '2.0.9.0', + 'reference' => '4393230e478c0006795770fe74c223b5c64ed68c', + 'type' => 'library', + 'install_path' => __DIR__ . '/../rector/rector', + 'aliases' => array(), + 'dev_requirement' => true, + ), 'stevenmaguire/oauth2-keycloak' => array( 'pretty_version' => '5.1.0', 'version' => '5.1.0.0', diff --git a/lib/aggregate.php b/lib/aggregate.php index 33b827ca3c..c2d69146cc 100644 --- a/lib/aggregate.php +++ b/lib/aggregate.php @@ -247,7 +247,7 @@ function api_aggregate_create($aggregate_name, $graphs, $agg_template_id = 0) { * @param array $vars - additional variables */ function aggregate_error_handler($errno, $errmsg, $filename, $linenum, $vars = array()) { - $errno = $errno & error_reporting(); + $errno &= error_reporting(); # return if error handling disabled by @ if ($errno == 0) { diff --git a/lib/api_aggregate.php b/lib/api_aggregate.php index 8cd13d389e..7023a065c2 100644 --- a/lib/api_aggregate.php +++ b/lib/api_aggregate.php @@ -72,7 +72,7 @@ function aggregate_graph_local_save($id = 0) { cacti_log(__FUNCTION__ . ' local_graph: ' . $id, true, 'AGGREGATE', POLLER_VERBOSITY_DEVDBG); /* create or update entry: graph_local */ - $local_graph['id'] = (isset($id) ? $id : 0); + $local_graph['id'] = ($id ?? 0); $local_graph['graph_template_id'] = 0; # no templating $local_graph['host_id'] = 0; # no host to be referred to $local_graph['snmp_query_id'] = 0; # no templating @@ -122,7 +122,7 @@ function aggregate_graph_templates_graph_save($local_graph_id, $graph_template_i if (cacti_sizeof($aggregate_data)) { foreach ($aggregate_data as $field => $value) { - if (substr($field, 0, 2) == 't_' && $value == 'on') { + if (str_starts_with($field, 't_') && $value == 'on') { $value_field_name = substr($field, 2); $template_data[$value_field_name] = $aggregate_data[$value_field_name]; } @@ -429,7 +429,7 @@ function aggregate_graphs_insert_graph_items($_new_graph_id, $_old_graph_id, $_g } if ($save['text_format'] != '') { - $save['text_format'] = substitute_host_data($save['text_format'], '|', '|', (isset($graph_local['host_id']) ? $graph_local['host_id']:0)); + $save['text_format'] = substitute_host_data($save['text_format'], '|', '|', ($graph_local['host_id'] ?? 0)); cacti_log(__FUNCTION__ . ' substituted:' . $save['text_format'], true, 'AGGREGATE', POLLER_VERBOSITY_DEBUG); /* if this is a data query graph type, try to substitute */ @@ -456,7 +456,7 @@ function aggregate_graphs_insert_graph_items($_new_graph_id, $_old_graph_id, $_g $save['id'] = 0; $save['local_graph_template_item_id'] = 0; # disconnect this graph item from the graph template item - $save['local_graph_id'] = (isset($_new_graph_id) ? $_new_graph_id : 0); + $save['local_graph_id'] = ($_new_graph_id ?? 0); $save['graph_template_id'] = 0; # disconnect this graph item from the graph template $save['hash'] = ''; # remove any template attribs @@ -1102,19 +1102,19 @@ function aggregate_create_update(&$local_graph_id, $member_graphs, $attribs) { set_error_handler('aggregate_error_handler'); if (cacti_sizeof($member_graphs)) { - $graph_title = (isset($attribs['graph_title']) ? $attribs['graph_title']:''); - $aggregate_template = (isset($attribs['aggregate_template_id']) ? $attribs['aggregate_template_id']:0); - $graph_template_id = (isset($attribs['graph_template_id']) ? $attribs['graph_template_id']:0); - $aggregate_graph = (isset($attribs['aggregate_graph_id']) ? $attribs['aggregate_graph_id']:0); - $template_propogation = (isset($attribs['template_propogation']) ? $attribs['template_propogation']:'on'); - $gprint_prefix = (isset($attribs['gprint_prefix']) ? $attribs['gprint_prefix']:''); - $gprint_format = (isset($attribs['gprint_format']) ? $attribs['gprint_format']:''); - $_graph_type = (isset($attribs['graph_type']) ? $attribs['graph_type']:0); - $_total = (isset($attribs['total']) ? $attribs['total']:0); - $_total_type = (isset($attribs['total_type']) ? $attribs['total_type']:0); - $_total_prefix = (isset($attribs['total_prefix']) ? $attribs['total_prefix']:''); - $_reorder = (isset($attribs['reorder']) ? $attribs['reorder']:0); - $item_no = (isset($attribs['item_no']) ? $attribs['item_no']:0); + $graph_title = ($attribs['graph_title'] ?? ''); + $aggregate_template = ($attribs['aggregate_template_id'] ?? 0); + $graph_template_id = ($attribs['graph_template_id'] ?? 0); + $aggregate_graph = ($attribs['aggregate_graph_id'] ?? 0); + $template_propogation = ($attribs['template_propogation'] ?? 'on'); + $gprint_prefix = ($attribs['gprint_prefix'] ?? ''); + $gprint_format = ($attribs['gprint_format'] ?? ''); + $_graph_type = ($attribs['graph_type'] ?? 0); + $_total = ($attribs['total'] ?? 0); + $_total_type = ($attribs['total_type'] ?? 0); + $_total_prefix = ($attribs['total_prefix'] ?? ''); + $_reorder = ($attribs['reorder'] ?? 0); + $item_no = ($attribs['item_no'] ?? 0); $color_templates = (is_array($attribs['color_templates']) ? $attribs['color_templates']:array()); $graph_item_types = (is_array($attribs['graph_item_types']) ? $attribs['graph_item_types']:array()); $cdefs = (is_array($attribs['cdefs']) ? $attribs['cdefs']:array()); @@ -1270,14 +1270,14 @@ function aggregate_create_update(&$local_graph_id, $member_graphs, $attribs) { // - explicitly marked as skipped (based on $skipped_items) // - OR NOT marked as 'totalling' items for ($k=1; $k <= $item_no; $k++) { - cacti_log(__FUNCTION__ . ' old skip: ' . (isset($skipped_items[$k]) ? $skipped_items[$k]:''), true, 'AGGREGATE', POLLER_VERBOSITY_DEBUG); + cacti_log(__FUNCTION__ . ' old skip: ' . ($skipped_items[$k] ?? ''), true, 'AGGREGATE', POLLER_VERBOSITY_DEBUG); // skip all items, that shall not be totalled if (!isset($total_items[$k])) { $skipped_items[$k] = $k; } - cacti_log(__FUNCTION__ . ' new skip: ' . (isset($skipped_items[$k]) ? $skipped_items[$k]:''), true, 'AGGREGATE', POLLER_VERBOSITY_DEBUG); + cacti_log(__FUNCTION__ . ' new skip: ' . ($skipped_items[$k] ?? ''), true, 'AGGREGATE', POLLER_VERBOSITY_DEBUG); } // add the 'templating' graph to the new graph, honoring skipped, hr and color diff --git a/lib/api_automation.php b/lib/api_automation.php index 41d115de0a..54633e4c33 100644 --- a/lib/api_automation.php +++ b/lib/api_automation.php @@ -226,8 +226,8 @@ function display_matching_hosts($rule, $rule_type, $url) { form_selectable_cell(get_colored_device_status((($host['disabled'] == 'on' || $host['site_disabled'] == 'on') ? true : false), $host['status']), $host['host_id'], '', 'center'); form_selectable_cell(filter_value($host['host_template_name'], get_request_var('filter')), $host['host_id']); form_selectable_cell(round(($host['host_id']), 2), $host['host_id'], '', 'right'); - form_selectable_cell((isset($host_graphs[$host['host_id']]) ? $host_graphs[$host['host_id']] : 0), $host['host_id'], '', 'right'); - form_selectable_cell((isset($host_data_sources[$host['host_id']]) ? $host_data_sources[$host['host_id']] : 0), $host['host_id'], '', 'right'); + form_selectable_cell(($host_graphs[$host['host_id']] ?? 0), $host['host_id'], '', 'right'); + form_selectable_cell(($host_data_sources[$host['host_id']] ?? 0), $host['host_id'], '', 'right'); form_end_row(); } @@ -2338,7 +2338,7 @@ function global_item_edit($rule_id, $rule_item_id, $rule_type) { draw_edit_form( array( 'config' => array('no_form_tag' => true), - 'fields' => inject_form_variables($_fields_rule_item_edit, (isset($automation_item) ? $automation_item : array()), (isset($automation_rule) ? $automation_rule : array())) + 'fields' => inject_form_variables($_fields_rule_item_edit, ($automation_item ?? array()), ($automation_rule ?? array())) ) ); @@ -2511,7 +2511,7 @@ function automation_graph_automation_eligible($graph_template_id) { // Check the Graph Template first for adherence if (cacti_sizeof($graph_template)) { foreach ($graph_template as $field => $value) { - if (substr($field, 0, 2) == 't_') { + if (str_starts_with($field, 't_')) { $parent = substr($field, 2); if (isset($graph_template[$parent])) { @@ -2539,7 +2539,7 @@ function automation_graph_automation_eligible($graph_template_id) { if (cacti_sizeof($data_templates)) { foreach ($data_templates as $dtd) { foreach ($dtd as $field => $value) { - if (substr($field, 0, 2) == 't_') { + if (str_starts_with($field, 't_')) { $parent = substr($field, 2); if (isset($dtd[$parent])) { @@ -3327,35 +3327,34 @@ function automation_add_device($device, $web = false) { $template_id = $device['host_template']; $snmp_sysName = $device['snmp_sysName']; - $description = isset($device['description']) ? - $device['description'] : ($snmp_sysName != '' ? $snmp_sysName : ($device['hostname'] == '' ? $device['ip'] : $device['hostname'])); + $description = $device['description'] ?? $snmp_sysName != '' ? $snmp_sysName : ($device['hostname'] == '' ? $device['ip'] : $device['hostname']); - $poller_id = isset($device['poller_id']) ? $device['poller_id'] : read_config_option('default_poller'); - $site_id = isset($device['site_id']) ? $device['site_id'] : read_config_option('default_site'); - $ip = isset($device['ip']) ? $device['ip']:$device['ip_address']; + $poller_id = $device['poller_id'] ?? read_config_option('default_poller'); + $site_id = $device['site_id'] ?? read_config_option('default_site'); + $ip = $device['ip'] ?? $device['ip_address']; $snmp_community = $device['snmp_community']; $snmp_ver = $device['snmp_version']; $snmp_username = $device['snmp_username']; $snmp_password = $device['snmp_password']; $snmp_port = $device['snmp_port']; - $snmp_timeout = isset($device['snmp_timeout']) ? $device['snmp_timeout']:read_config_option('snmp_timeout'); + $snmp_timeout = $device['snmp_timeout'] ?? read_config_option('snmp_timeout'); $disable = ''; - $availability_method = isset($device['availability_method']) ? $device['availability_method']:read_config_option('availability_method'); - $ping_method = isset($device['ping_method']) ? $device['ping_method'] : read_config_option('ping_method'); - $ping_port = isset($device['ping_port']) ? $device['ping_port'] : read_config_option('ping_port'); - $ping_timeout = isset($device['ping_timeout']) ? $device['ping_timeout'] : read_config_option('ping_timeout'); - $ping_retries = isset($device['ping_retries']) ? $device['ping_retries'] : read_config_option('ping_retries'); - $notes = isset($device['notes']) ? $device['notes'] : __('Added by Cacti Automation'); + $availability_method = $device['availability_method'] ?? read_config_option('availability_method'); + $ping_method = $device['ping_method'] ?? read_config_option('ping_method'); + $ping_port = $device['ping_port'] ?? read_config_option('ping_port'); + $ping_timeout = $device['ping_timeout'] ?? read_config_option('ping_timeout'); + $ping_retries = $device['ping_retries'] ?? read_config_option('ping_retries'); + $notes = $device['notes'] ?? __('Added by Cacti Automation'); $snmp_auth_protocol = $device['snmp_auth_protocol']; $snmp_priv_passphrase = $device['snmp_priv_passphrase']; $snmp_priv_protocol = $device['snmp_priv_protocol']; $snmp_context = $device['snmp_context']; $snmp_engine_id = $device['snmp_engine_id']; - $max_oids = isset($device['max_oids']) ? $device['max_oids']:10; - $device_threads = isset($device['device_threads']) ? $device['device_threads']:1; - $external_id = isset($device['external_id']) ? $device['external_id']:''; - $location = isset($device['location']) ? $device['location']:''; - $bulk_walk_size = isset($device['bulk_walk_size']) ? $device['bulk_walk_size']:-1; + $max_oids = $device['max_oids'] ?? 10; + $device_threads = $device['device_threads'] ?? 1; + $external_id = $device['external_id'] ?? ''; + $location = $device['location'] ?? ''; + $bulk_walk_size = $device['bulk_walk_size'] ?? -1; automation_debug(' - Adding Device'); @@ -3442,7 +3441,7 @@ function automation_debug($text) { global $debug, $config; static $message = ''; - if (strstr($text, "\n") !== false) { + if (str_contains($text, "\n")) { $logLevel = POLLER_VERBOSITY_MEDIUM; if ($debug) { @@ -3522,7 +3521,7 @@ function automation_get_valid_mask($range) { $cidr = $range; $mask = array( 'cidr' => $cidr, - 'subnet' => long2ip((pow(2, $range) - 1) << (32 - $range)), + 'subnet' => long2ip((2 ** $range - 1) << (32 - $range)), ); } else { $mask = false; @@ -3550,7 +3549,7 @@ function automation_get_network_info($range) { $range = trim($range); - if (strpos($range, '/') !== false) { + if (str_contains($range, '/')) { // 10.1.0.0/24 or 10.1.0.0/255.255.255.0 $range_parts = explode('/', $range); @@ -3570,7 +3569,7 @@ function automation_get_network_info($range) { $broadcast = long2ip($dec + $count); } } - } elseif (strpos($range, '*') !== false && strpos($range, '-') === false) { + } elseif (str_contains($range, '*') && !str_contains($range, '-')) { $test = str_replace('*', 0, $range); if (!filter_var($test, FILTER_VALIDATE_IP)) { @@ -3617,7 +3616,7 @@ function automation_get_network_info($range) { return automation_get_network_info(rtrim($network,'.').'/'.rtrim($broadcast,'.')); } - } elseif (strpos($range, '-') !== false) { + } elseif (str_contains($range, '-')) { raise_message('automation_iprange', __('ERROR: IP ranges in the form of range1-range2 are no longer supported.'), MESSAGE_LEVEL_ERROR); return false; @@ -3630,7 +3629,7 @@ function automation_get_network_info($range) { if (ip2long($network) <= ip2long($broadcast)) { $detail['network'] = $network; $detail['broadcast'] = $broadcast; - $detail['cidr'] = isset($mask['cidr']) ? $mask['cidr'] : false; + $detail['cidr'] = $mask['cidr'] ?? false; if ($network == $broadcast) { $detail['type'] = 'single'; @@ -3692,7 +3691,7 @@ function automation_get_next_host($start, $total, $count, $range) { for ($x = 0; $x < 4; $x++) { $ip[$x] += intval($count / $y); $count -= ((intval($count / $y)) * 256); - $y = $y / 256; + $y /= 256; if ($ip[$x] == 256 && $x > 0) { $ip[$x] = 0; @@ -3729,7 +3728,7 @@ function automation_primeIPAddressTable($network_id) { } if (cacti_sizeof($subNets)) { - foreach ($subNets as $position => $subNet) { + foreach ($subNets as $subNet) { $count = 1; $sql = array(); $subNetTotal = automation_calculate_total_ips($subNet); @@ -3909,7 +3908,7 @@ function automation_valid_snmp_device(&$device) { */ function automation_get_dns_from_ip($ip, $dns, $timeout = 1000) { /* random transaction number (for routers etc to get the reply back) */ - $data = rand(10, 99); + $data = random_int(10, 99); /* trim it to 2 bytes */ $data = substr($data, 0, 2); @@ -4209,35 +4208,18 @@ function automation_change_tree_rule_leaf_type($leaf_type, $rule_id) { function automation_type_to_table($type) { $table = ''; - switch($type) { - case 'network': - $table = 'automation_networks'; - break; - case 'device': - $table = 'automation_templates'; - break; - case 'device_rules': - $table = 'automation_templates_rules'; - break; - case 'graph': - $table = 'automation_graph_rules'; - break; - case 'graph_items': - $table = 'automation_graph_rule_items'; - break; - case 'tree': - $table = 'automation_tree_rules'; - break; - case 'tree_items': - $table = 'automation_tree_rule_items'; - break; - case 'snmp': - $table = 'automation_snmp'; - break; - case 'snmp_items': - $table = 'automation_snmp_items'; - break; - } + $table = match ($type) { + 'network' => 'automation_networks', + 'device' => 'automation_templates', + 'device_rules' => 'automation_templates_rules', + 'graph' => 'automation_graph_rules', + 'graph_items' => 'automation_graph_rule_items', + 'tree' => 'automation_tree_rules', + 'tree_items' => 'automation_tree_rule_items', + 'snmp' => 'automation_snmp', + 'snmp_items' => 'automation_snmp_items', + default => $table, + }; return $table; } @@ -5077,7 +5059,7 @@ function automation_network_import($json_data) { $error = false; $save = array(); - foreach ($json_data['network'] as $network => $data) { + foreach ($json_data['network'] as $data) { if (isset($data['snmp'])) { $debug_data += automation_snmp_option_import($data['snmp']); unset($data['snmp']); @@ -5338,7 +5320,7 @@ function automation_tree_rule_import($json_data, $tree_branches = false) { if ($tree_branches) { if (isset($rule['tree_data']) && isset($rule['tree_branch_data'])) { - list($save['tree_id'], $save['tree_item_id']) = automation_tree_rule_create_tree($rule['tree_data'], $rule['tree_branch_data']); + [$save['tree_id'], $save['tree_item_id']] = automation_tree_rule_create_tree($rule['tree_data'], $rule['tree_branch_data']); } } @@ -5662,7 +5644,7 @@ function automation_template_import($json_data, $tree_branches = false) { if ($tree_branches) { if (isset($rule['tree_data']) && isset($rule['tree_branch_data'])) { - list($save['tree_id'], $save['tree_item_id']) = automation_tree_rule_create_tree($rule['tree_data'], $rule['tree_branch_data']); + [$save['tree_id'], $save['tree_item_id']] = automation_tree_rule_create_tree($rule['tree_data'], $rule['tree_branch_data']); } } diff --git a/lib/api_data_source.php b/lib/api_data_source.php index ef58ab3cc0..588ec148e3 100644 --- a/lib/api_data_source.php +++ b/lib/api_data_source.php @@ -27,7 +27,7 @@ @arg $poller_id - the id of the poller impacted by hash update @arg $variable - the hash variable prefix for the replication setting. */ function api_data_source_cache_crc_update($poller_id, $variable = 'poller_replicate_data_source_cache_crc') { - $hash = hash('ripemd160', date('Y-m-d H:i:s') . rand() . $poller_id); + $hash = hash('ripemd160', date('Y-m-d H:i:s') . random_int(0, mt_getrandmax()) . $poller_id); db_execute_prepared("REPLACE INTO settings SET value = ?, name='$variable" . '_' . "$poller_id'", @@ -501,7 +501,7 @@ function api_data_source_get_interface_speed($data_local) { cacti_log('Interface Speed Detected by Default: "' . $speed . '"', false, 'DSTRACE'); } } else { - $speed = $speed * 1000000; + $speed *= 1000000; if (read_config_option('data_source_trace') == 'on') { cacti_log('Interface Speed Detected by Settings: "' . $speed . '"', false, 'DSTRACE'); @@ -596,7 +596,7 @@ function api_reapply_suggested_data_source_data($local_data_id) { } /* if there are no '|query' characters, all of the substitutions were successful */ - if (strpos($subs_string, '|query') === false) { + if (!str_contains($subs_string, '|query')) { if (in_array($sv['field_name'], $matches, true)) { continue; } @@ -699,8 +699,8 @@ function api_duplicate_data_source($_local_data_id, $_data_template_id, $data_so /* create new entry: data_template_data */ $save['id'] = 0; - $save['local_data_id'] = (isset($local_data_id) ? $local_data_id : 0); - $save['local_data_template_data_id'] = (isset($data_template_data['local_data_template_data_id']) ? $data_template_data['local_data_template_data_id'] : 0); + $save['local_data_id'] = ($local_data_id ?? 0); + $save['local_data_template_data_id'] = ($data_template_data['local_data_template_data_id'] ?? 0); $save['data_template_id'] = (!empty($_local_data_id) ? $data_template_data['data_template_id'] : $data_template_id); $save['name_cache'] = $data_template_data['name_cache']; @@ -720,8 +720,8 @@ function api_duplicate_data_source($_local_data_id, $_data_template_id, $data_so unset($save); $save['id'] = 0; - $save['local_data_id'] = (isset($local_data_id) ? $local_data_id : 0); - $save['local_data_template_rrd_id'] = (isset($data_template_rrd['local_data_template_rrd_id']) ? $data_template_rrd['local_data_template_rrd_id'] : 0); + $save['local_data_id'] = ($local_data_id ?? 0); + $save['local_data_template_rrd_id'] = ($data_template_rrd['local_data_template_rrd_id'] ?? 0); $save['data_template_id'] = (!empty($_local_data_id) ? $data_template_rrd['data_template_id'] : $data_template_id); if ($save['local_data_id'] == 0) { diff --git a/lib/api_device.php b/lib/api_device.php index d441306aa4..6a50d2112d 100644 --- a/lib/api_device.php +++ b/lib/api_device.php @@ -34,7 +34,7 @@ * @return (void) */ function api_device_cache_crc_update($poller_id, $variable = 'poller_replicate_device_cache_crc') { - $hash = hash('ripemd160', date('Y-m-d H:i:s') . rand() . $poller_id); + $hash = hash('ripemd160', date('Y-m-d H:i:s') . random_int(0, mt_getrandmax()) . $poller_id); db_execute_prepared("REPLACE INTO settings SET value = ?, name='$variable" . '_' . "$poller_id'", array($hash)); } @@ -265,7 +265,7 @@ function api_device_remove_multi($device_ids, $delete_type = 2) { if ($delete_type == 2) { api_delete_graphs($graphs, $delete_type, false); } else { - api_data_source_disable_multi($data_sources, false); + api_data_source_disable_multi($data_sources); db_execute("UPDATE graph_local SET host_id = 0 WHERE host_id IN($devices_to_delete)"); db_execute("UPDATE data_local SET host_id = 0 WHERE host_id IN($devices_to_delete)"); @@ -1711,7 +1711,7 @@ function api_device_ping_device($device_id, $from_remote = false) { $days = intval($snmp_uptime_ticks / (60 * 60 * 24 * 100)); $remainder = $snmp_uptime_ticks % (60 * 60 * 24 * 100); $hours = intval($remainder / (60 * 60 * 100)); - $remainder = $remainder % (60 * 60 * 100); + $remainder %= 60 * 60 * 100; $minutes = intval($remainder / (60 * 100)); print '' . __('Uptime:') . " $snmp_uptime"; print ' (' . $days . __('days') . ', ' . $hours . __('hours') . ', ' . $minutes . __('minutes') . ')
'; @@ -2196,7 +2196,7 @@ function api_clone_device_template_check_for_errors($device_template_id, $device $script_base = trim(str_replace($config['base_path'], '', $script_path), '/'); if (file_exists($script_path)) { - if (!is_writeable($script_path)) { + if (!is_writable($script_path)) { $errors++; $return['errors'][] = sprintf('FATAL: Data Template Script Base path \'%s\' for \'%s\' already exists and the directory is not writable!', $script_base, $name); } else { @@ -2303,7 +2303,7 @@ function api_clone_device_template_check_for_errors($device_template_id, $device } } - foreach($objects['data_query_graph_templates'] as $id => $graph_template) { + foreach($objects['data_query_graph_templates'] as $graph_template) { $name = $graph_template['name']; $snmp_query_id = $graph_template['snmp_query_id']; @@ -2460,7 +2460,7 @@ function api_clone_device_template_get_objects($device_template_id) { $parts = explode(' ', $data_template['input_string']); foreach($parts as $p) { - if (strpos($p, $config['base_path']) !== false) { + if (str_contains($p, $config['base_path'])) { if (file_exists($p)) { $objects['data_templates'][$id]['script_path'] = $p; break; @@ -3099,7 +3099,7 @@ function api_device_template_archive_for_export($id) { /* search xml files for scripts */ if (cacti_sizeof($files)) { foreach($files as $file) { - if (strpos($file['file'], '.xml') !== false) { + if (str_contains($file['file'], '.xml')) { $files = array_merge($files, find_dependent_files(file_get_contents($file['file']))); } } @@ -3171,7 +3171,7 @@ function api_device_template_archive($id, $archive_note) { /* search xml files for scripts */ if (cacti_sizeof($files)) { foreach($files as $file) { - if (strpos($file['file'], '.xml') !== false) { + if (str_contains($file['file'], '.xml')) { $files = array_merge($files, find_dependent_files(file_get_contents($file['file']))); } } diff --git a/lib/api_graph.php b/lib/api_graph.php index 0f2e74f82d..99f271689d 100644 --- a/lib/api_graph.php +++ b/lib/api_graph.php @@ -76,7 +76,7 @@ function api_delete_graphs(&$local_graph_ids, $delete_type, $update_totals = tru api_data_source_remove_multi($data_sources, false); } - api_graph_remove_multi($local_graph_ids, false); + api_graph_remove_multi($local_graph_ids); /* Remove orphaned data sources */ $data_sources = array_rekey( @@ -97,12 +97,12 @@ function api_delete_graphs(&$local_graph_ids, $delete_type, $update_totals = tru api_data_source_remove_multi($data_sources, false); } } else { - api_graph_remove_multi($local_graph_ids, false); + api_graph_remove_multi($local_graph_ids); } break; case '1': - api_graph_remove_multi($local_graph_ids, false); + api_graph_remove_multi($local_graph_ids); break; } @@ -434,8 +434,8 @@ function api_duplicate_graph($_local_graph_id, $_graph_template_id, $graph_title /* create new entry: graph_templates_graph */ $save['id'] = 0; - $save['local_graph_id'] = (isset($local_graph_id) ? $local_graph_id : 0); - $save['local_graph_template_graph_id'] = (isset($graph_template_graph['local_graph_template_graph_id']) ? $graph_template_graph['local_graph_template_graph_id'] : 0); + $save['local_graph_id'] = ($local_graph_id ?? 0); + $save['local_graph_template_graph_id'] = ($graph_template_graph['local_graph_template_graph_id'] ?? 0); $save['graph_template_id'] = (!empty($_local_graph_id) ? $graph_template_graph['graph_template_id'] : $graph_template_id); $save['title_cache'] = $graph_template_graph['title_cache']; @@ -457,9 +457,9 @@ function api_duplicate_graph($_local_graph_id, $_graph_template_id, $graph_title $save['id'] = 0; /* save a hash only for graph_template copy operations */ $save['hash'] = (!empty($_graph_template_id) ? get_hash_graph_template(0, 'graph_template_item') : 0); - $save['local_graph_id'] = (isset($local_graph_id) ? $local_graph_id : 0); + $save['local_graph_id'] = ($local_graph_id ?? 0); $save['graph_template_id'] = (!empty($_local_graph_id) ? $graph_template_item['graph_template_id'] : $graph_template_id); - $save['local_graph_template_item_id'] = (isset($graph_template_item['local_graph_template_item_id']) ? $graph_template_item['local_graph_template_item_id'] : 0); + $save['local_graph_template_item_id'] = ($graph_template_item['local_graph_template_item_id'] ?? 0); foreach ($struct_graph_item as $field => $array) { $save[$field] = $graph_template_item[$field]; diff --git a/lib/api_scheduler.php b/lib/api_scheduler.php index 935d8ce7c2..63a8b29c1f 100644 --- a/lib/api_scheduler.php +++ b/lib/api_scheduler.php @@ -484,7 +484,7 @@ function api_scheduler_is_time_to_start($schedule, $table = 'automation_networks break; case SCHEDULE_MONTHLY: case SCHEDULE_MONTHLY_ON_DAY: - $next = api_scheduler_calculate_next_start($schedule, $now); + $next = api_scheduler_calculate_next_start($schedule); db_execute_prepared("UPDATE $table SET next_start = ? diff --git a/lib/api_tree.php b/lib/api_tree.php index 794e5b6043..b9aacbedf9 100644 --- a/lib/api_tree.php +++ b/lib/api_tree.php @@ -219,7 +219,7 @@ function api_tree_create_node($tree_id, $node_id, $position, $title = '') { $data = api_tree_parse_node_data($node_id); if ($data['leaf_id'] < 0) { - cacti_log("ERROR: Invalid BranchID: '" . (isset($data['leaf_id']) ? $data['leaf_id']:'-') . "', Function create_node", false); + cacti_log("ERROR: Invalid BranchID: '" . ($data['leaf_id'] ?? '-') . "', Function create_node", false); return; } @@ -528,7 +528,7 @@ function api_tree_parse_node_data($variable) { if (cacti_sizeof($ndata)) { foreach ($ndata as $data) { - list($type, $tid) = explode(':', $data); + [$type, $tid] = explode(':', $data); /* watch out for monkey business */ input_validate_input_number($tid, 'tid'); @@ -606,7 +606,7 @@ function api_tree_rename_node($tree_id, $node_id = '', $title = '') { if (cacti_sizeof($ndata)) { foreach ($ndata as $data) { - if (strpos($data, ':') === false) { + if (!str_contains($data, ':')) { cacti_log("ERROR: Invalid NodeID: '" . $node_id . "', Function rename_node", false); header('Content-Type: application/json; charset=utf-8'); @@ -615,7 +615,7 @@ function api_tree_rename_node($tree_id, $node_id = '', $title = '') { return; } - list($type, $tid) = explode(':', $data); + [$type, $tid] = explode(':', $data); /* watch out for monkey business */ input_validate_input_number($tid, 'tid'); diff --git a/lib/auth.php b/lib/auth.php index 044aee5dc6..3b79c4613f 100644 --- a/lib/auth.php +++ b/lib/auth.php @@ -244,7 +244,7 @@ function get_basic_auth_username() { } if ($username !== false) { - if (strpos($username, '@') !== false) { + if (str_contains($username, '@')) { $upart = explode('@', $username); $username = $upart[0]; } @@ -259,7 +259,7 @@ function get_basic_auth_username() { if (cacti_sizeof($records)) { foreach ($records as $r) { - list($basic, $shortform) = str_getcsv($r); + [$basic, $shortform] = str_getcsv($r); if (trim($basic) == $username) { $username = trim($shortform); @@ -3685,7 +3685,7 @@ function auth_process_lockout($username, $realm) { db_execute_prepared('INSERT IGNORE INTO user_log (username, user_id, result, ip, time) VALUES (?, ?, 0, ?, NOW())', - array($username, isset($user['id']) ? $user['id']:0, get_client_addr())); + array($username, $user['id'] ?? 0, get_client_addr())); if ($user['locked'] == 'on') { cacti_log(sprintf("LOGIN FAILED: Local Login Failed for user '%s' from IP Address '%s'. Account is locked out.", $username, get_client_addr()), false, 'AUTH'); @@ -4888,7 +4888,7 @@ function auth_login_redirect($login_opts = '') { if (auth_basename($referer) == 'logout.php') { $referer = CACTI_PATH_URL . 'index.php'; - } elseif (strpos($referer, CACTI_PATH_URL) === false) { + } elseif (!str_contains($referer, CACTI_PATH_URL)) { if (!is_realm_allowed(8)) { $referer = CACTI_PATH_URL . 'graph_view.php' . ($newtheme ? '?newtheme=1':''); } else { @@ -4911,7 +4911,7 @@ function auth_login_redirect($login_opts = '') { cacti_log(sprintf("DEBUG: Referer Short Circuit to '%s'", 'index.php'), false, 'AUTH', POLLER_VERBOSITY_DEBUG); } - $referer .= ($newtheme ? (strpos($referer, '?') === false ? '?':'&') . 'newtheme=1':''); + $referer .= ($newtheme ? (!str_contains($referer, '?') ? '?':'&') . 'newtheme=1':''); /* Strip out the login from the referer if present */ $referer = str_replace('?action=login', '', $referer); @@ -5013,8 +5013,8 @@ function auth_login_create_user_from_template($username, $realm) { user_copy($user_template['username'], $username, $user_template['realm'], $realm, false, $data_override); } else { - $ldap_response = (isset($ldap_cn_search_response[0]) ? $ldap_cn_search_response[0] : '(no response given)'); - $ldap_code = (isset($ldap_cn_search_response['error_num']) ? $ldap_cn_search_response['error_num'] : '(no code given)'); + $ldap_response = ($ldap_cn_search_response[0] ?? '(no response given)'); + $ldap_code = ($ldap_cn_search_response['error_num'] ?? '(no code given)'); cacti_log('LOGIN: Email Address and Full Name fields not found, reason: ' . $ldap_response . 'code: ' . $ldap_code, false, 'AUTH'); user_copy($user_template['username'], $username, $user_template['realm'], $realm); } @@ -5130,7 +5130,7 @@ function check_reset_no_authentication($auth_method) { $_SESSION[SESS_USER_ID] = $admin_id; $_SESSION[SESS_CHANGE_PASSWORD] = true; - header('Location: ' . CACTI_PATH_URL . 'auth_changepassword.php?action=force&ref=' . (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'index.php')); + header('Location: ' . CACTI_PATH_URL . 'auth_changepassword.php?action=force&ref=' . ($_SERVER['HTTP_REFERER'] ?? 'index.php')); exit; } diff --git a/lib/boost.php b/lib/boost.php index c0adbdc807..90561ed004 100644 --- a/lib/boost.php +++ b/lib/boost.php @@ -51,13 +51,13 @@ function boost_array_orderby() { function boost_file_size_display($file_size, $digits = 2) { if ($file_size > 1024) { - $file_size = $file_size / 1024; + $file_size /= 1024; if ($file_size > 1024) { - $file_size = $file_size / 1024; + $file_size /= 1024; if ($file_size > 1024) { - $file_size = $file_size / 1024; + $file_size /= 1024; return __('%s GBytes', number_format_i18n($file_size, $digits)); } else { @@ -754,7 +754,7 @@ function boost_process_poller_output($local_data_id, $rrdtool_pipe = null) { db_execute("CREATE TEMPORARY TABLE $temp_table LIKE poller_output_boost"); - foreach($archive_tables as $index => $table) { + foreach($archive_tables as $table) { db_execute_prepared("INSERT INTO $temp_table SELECT * FROM $table @@ -932,12 +932,12 @@ function boost_process_poller_output($local_data_id, $rrdtool_pipe = null) { $vals_in_buffer = 0; /* check return status for delete operation */ - if (strpos(trim($return_value), 'OK') === false && $return_value != '') { + if (!str_contains(trim($return_value), 'OK') && $return_value != '') { cacti_log("WARNING: RRD Update Warning '" . $return_value . "' for Local Data ID '$local_data_id'", false, 'BOOST'); } } - if (strpos($value, 'DNP') === false) { + if (!str_contains($value, 'DNP')) { $output = ' ' . $item['timestamp']; $outbuf .= $output; $outlen += strlen($output); @@ -947,7 +947,7 @@ function boost_process_poller_output($local_data_id, $rrdtool_pipe = null) { } /* single one value output */ - if (strpos($value, 'DNP') !== false) { + if (str_contains($value, 'DNP')) { /* continue, bad time */ } elseif ((is_numeric($value)) || ($value == 'U' && $item['rrd_name'] != '')) { $output = ':' . $value; @@ -959,7 +959,7 @@ function boost_process_poller_output($local_data_id, $rrdtool_pipe = null) { $outbuf .= $output; $outlen += strlen($output); $vals_in_buffer++; - } elseif (strpos($value, ':') !== false) { + } elseif (str_contains($value, ':')) { $values = preg_split('/\s+/', $value); if (!$multi_vals_set) { @@ -1138,7 +1138,7 @@ function boost_process_poller_output($local_data_id, $rrdtool_pipe = null) { boost_timer('rrdupdate', BOOST_TIMER_END); /* check return status for delete operation */ - if (strpos(trim($return_value), 'OK') === false && $return_value != '') { + if (!str_contains(trim($return_value), 'OK') && $return_value != '') { cacti_log("WARNING: RRD Update Warning '" . $return_value . "' for Local Data ID '$local_data_id'", false, 'BOOST'); } } @@ -1377,7 +1377,7 @@ function boost_rrdtool_function_create($local_data_id, $show_source, $rrdtool_pi if (empty($data_source['rrd_maximum'])) { /* in case no maximum is given, use "Undef" value */ $data_source['rrd_maximum'] = 'U'; - } elseif (strpos($data_source['rrd_maximum'], '|query_') !== false) { + } elseif (str_contains($data_source['rrd_maximum'], '|query_')) { $data_local = db_fetch_row_prepared('SELECT * FROM data_local WHERE id = ?', array($local_data_id)); $speed = rrdtool_function_interface_speed($data_local); diff --git a/lib/clog_webapi.php b/lib/clog_webapi.php index 73d87ff5d9..e1712e81ac 100644 --- a/lib/clog_webapi.php +++ b/lib/clog_webapi.php @@ -60,15 +60,15 @@ function clog_validate_filename(&$file, &$filepath, &$filename, $filecheck = fal $filename = ''; $filefull = ''; - if (!empty($errfile) && strpos($file, $errbase) === 0) { + if (!empty($errfile) && str_starts_with($file, $errbase)) { $filepath = dirname($errfile); $filename = $errbase; $filefull = $filepath . '/' . $file; - } elseif (!empty($logfile) && strpos($file, $logbase) === 0) { + } elseif (!empty($logfile) && str_starts_with($file, $logbase)) { $filepath = dirname($logfile); $filename = $logbase; $filefull = $filepath . '/' . $file; - } elseif (!empty($boostfile) && strpos($file, $boostbase) === 0) { + } elseif (!empty($boostfile) && str_starts_with($file, $boostbase)) { $filepath = dirname($boostfile); $filename = $boostbase; $filefull = $filepath . '/' . $file; @@ -288,15 +288,15 @@ function clog_view_logfile() { } /* get the background color */ - if (strpos($new_item, 'ERROR') !== false || strpos($new_item, 'FATAL') !== false) { + if (str_contains($new_item, 'ERROR') || str_contains($new_item, 'FATAL')) { $class = 'clogError'; - } elseif (strpos($new_item, 'WARN') !== false) { + } elseif (str_contains($new_item, 'WARN')) { $class = 'clogWarning'; - } elseif (strpos($new_item, ' SQL ') !== false) { + } elseif (str_contains($new_item, ' SQL ')) { $class = 'clogSQL'; - } elseif (strpos($new_item, 'DEBUG') !== false) { + } elseif (str_contains($new_item, 'DEBUG')) { $class = 'clogDebug'; - } elseif (strpos($new_item, 'STATS') !== false) { + } elseif (str_contains($new_item, 'STATS')) { $class = 'clogStats'; } else { if ($linecolor) { @@ -378,7 +378,7 @@ function clog_get_logfiles() { $explode = explode('.', $logFile); - if (substr($explode[max(array_keys($explode))], 0, 3) != 'log') { + if (!str_starts_with($explode[max(array_keys($explode))], 'log')) { continue; } @@ -386,9 +386,9 @@ function clog_get_logfiles() { continue; } - if (!empty($stderrLogBase) && strpos($logFile, $stderrLogBase) === 0){ + if (!empty($stderrLogBase) && str_starts_with($logFile, $stderrLogBase)){ $stdErrFileArray[] = $logFile; - } elseif (!empty($boostLogBase) && strpos($logFile, $boostLogBase) === 0){ + } elseif (!empty($boostLogBase) && str_starts_with($logFile, $boostLogBase)){ $boostFileArray[] = $logFile; } else { $stdLogFileArray[] = $logFile; @@ -419,7 +419,7 @@ function clog_get_logfiles() { $explode = explode('.', $logFile); - if (substr($explode[max(array_keys($explode))], 0, 3) != 'log') { + if (!str_starts_with($explode[max(array_keys($explode))], 'log')) { continue; } @@ -455,7 +455,7 @@ function create_filter($logfile, $clogAdmin) { $newLogArray = array(); if (cacti_sizeof($logFileArray)) { - foreach ($logFileArray as $index => $logFile) { + foreach ($logFileArray as $logFile) { $logParts = explode('-', $logFile); $logDate = cacti_count($logParts) < 2 ? '' : $logParts[1] . (isset($logParts[2]) ? '-' . $logParts[2]:''); $logName = $logParts[0]; diff --git a/lib/data_query.php b/lib/data_query.php index ef8b1f4676..b1c2c7b41e 100644 --- a/lib/data_query.php +++ b/lib/data_query.php @@ -472,7 +472,7 @@ function run_data_query($host_id, $snmp_query_id, $automation = false, $force = data_query_remove_disabled_items($orphaned_ids); } - return (isset($result) ? $result : true); + return ($result ?? true); } function data_query_remove_disabled_items($orphaned_ids) { @@ -729,7 +729,7 @@ function query_script_host($host_id, $snmp_query_id) { foreach ($script_queries['fields'] as $field_name => $field_array) { if ($field_array['direction'] == 'input' || $field_array['direction'] == 'input-output') { - $rewrite_value = isset($field_array['rewrite_value']) ? $field_array['rewrite_value'] : null; + $rewrite_value = $field_array['rewrite_value'] ?? null; $script_path = get_script_query_path((isset($script_queries['arg_prepend']) ? $script_queries['arg_prepend'] . ' ': '') . $script_queries['arg_query'] . ' ' . $field_array['query_name'], $script_queries['script_path'], $host_id); debug_log_insert_section_start('data_query', __esc('Click to show Data Query output for field \'%s\'', $field_name), true); @@ -1011,10 +1011,10 @@ function query_snmp_host($host_id, $snmp_query_id) { debug_log_insert('data_query', __esc('Fixing wrong \'method\' field for \'%s\' since \'rewrite_index\' or \'oid_suffix\' is defined', $field_name)); } - $rewrite_value = isset($field_array['rewrite_value']) ? $field_array['rewrite_value'] : null; + $rewrite_value = $field_array['rewrite_value'] ?? null; if ((!isset($field_array['oid'])) && ($field_array['source'] == 'index')) { - foreach ($snmp_indexes as $oid => $value) { + foreach ($snmp_indexes as $value) { query_debug_timer_offset('data_query', __esc('Inserting index data for field \'%s\' [value=\'%s\']' , $field_name, $value)); $output_array[] = data_query_format_record($host_id, $snmp_query_id, $field_name, $rewrite_value, $value, $value, ''); @@ -1080,7 +1080,7 @@ function query_snmp_host($host_id, $snmp_query_id) { $values = array(); - foreach ($snmp_indexes as $index_oid => $index) { + foreach ($snmp_indexes as $index) { $oid = $field_array['oid']; if (isset($field_array['rewrite_index'])) { @@ -1098,9 +1098,9 @@ function query_snmp_host($host_id, $snmp_query_id) { $oid .= isset($field_array['oid_suffix']) ? ('.' . $field_array['oid_suffix']) : ''; $value = null; - if (substr($field_array['source'], 0, 11) == 'OID/REGEXP:') { + if (str_starts_with($field_array['source'], 'OID/REGEXP:')) { $value = preg_replace('/' . str_replace('OID/REGEXP:', '', $field_array['source']) . '/', '\\1', $oid); - } elseif (substr($field_array['source'], 0, 15) == 'OID2HEX/REGEXP:') { + } elseif (str_starts_with($field_array['source'], 'OID2HEX/REGEXP:')) { $value = preg_replace('/' . str_replace('OID2HEX/REGEXP:', '', $field_array['source']) . '/', '\\1', $oid); $parts = explode('.', $value); @@ -1130,7 +1130,7 @@ function query_snmp_host($host_id, $snmp_query_id) { $values[] = array('value' => $value, 'index' => $index, 'oid' => $oid); } - if (cacti_sizeof($values) > 0 && (substr($field_array['source'], 0, 13) == 'VALUE/REGEXP:' || $field_array['source'] == 'value')) { + if (cacti_sizeof($values) > 0 && (str_starts_with($field_array['source'], 'VALUE/REGEXP:') || $field_array['source'] == 'value')) { $oids = array(); foreach ($values as $key => $value) { @@ -1186,7 +1186,7 @@ function query_snmp_host($host_id, $snmp_query_id) { } foreach ($values as $key => $value) { - if (substr($field_array['source'], 0, 13) == 'VALUE/REGEXP:') { + if (str_starts_with($field_array['source'], 'VALUE/REGEXP:')) { $values[$key]['value'] = preg_replace('/' . str_replace('VALUE/REGEXP:', '', $field_array['source']) . '/', '\\1', $values[$key]['value']); } } @@ -1199,7 +1199,7 @@ function query_snmp_host($host_id, $snmp_query_id) { } $values = null; - } elseif (substr($field_array['source'], 0, 13) == 'VALUE/REGEXP:') { + } elseif (str_starts_with($field_array['source'], 'VALUE/REGEXP:')) { foreach ($snmp_indexes as $oid => $index) { $oid = $field_array['oid'] . '.' . $index; $oid .= isset($field_array['oid_suffix']) ? ('.' . $field_array['oid_suffix']) : ''; @@ -1282,7 +1282,7 @@ function query_snmp_host($host_id, $snmp_query_id) { if (preg_match('/^value/i', $field_array['source'])) { if (cacti_sizeof($snmp_data)) { foreach ($snmp_data as $oid => $value) { - $index_regex = (isset($field_array['oid_index_parse']) ? $field_array['oid_index_parse'] : $index_parse_regexp) . (isset($field_array['oid_suffix']) ? ('.' . $field_array['oid_suffix']) : ''); + $index_regex = ($field_array['oid_index_parse'] ?? $index_parse_regexp) . (isset($field_array['oid_suffix']) ? ('.' . $field_array['oid_suffix']) : ''); if (!preg_match($index_regex, $oid)) { continue; @@ -1302,23 +1302,12 @@ function query_snmp_host($host_id, $snmp_query_id) { $oid = $field_array['oid'] . ".$snmp_index" . (isset($field_array['oid_suffix']) ? ('.' . $field_array['oid_suffix']) : ''); if ($field_name == 'ifOperStatus' || $field_name == 'ifAdminStatus') { - switch(true) { - case preg_match('/^(down|2)/i',$value): - $value = 'Down'; - - break; - case preg_match('/^(up|1)/i',$value): - $value = 'Up'; - - break; - case preg_match('/^(notpresent|6)/i',$value): - $value = 'notPresent'; - - break; - - default: - $value = 'Testing'; - } + $value = match (true) { + preg_match('/^(down|2)/i', $value) => 'Down', + preg_match('/^(up|1)/i', $value) => 'Up', + preg_match('/^(notpresent|6)/i', $value) => 'notPresent', + default => 'Testing', + }; $mode = 'value'; } elseif (preg_match('/VALUE\/REGEXP:(.*)/', $field_array['source'], $matches)) { $modified_value = preg_replace('/' . $matches[1] . '/', '\\1', $value); @@ -1338,12 +1327,12 @@ function query_snmp_host($host_id, $snmp_query_id) { $mode = 'value'; } - $output_array[] = data_query_format_record($host_id, $snmp_query_id, $field_name, $rewrite_value, isset($modified_value)?$modified_value:$value , $snmp_index, $oid); + $output_array[] = data_query_format_record($host_id, $snmp_query_id, $field_name, $rewrite_value, $modified_value ?? $value, $snmp_index, $oid); debug_log_insert('data_query', __esc('Found item [%s=\'%s\'] index: %s [from %s]',$field_name,isset($modified_value)?"$modified_value ($value)":$value,$snmp_index,$mode)); unset($modified_value); } } - } elseif (substr($field_array['source'], 0, 11) == 'OID/REGEXP:') { + } elseif (str_starts_with($field_array['source'], 'OID/REGEXP:')) { if (cacti_sizeof($snmp_data)) { foreach ($snmp_data as $oid => $value) { $parse_value = preg_replace('/' . str_replace('OID/REGEXP:', '', $field_array['source']) . '/', '\\1', $oid); @@ -1394,7 +1383,7 @@ function query_snmp_host($host_id, $snmp_query_id) { $output_array[] = data_query_format_record($host_id, $snmp_query_id, $field_name, $rewrite_value, $parse_value, $snmp_index, $oid); } } - } elseif (substr($field_array['source'], 0, 15) == 'OID2HEX/REGEXP:') { + } elseif (str_starts_with($field_array['source'], 'OID2HEX/REGEXP:')) { if (cacti_sizeof($snmp_data)) { foreach ($snmp_data as $oid => $value) { $parse_value = preg_replace('/' . str_replace('OID2HEX/REGEXP:', '', $field_array['source']) . '/', '\\1', $oid); @@ -1445,7 +1434,7 @@ function query_snmp_host($host_id, $snmp_query_id) { $output_array[] = data_query_format_record($host_id, $snmp_query_id, $field_name, $rewrite_value, $parse_value, $snmp_index, $oid); } } - } elseif (substr($field_array['source'], 0, 16) == 'OIDVALUE/REGEXP:') { + } elseif (str_starts_with($field_array['source'], 'OIDVALUE/REGEXP:')) { $regex_array = explode(':', str_replace('OIDVALUE/REGEXP:', '', $field_array['source'])); if (cacti_sizeof($snmp_data)) { @@ -1656,7 +1645,7 @@ function data_query_rewrite_indexes(&$errmsg, $host_id, $snmp_query_id, $rewrite $numeric_output = true; } - foreach ($snmp_indexes as $oid => $num_index) { + foreach ($snmp_indexes as $num_index) { $index = $rewrite_index; foreach ($chain_indexes as $key => $values) { diff --git a/lib/database.php b/lib/database.php index 4fc62b07b6..e0ea977f08 100644 --- a/lib/database.php +++ b/lib/database.php @@ -130,7 +130,7 @@ function db_connect_real($device, $user, $pass, $db_name, $db_type = 'mysql', $p while ($i <= $retries) { try { - if (strpos($device, '/') !== false && filetype($device) == 'socket') { + if (str_contains($device, '/') && filetype($device) == 'socket') { $cnn_id = new PDO("$db_type:unix_socket=$device;dbname=$db_name;charset=utf8", $user, $pass, $flags); } else { $cnn_id = new PDO("$db_type:host=$device;port=$port;dbname=$db_name;charset=utf8", $user, $pass, $flags); @@ -175,7 +175,7 @@ function db_connect_real($device, $user, $pass, $db_name, $db_type = 'mysql', $p $ver = db_get_global_variable('version', $cnn_id); - if (strpos($ver, 'MariaDB') !== false) { + if (str_contains($ver, 'MariaDB')) { $srv = 'MariaDB'; $ver = str_replace('-MariaDB', '', $ver); $required_modes[] = 'NO_ENGINE_SUBSTITUTION'; @@ -650,7 +650,7 @@ function db_execute_prepared($sql, $params = array(), $log = true, $db_conn = fa return $return_value; } else { - $database_last_error = 'DB ' . $execute_name . ' Failed!, Error ' . $en . ': ' . (isset($errorinfo[2]) ? $errorinfo[2] : ''); + $database_last_error = 'DB ' . $execute_name . ' Failed!, Error ' . $en . ': ' . ($errorinfo[2] ?? ''); if (isset($query)) { $query->closeCursor(); @@ -688,7 +688,7 @@ function db_execute_prepared($sql, $params = array(), $log = true, $db_conn = fa cacti_log('ERROR: A DB ' . $execute_name . ' Failed!, Error: ' . $errorinfo[2], false); cacti_debug_backtrace('SQL', false, true, 0, 1); - $database_last_error = 'DB ' . $execute_name . ' Failed!, Error ' . $en . ': ' . (isset($errorinfo[2]) ? $errorinfo[2] : ''); + $database_last_error = 'DB ' . $execute_name . ' Failed!, Error ' . $en . ': ' . ($errorinfo[2] ?? ''); } } @@ -860,7 +860,7 @@ function db_fetch_row_return($query) { $r = $query->fetchAll(PDO::FETCH_ASSOC); } - return (isset($r[0])) ? $r[0] : array(); + return $r[0] ?? array(); } /** @@ -1037,7 +1037,7 @@ function db_add_column($table, $column, $log = true, $db_conn = false) { } if (isset($column['default'])) { - if (in_array(strtolower($column['type']), array('timestamp', 'datetime', 'date'), true) && strpos($column['default'], 'CURRENT_TIMESTAMP') !== false) { + if (in_array(strtolower($column['type']), array('timestamp', 'datetime', 'date'), true) && str_contains($column['default'], 'CURRENT_TIMESTAMP')) { $sql .= ' default ' . $column['default']; } else { $sql .= ' default ' . (is_numeric($column['default']) ? $column['default'] : "'" . $column['default'] . "'"); @@ -1575,7 +1575,7 @@ function db_update_table($table, $data, $removecolumns = false, $log = true, $db // FIXME: Need to still check default value $arr = db_fetch_row("SHOW columns FROM `$table` LIKE '" . $column['name'] . "'", $log, $db_conn); - if (strpos(strtolower($arr['Type']), ' unsigned') !== false) { + if (str_contains(strtolower($arr['Type']), ' unsigned')) { $arr['Type'] = str_ireplace(' unsigned', '', $arr['Type']); $arr['unsigned'] = true; } @@ -1750,7 +1750,7 @@ function db_format_index_create($indexes) { foreach ($indexes as $index) { $index = trim($index); - if (substr($index, -1) == ')') { + if (str_ends_with($index, ')')) { $outindex .= ($outindex != '' ? ',':'') . $index; } else { $outindex .= ($outindex != '' ? ',':'') . '`' . $index . '`'; @@ -1761,7 +1761,7 @@ function db_format_index_create($indexes) { } else { $indexes = trim($indexes); - if (substr($indexes, -1) == ')') { + if (str_ends_with($indexes, ')')) { return $indexes; } else { return '`' . trim($indexes, ' `') . '`'; @@ -2194,15 +2194,15 @@ function sql_save($array_items, $table_name, $key_cols = 'id', $autoinc = true, return false; } - if (strstr($cols[$key]['type'], 'int') !== false || - strstr($cols[$key]['type'], 'float') !== false || - strstr($cols[$key]['type'], 'double') !== false || - strstr($cols[$key]['type'], 'decimal') !== false) { + if (str_contains($cols[$key]['type'], 'int') || + str_contains($cols[$key]['type'], 'float') || + str_contains($cols[$key]['type'], 'double') || + str_contains($cols[$key]['type'], 'decimal')) { if ($value == '') { if ($cols[$key]['null'] == 'YES') { // TODO: We should make 'NULL', but there are issues that need to be addressed first $array_items[$key] = 0; - } elseif (strpos($cols[$key]['extra'], 'auto_increment') !== false) { + } elseif (str_contains($cols[$key]['extra'], 'auto_increment')) { $array_items[$key] = 0; } elseif ($cols[$key]['default'] == '') { // TODO: We should make 'NULL', but there are issues that need to be addressed first @@ -2519,7 +2519,7 @@ function db_dump_data($database = '', $tables = '', $credentials = array(), $out foreach ($credentials as $key => $value) { $name = trim($key); - if (strstr($name, '--') !== false) { //name like --host + if (str_contains($name, '--')) { //name like --host if ($name == '--password') { $password = $value; } elseif ($name == '--user') { @@ -2527,7 +2527,7 @@ function db_dump_data($database = '', $tables = '', $credentials = array(), $out } else { $credentials_string .= $name . '=' . $value . ' '; } - } elseif (strstr($name, '-') !== false) { //name like -h + } elseif (str_contains($name, '-')) { //name like -h if ($name == '-p') { $password = $value; } elseif ($name == '-u') { @@ -2561,7 +2561,7 @@ function db_dump_data($database = '', $tables = '', $credentials = array(), $out $dump = 'mysqldump'; } - if (strstr($options, '--defaults-extra-file') !== false) { + if (str_contains($options, '--defaults-extra-file')) { exec("$dump $options $credentials_string $database $tables > $output_file", $output, $retval); } else { exec("$dump $options $credentials_string $database version >/dev/null 2>&1", $output, $retval); @@ -2660,7 +2660,7 @@ function db_get_permissions($include_unknown = false, $log = false, $db_conn = f } if (array_key_exists($db_grant_perm, $perms)) { - if (strpos($db_grant, "`$database_default`.*") !== false) { + if (str_contains($db_grant, "`$database_default`.*")) { $perms[$db_name][$db_grant_perm . ' ON *'] = true; } else { $perms[$db_name][$db_grant_perm] = true; diff --git a/lib/dbparallel.php b/lib/dbparallel.php index 443b9957b6..41e9a09dde 100644 --- a/lib/dbparallel.php +++ b/lib/dbparallel.php @@ -321,7 +321,7 @@ function db_query_parallelize($sql, $log = true, $db_conn = false) { */ if (stripos($sql, 'UNION') === false && stripos($sql, 'UNION ALL') === false) { // Find the table name if not a union query - if (sizeof($from_split) > 1) { + if (count($from_split) > 1) { $bits = explode(' ', trim($from_split[1])); $table_name = trim($bits[0], '`'); @@ -348,7 +348,7 @@ function db_query_parallelize($sql, $log = true, $db_conn = false) { * to skip the checks below GROUP BY, LIMIT, ORDER, etc. below as * they are each contained within the UNION's themselves. */ - if (substr(trim($from_split[1]), 0, 1) == '(') { + if (str_starts_with(trim($from_split[1]), '(')) { $simple_union = false; } else { $simple_union = true; diff --git a/lib/dsdebug.php b/lib/dsdebug.php index 8b7d4615f6..4892c717e2 100644 --- a/lib/dsdebug.php +++ b/lib/dsdebug.php @@ -209,13 +209,13 @@ function dsdebug_poller_bottom() { $info['runas_poller'] = get_running_user(); // convert_name - $info['convert_name'] = (strpos('|', get_data_source_title($c['datasource'])) === false ? 1 : 0); + $info['convert_name'] = (!str_contains('|', get_data_source_title($c['datasource'])) ? 1 : 0); // last_result (processed by hook) if (is_array($info['last_result']) && !empty($info['last_result']) && $info['valid_data'] == '') { $info['valid_data'] = 1; - foreach ($info['last_result'] as $k => $l) { + foreach ($info['last_result'] as $l) { if ($l == 'U') { cacti_log('Bad Data Found for Data Source ID ' . $c['datasource'], false, 'DSDEBUG'); $info['valid_data'] = 0; @@ -345,7 +345,7 @@ function dsdebug_run_repair($id) { if (isset($check['info']['rrd_match_array']['tune'])) { $path = get_data_source_path($id, true); - if (is_writeable($path)) { + if (is_writable($path)) { $rrdtool_path = read_config_option('path_rrdtool'); $failures = 0; $failure_data = ''; diff --git a/lib/dsstats.php b/lib/dsstats.php index 6e6aecf83a..2b1c712cba 100644 --- a/lib/dsstats.php +++ b/lib/dsstats.php @@ -400,7 +400,7 @@ function dsstats_obtain_data_source_avgpeak_values($local_data_id, $rrdfile, $in if ($index > 0) { // Catch the last line - if (substr($line, 0, 2) == 'OK') { + if (str_starts_with($line, 'OK')) { $line = trim($line, ' OK'); $parts = explode(' ', $line); //print $line . PHP_EOL; @@ -495,22 +495,22 @@ function dsstats_get_stats_command($local_data_id, $rrdfile, $use_proxy, $mode, */ if (cacti_sizeof($info_array)) { foreach ($info_array as $line) { - if (strpos($line, 'ds[') !== false) { + if (str_contains($line, 'ds[')) { $parts = explode(']', $line); $parts2 = explode('[', $parts[0]); $dsnames[trim($parts2[1])] = 1; - } elseif (strpos($line, '.cf') !== false) { + } elseif (str_contains($line, '.cf')) { $parts = explode('=', $line); - if (strpos($parts[1], 'AVERAGE') !== false) { + if (str_contains($parts[1], 'AVERAGE')) { $average = true; } - if (strpos($parts[1], 'MAX') !== false) { + if (str_contains($parts[1], 'MAX')) { $max = true; } - } elseif (strpos($line, 'step') !== false) { + } elseif (str_contains($line, 'step')) { $parts = explode('=', $line); $poller_interval = trim($parts[1]); @@ -772,11 +772,11 @@ function dsstats_error_handler($errno, $errmsg, $filename, $linenum, $vars = arr "' LINE NO:'" . $linenum . "'"; /* let's ignore some lesser issues */ - if (strpos($errmsg, 'date_default_timezone') !== false) { + if (str_contains($errmsg, 'date_default_timezone')) { return; } - if (strpos($errmsg, 'Only variables') !== false) { + if (str_contains($errmsg, 'Only variables')) { return; } @@ -959,7 +959,7 @@ function dsstats_poller_output(&$rrd_update_array) { } if ($currentval != 'NULL') { - $currentval = $currentval / $polling_interval; + $currentval /= $polling_interval; if ($ds_type == 6) { $currentval = round($currentval, 0); @@ -1270,11 +1270,11 @@ function dsstats_rrdtool_execute($command, $rrd_process) { while (!feof($pipes[1])) { $stdout .= fgets($pipes[1], 4096); - if (strpos($stdout, 'OK') !== false) { + if (str_contains($stdout, 'OK')) { break; } - if (strpos($stdout, 'ERROR') !== false) { + if (str_contains($stdout, 'ERROR')) { break; } } diff --git a/lib/export.php b/lib/export.php index 896d3115c9..30b165af38 100644 --- a/lib/export.php +++ b/lib/export.php @@ -98,33 +98,14 @@ function graph_template_to_xml($graph_template_id) { foreach ($struct_graph_item as $field_name => $field_array) { if (!empty($item[$field_name])) { - switch ($field_name) { - case 'task_item_id': - $xml_text .= "\t\t\t<$field_name>hash_" . get_hash_version('data_template_item') . get_hash_data_template($item[$field_name], 'data_template_item') . "\n"; - - break; - case 'cdef_id': - $xml_text .= "\t\t\t<$field_name>hash_" . get_hash_version('cdef') . get_hash_cdef($item[$field_name]) . "\n"; - - break; - case 'vdef_id': - $xml_text .= "\t\t\t<$field_name>hash_" . get_hash_version('vdef') . get_hash_vdef($item[$field_name]) . "\n"; - - break; - case 'gprint_id': - $xml_text .= "\t\t\t<$field_name>hash_" . get_hash_version('gprint_preset') . get_hash_gprint($item[$field_name]) . "\n"; - - break; - case 'color_id': - case 'color2_id': - $xml_text .= "\t\t\t<$field_name>" . db_fetch_cell_prepared('SELECT hex FROM colors WHERE id = ?', array($item[$field_name])) . "\n"; - - break; - default: - $xml_text .= "\t\t\t<$field_name>" . xml_character_encode($item[$field_name]) . "\n"; - - break; - } + match ($field_name) { + 'task_item_id' => $xml_text .= "\t\t\t<$field_name>hash_" . get_hash_version('data_template_item') . get_hash_data_template($item[$field_name], 'data_template_item') . "\n", + 'cdef_id' => $xml_text .= "\t\t\t<$field_name>hash_" . get_hash_version('cdef') . get_hash_cdef($item[$field_name]) . "\n", + 'vdef_id' => $xml_text .= "\t\t\t<$field_name>hash_" . get_hash_version('vdef') . get_hash_vdef($item[$field_name]) . "\n", + 'gprint_id' => $xml_text .= "\t\t\t<$field_name>hash_" . get_hash_version('gprint_preset') . get_hash_gprint($item[$field_name]) . "\n", + 'color_id', 'color2_id' => $xml_text .= "\t\t\t<$field_name>" . db_fetch_cell_prepared('SELECT hex FROM colors WHERE id = ?', array($item[$field_name])) . "\n", + default => $xml_text .= "\t\t\t<$field_name>" . xml_character_encode($item[$field_name]) . "\n", + }; } else { $xml_text .= "\t\t\t<$field_name>" . xml_character_encode($item[$field_name]) . "\n"; } diff --git a/lib/functions.php b/lib/functions.php index cfcf3bff03..5d1b1a2085 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -157,9 +157,9 @@ function save_user_settings(?int $user = null):void { global $settings_user; // Passed user id, or session id, or else 0 - $user = $user ?? ($_SESSION[SESS_USER_ID] ?? 0); + $user ??= $_SESSION[SESS_USER_ID] ?? 0; - foreach ($settings_user as $tab_short_name => $tab_fields) { + foreach ($settings_user as $tab_fields) { foreach ($tab_fields as $field_name => $field_array) { /* Check every field with a numeric default value and reset it to default if the inputted value is not numeric */ if (isset($field_array['default']) && is_numeric($field_array['default']) && !is_numeric(get_nfilter_request_var($field_name))) { @@ -210,7 +210,7 @@ function set_user_setting(string $config_name, mixed $value, ?int $user = null): global $settings_user; // Passed user id, or session id, or else 0 - $user = $user ?? ($_SESSION[SESS_USER_ID] ?? 0); + $user ??= $_SESSION[SESS_USER_ID] ?? 0; if ($user == 0) { $mode = isset($_SESSION[SESS_USER_ID]) ? 'WEBUI' : 'POLLER'; @@ -386,7 +386,7 @@ function read_user_setting(string $config_name, mixed $default = false, bool $fo $set_var = $config['is_web'] ? '_SESSION' : 'config'; $set_key = $config['is_web'] ? OPTIONS_USER : 'config_user_options_array'; - $$set_var[$set_key] = $user_config_array; + ${$set_var}[$set_key] = $user_config_array; } return $user_config_array[$config_name]; @@ -405,7 +405,7 @@ function read_user_setting(string $config_name, mixed $default = false, bool $fo function is_remote_path_setting(string $config_name):bool { global $config; - if ($config['poller_id'] > 1 && (strpos($config_name, 'path_') !== false || strpos($config_name, '_path') !== false)) { + if ($config['poller_id'] > 1 && (str_contains($config_name, 'path_') || str_contains($config_name, '_path'))) { return true; } else { return false; @@ -478,11 +478,11 @@ function set_config_option(string $config_name, mixed $value, bool $remote = fal $set_key = $config['is_web'] ? OPTIONS_WEB : OPTIONS_CLI; // Store whatever value we have in the array - if (!isset($$set_var[$set_key]) || !is_array($$set_var[$set_key])) { - $$set_var[$set_key] = array(); + if (!isset(${$set_var}[$set_key]) || !is_array(${$set_var}[$set_key])) { + ${$set_var}[$set_key] = array(); } - $$set_var[$set_key][$config_name] = $value; + ${$set_var}[$set_key][$config_name] = $value; if (!empty($config['DEBUG_SET_CONFIG_OPTION'])) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . cacti_debug_backtrace($config_name, false, false, 0, 1) . "\n", FILE_APPEND); @@ -666,15 +666,15 @@ function cache_common_config_settings():array { $set_key = $config['is_web'] ? OPTIONS_WEB : OPTIONS_CLI; // Store whatever value we have in the array - if (!isset($$set_var[$set_key]) || !is_array($$set_var[$set_key])) { - $$set_var[$set_key] = array(); + if (!isset(${$set_var}[$set_key]) || !is_array(${$set_var}[$set_key])) { + ${$set_var}[$set_key] = array(); } foreach ($settings as $name => $value) { - $$set_var[$set_key][$name] = $value; + ${$set_var}[$set_key][$name] = $value; } - return $$set_var; + return ${$set_var}; } return array(); @@ -698,11 +698,11 @@ function read_config_option(string $config_name, bool $force = false):string|fal $set_key = $config['is_web'] ? OPTIONS_WEB : OPTIONS_CLI; // Store whatever value we have in the array - if (!isset($$set_var[$set_key]) || !is_array($$set_var[$set_key])) { - $$set_var[$set_key] = array(); + if (!isset(${$set_var}[$set_key]) || !is_array(${$set_var}[$set_key])) { + ${$set_var}[$set_key] = array(); } - $loaded = isset($$set_var[$set_key][$config_name]); + $loaded = isset(${$set_var}[$set_key][$config_name]); if (!empty($config['DEBUG_READ_CONFIG_OPTION'])) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . cacti_debug_backtrace($config_name, false, false, 0, 1) . "\n", FILE_APPEND); @@ -745,10 +745,10 @@ function read_config_option(string $config_name, bool $force = false):string|fal } // Store whatever value we have in the array - $$set_var[$set_key][$config_name] = $value; + ${$set_var}[$set_key][$config_name] = $value; } - $value = $$set_var[$set_key][$config_name]; + $value = ${$set_var}[$set_key][$config_name]; return $value; } @@ -1025,33 +1025,14 @@ function get_format_message_instance($current_message): string { $level = MESSAGE_LEVEL_INFO; } - switch ($level) { - case MESSAGE_LEVEL_NONE: - $message = '' . $fmessage . ''; - - break; - case MESSAGE_LEVEL_INFO: - $message = '' . $fmessage . ''; - - break; - case MESSAGE_LEVEL_WARN: - $message = '' . $fmessage . ''; - - break; - case MESSAGE_LEVEL_ERROR: - $message = '' . $fmessage . ''; - - break; - case MESSAGE_LEVEL_CSRF: - $message = '' . $fmessage . ''; - - break; - - default: - $message = '' . $fmessage . ''; - - break; - } + $message = match ($level) { + MESSAGE_LEVEL_NONE => '' . $fmessage . '', + MESSAGE_LEVEL_INFO => '' . $fmessage . '', + MESSAGE_LEVEL_WARN => '' . $fmessage . '', + MESSAGE_LEVEL_ERROR => '' . $fmessage . '', + MESSAGE_LEVEL_CSRF => '' . $fmessage . '', + default => '' . $fmessage . '', + }; return $message; } @@ -1434,14 +1415,14 @@ function get_selective_log_level(): ?int { } /* Check for Plugin files in debug next */ - if (strpos($dir_name, 'plugins') !== false) { + if (str_contains($dir_name, 'plugins')) { $debug_plugins = read_config_option('selective_plugin_debug'); if ($debug_plugins != '') { $debug_plugins = explode(',', $debug_plugins); foreach ($debug_plugins as $myplugin) { - if (strpos($dir_name, DIRECTORY_SEPARATOR . $myplugin) !== false) { + if (str_contains($dir_name, DIRECTORY_SEPARATOR . $myplugin)) { $force_level = POLLER_VERBOSITY_DEBUG; break; @@ -1566,13 +1547,13 @@ function cacti_log($string, $output = false, $environ = 'CMDPHP', $level = '') { if ($logdestination == 2 || $logdestination == 3) { $log_type = ''; - if (strpos($string, 'ERROR:') !== false) { + if (str_contains($string, 'ERROR:')) { $log_type = 'err'; - } elseif (strpos($string, 'WARNING:') !== false) { + } elseif (str_contains($string, 'WARNING:')) { $log_type = 'warn'; - } elseif (strpos($string, 'STATS:') !== false) { + } elseif (str_contains($string, 'STATS:')) { $log_type = 'stat'; - } elseif (strpos($string, 'NOTICE:') !== false) { + } elseif (str_contains($string, 'NOTICE:')) { $log_type = 'note'; } @@ -1792,87 +1773,87 @@ function determine_display_log_entry($message_type, $line, $filter, $matches = t /* determine if we are to display the line */ switch ($message_type) { case 1: /* stats only */ - $display = (strpos($line, 'STATS') !== false); + $display = (str_contains($line, 'STATS')); break; case 2: /* warnings only */ - $display = (strpos($line, 'WARN') !== false); + $display = (str_contains($line, 'WARN')); break; case 3: /* warnings + */ - $display = (strpos($line, 'WARN') !== false); + $display = (str_contains($line, 'WARN')); if (!$display) { - $display = (strpos($line, 'ERROR') !== false); + $display = (str_contains($line, 'ERROR')); } if (!$display) { - $display = (strpos($line, 'DEBUG') !== false); + $display = (str_contains($line, 'DEBUG')); } if (!$display) { - $display = (strpos($line, ' SQL') !== false); + $display = (str_contains($line, ' SQL')); } break; case 4: /* errors only */ - $display = (strpos($line, 'ERROR') !== false); + $display = (str_contains($line, 'ERROR')); break; case 5: /* errors + */ - $display = (strpos($line, 'ERROR') !== false); + $display = (str_contains($line, 'ERROR')); if (!$display) { - $display = (strpos($line, 'DEBUG') !== false); + $display = (str_contains($line, 'DEBUG')); } if (!$display) { - $display = (strpos($line, ' SQL') !== false); + $display = (str_contains($line, ' SQL')); } break; case 6: /* debug only */ - $display = (strpos($line, 'DEBUG') !== false && strpos($line, ' SQL ') === false); + $display = (str_contains($line, 'DEBUG') && !str_contains($line, ' SQL ')); break; case 7: /* sql calls only */ - $display = (strpos($line, ' SQL ') !== false); + $display = (str_contains($line, ' SQL ')); break; case 8: /* AutoM8 Only */ - $display = (strpos($line, 'AUTOM8') !== false); + $display = (str_contains($line, 'AUTOM8')); break; case 9: /* Non Stats */ - $display = (strpos($line, 'STATS') === false); + $display = (!str_contains($line, 'STATS')); break; case 10: /* Boost Only*/ - $display = (strpos($line, 'BOOST') !== false); + $display = (str_contains($line, 'BOOST')); break; case 11: /* device events + */ - $display = (strpos($line, 'HOST EVENT') !== false); + $display = (str_contains($line, 'HOST EVENT')); if (!$display) { - $display = (strpos($line, '] is recovering!') !== false); + $display = (str_contains($line, '] is recovering!')); } if (!$display) { - $display = (strpos($line, '] is down!') !== false); + $display = (str_contains($line, '] is down!')); } break; case 12: /* Assertions */ - $display = (strpos($line, 'ASSERT FAILED') !== false); + $display = (str_contains($line, 'ASSERT FAILED')); if (!$display) { - $display = (strpos($line, 'Recache Event') !== false); + $display = (str_contains($line, 'Recache Event')); } break; case 13: /* SECURITY */ - $display = (strpos($line, 'SECURITY') !== false); + $display = (str_contains($line, 'SECURITY')); break; case -1: /* all */ @@ -1882,7 +1863,7 @@ function determine_display_log_entry($message_type, $line, $filter, $matches = t default: /* all other lines */ if ($thold_enabled) { if ($message_type == 99) { - $display = (strpos($line, 'THOLD: Threshold') !== false); + $display = (str_contains($line, 'THOLD: Threshold')); } } else { $display = true; @@ -2240,9 +2221,9 @@ function is_hex_string(&$result) { * Hex- is considered due to the stripping of 'String:' in * lib/snmp.php */ - if (substr($compare, 0, 4) == 'hex-') { + if (str_starts_with($compare, 'hex-')) { $check = trim(str_ireplace('hex-', '', $result)); - } elseif (substr($compare, 0, 11) == 'hex-string:') { + } elseif (str_starts_with($compare, 'hex-string:')) { $check = trim(str_ireplace('hex-string:', '', $result)); } else { return false; @@ -2381,7 +2362,7 @@ function is_valid_pathname($path) { */ function dsv_log($message, $data = null, $level = POLLER_VERBOSITY_LOW) { if (read_config_option('data_source_trace') == 'on') { - cacti_log(($message . ' = ') . (is_array($data) ? json_encode($data) : ($data === null ? 'NULL' : $data)), false, 'DSTRACE', $level); + cacti_log(($message . ' = ') . (is_array($data) ? json_encode($data) : ($data ?? 'NULL')), false, 'DSTRACE', $level); } } @@ -2575,7 +2556,7 @@ function test_data_source($data_template_id, $host_id, $snmp_query_id = 0, $snmp if ($output == '' || $output == false) { $output = 'U'; - } elseif (strpos($output, ':U') !== false) { + } elseif (str_contains($output, ':U')) { $output = 'U'; } } else { @@ -2840,7 +2821,7 @@ function test_data_source($data_template_id, $host_id, $snmp_query_id = 0, $snmp $script_path = read_config_option('path_php_binary') . ' -q ' . get_script_query_path(trim($prepend . ' ' . $script_queries['arg_get'] . ' ' . $identifier . ' "' . $snmp_index . '"'), $script_queries['script_path'], $host_id); } else { $action = POLLER_ACTION_SCRIPT; - $script_path = get_script_query_path(trim((isset($script_queries['arg_prepend']) ? $script_queries['arg_prepend'] : '') . ' ' . $script_queries['arg_get'] . ' ' . $identifier . ' "' . $snmp_index . '"'), $script_queries['script_path'], $host_id); + $script_path = get_script_query_path(trim(($script_queries['arg_prepend'] ?? '') . ' ' . $script_queries['arg_get'] . ' ' . $identifier . ' "' . $snmp_index . '"'), $script_queries['script_path'], $host_id); } } @@ -3086,7 +3067,7 @@ function stri_replace(string $find, string $replace, string $string):string { $pos += $partLength + $findLength; } - return (join($replace, $parts)); + return (implode($replace, $parts)); } /** @@ -3183,7 +3164,7 @@ function get_data_source_title(int $local_data_id):string { $title = 'Missing Datasource ' . $local_data_id; if (cacti_sizeof($data)) { - if (strstr($data['name'], '|') !== false && $data['host_id'] > 0) { + if (str_contains($data['name'], '|') && $data['host_id'] > 0) { $data['name'] = substitute_data_input_data($data['name'], '', $local_data_id); $title = expand_title($data['host_id'], $data['snmp_query_id'], $data['snmp_index'], $data['name']); } else { @@ -3287,7 +3268,7 @@ function get_graph_title($local_graph_id) { array($local_graph_id)); if (cacti_sizeof($graph)) { - if (strstr($graph['title'], '|') !== false && $graph['host_id'] > 0 && empty($graph['t_title'])) { + if (str_contains($graph['title'], '|') && $graph['host_id'] > 0 && empty($graph['t_title'])) { $graph['title'] = substitute_data_input_data($graph['title'], $graph, 0); return expand_title($graph['host_id'], $graph['snmp_query_id'], $graph['snmp_index'], $graph['title']); @@ -3808,14 +3789,14 @@ function get_graph_group($graph_template_item_id) { return $graph_item_children_array; } - if (strstr($graph_item_types[$item['graph_type_id']], 'GPRINT') !== false) { + if (str_contains($graph_item_types[$item['graph_type_id']], 'GPRINT')) { /* a child must be a GPRINT */ $graph_item_children_array[$item['id']] = $item['id']; if ($item['hard_return'] == 'on') { $is_hard = true; } - } elseif (strstr($graph_item_types[$item['graph_type_id']], 'COMMENT') !== false) { + } elseif (str_contains($graph_item_types[$item['graph_type_id']], 'COMMENT')) { if (preg_match_all('/\|([0-9]{1,2}):(bits|bytes):(\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\d)?\|/', $item['text_format'], $matches, PREG_SET_ORDER)) { $graph_item_children_array[$item['id']] = $item['id']; } elseif (preg_match_all('/\|sum:(\d|auto):(current|total|atomic):(\d):(\d+|auto)\|/', $item['text_format'], $matches, PREG_SET_ORDER)) { @@ -4185,7 +4166,7 @@ function draw_navigation_text($type = 'url') { } else { // No breadcrumb was found for the current path, make one up $current_array = $navigation[$current_page . ':' . $current_action]; - $url = (isset($current_array['url']) ? $current_array['url']:''); + $url = ($current_array['url'] ?? ''); if (isset($current_array['title'])) { $current_nav .= "
  • " . html_escape(resolve_navigation_variables($current_array['title'])) . '
  • '; @@ -4201,10 +4182,10 @@ function draw_navigation_text($type = 'url') { $parts = explode('-', get_request_var('node')); // Check for tree anchor - if (strpos(get_request_var('node'), 'tree_anchor') !== false) { + if (str_contains(get_request_var('node'), 'tree_anchor')) { $tree_id = $parts[1]; $leaf_id = 0; - } elseif (strpos(get_request_var('node'), 'tbranch') !== false) { + } elseif (str_contains(get_request_var('node'), 'tbranch')) { // Check for branch $leaf_id = $parts[1]; $tree_id = db_fetch_cell_prepared('SELECT graph_tree_id @@ -4771,7 +4752,7 @@ function get_hash_version(string $type): string { * @return mixed a 128-bit, hexadecimal hash */ function generate_hash() { - return md5(session_id() . microtime() . rand(0,1000)); + return md5(session_id() . microtime() . random_int(0,1000)); } /** @@ -4861,7 +4842,7 @@ function debug_log_return($type) { if (isset($_SESSION['debug_log'][$type])) { $log_text .= ""; - foreach($_SESSION['debug_log'][$type] as $key => $val) { + foreach($_SESSION['debug_log'][$type] as $val) { $log_text .= ''; } @@ -5325,8 +5306,8 @@ function mailer(array|string $from, array|string $to, null|array|string $cc = nu $start_time = microtime(true); - $subject = $subject ?? ''; - $body = $body ?? ''; + $subject ??= ''; + $body ??= ''; // Create the PHPMailer instance $mail = new PHPMailer\PHPMailer\PHPMailer; @@ -5454,7 +5435,7 @@ function mailer(array|string $from, array|string $to, null|array|string $cc = nu } /* perform data substitution */ - if (strpos($subject, '|date_time|') !== false) { + if (str_contains($subject, '|date_time|')) { $date = read_config_option('date'); if (!empty($date)) { @@ -5683,7 +5664,7 @@ function mailer(array|string $from, array|string $to, null|array|string $cc = nu $brs = array('
    ', '
    ', '
    '); if ($html) { - $body = $body . '
    '; + $body .= '
    '; } if ($body_text == '') { @@ -5998,7 +5979,7 @@ function email_test() { */ function get_dns_from_ip($ip, $dns, $timeout = 1000) { /* random transaction number (for routers etc to get the reply back) */ - $data = rand(10, 99); + $data = random_int(10, 99); /* trim it to 2 bytes */ $data = substr($data, 0, 2); @@ -6452,7 +6433,7 @@ function get_classic_tabimage($text, $down = false) { $lines = array(); // if no wrapping is requested, or no wrapping is possible... - if ((!$variation[2]) || ($variation[2] && strpos($text,' ') === false)) { + if ((!$variation[2]) || ($variation[2] && !str_contains($text,' '))) { $bounds = imagettfbbox($fontsize, 0, $font, $text); $w = $bounds[4] - $bounds[0]; $h = $bounds[1] - $bounds[5]; @@ -6676,7 +6657,7 @@ function CactiErrorHandler($level, $message, $file, $line, $context = array()) { function CactiShutdownHandler() { global $phperrors; - $phperrors = $phperrors ?? array( + $phperrors ??= array( E_ERROR => 'ERROR', E_WARNING => 'WARNING', E_PARSE => 'PARSE', @@ -6712,7 +6693,7 @@ function CactiShutdownHandler() { case E_PARSE: preg_match('/.*\/plugins\/([\w-]*)\/.*/', $error['file'], $output_array); - $plugin = (isset($output_array[1]) ? $output_array[1] : ''); + $plugin = ($output_array[1] ?? ''); if ($error['type'] !== null && isset($phperrors[$error['type']])) { $message = 'PHP ' . $phperrors[$error['type']] . @@ -7764,7 +7745,7 @@ function get_rrdtool_version() { static $version = ''; if ($version == '') { - $version = str_replace('rrd-', '', str_replace('.x', '.0', read_config_option('rrdtool_version') ?: read_default_config_option('rrdtool_version') ?: '1.4.0')); + $version = str_replace('rrd-', '', str_replace('.x', '.0', (read_config_option('rrdtool_version') ?: read_default_config_option('rrdtool_version')) ?: '1.4.0')); } return $version; @@ -7914,7 +7895,7 @@ function get_theme_paths(string $format, string $path, ?string $theme = null, ?s $paths[] = $path; } - foreach ($paths as $index => $srcPath) { + foreach ($paths as $srcPath) { $srcFile = $srcPath . $file; $relFile = get_include_relpath($srcFile); @@ -8305,7 +8286,7 @@ function get_cacti_base_tables() { if (cacti_sizeof($schema)) { foreach($schema as $line) { - if (strpos($line, 'CREATE TABLE') !== false) { + if (str_contains($line, 'CREATE TABLE')) { $table = str_replace(array('CREATE TABLE', '`', '(', ' '), '', $line); $base_tables[] = trim($table); } @@ -8419,7 +8400,7 @@ function cacti_ptoa($title, $addr) { } function cacti_sizeof($array) { - return ($array === false || !is_array($array)) ? 0 : sizeof($array); + return ($array === false || !is_array($array)) ? 0 : count($array); } function cacti_count($array) { @@ -8540,7 +8521,7 @@ function cacti_cookie_set($session, $val, $timeout = null) { setcookie($session, $val, $options); } else { - setcookie($session, $val, time() + 3600, CACTI_PATH_URL, $domain, $secure, true); + setcookie($session, $val, ['expires' => time() + 3600, 'path' => CACTI_PATH_URL, 'domain' => $domain, 'secure' => $secure, 'httponly' => true]); } } @@ -8581,7 +8562,7 @@ function cacti_cookie_logout() { } } else { foreach ($cookies as $cookie) { - setcookie($cookie, '', time() - 3600, CACTI_PATH_URL, $domain, $secure, true); + setcookie($cookie, '', ['expires' => time() - 3600, 'path' => CACTI_PATH_URL, 'domain' => $domain, 'secure' => $secure, 'httponly' => true]); } } @@ -8626,7 +8607,7 @@ function cacti_cookie_session_set($user, $realm, $nssecret) { setcookie('cacti_remembers', $user . ',' . $realm . ',' . $nssecret, $options); } else { - setcookie('cacti_remembers', $user . ',' . $realm . ',' . $nssecret, time() + (86400 * 30), CACTI_PATH_URL, $domain, $secure, true); + setcookie('cacti_remembers', $user . ',' . $realm . ',' . $nssecret, ['expires' => time() + (86400 * 30), 'path' => CACTI_PATH_URL, 'domain' => $domain, 'secure' => $secure, 'httponly' => true]); } } @@ -8662,7 +8643,7 @@ function cacti_cookie_session_logout() { setcookie('cacti_remembers', '', $options); } else { - setcookie('cacti_remembers', '', time() - 3600, CACTI_PATH_URL, $domain, $secure, true); + setcookie('cacti_remembers', '', ['expires' => time() - 3600, 'path' => CACTI_PATH_URL, 'domain' => $domain, 'secure' => $secure, 'httponly' => true]); } } @@ -8915,11 +8896,11 @@ function cacti_format_ipv6_colon($address) { return $address; } - if (strpos($address, '[') !== false) { + if (str_contains($address, '[')) { return $address; } - if (strpos($address, ':') !== false) { + if (str_contains($address, ':')) { return '[' . $address . ']'; } @@ -8931,8 +8912,8 @@ function text_substitute(null|array|string $text, bool $isHtml = true, bool $inc if (!empty($text)) { $parser = 'text_regex_parser' . ($isHtml ? '_html' : ''); - $extraSubstitutions = $extraSubstitutions ?? array(); - $extraMatches = $extraMatches ?? array(); + $extraSubstitutions ??= array(); + $extraMatches ??= array(); /* Get parts for text substitution */ $extra_search = array_keys($extraSubstitutions); @@ -8943,7 +8924,7 @@ function text_substitute(null|array|string $text, bool $isHtml = true, bool $inc if (!empty($regex_array)) { $regex_complete = ''; - foreach ($regex_array as $regex_key => $regex_setting) { + foreach ($regex_array as $regex_setting) { $regex_text = $regex_setting['regex'] ?? ''; if (!empty($regex_text)) { @@ -9023,7 +9004,7 @@ function text_regex_replace($id, $link, $url, $matches, $cache) { if ($link) { return $matches[1] . '' . (isset($cache[$id]) ? html_escape($cache[$id]) : $id) . '' . $matches[3]; } else { - return $matches[1] . (isset($cache[$id]) ? $cache[$id] : $id) . $matches[3]; + return $matches[1] . ($cache[$id] ?? $id) . $matches[3]; } } diff --git a/lib/graph_variables.php b/lib/graph_variables.php index d83c0b46b5..8ed68842de 100644 --- a/lib/graph_variables.php +++ b/lib/graph_variables.php @@ -241,7 +241,7 @@ function nth_percentile_fetch_statistics($percentile, &$local_data_ids, &$fetch_ $max_values_array = array(); if (cacti_sizeof($asum_array)) { - foreach ($asum_array as $ds_name => $sum_by_timestamp) { + foreach ($asum_array as $sum_by_timestamp) { foreach ($sum_by_timestamp as $timestamp => $data) { if (!isset($max_values_array[$timestamp])) { $max_values_array[$timestamp] = $data; @@ -338,7 +338,7 @@ function cacti_stats_calc($array, $ptile = 95) { } foreach ($array as $number) { - $rsquared += pow($number - $average, 2); + $rsquared += ($number - $average) ** 2; } $variance = $rsquared / $elements; @@ -351,11 +351,11 @@ function cacti_stats_calc($array, $ptile = 95) { $p25n_index = ceil($elements * 0.75); $results = array( - 'p95n' => (isset($array[$p95n_index]) ? $array[$p95n_index] : 0), - 'p90n' => (isset($array[$p90n_index]) ? $array[$p90n_index] : 0), - 'p75n' => (isset($array[$p75n_index]) ? $array[$p75n_index] : 0), - 'p50n' => (isset($array[$p50n_index]) ? $array[$p50n_index] : 0), - 'p25n' => (isset($array[$p25n_index]) ? $array[$p25n_index] : 0), + 'p95n' => ($array[$p95n_index] ?? 0), + 'p90n' => ($array[$p90n_index] ?? 0), + 'p75n' => ($array[$p75n_index] ?? 0), + 'p50n' => ($array[$p50n_index] ?? 0), + 'p25n' => ($array[$p25n_index] ?? 0), 'average' => $average, 'peak' => $peak, 'sum' => $sum, @@ -491,7 +491,7 @@ function variable_nth_percentile(&$regexp_match_array, &$graph, &$graph_item, &$ } foreach ($gi as $data_source => $true) { - list($data_source_name, $local_data_id) = explode('|||', $data_source); + [$data_source_name, $local_data_id] = explode('|||', $data_source); $local_data_array[$local_data_id][] = $data_source_name; } } @@ -577,7 +577,7 @@ function variable_nth_percentile(&$regexp_match_array, &$graph, &$graph_item, &$ if (!empty($nth_cache[$graph_item['data_source_name']])) { $nth = $nth_cache[$graph_item['data_source_name']]; $nth = ($bytebit == 'bits') ? $nth * 8 : $nth; - $nth /= pow($base, $power); + $nth /= $base ** $power; } break; @@ -588,7 +588,7 @@ function variable_nth_percentile(&$regexp_match_array, &$graph, &$graph_item, &$ if (!empty($nth_cache['nth_percentile_sum'])) { $nth = $nth_cache['nth_percentile_sum']; $nth = ($bytebit == 'bits') ? $nth * 8 : $nth; - $nth /= pow($base, $power); + $nth /= $base ** $power; } break; @@ -601,7 +601,7 @@ function variable_nth_percentile(&$regexp_match_array, &$graph, &$graph_item, &$ if (!empty($nth_cache['nth_percentile_maximum'])) { $nth = $nth_cache['nth_percentile_maximum']; $nth = ($bytebit == 'bits') ? $nth * 8 : $nth; - $nth /= pow($base, $power); + $nth /= $base ** $power; } break; @@ -610,7 +610,7 @@ function variable_nth_percentile(&$regexp_match_array, &$graph, &$graph_item, &$ if (!empty($nth_cache['nth_percentile_aggregate_total'])) { $nth = $nth_cache['nth_percentile_aggregate_total']; $nth = ($bytebit == 'bits') ? $nth * 8 : $nth; - $nth /= pow($base, $power); + $nth /= $base ** $power; } break; @@ -714,7 +714,7 @@ function variable_bandwidth_summation(&$regexp_match_array, &$graph, &$graph_ite } if (preg_match('/\d+/', $regexp_match_array[1])) { - $summation /= pow($base, $regexp_match_array[1]); + $summation /= $base ** $regexp_match_array[1]; } elseif ($regexp_match_array[1] == 'auto') { if ($graph['base_value'] == 1000) { if ($summation < 1000) { diff --git a/lib/html.php b/lib/html.php index a37c1f76c2..0aa7ccf6ee 100644 --- a/lib/html.php +++ b/lib/html.php @@ -351,7 +351,7 @@ function html_graph_area(&$graph_array, $no_graphs_message = '', $extra_url_args foreach ($graph_array as $graph) { if (!isset($graph['host_id'])) { - list($graph['host_id'], $graph['disabled']) = db_fetch_row_prepared('SELECT host_id, disabled + [$graph['host_id'], $graph['disabled']] = db_fetch_row_prepared('SELECT host_id, disabled FROM graph_local AS gl LEFT JOIN host AS h ON gl.host_id = h.id @@ -437,7 +437,7 @@ function html_graph_thumbnail_area(&$graph_array, $no_graphs_message = '', $extr foreach ($graph_array as $graph) { if (!isset($graph['host_id'])) { - list($graph['host_id'], $graph['disabled']) = db_fetch_row_prepared('SELECT host_id, disabled + [$graph['host_id'], $graph['disabled']] = db_fetch_row_prepared('SELECT host_id, disabled FROM graph_local AS gl LEFT JOIN host AS h ON gl.host_id = h.id @@ -1673,8 +1673,8 @@ function is_menu_pick_active($menu_url) { $menu_parts = array(); /* special case for host.php?action=edit&create=true */ - if (strpos($_SERVER['REQUEST_URI'], 'host.php?action=edit&create=true') !== false) { - if (strpos($menu_url, 'host.php?action=edit&create=true') !== false) { + if (str_contains($_SERVER['REQUEST_URI'], 'host.php?action=edit&create=true')) { + if (str_contains($menu_url, 'host.php?action=edit&create=true')) { return true; } else { return false; @@ -1691,7 +1691,7 @@ function is_menu_pick_active($menu_url) { } // Host requires another check - if (strpos($menu_url, 'host.php?action=edit&create=true') !== false) { + if (str_contains($menu_url, 'host.php?action=edit&create=true')) { return false; } @@ -1767,7 +1767,7 @@ function draw_menu($user_menu = '') { $show_header_items = false; } } else { - $current_realm_id = (isset($user_auth_realm_filenames[basename($item_url)]) ? $user_auth_realm_filenames[basename($item_url)] : 0); + $current_realm_id = ($user_auth_realm_filenames[basename($item_url)] ?? 0); if (is_realm_allowed($current_realm_id)) { $show_header_items = true; @@ -1799,7 +1799,7 @@ function draw_menu($user_menu = '') { foreach ($header_array as $item_url => $item_title) { $basename = explode('?', basename($item_url)); $basename = $basename[0]; - $current_realm_id = (isset($user_auth_realm_filenames[$basename]) ? $user_auth_realm_filenames[$basename] : 0); + $current_realm_id = ($user_auth_realm_filenames[$basename] ?? 0); /** * if this item is an array, then it contains sub-items. if not, is just @@ -1817,7 +1817,7 @@ function draw_menu($user_menu = '') { } foreach ($item_title as $item_sub_url => $item_sub_title) { - if (substr($item_sub_url, 0, 10) == 'EXTERNAL::') { + if (str_starts_with($item_sub_url, 'EXTERNAL::')) { $item_sub_external = true; $item_sub_url = substr($item_sub_url, 10); } else { @@ -1853,7 +1853,7 @@ function draw_menu($user_menu = '') { } else { if ($current_realm_id == -1 || is_realm_allowed($current_realm_id) || !isset($user_auth_realm_filenames[$basename])) { /* draw normal (non sub-item) menu item */ - if (substr($item_url, 0, 10) == 'EXTERNAL::') { + if (str_starts_with($item_url, 'EXTERNAL::')) { $item_external = true; $item_url = substr($item_url, 10); } else { @@ -2056,7 +2056,7 @@ function is_console_page($url) { } if (cacti_sizeof($menu)) { - foreach ($menu as $section => $children) { + foreach ($menu as $children) { if (cacti_sizeof($children)) { foreach ($children as $page => $name) { if (basename($page) == $basename) { @@ -2354,7 +2354,7 @@ function html_graph_tabs_right() { function html_transform_graph_template_ids($ids) { $return_ids = array(); - if (strpos($ids, ',') !== false) { + if (str_contains($ids, ',')) { $ids = explode(',', $ids); } else { $ids = array($ids); @@ -2363,7 +2363,7 @@ function html_transform_graph_template_ids($ids) { foreach($ids as $id) { if (is_numeric($id)) { $return_ids[] = $id; - } elseif (strpos($id, 'cg_') !== false) { + } elseif (str_contains($id, 'cg_')) { $new_id = str_replace('cg_', '', $id); $return_ids[] = $new_id; } else { @@ -2426,7 +2426,7 @@ function html_graph_order_filter_array() { if (isset_request_var('graph_template_id')) { $graph_templates = html_transform_graph_template_ids(get_nfilter_request_var('graph_template_id')); - if (strpos($graph_templates, ',') !== false || $graph_templates == '' || $graph_templates <= 0) { + if (str_contains($graph_templates, ',') || $graph_templates == '' || $graph_templates <= 0) { $show_sort = false; $data_sources = array('-1' => __('Select a Single Template')); @@ -2581,7 +2581,7 @@ function html_business_hours_filter($callBack = 'applyGraphFilter') { function html_host_filter($host_id = '-1', $call_back = 'applyFilter', $sql_where = '', $noany = false, $nonone = false) { $theme = get_selected_theme(); - if (strpos($call_back, '()') === false) { + if (!str_contains($call_back, '()')) { $call_back .= '()'; } @@ -2648,7 +2648,7 @@ function html_host_filter($host_id = '-1', $call_back = 'applyFilter', $sql_wher function html_site_filter($site_id = '-1', $call_back = 'applyFilter', $sql_where = '', $noany = false, $nonone = false) { $theme = get_selected_theme(); - if (strpos($call_back, '()') === false) { + if (!str_contains($call_back, '()')) { $call_back .= '()'; } @@ -2693,7 +2693,7 @@ function html_site_filter($site_id = '-1', $call_back = 'applyFilter', $sql_wher function html_location_filter($location = '', $call_back = 'applyFilter', $sql_where = '', $noany = false, $nonone = false) { $theme = get_selected_theme(); - if (strpos($call_back, '()') === false) { + if (!str_contains($call_back, '()')) { $call_back .= '()'; } @@ -2707,7 +2707,7 @@ function html_location_filter($location = '', $call_back = 'applyFilter', $sql_w '; print '
    '; print ''; - print ''; + print ''; print ''; print ''; print '
    '; @@ -557,7 +557,7 @@ private function create_filter() { print ''; print '
    '; print ''; - print ''; + print ''; print ''; print ''; print '
    '; @@ -615,7 +615,7 @@ private function create_filter() { print '
    ' . PHP_EOL; } - if (isset_request_var($field_name) && strpos($field_array['method'], 'callback') === false) { + if (isset_request_var($field_name) && !str_contains($field_array['method'], 'callback')) { $field_array['value'] = get_nfilter_request_var($field_name); } @@ -704,7 +704,7 @@ private function create_javascript() { $clearFilter = $applyFilter; $defaultFilter = $applyFilter; - if (strpos($applyFilter, '?') === false) { + if (!str_contains($applyFilter, '?')) { $separator = '?'; } else { $separator = '&'; @@ -738,7 +738,7 @@ private function create_javascript() { $globalAdd = ''; if (isset($this->filter_array['rows'])) { - foreach($this->filter_array['rows'] as $index => $row) { + foreach($this->filter_array['rows'] as $row) { foreach($row as $field_name => $field_array) { switch($field_array['method']) { case 'content': @@ -928,7 +928,7 @@ private function sanitize_filter_variables() { $filters = array(); if (isset($this->filter_array['rows'])) { - foreach($this->filter_array['rows'] as $index => $row) { + foreach($this->filter_array['rows'] as $row) { foreach($row as $field_name => $field_array) { switch($field_array['method']) { case 'timespan': diff --git a/lib/html_form.php b/lib/html_form.php index 54be47dddb..537ac5246e 100644 --- a/lib/html_form.php +++ b/lib/html_form.php @@ -44,7 +44,7 @@ function draw_edit_form($array) { if (cacti_sizeof($fields_array)) { if (!isset($config_array['no_form_tag'])) { - print ""; + print ""; } $i = 0; @@ -65,7 +65,7 @@ function draw_edit_form($array) { } print ''; } elseif ($field_array['method'] == 'hidden_zero') { if (!isset($field_array['value'])) { @@ -125,21 +125,21 @@ function draw_edit_form($array) { $field_array['sub_checkbox']['name'], $field_array['sub_checkbox']['value'], '', - ((isset($field_array['sub_checkbox']['default'])) ? $field_array['sub_checkbox']['default'] : ''), - ((isset($field_array['sub_checkbox']['form_id'])) ? $field_array['sub_checkbox']['form_id'] : ''), - ((isset($field_array['sub_checkbox']['class'])) ? $field_array['sub_checkbox']['class'] : ''), - ((isset($field_array['sub_checkbox']['on_change'])) ? $field_array['sub_checkbox']['on_change'] : ''), - ((isset($field_array['sub_checkbox']['friendly_name'])) ? $field_array['sub_checkbox']['friendly_name'] : '') + ($field_array['sub_checkbox']['default'] ?? ''), + ($field_array['sub_checkbox']['form_id'] ?? ''), + ($field_array['sub_checkbox']['class'] ?? ''), + ($field_array['sub_checkbox']['on_change'] ?? ''), + ($field_array['sub_checkbox']['friendly_name'] ?? '') ); } print html_escape($field_array['friendly_name']); if (read_config_option('hide_form_description') == 'on') { - print '
    ' . ((isset($field_array['description'])) ? $field_array['description'] : '') . ""; + print '
    ' . ($field_array['description'] ?? '') . ""; } else { print '
    '; - print display_tooltip((isset($field_array['description'])) ? $field_array['description'] : ''); + print display_tooltip($field_array['description'] ?? ''); print '
    '; } @@ -182,12 +182,12 @@ function draw_edit_control($field_name, &$field_array) { form_text_box( $field_name, $field_array['value'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), + ($field_array['default'] ?? ''), $field_array['max_length'], - ((isset($field_array['size'])) ? $field_array['size'] : '40'), - ((isset($field_array['type'])) ? $field_array['type'] : 'text'), - ((isset($field_array['form_id'])) ? $field_array['form_id'] : ''), - ((isset($field_array['placeholder'])) ? $field_array['placeholder'] : '') + ($field_array['size'] ?? '40'), + ($field_array['type'] ?? 'text'), + ($field_array['form_id'] ?? ''), + ($field_array['placeholder'] ?? '') ); break; @@ -195,11 +195,11 @@ function draw_edit_control($field_name, &$field_array) { form_filepath_box( $field_name, $field_array['value'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), + ($field_array['default'] ?? ''), $field_array['max_length'], - ((isset($field_array['size'])) ? $field_array['size'] : '40'), + ($field_array['size'] ?? '40'), 'text', - ((isset($field_array['form_id'])) ? $field_array['form_id'] : '') + ($field_array['form_id'] ?? '') ); break; @@ -207,11 +207,11 @@ function draw_edit_control($field_name, &$field_array) { form_dirpath_box( $field_name, $field_array['value'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), + ($field_array['default'] ?? ''), $field_array['max_length'], - ((isset($field_array['size'])) ? $field_array['size'] : '40'), + ($field_array['size'] ?? '40'), 'text', - ((isset($field_array['form_id'])) ? $field_array['form_id'] : '') + ($field_array['form_id'] ?? '') ); break; @@ -219,11 +219,11 @@ function draw_edit_control($field_name, &$field_array) { form_text_box( $field_name, $field_array['value'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), + ($field_array['default'] ?? ''), $field_array['max_length'], - ((isset($field_array['size'])) ? $field_array['size'] : '40'), + ($field_array['size'] ?? '40'), 'password', - ((isset($field_array['form_id'])) ? $field_array['form_id'] : ''), + ($field_array['form_id'] ?? ''), '********' ); @@ -233,11 +233,11 @@ function draw_edit_control($field_name, &$field_array) { form_text_box( $field_name . '_confirm', $field_array['value'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), + ($field_array['default'] ?? ''), $field_array['max_length'], - ((isset($field_array['size'])) ? $field_array['size'] : '40'), + ($field_array['size'] ?? '40'), 'password', - ((isset($field_array['form_id'])) ? $field_array['form_id'] : ''), + ($field_array['form_id'] ?? ''), '********' ); } @@ -249,10 +249,10 @@ function draw_edit_control($field_name, &$field_array) { $field_array['value'], $field_array['textarea_rows'], $field_array['textarea_cols'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : ''), - ((isset($field_array['placeholder'])) ? $field_array['placeholder'] : '') + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? ''), + ($field_array['placeholder'] ?? '') ); break; @@ -263,11 +263,11 @@ function draw_edit_control($field_name, &$field_array) { '', '', $field_array['value'], - ((isset($field_array['none_value'])) ? $field_array['none_value'] : ''), - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : ''), - ((isset($field_array['friendly_name'])) ? $field_array['friendly_name'] : '') + ($field_array['none_value'] ?? ''), + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? ''), + ($field_array['friendly_name'] ?? '') ); break; @@ -278,10 +278,10 @@ function draw_edit_control($field_name, &$field_array) { '', '', $field_array['value'], - ((isset($field_array['none_value'])) ? $field_array['none_value'] : ''), - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : '') + ($field_array['none_value'] ?? ''), + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? '') ); break; @@ -291,10 +291,10 @@ function draw_edit_control($field_name, &$field_array) { '', '', $field_array['value'], - ((isset($field_array['none_value'])) ? $field_array['none_value'] : ''), - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : '') + ($field_array['none_value'] ?? ''), + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? '') ); break; @@ -332,11 +332,11 @@ function draw_edit_control($field_name, &$field_array) { '', '', $field_array['value'], - ((isset($field_array['none_value'])) ? $field_array['none_value'] : ''), - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : ''), - ((isset($field_array['friendly_name'])) ? $field_array['friendly_name'] : '') + ($field_array['none_value'] ?? ''), + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? ''), + ($field_array['friendly_name'] ?? '') ); break; @@ -347,11 +347,11 @@ function draw_edit_control($field_name, &$field_array) { 'name', 'id', $field_array['value'], - ((isset($field_array['none_value'])) ? $field_array['none_value'] : ''), - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : ''), - ((isset($field_array['friendly_name'])) ? $field_array['friendly_name'] : '') + ($field_array['none_value'] ?? ''), + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? ''), + ($field_array['friendly_name'] ?? '') ); break; @@ -364,12 +364,12 @@ function draw_edit_control($field_name, &$field_array) { $field_array['action'], $field_array['id'], $field_array['value'], - ((isset($field_array['none_value'])) ? $field_array['none_value'] : ''), - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : ''), - ((isset($field_array['friendly_name'])) ? $field_array['friendly_name'] : ''), - ((isset($field_array['request_vars'])) ? $field_array['request_vars'] : '') + ($field_array['none_value'] ?? ''), + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? ''), + ($field_array['friendly_name'] ?? ''), + ($field_array['request_vars'] ?? '') ); break; @@ -379,8 +379,8 @@ function draw_edit_control($field_name, &$field_array) { $field_array['array'], (isset($field_array['sql']) ? db_fetch_assoc($field_array['sql']) : $field_array['value']), 'id', - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : '') + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? '') ); break; @@ -398,9 +398,9 @@ function draw_edit_control($field_name, &$field_array) { $field_name, $field_array['value'], __('None'), - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : '') + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? '') ); break; @@ -409,10 +409,10 @@ function draw_edit_control($field_name, &$field_array) { $field_name, $field_array['value'], $field_array['friendly_name'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['form_id'])) ? $field_array['form_id'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : ''), + ($field_array['default'] ?? ''), + ($field_array['form_id'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? ''), $field_array['friendly_name'] ); @@ -433,10 +433,10 @@ function draw_edit_control($field_name, &$field_array) { $check_name, $check_array['value'], $check_array['friendly_name'], - ((isset($check_array['default'])) ? $check_array['default'] : ''), - ((isset($check_array['form_id'])) ? $check_array['form_id'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($check_array['on_change'])) ? $check_array['on_change'] : (((isset($field_array['on_change'])) ? $field_array['on_change'] : ''))), + ($check_array['default'] ?? ''), + ($check_array['form_id'] ?? ''), + ($field_array['class'] ?? ''), + ($check_array['on_change'] ?? $field_array['on_change'] ?? ''), $field_array['friendly_name'], true ); @@ -458,15 +458,15 @@ function draw_edit_control($field_name, &$field_array) { case 'radio': print "
    " . PHP_EOL; - foreach ($field_array['items'] as $radio_index => $radio_array) { + foreach ($field_array['items'] as $radio_array) { form_radio_button( $field_name, $field_array['value'], $radio_array['radio_value'], $radio_array['radio_caption'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), - ((isset($field_array['class'])) ? $field_array['class'] : ''), - ((isset($field_array['on_change'])) ? $field_array['on_change'] : '') + ($field_array['default'] ?? ''), + ($field_array['class'] ?? ''), + ($field_array['on_change'] ?? '') ); print '
    '; @@ -495,38 +495,38 @@ function draw_edit_control($field_name, &$field_array) { form_font_box( $field_name, $field_array['value'], - ((isset($field_array['default'])) ? $field_array['default'] : ''), + ($field_array['default'] ?? ''), $field_array['max_length'], - ((isset($field_array['size'])) ? $field_array['size'] : '40'), + ($field_array['size'] ?? '40'), 'text', - ((isset($field_array['form_id'])) ? $field_array['form_id'] : ''), - ((isset($field_array['placeholder'])) ? $field_array['placeholder'] : '') + ($field_array['form_id'] ?? ''), + ($field_array['placeholder'] ?? '') ); break; case 'file': form_file( $field_name, - ((isset($field_array['size'])) ? $field_array['size'] : '40'), - ((isset($field_array['accept'])) ? $field_array['accept'] : '') + ($field_array['size'] ?? '40'), + ($field_array['accept'] ?? '') ); break; case 'button': form_button( $field_name, - ((isset($field_array['value'])) ? $field_array['value'] : ''), - ((isset($field_array['title'])) ? $field_array['title'] : ''), - ((isset($field_array['on_click'])) ? $field_array['on_click'] : '') + ($field_array['value'] ?? ''), + ($field_array['title'] ?? ''), + ($field_array['on_click'] ?? '') ); break; case 'submit': form_submit( $field_name, - ((isset($field_array['value'])) ? $field_array['value'] : ''), - ((isset($field_array['title'])) ? $field_array['title'] : ''), - ((isset($field_array['on_click'])) ? $field_array['on_click'] : '') + ($field_array['value'] ?? ''), + ($field_array['title'] ?? ''), + ($field_array['on_click'] ?? '') ); break; diff --git a/lib/html_form_template.php b/lib/html_form_template.php index 13f5bd9d60..de9e08e033 100644 --- a/lib/html_form_template.php +++ b/lib/html_form_template.php @@ -58,8 +58,8 @@ function draw_nontemplated_fields_graph($graph_template_id, &$values_array, $fie $form_array += array($form_field_name => $struct_graph[$field_name]); /* modifications to the default form array */ - $form_array[$form_field_name]['value'] = (isset($values_array[$field_name]) ? $values_array[$field_name] : ''); - $form_array[$form_field_name]['form_id'] = (isset($values_array['id']) ? $values_array['id'] : '0'); + $form_array[$form_field_name]['value'] = ($values_array[$field_name] ?? ''); + $form_array[$form_field_name]['form_id'] = ($values_array['id'] ?? '0'); unset($form_array[$form_field_name]['default']); if ($field_array['method'] == 'spacer') { @@ -216,7 +216,7 @@ function draw_nontemplated_fields_graph_item($graph_template_id, $local_graph_id } if ($locked == 'true') { - if (strpos($form_field_name, 'task_item_id') !== false) { + if (str_contains($form_field_name, 'task_item_id')) { $form_array[$form_field_name]['method'] = 'value'; if (isset($current_def_value[$item['column_name']])) { @@ -233,7 +233,7 @@ function draw_nontemplated_fields_graph_item($graph_template_id, $local_graph_id } } } else { - if (strpos($form_field_name, 'task_item_id') !== false) { + if (str_contains($form_field_name, 'task_item_id')) { if (isset($current_def_value[$item['column_name']])) { $value = db_fetch_cell_prepared("SELECT CONCAT_WS('', CASE WHEN host.description IS NULL THEN 'No Device - ' ELSE '' END, data_template_data.name_cache, ' (', data_template_rrd.data_source_name, ')') AS name @@ -323,12 +323,12 @@ function draw_nontemplated_fields_data_source($data_template_id, $local_data_id, $form_array += array($form_field_name => $struct_data_source[$field_name]); /* modifications to the default form array */ - $form_array[$form_field_name]['value'] = (isset($values_array[$field_name]) ? $values_array[$field_name] : ''); - $form_array[$form_field_name]['form_id'] = (isset($values_array['id']) ? $values_array['id'] : '0'); + $form_array[$form_field_name]['value'] = ($values_array[$field_name] ?? ''); + $form_array[$form_field_name]['form_id'] = ($values_array['id'] ?? '0'); unset($form_array[$form_field_name]['default']); - $current_flag = (isset($field_array['flags']) ? $field_array['flags'] : ''); - $current_template_flag = (isset($data_template['t_' . $field_name]) ? $data_template['t_' . $field_name] : 'on'); + $current_flag = ($field_array['flags'] ?? ''); + $current_template_flag = ($data_template['t_' . $field_name] ?? 'on'); if (($current_template_flag != 'on') || ($current_flag == 'ALWAYSTEMPLATE')) { if ($include_hidden_fields == true) { @@ -426,8 +426,8 @@ function draw_nontemplated_fields_data_source_item($data_template_id, &$values_a $form_array += array($form_field_name => $struct_data_source_item[$field_name]); /* modifications to the default form array */ - $form_array[$form_field_name]['value'] = (isset($rrd[$field_name]) ? $rrd[$field_name] : ''); - $form_array[$form_field_name]['form_id'] = (isset($rrd['id']) ? $rrd['id'] : '0'); + $form_array[$form_field_name]['value'] = ($rrd[$field_name] ?? ''); + $form_array[$form_field_name]['form_id'] = ($rrd['id'] ?? '0'); unset($form_array[$form_field_name]['default']); /* append the data source item name so the user will recognize it */ diff --git a/lib/html_graph.php b/lib/html_graph.php index 515e232d32..456eadb8ad 100644 --- a/lib/html_graph.php +++ b/lib/html_graph.php @@ -139,7 +139,7 @@ function create_preview_filter() { /* unset the ordering if we have a setup that does not support ordering */ if (isset_request_var('graph_template_id')) { - if (strpos(get_nfilter_request_var('graph_template_id'), ',') !== false || get_nfilter_request_var('graph_template_id') <= 0) { + if (str_contains(get_nfilter_request_var('graph_template_id'), ',') || get_nfilter_request_var('graph_template_id') <= 0) { set_request_var('graph_order', ''); set_request_var('graph_source', ''); } @@ -569,7 +569,7 @@ function html_graph_new_graphs($page, $host_id, $host_template_id, $selected_gra form_hidden_box('save_component_new_graphs', '1', ''); form_hidden_box('selected_graphs_array', serialize($selected_graphs_array), ''); - if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'graphs_new') === false) { + if (isset($_SERVER['HTTP_REFERER']) && !str_contains($_SERVER['HTTP_REFERER'], 'graphs_new')) { set_request_var('returnto', basename($_SERVER['HTTP_REFERER'])); } @@ -678,14 +678,14 @@ function html_graph_custom_data($host_id, $host_template_id, $snmp_query_id, $fo AND gtg.local_graph_id = 0', array($graph_template_id)); - array_push($num_output_fields, draw_nontemplated_fields_graph($graph_template_id, $graph_template, "g_$snmp_query_id" . '_' . $graph_template_id . '_|field|', __('Graph [Template: %s]', html_escape($graph_template['graph_template_name'])), true, false, (isset($snmp_query_graph_id) ? $snmp_query_graph_id : 0))); + array_push($num_output_fields, draw_nontemplated_fields_graph($graph_template_id, $graph_template, "g_$snmp_query_id" . '_' . $graph_template_id . '_|field|', __('Graph [Template: %s]', html_escape($graph_template['graph_template_name'])), true, false, ($snmp_query_graph_id ?? 0))); array_push($num_output_fields, draw_nontemplated_fields_graph_item($graph_template_id, 0, 'gi_' . $snmp_query_id . '_' . $graph_template_id . '_|id|_|field|', __('Graph Items [Template: %s]', html_escape($graph_template['graph_template_name'])), true)); /* DRAW: Data Sources */ if (cacti_sizeof($data_templates)) { foreach ($data_templates as $data_template) { - array_push($num_output_fields, draw_nontemplated_fields_data_source($data_template['data_template_id'], 0, $data_template, 'd_' . $snmp_query_id . '_' . $graph_template_id . '_' . $data_template['data_template_id'] . '_|field|', __('Data Source [Template: %s]', html_escape($data_template['data_template_name'])), true, false, (isset($snmp_query_graph_id) ? $snmp_query_graph_id : 0))); + array_push($num_output_fields, draw_nontemplated_fields_data_source($data_template['data_template_id'], 0, $data_template, 'd_' . $snmp_query_id . '_' . $graph_template_id . '_' . $data_template['data_template_id'] . '_|field|', __('Data Source [Template: %s]', html_escape($data_template['data_template_name'])), true, false, ($snmp_query_graph_id ?? 0))); $data_template_items = db_fetch_assoc_prepared('SELECT data_template_rrd.* @@ -694,7 +694,7 @@ function html_graph_custom_data($host_id, $host_template_id, $snmp_query_id, $fo AND local_data_id = 0', array($data_template['data_template_id'])); - array_push($num_output_fields, draw_nontemplated_fields_data_source_item($data_template['data_template_id'], $data_template_items, 'di_' . $snmp_query_id . '_' . $graph_template_id . '_' . $data_template['data_template_id'] . '_|id|_|field|', '', true, false, false, (isset($snmp_query_graph_id) ? $snmp_query_graph_id : 0))); + array_push($num_output_fields, draw_nontemplated_fields_data_source_item($data_template['data_template_id'], $data_template_items, 'di_' . $snmp_query_id . '_' . $graph_template_id . '_' . $data_template['data_template_id'] . '_|id|_|field|', '', true, false, false, ($snmp_query_graph_id ?? 0))); array_push($num_output_fields, draw_nontemplated_fields_custom_data($data_template['id'], 'c_' . $snmp_query_id . '_' . $graph_template_id . '_' . $data_template['data_template_id'] . '_|id|', __('Custom Data [Template: %s]', html_escape($data_template['data_template_name'])), true, false, $snmp_query_id)); } } @@ -1702,7 +1702,7 @@ function html_graph_single_view() { general_header(); } - if (strpos(get_request_var('action'), 'tree') !== false) { + if (str_contains(get_request_var('action'), 'tree')) { $suffix = 'tree'; } else { $suffix = 'preview'; @@ -1936,7 +1936,7 @@ function html_graph_zoom() { $rras = $info['rras']; $graph_title = $info['title']; - if (strpos(get_nfilter_request_var('action'), 'tree') !== false) { + if (str_contains(get_nfilter_request_var('action'), 'tree')) { $suffix = 'tree'; } else { $suffix = 'preview'; diff --git a/lib/html_reports.php b/lib/html_reports.php index 9b78d7e2df..8c93baeb35 100644 --- a/lib/html_reports.php +++ b/lib/html_reports.php @@ -299,7 +299,7 @@ function reports_form_save() { $save['from_name'] = $post['from_name']; $save['from_email'] = $post['from_email']; $save['bcc'] = $post['bcc']; - $save['notify_list'] = (isset($post['notify_list']) ? $post['notify_list']:''); + $save['notify_list'] = ($post['notify_list'] ?? ''); $atype = $post['attachment_type']; @@ -409,7 +409,7 @@ function reports_form_actions() { if ($selected_items != false) { foreach($selected_items as $report) { - list($type, $report_id) = explode('_', $report); + [$type, $report_id] = explode('_', $report); if (get_nfilter_request_var('drp_action') == REPORTS_DELETE) { // delete if ($type == 'reports') { @@ -477,7 +477,7 @@ function reports_form_actions() { /* loop through each of the graphs selected on the previous page and get more info about them */ foreach ($_POST as $var => $val) { if (preg_match('/^chk_([a-z_0-9]+)$/', $var, $matches)) { - list($type, $id) = explode('_', $matches[1]); + [$type, $id] = explode('_', $matches[1]); /* ================= input validation ================= */ input_validate_input_number($id); /* ==================================================== */ @@ -1208,14 +1208,14 @@ function reports_item_edit() { draw_edit_form( array( 'config' => array('no_form_tag' => true), - 'fields' => inject_form_variables($fields_reports_item_edit, (isset($report_item) ? $report_item : array())) + 'fields' => inject_form_variables($fields_reports_item_edit, ($report_item ?? array())) ) ); html_end_box(true, true); - form_hidden_box('id', (isset($report_item['id']) ? $report_item['id'] : '0'), ''); - form_hidden_box('report_id', (isset($report_item['report_id']) ? $report_item['report_id'] : '0'), ''); + form_hidden_box('id', ($report_item['id'] ?? '0'), ''); + form_hidden_box('report_id', ($report_item['report_id'] ?? '0'), ''); form_hidden_box('save_component_report_item', '1', ''); form_save_button(get_reports_page() . '?action=edit&tab=items&id=' . get_request_var('id'), 'return'); @@ -1541,7 +1541,7 @@ function reports_edit() { html_end_box(true, true); - form_hidden_box('id', (isset($report['id']) ? $report['id'] : '0'), ''); + form_hidden_box('id', ($report['id'] ?? '0'), ''); form_hidden_box('save_component_report', '1', ''); ?> @@ -2264,7 +2264,7 @@ function reports() { form_selectable_cell($type, $id); if (reports_html_account_exists($report['user_id'])) { - form_selectable_ecell($report['full_name'] ? $report['full_name'] : $report['username'], $id); + form_selectable_ecell($report['full_name'] ?: $report['username'], $id); } else { form_selectable_cell(__('Report Disabled - No Owner'), $id); } diff --git a/lib/html_tree.php b/lib/html_tree.php index 711c7ff13a..e15b52a9b9 100644 --- a/lib/html_tree.php +++ b/lib/html_tree.php @@ -415,7 +415,7 @@ function get_tree_path() { $nnodes = array(); $rnodes = array(); - if (strpos(get_request_var('node'), 'tbranch') !== false) { + if (str_contains(get_request_var('node'), 'tbranch')) { $parts = explode('-', get_request_var('node')); $node = $parts[1]; @@ -496,7 +496,7 @@ function get_tree_path() { if (cacti_sizeof($nnodes)) { $nodes = array_merge($nodes, $nnodes); } - } elseif (strpos(get_request_var('node'), 'tree_anchor') !== false) { + } elseif (str_contains(get_request_var('node'), 'tree_anchor')) { $parts = explode('-', get_request_var('node')); $nodes[] = 'tree_anchor-' . $parts[1] . '_anchor'; } @@ -958,7 +958,7 @@ function create_tree_filter() { /* unset the ordering if we have a setup that does not support ordering */ if (isset_request_var('graph_template_id')) { - if (strpos(get_nfilter_request_var('graph_template_id'), ',') !== false || get_nfilter_request_var('graph_template_id') <= 0) { + if (str_contains(get_nfilter_request_var('graph_template_id'), ',') || get_nfilter_request_var('graph_template_id') <= 0) { set_request_var('graph_order', ''); set_request_var('graph_source', ''); } @@ -1898,7 +1898,7 @@ function get_matching_nodes() { $fa = array(); if (cacti_sizeof($final_array)) { - foreach ($final_array as $key => $matches) { + foreach ($final_array as $matches) { foreach ($matches as $branch => $dnc) { $fa[] = $branch; } @@ -1935,7 +1935,7 @@ function html_tree_get_node() { $tree_id = 0; if (isset_request_var('tree_id')) { - if (get_nfilter_request_var('tree_id') == 0 && strstr(get_nfilter_request_var('id'), 'tbranch-') !== false) { + if (get_nfilter_request_var('tree_id') == 0 && str_contains(get_nfilter_request_var('id'), 'tbranch-')) { $tree_id = db_fetch_cell_prepared('SELECT graph_tree_id FROM graph_tree_items WHERE id = ?', @@ -2046,10 +2046,10 @@ function html_tree_get_content() { $parts = explode('-', sanitize_search_string(get_request_var('node'))); // Check for tree anchor - if (strpos(get_nfilter_request_var('node'), 'tree_anchor') !== false) { + if (str_contains(get_nfilter_request_var('node'), 'tree_anchor')) { $tree_id = $parts[1]; $node_id = 0; - } elseif (strpos(get_nfilter_request_var('node'), 'tbranch') !== false) { + } elseif (str_contains(get_nfilter_request_var('node'), 'tbranch')) { // Check for branch $node_id = $parts[1]; $tree_id = db_fetch_cell_prepared('SELECT graph_tree_id diff --git a/lib/html_utility.php b/lib/html_utility.php index 53272125e0..d95441b830 100644 --- a/lib/html_utility.php +++ b/lib/html_utility.php @@ -67,20 +67,20 @@ function inject_form_variables(&$form_array, $arg1 = array(), $arg2 = array(), $ /* an empty field name in the variable means don't treat this as an array */ if ($matches2 == '') { - if (is_array($$matches1)) { + if (is_array(${$matches1})) { /* the existing value is already an array, leave it alone */ - $form_array[$field_name][$field_to_check] = $$matches1; + $form_array[$field_name][$field_to_check] = ${$matches1}; } else { /* the existing value is probably a single variable */ - $form_array[$field_name][$field_to_check] = str_replace($matches0, $$matches1, $field_array[$field_to_check]); + $form_array[$field_name][$field_to_check] = str_replace($matches0, ${$matches1}, $field_array[$field_to_check]); } } else { /* copy the value down from the array/key specified in the variable * replace up to three times for arg1:arg2:arg3 variables */ - if (isset($$matches1)) { - if (is_array($$matches1)) { - $array = $$matches1; + if (isset(${$matches1})) { + if (is_array(${$matches1})) { + $array = ${$matches1}; if (is_array($array) && isset($array[$matches2]) && $array[$matches2] != '') { $string = str_replace($matches0, $array[$matches2], $string); @@ -204,9 +204,9 @@ function form_alternate_row($row_id = '', $light = false, $disabled = false) { $i++; - if ($row_id != '' && !$disabled && substr($row_id, 0, 4) != 'row_') { + if ($row_id != '' && !$disabled && !str_starts_with($row_id, 'row_')) { print "
    \n"; - } elseif (substr($row_id, 0, 4) == 'row_') { + } elseif (str_starts_with($row_id, 'row_')) { print "\n"; } elseif ($row_id != '') { print "\n"; @@ -291,7 +291,7 @@ function form_selectable_cell($contents, $id, $width = '', $style_or_class = '', $output = ''; if ($style_or_class != '') { - if (strpos($style_or_class, ':') === false) { + if (!str_contains($style_or_class, ':')) { $output = "class='nowrap " . $style_or_class . "'"; if ($width != '') { @@ -369,7 +369,7 @@ function form_selectable_vcell($contents, $table_id = '', $columnid = '', $style $output = ''; if ($style_or_class != '') { - if (strpos($style_or_class, ':') === false) { + if (!str_contains($style_or_class, ':')) { $output = "class='nowrap " . $style_or_class . "'"; if ($width != '') { @@ -1145,7 +1145,7 @@ function update_order_string($inplace = false) { $order = ''; - if (strpos(get_request_var('sort_column'), '(') === false && strpos(get_request_var('sort_column'), '`') === false) { + if (!str_contains(get_request_var('sort_column'), '(') && !str_contains(get_request_var('sort_column'), '`')) { $del = '`'; } else { $del = ''; @@ -1190,7 +1190,7 @@ function update_order_string($inplace = false) { $_SESSION['sort_string'][$page] = 'ORDER BY '; foreach ($_SESSION['sort_data'][$page] as $column => $direction) { - if (strpos($column, '(') === false && strpos($column, '`') === false) { + if (!str_contains($column, '(') && !str_contains($column, '`')) { $del = '`'; } else { $del = ''; @@ -1227,7 +1227,7 @@ function update_order_string($inplace = false) { function get_order_string() { $page = get_order_string_page(); - if (strpos(get_request_var('sort_column'), '(') === false && strpos(get_request_var('sort_column'), '`') === false) { + if (!str_contains(get_request_var('sort_column'), '(') && !str_contains(get_request_var('sort_column'), '`')) { $del = '`'; } else { $del = ''; @@ -1313,7 +1313,7 @@ function validate_is_regex($regex) { return __('Cacti regular expressions are limited to 50 characters only for security reasons.'); } - if (strpos($regex, ';') !== false) { + if (str_contains($regex, ';')) { return __('Cacti regular expressions can not includes the semi-color character.'); } @@ -1402,29 +1402,13 @@ function get_colored_device_status($disabled, $status, $thold_failure_count = -1 } } - switch ($status) { - case HOST_DOWN: - return "" . __('Down') . ''; - - break; - case HOST_RECOVERING: - return "" . __('Recovering') . ''; - - break; - case HOST_UP: - return "" . __('Up') . ''; - - break; - case HOST_ERROR: - return "" . __('Error') . ''; - - break; - - default: - return "" . __('Unknown') . ''; - - break; - } + return match ($status) { + HOST_DOWN => "" . __('Down') . '', + HOST_RECOVERING => "" . __('Recovering') . '', + HOST_UP => "" . __('Up') . '', + HOST_ERROR => "" . __('Error') . '', + default => "" . __('Unknown') . '', + }; } } @@ -1512,7 +1496,7 @@ function get_page_list($current_page, $pages_per_screen, $rows_per_page, $total_ $pages_per_screen += 2; $url_page_select = "
      "; - if (strpos($url, '?') !== false) { + if (str_contains($url, '?')) { $url . '&'; } else { $url . '?'; @@ -1596,7 +1580,7 @@ function get_page_list($current_page, $pages_per_screen, $rows_per_page, $total_ $return_to = 'main'; } - $url = $url . $page_var; + $url .= $page_var; $url_page_select .= "
    ' . $val . '